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();
205 $resp = $this->asAdmin()->get('/settings/users/' . $guest->id);
206 $resp->assertSee('Guest');
207 $this->withHtml($resp)->assertElementNotExists('#password');
210 public function test_guest_profile_cannot_be_deleted()
212 $guestUser = $this->users->guest();
213 $resp = $this->asAdmin()->get('/settings/users/' . $guestUser->id . '/delete');
214 $resp->assertSee('Delete User');
215 $resp->assertSee('Guest');
216 $this->withHtml($resp)->assertElementContains('form[action$="/settings/users/' . $guestUser->id . '"] button', 'Confirm');
218 $resp = $this->delete('/settings/users/' . $guestUser->id);
219 $resp->assertRedirect('/settings/users/' . $guestUser->id);
220 $resp = $this->followRedirects($resp);
221 $resp->assertSee('cannot delete the guest user');
224 public function test_user_create_language_reflects_default_system_locale()
226 $langs = ['en', 'fr', 'hr'];
227 foreach ($langs as $lang) {
228 config()->set('app.default_locale', $lang);
229 $resp = $this->asAdmin()->get('/settings/users/create');
230 $this->withHtml($resp)->assertElementExists('select[name="language"] option[value="' . $lang . '"][selected]');
234 public function test_user_creation_is_not_performed_if_the_invitation_sending_fails()
236 /** @var User $user */
237 $user = User::factory()->make();
238 $adminRole = Role::getRole('admin');
240 // Simulate an invitation sending failure
241 $this->mock(UserInviteService::class, function (MockInterface $mock) {
242 $mock->shouldReceive('sendInvitation')->once()->andThrow(UserInviteException::class);
245 $this->asAdmin()->post('/settings/users/create', [
246 'name' => $user->name,
247 'email' => $user->email,
248 'send_invite' => 'true',
249 'roles[' . $adminRole->id . ']' => 'true',
252 // Since the invitation failed, the user should not exist in the database
253 $this->assertDatabaseMissing('users', $user->only('name', 'email'));
256 public function test_user_create_activity_is_not_persisted_if_the_invitation_sending_fails()
258 /** @var User $user */
259 $user = User::factory()->make();
261 $this->mock(UserInviteService::class, function (MockInterface $mock) {
262 $mock->shouldReceive('sendInvitation')->once()->andThrow(UserInviteException::class);
265 $this->asAdmin()->post('/settings/users/create', [
266 'name' => $user->name,
267 'email' => $user->email,
268 'send_invite' => 'true',
271 $this->assertDatabaseMissing('activities', ['type' => 'USER_CREATE']);
274 public function test_return_to_form_with_warning_if_the_invitation_sending_fails()
276 $logger = $this->withTestLogger();
277 /** @var User $user */
278 $user = User::factory()->make();
280 $this->mock(UserInviteService::class, function (MockInterface $mock) {
281 $mock->shouldReceive('sendInvitation')->once()->andThrow(UserInviteException::class);
284 $resp = $this->asAdmin()->post('/settings/users/create', [
285 'name' => $user->name,
286 'email' => $user->email,
287 'send_invite' => 'true',
290 $resp->assertRedirect('/settings/users/create');
291 $this->assertSessionError('Could not create user since invite email failed to send');
292 $this->assertEquals($user->email, session()->getOldInput('email'));
293 $this->assertTrue($logger->hasErrorThatContains('Failed to send user invite with error:'));
296 public function test_user_create_update_fails_if_locale_is_invalid()
298 $user = $this->users->editor();
301 $resp = $this->asAdmin()->put($user->getEditUrl(), ['language' => 'this_is_too_long']);
302 $resp->assertSessionHasErrors(['language' => 'The language may not be greater than 15 characters.']);
305 // Invalid characters
306 $resp = $this->put($user->getEditUrl(), ['language' => 'en<GB']);
307 $resp->assertSessionHasErrors(['language' => 'The language may only contain letters, numbers, dashes and underscores.']);
311 $resp = $this->post('/settings/users/create', [
312 'language' => 'en<GB_and_this_is_longer',
316 $resp->assertSessionHasErrors(['language' => 'The language may not be greater than 15 characters.']);
317 $resp->assertSessionHasErrors(['language' => 'The language may only contain letters, numbers, dashes and underscores.']);
320 public function test_user_avatar_update_and_reset()
322 $user = $this->users->viewer();
323 $avatarFile = $this->files->uploadedImage('avatar-icon.png');
325 $this->assertEquals(0, $user->image_id);
327 $upload = $this->asAdmin()->call('PUT', "/settings/users/{$user->id}", [
328 'name' => 'Barry Scott',
329 ], [], ['profile_image' => $avatarFile], []);
330 $upload->assertRedirect('/settings/users');
333 $this->assertNotEquals(0, $user->image_id);
334 /** @var Image $image */
335 $image = Image::query()->findOrFail($user->image_id);
336 $this->assertFileExists(public_path($image->path));
338 $reset = $this->put("/settings/users/{$user->id}", [
339 'name' => 'Barry Scott',
340 'profile_image_reset' => 'true',
342 $upload->assertRedirect('/settings/users');
345 $this->assertFileDoesNotExist(public_path($image->path));
346 $this->assertEquals(0, $user->image_id);