5 use BookStack\Access\UserInviteException;
6 use BookStack\Access\UserInviteService;
7 use BookStack\Activity\ActivityType;
8 use BookStack\Uploads\Image;
9 use BookStack\Users\Models\Role;
10 use BookStack\Users\Models\User;
11 use Illuminate\Support\Facades\Hash;
12 use Illuminate\Support\Str;
13 use Mockery\MockInterface;
16 class UserManagementTest extends TestCase
18 public function test_user_creation()
20 /** @var User $user */
21 $user = User::factory()->make();
22 $adminRole = Role::getRole('admin');
24 $resp = $this->asAdmin()->get('/settings/users');
25 $this->withHtml($resp)->assertElementContains('a[href="' . url('/settings/users/create') . '"]', 'Add New User');
27 $resp = $this->get('/settings/users/create');
28 $this->withHtml($resp)->assertElementContains('form[action="' . url('/settings/users/create') . '"]', 'Save');
30 $resp = $this->post('/settings/users/create', [
31 'name' => $user->name,
32 'email' => $user->email,
33 'password' => $user->password,
34 'password-confirm' => $user->password,
35 'roles[' . $adminRole->id . ']' => 'true',
37 $resp->assertRedirect('/settings/users');
39 $resp = $this->get('/settings/users');
40 $resp->assertSee($user->name);
42 $this->assertDatabaseHas('users', $user->only('name', 'email'));
45 $this->assertStringStartsWith(Str::slug($user->name), $user->slug);
48 public function test_user_updating()
50 $user = $this->users->viewer();
51 $password = $user->password;
53 $resp = $this->asAdmin()->get('/settings/users/' . $user->id);
54 $resp->assertSee($user->email);
56 $this->put($user->getEditUrl(), [
57 'name' => 'Barry Scott',
58 ])->assertRedirect('/settings/users');
60 $this->assertDatabaseHas('users', ['id' => $user->id, 'name' => 'Barry Scott', 'password' => $password]);
61 $this->assertDatabaseMissing('users', ['name' => $user->name]);
64 $this->assertStringStartsWith(Str::slug($user->name), $user->slug);
67 public function test_user_password_update()
69 $user = $this->users->viewer();
70 $userProfilePage = '/settings/users/' . $user->id;
72 $this->asAdmin()->get($userProfilePage);
73 $this->put($userProfilePage, [
74 'password' => 'newpassword',
75 ])->assertRedirect($userProfilePage);
77 $this->get($userProfilePage)->assertSee('Password confirmation required');
79 $this->put($userProfilePage, [
80 'password' => 'newpassword',
81 'password-confirm' => 'newpassword',
82 ])->assertRedirect('/settings/users');
84 $userPassword = User::query()->find($user->id)->password;
85 $this->assertTrue(Hash::check('newpassword', $userPassword));
88 public function test_user_can_be_updated_with_single_char_name()
90 $user = $this->users->viewer();
91 $this->asAdmin()->put("/settings/users/{$user->id}", [
93 ])->assertRedirect('/settings/users');
95 $this->assertEquals('b', $user->refresh()->name);
98 public function test_user_cannot_be_deleted_if_last_admin()
100 $adminRole = Role::getRole('admin');
102 // Delete all but one admin user if there are more than one
103 $adminUsers = $adminRole->users;
104 if (count($adminUsers) > 1) {
105 /** @var User $user */
106 foreach ($adminUsers->splice(1) as $user) {
111 // Ensure we currently only have 1 admin user
112 $this->assertEquals(1, $adminRole->users()->count());
113 /** @var User $user */
114 $user = $adminRole->users->first();
116 $resp = $this->asAdmin()->delete('/settings/users/' . $user->id);
117 $resp->assertRedirect('/settings/users/' . $user->id);
119 $resp = $this->get('/settings/users/' . $user->id);
120 $resp->assertSee('You cannot delete the only admin');
122 $this->assertDatabaseHas('users', ['id' => $user->id]);
125 public function test_delete()
127 $editor = $this->users->editor();
128 $resp = $this->asAdmin()->delete("settings/users/{$editor->id}");
129 $resp->assertRedirect('/settings/users');
130 $resp = $this->followRedirects($resp);
132 $resp->assertSee('User successfully removed');
133 $this->assertActivityExists(ActivityType::USER_DELETE);
135 $this->assertDatabaseMissing('users', ['id' => $editor->id]);
138 public function test_delete_offers_migrate_option()
140 $editor = $this->users->editor();
141 $resp = $this->asAdmin()->get("settings/users/{$editor->id}/delete");
142 $resp->assertSee('Migrate Ownership');
143 $resp->assertSee('new_owner_id');
146 public function test_migrate_option_hidden_if_user_cannot_manage_users()
148 $editor = $this->users->editor();
150 $resp = $this->asEditor()->get("settings/users/{$editor->id}/delete");
151 $resp->assertDontSee('Migrate Ownership');
152 $resp->assertDontSee('new_owner_id');
154 $this->permissions->grantUserRolePermissions($editor, ['users-manage']);
156 $resp = $this->asEditor()->get("settings/users/{$editor->id}/delete");
157 $resp->assertSee('Migrate Ownership');
158 $this->withHtml($resp)->assertElementExists('form input[name="new_owner_id"]');
159 $resp->assertSee('new_owner_id');
162 public function test_delete_with_new_owner_id_changes_ownership()
164 $page = $this->entities->page();
165 $owner = $page->ownedBy;
166 $newOwner = User::query()->where('id', '!=', $owner->id)->first();
168 $this->asAdmin()->delete("settings/users/{$owner->id}", ['new_owner_id' => $newOwner->id]);
169 $this->assertDatabaseHas('pages', [
171 'owned_by' => $newOwner->id,
175 public function test_delete_with_empty_owner_migration_id_works()
177 $user = $this->users->editor();
179 $resp = $this->asAdmin()->delete("settings/users/{$user->id}", ['new_owner_id' => '']);
180 $resp->assertRedirect('/settings/users');
181 $this->assertActivityExists(ActivityType::USER_DELETE);
182 $this->assertSessionHas('success');
185 public function test_delete_removes_user_preferences()
187 $editor = $this->users->editor();
188 setting()->putUser($editor, 'dark-mode-enabled', 'true');
190 $this->assertDatabaseHas('settings', [
191 'setting_key' => 'user:' . $editor->id . ':dark-mode-enabled',
195 $this->asAdmin()->delete("settings/users/{$editor->id}");
197 $this->assertDatabaseMissing('settings', [
198 'setting_key' => 'user:' . $editor->id . ':dark-mode-enabled',
202 public function test_guest_profile_shows_limited_form()
204 $guest = $this->users->guest();
206 $resp = $this->asAdmin()->get('/settings/users/' . $guest->id);
207 $resp->assertSee('Guest');
208 $html = $this->withHtml($resp);
210 $html->assertElementNotExists('#password');
211 $html->assertElementNotExists('[name="language"]');
214 public function test_guest_profile_cannot_be_deleted()
216 $guestUser = $this->users->guest();
217 $resp = $this->asAdmin()->get('/settings/users/' . $guestUser->id . '/delete');
218 $resp->assertSee('Delete User');
219 $resp->assertSee('Guest');
220 $this->withHtml($resp)->assertElementContains('form[action$="/settings/users/' . $guestUser->id . '"] button', 'Confirm');
222 $resp = $this->delete('/settings/users/' . $guestUser->id);
223 $resp->assertRedirect('/settings/users/' . $guestUser->id);
224 $resp = $this->followRedirects($resp);
225 $resp->assertSee('cannot delete the guest user');
228 public function test_user_create_language_reflects_default_system_locale()
230 $langs = ['en', 'fr', 'hr'];
231 foreach ($langs as $lang) {
232 config()->set('app.default_locale', $lang);
233 $resp = $this->asAdmin()->get('/settings/users/create');
234 $this->withHtml($resp)->assertElementExists('select[name="language"] option[value="' . $lang . '"][selected]');
238 public function test_user_creation_is_not_performed_if_the_invitation_sending_fails()
240 /** @var User $user */
241 $user = User::factory()->make();
242 $adminRole = Role::getRole('admin');
244 // Simulate an invitation sending failure
245 $this->mock(UserInviteService::class, function (MockInterface $mock) {
246 $mock->shouldReceive('sendInvitation')->once()->andThrow(UserInviteException::class);
249 $this->asAdmin()->post('/settings/users/create', [
250 'name' => $user->name,
251 'email' => $user->email,
252 'send_invite' => 'true',
253 'roles[' . $adminRole->id . ']' => 'true',
256 // Since the invitation failed, the user should not exist in the database
257 $this->assertDatabaseMissing('users', $user->only('name', 'email'));
260 public function test_user_create_activity_is_not_persisted_if_the_invitation_sending_fails()
262 /** @var User $user */
263 $user = User::factory()->make();
265 $this->mock(UserInviteService::class, function (MockInterface $mock) {
266 $mock->shouldReceive('sendInvitation')->once()->andThrow(UserInviteException::class);
269 $this->asAdmin()->post('/settings/users/create', [
270 'name' => $user->name,
271 'email' => $user->email,
272 'send_invite' => 'true',
275 $this->assertDatabaseMissing('activities', ['type' => 'USER_CREATE']);
278 public function test_return_to_form_with_warning_if_the_invitation_sending_fails()
280 $logger = $this->withTestLogger();
281 /** @var User $user */
282 $user = User::factory()->make();
284 $this->mock(UserInviteService::class, function (MockInterface $mock) {
285 $mock->shouldReceive('sendInvitation')->once()->andThrow(UserInviteException::class);
288 $resp = $this->asAdmin()->post('/settings/users/create', [
289 'name' => $user->name,
290 'email' => $user->email,
291 'send_invite' => 'true',
294 $resp->assertRedirect('/settings/users/create');
295 $this->assertSessionError('Could not create user since invite email failed to send');
296 $this->assertEquals($user->email, session()->getOldInput('email'));
297 $this->assertTrue($logger->hasErrorThatContains('Failed to send user invite with error:'));
300 public function test_user_create_update_fails_if_locale_is_invalid()
302 $user = $this->users->editor();
305 $resp = $this->asAdmin()->put($user->getEditUrl(), ['language' => 'this_is_too_long']);
306 $resp->assertSessionHasErrors(['language' => 'The language may not be greater than 15 characters.']);
309 // Invalid characters
310 $resp = $this->put($user->getEditUrl(), ['language' => 'en<GB']);
311 $resp->assertSessionHasErrors(['language' => 'The language may only contain letters, numbers, dashes and underscores.']);
315 $resp = $this->post('/settings/users/create', [
316 'language' => 'en<GB_and_this_is_longer',
320 $resp->assertSessionHasErrors(['language' => 'The language may not be greater than 15 characters.']);
321 $resp->assertSessionHasErrors(['language' => 'The language may only contain letters, numbers, dashes and underscores.']);
324 public function test_user_avatar_update_and_reset()
326 $user = $this->users->viewer();
327 $avatarFile = $this->files->uploadedImage('avatar-icon.png');
329 $this->assertEquals(0, $user->image_id);
331 $upload = $this->asAdmin()->call('PUT', "/settings/users/{$user->id}", [
332 'name' => 'Barry Scott',
333 ], [], ['profile_image' => $avatarFile], []);
334 $upload->assertRedirect('/settings/users');
337 $this->assertNotEquals(0, $user->image_id);
338 /** @var Image $image */
339 $image = Image::query()->findOrFail($user->image_id);
340 $this->assertFileExists(public_path($image->path));
342 $reset = $this->put("/settings/users/{$user->id}", [
343 'name' => 'Barry Scott',
344 'profile_image_reset' => 'true',
346 $upload->assertRedirect('/settings/users');
349 $this->assertFileDoesNotExist(public_path($image->path));
350 $this->assertEquals(0, $user->image_id);