]> BookStack Code Mirror - bookstack/blob - tests/User/UserManagementTest.php
Updates the OIDC userinfo endpoint request to allow for a `Content-Type` response...
[bookstack] / tests / User / UserManagementTest.php
1 <?php
2
3 namespace Tests\User;
4
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;
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_can_be_updated_with_single_char_name()
89     {
90         $user = $this->users->viewer();
91         $this->asAdmin()->put("/settings/users/{$user->id}", [
92             'name' => 'b'
93         ])->assertRedirect('/settings/users');
94
95         $this->assertEquals('b', $user->refresh()->name);
96     }
97
98     public function test_user_cannot_be_deleted_if_last_admin()
99     {
100         $adminRole = Role::getRole('admin');
101
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) {
107                 $user->delete();
108             }
109         }
110
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();
115
116         $resp = $this->asAdmin()->delete('/settings/users/' . $user->id);
117         $resp->assertRedirect('/settings/users/' . $user->id);
118
119         $resp = $this->get('/settings/users/' . $user->id);
120         $resp->assertSee('You cannot delete the only admin');
121
122         $this->assertDatabaseHas('users', ['id' => $user->id]);
123     }
124
125     public function test_delete()
126     {
127         $editor = $this->users->editor();
128         $resp = $this->asAdmin()->delete("settings/users/{$editor->id}");
129         $resp->assertRedirect('/settings/users');
130         $resp = $this->followRedirects($resp);
131
132         $resp->assertSee('User successfully removed');
133         $this->assertActivityExists(ActivityType::USER_DELETE);
134
135         $this->assertDatabaseMissing('users', ['id' => $editor->id]);
136     }
137
138     public function test_delete_offers_migrate_option()
139     {
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');
144     }
145
146     public function test_migrate_option_hidden_if_user_cannot_manage_users()
147     {
148         $editor = $this->users->editor();
149
150         $resp = $this->asEditor()->get("settings/users/{$editor->id}/delete");
151         $resp->assertDontSee('Migrate Ownership');
152         $resp->assertDontSee('new_owner_id');
153
154         $this->permissions->grantUserRolePermissions($editor, ['users-manage']);
155
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');
160     }
161
162     public function test_delete_with_new_owner_id_changes_ownership()
163     {
164         $page = $this->entities->page();
165         $owner = $page->ownedBy;
166         $newOwner = User::query()->where('id', '!=', $owner->id)->first();
167
168         $this->asAdmin()->delete("settings/users/{$owner->id}", ['new_owner_id' => $newOwner->id]);
169         $this->assertDatabaseHas('pages', [
170             'id'       => $page->id,
171             'owned_by' => $newOwner->id,
172         ]);
173     }
174
175     public function test_delete_with_empty_owner_migration_id_works()
176     {
177         $user = $this->users->editor();
178
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');
183     }
184
185     public function test_delete_removes_user_preferences()
186     {
187         $editor = $this->users->editor();
188         setting()->putUser($editor, 'dark-mode-enabled', 'true');
189
190         $this->assertDatabaseHas('settings', [
191             'setting_key' => 'user:' . $editor->id . ':dark-mode-enabled',
192             'value' => 'true',
193         ]);
194
195         $this->asAdmin()->delete("settings/users/{$editor->id}");
196
197         $this->assertDatabaseMissing('settings', [
198             'setting_key' => 'user:' . $editor->id . ':dark-mode-enabled',
199         ]);
200     }
201
202     public function test_guest_profile_shows_limited_form()
203     {
204         $guest = $this->users->guest();
205         $resp = $this->asAdmin()->get('/settings/users/' . $guest->id);
206         $resp->assertSee('Guest');
207         $this->withHtml($resp)->assertElementNotExists('#password');
208     }
209
210     public function test_guest_profile_cannot_be_deleted()
211     {
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');
217
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');
222     }
223
224     public function test_user_create_language_reflects_default_system_locale()
225     {
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]');
231         }
232     }
233
234     public function test_user_creation_is_not_performed_if_the_invitation_sending_fails()
235     {
236         /** @var User $user */
237         $user = User::factory()->make();
238         $adminRole = Role::getRole('admin');
239
240         // Simulate an invitation sending failure
241         $this->mock(UserInviteService::class, function (MockInterface $mock) {
242             $mock->shouldReceive('sendInvitation')->once()->andThrow(UserInviteException::class);
243         });
244
245         $this->asAdmin()->post('/settings/users/create', [
246             'name'                          => $user->name,
247             'email'                         => $user->email,
248             'send_invite'                   => 'true',
249             'roles[' . $adminRole->id . ']' => 'true',
250         ]);
251
252         // Since the invitation failed, the user should not exist in the database
253         $this->assertDatabaseMissing('users', $user->only('name', 'email'));
254     }
255
256     public function test_user_create_activity_is_not_persisted_if_the_invitation_sending_fails()
257     {
258         /** @var User $user */
259         $user = User::factory()->make();
260
261         $this->mock(UserInviteService::class, function (MockInterface $mock) {
262             $mock->shouldReceive('sendInvitation')->once()->andThrow(UserInviteException::class);
263         });
264
265         $this->asAdmin()->post('/settings/users/create', [
266             'name'                          => $user->name,
267             'email'                         => $user->email,
268             'send_invite'                   => 'true',
269         ]);
270
271         $this->assertDatabaseMissing('activities', ['type' => 'USER_CREATE']);
272     }
273
274     public function test_return_to_form_with_warning_if_the_invitation_sending_fails()
275     {
276         $logger = $this->withTestLogger();
277         /** @var User $user */
278         $user = User::factory()->make();
279
280         $this->mock(UserInviteService::class, function (MockInterface $mock) {
281             $mock->shouldReceive('sendInvitation')->once()->andThrow(UserInviteException::class);
282         });
283
284         $resp = $this->asAdmin()->post('/settings/users/create', [
285             'name'                          => $user->name,
286             'email'                         => $user->email,
287             'send_invite'                   => 'true',
288         ]);
289
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:'));
294     }
295
296     public function test_user_create_update_fails_if_locale_is_invalid()
297     {
298         $user = $this->users->editor();
299
300         // Too long
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.']);
303         session()->flush();
304
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.']);
308         session()->flush();
309
310         // Both on create
311         $resp = $this->post('/settings/users/create', [
312             'language' => 'en<GB_and_this_is_longer',
313             'name'     => 'My name',
314             'email'    => '[email protected]',
315         ]);
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.']);
318     }
319
320     public function test_user_avatar_update_and_reset()
321     {
322         $user = $this->users->viewer();
323         $avatarFile = $this->files->uploadedImage('avatar-icon.png');
324
325         $this->assertEquals(0, $user->image_id);
326
327         $upload = $this->asAdmin()->call('PUT', "/settings/users/{$user->id}", [
328             'name' => 'Barry Scott',
329         ], [], ['profile_image' => $avatarFile], []);
330         $upload->assertRedirect('/settings/users');
331
332         $user->refresh();
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));
337
338         $reset = $this->put("/settings/users/{$user->id}", [
339             'name' => 'Barry Scott',
340             'profile_image_reset' => 'true',
341         ]);
342         $upload->assertRedirect('/settings/users');
343
344         $user->refresh();
345         $this->assertFileDoesNotExist(public_path($image->path));
346         $this->assertEquals(0, $user->image_id);
347     }
348 }