]> BookStack Code Mirror - bookstack/blob - tests/User/UserManagementTest.php
Merge branch 'v23.02-branch' into development
[bookstack] / tests / User / UserManagementTest.php
1 <?php
2
3 namespace Tests\User;
4
5 use BookStack\Actions\ActivityType;
6 use BookStack\Auth\Access\UserInviteService;
7 use BookStack\Auth\Role;
8 use BookStack\Auth\User;
9 use BookStack\Uploads\Image;
10 use Illuminate\Support\Facades\Hash;
11 use Illuminate\Support\Str;
12 use Mockery\MockInterface;
13 use RuntimeException;
14 use Tests\TestCase;
15
16 class UserManagementTest extends TestCase
17 {
18     public function test_user_creation()
19     {
20         /** @var User $user */
21         $user = User::factory()->make();
22         $adminRole = Role::getRole('admin');
23
24         $resp = $this->asAdmin()->get('/settings/users');
25         $this->withHtml($resp)->assertElementContains('a[href="' . url('/settings/users/create') . '"]', 'Add New User');
26
27         $resp = $this->get('/settings/users/create');
28         $this->withHtml($resp)->assertElementContains('form[action="' . url('/settings/users/create') . '"]', 'Save');
29
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',
36         ]);
37         $resp->assertRedirect('/settings/users');
38
39         $resp = $this->get('/settings/users');
40         $resp->assertSee($user->name);
41
42         $this->assertDatabaseHas('users', $user->only('name', 'email'));
43
44         $user->refresh();
45         $this->assertStringStartsWith(Str::slug($user->name), $user->slug);
46     }
47
48     public function test_user_updating()
49     {
50         $user = $this->users->viewer();
51         $password = $user->password;
52
53         $resp = $this->asAdmin()->get('/settings/users/' . $user->id);
54         $resp->assertSee($user->email);
55
56         $this->put($user->getEditUrl(), [
57             'name' => 'Barry Scott',
58         ])->assertRedirect('/settings/users');
59
60         $this->assertDatabaseHas('users', ['id' => $user->id, 'name' => 'Barry Scott', 'password' => $password]);
61         $this->assertDatabaseMissing('users', ['name' => $user->name]);
62
63         $user->refresh();
64         $this->assertStringStartsWith(Str::slug($user->name), $user->slug);
65     }
66
67     public function test_user_password_update()
68     {
69         $user = $this->users->viewer();
70         $userProfilePage = '/settings/users/' . $user->id;
71
72         $this->asAdmin()->get($userProfilePage);
73         $this->put($userProfilePage, [
74             'password' => 'newpassword',
75         ])->assertRedirect($userProfilePage);
76
77         $this->get($userProfilePage)->assertSee('Password confirmation required');
78
79         $this->put($userProfilePage, [
80             'password'         => 'newpassword',
81             'password-confirm' => 'newpassword',
82         ])->assertRedirect('/settings/users');
83
84         $userPassword = User::query()->find($user->id)->password;
85         $this->assertTrue(Hash::check('newpassword', $userPassword));
86     }
87
88     public function test_user_cannot_be_deleted_if_last_admin()
89     {
90         $adminRole = Role::getRole('admin');
91
92         // Delete all but one admin user if there are more than one
93         $adminUsers = $adminRole->users;
94         if (count($adminUsers) > 1) {
95             /** @var User $user */
96             foreach ($adminUsers->splice(1) as $user) {
97                 $user->delete();
98             }
99         }
100
101         // Ensure we currently only have 1 admin user
102         $this->assertEquals(1, $adminRole->users()->count());
103         /** @var User $user */
104         $user = $adminRole->users->first();
105
106         $resp = $this->asAdmin()->delete('/settings/users/' . $user->id);
107         $resp->assertRedirect('/settings/users/' . $user->id);
108
109         $resp = $this->get('/settings/users/' . $user->id);
110         $resp->assertSee('You cannot delete the only admin');
111
112         $this->assertDatabaseHas('users', ['id' => $user->id]);
113     }
114
115     public function test_delete()
116     {
117         $editor = $this->users->editor();
118         $resp = $this->asAdmin()->delete("settings/users/{$editor->id}");
119         $resp->assertRedirect('/settings/users');
120         $resp = $this->followRedirects($resp);
121
122         $resp->assertSee('User successfully removed');
123         $this->assertActivityExists(ActivityType::USER_DELETE);
124
125         $this->assertDatabaseMissing('users', ['id' => $editor->id]);
126     }
127
128     public function test_delete_offers_migrate_option()
129     {
130         $editor = $this->users->editor();
131         $resp = $this->asAdmin()->get("settings/users/{$editor->id}/delete");
132         $resp->assertSee('Migrate Ownership');
133         $resp->assertSee('new_owner_id');
134     }
135
136     public function test_migrate_option_hidden_if_user_cannot_manage_users()
137     {
138         $editor = $this->users->editor();
139
140         $resp = $this->asEditor()->get("settings/users/{$editor->id}/delete");
141         $resp->assertDontSee('Migrate Ownership');
142         $resp->assertDontSee('new_owner_id');
143
144         $this->permissions->grantUserRolePermissions($editor, ['users-manage']);
145
146         $resp = $this->asEditor()->get("settings/users/{$editor->id}/delete");
147         $resp->assertSee('Migrate Ownership');
148         $this->withHtml($resp)->assertElementExists('form input[name="new_owner_id"]');
149         $resp->assertSee('new_owner_id');
150     }
151
152     public function test_delete_with_new_owner_id_changes_ownership()
153     {
154         $page = $this->entities->page();
155         $owner = $page->ownedBy;
156         $newOwner = User::query()->where('id', '!=', $owner->id)->first();
157
158         $this->asAdmin()->delete("settings/users/{$owner->id}", ['new_owner_id' => $newOwner->id]);
159         $this->assertDatabaseHas('pages', [
160             'id'       => $page->id,
161             'owned_by' => $newOwner->id,
162         ]);
163     }
164
165     public function test_delete_with_empty_owner_migration_id_works()
166     {
167         $user = $this->users->editor();
168
169         $resp = $this->asAdmin()->delete("settings/users/{$user->id}", ['new_owner_id' => '']);
170         $resp->assertRedirect('/settings/users');
171         $this->assertActivityExists(ActivityType::USER_DELETE);
172         $this->assertSessionHas('success');
173     }
174
175     public function test_delete_removes_user_preferences()
176     {
177         $editor = $this->users->editor();
178         setting()->putUser($editor, 'dark-mode-enabled', 'true');
179
180         $this->assertDatabaseHas('settings', [
181             'setting_key' => 'user:' . $editor->id . ':dark-mode-enabled',
182             'value' => 'true',
183         ]);
184
185         $this->asAdmin()->delete("settings/users/{$editor->id}");
186
187         $this->assertDatabaseMissing('settings', [
188             'setting_key' => 'user:' . $editor->id . ':dark-mode-enabled',
189         ]);
190     }
191
192     public function test_guest_profile_shows_limited_form()
193     {
194         $guest = User::getDefault();
195         $resp = $this->asAdmin()->get('/settings/users/' . $guest->id);
196         $resp->assertSee('Guest');
197         $this->withHtml($resp)->assertElementNotExists('#password');
198     }
199
200     public function test_guest_profile_cannot_be_deleted()
201     {
202         $guestUser = User::getDefault();
203         $resp = $this->asAdmin()->get('/settings/users/' . $guestUser->id . '/delete');
204         $resp->assertSee('Delete User');
205         $resp->assertSee('Guest');
206         $this->withHtml($resp)->assertElementContains('form[action$="/settings/users/' . $guestUser->id . '"] button', 'Confirm');
207
208         $resp = $this->delete('/settings/users/' . $guestUser->id);
209         $resp->assertRedirect('/settings/users/' . $guestUser->id);
210         $resp = $this->followRedirects($resp);
211         $resp->assertSee('cannot delete the guest user');
212     }
213
214     public function test_user_create_language_reflects_default_system_locale()
215     {
216         $langs = ['en', 'fr', 'hr'];
217         foreach ($langs as $lang) {
218             config()->set('app.locale', $lang);
219             $resp = $this->asAdmin()->get('/settings/users/create');
220             $this->withHtml($resp)->assertElementExists('select[name="language"] option[value="' . $lang . '"][selected]');
221         }
222     }
223
224     public function test_user_creation_is_not_performed_if_the_invitation_sending_fails()
225     {
226         /** @var User $user */
227         $user = User::factory()->make();
228         $adminRole = Role::getRole('admin');
229
230         // Simulate an invitation sending failure
231         $this->mock(UserInviteService::class, function (MockInterface $mock) {
232             $mock->shouldReceive('sendInvitation')->once()->andThrow(RuntimeException::class);
233         });
234
235         $this->asAdmin()->post('/settings/users/create', [
236             'name'                          => $user->name,
237             'email'                         => $user->email,
238             'send_invite'                   => 'true',
239             'roles[' . $adminRole->id . ']' => 'true',
240         ]);
241
242         // Since the invitation failed, the user should not exist in the database
243         $this->assertDatabaseMissing('users', $user->only('name', 'email'));
244     }
245
246     public function test_user_create_activity_is_not_persisted_if_the_invitation_sending_fails()
247     {
248         /** @var User $user */
249         $user = User::factory()->make();
250         $adminRole = Role::getRole('admin');
251
252         $this->mock(UserInviteService::class, function (MockInterface $mock) {
253             $mock->shouldReceive('sendInvitation')->once()->andThrow(RuntimeException::class);
254         });
255
256         $this->asAdmin()->post('/settings/users/create', [
257             'name'                          => $user->name,
258             'email'                         => $user->email,
259             'send_invite'                   => 'true',
260             'roles[' . $adminRole->id . ']' => 'true',
261         ]);
262
263         $this->assertDatabaseMissing('activities', ['type' => 'USER_CREATE']);
264     }
265
266     public function test_user_create_update_fails_if_locale_is_invalid()
267     {
268         $user = $this->users->editor();
269
270         // Too long
271         $resp = $this->asAdmin()->put($user->getEditUrl(), ['language' => 'this_is_too_long']);
272         $resp->assertSessionHasErrors(['language' => 'The language may not be greater than 15 characters.']);
273         session()->flush();
274
275         // Invalid characters
276         $resp = $this->put($user->getEditUrl(), ['language' => 'en<GB']);
277         $resp->assertSessionHasErrors(['language' => 'The language may only contain letters, numbers, dashes and underscores.']);
278         session()->flush();
279
280         // Both on create
281         $resp = $this->post('/settings/users/create', [
282             'language' => 'en<GB_and_this_is_longer',
283             'name'     => 'My name',
284             'email'    => '[email protected]',
285         ]);
286         $resp->assertSessionHasErrors(['language' => 'The language may not be greater than 15 characters.']);
287         $resp->assertSessionHasErrors(['language' => 'The language may only contain letters, numbers, dashes and underscores.']);
288     }
289
290     public function test_user_avatar_update_and_reset()
291     {
292         $user = $this->users->viewer();
293         $avatarFile = $this->files->uploadedImage('avatar-icon.png');
294
295         $this->assertEquals(0, $user->image_id);
296
297         $upload = $this->asAdmin()->call('PUT', "/settings/users/{$user->id}", [
298             'name' => 'Barry Scott',
299         ], [], ['profile_image' => $avatarFile], []);
300         $upload->assertRedirect('/settings/users');
301
302         $user->refresh();
303         $this->assertNotEquals(0, $user->image_id);
304         /** @var Image $image */
305         $image = Image::query()->findOrFail($user->image_id);
306         $this->assertFileExists(public_path($image->path));
307
308         $reset = $this->put("/settings/users/{$user->id}", [
309             'name' => 'Barry Scott',
310             'profile_image_reset' => 'true',
311         ]);
312         $upload->assertRedirect('/settings/users');
313
314         $user->refresh();
315         $this->assertFileDoesNotExist(public_path($image->path));
316         $this->assertEquals(0, $user->image_id);
317     }
318 }