]> BookStack Code Mirror - bookstack/blob - tests/User/UserManagementTest.php
Users: Hid lanuage preference for guest user
[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
206         $resp = $this->asAdmin()->get('/settings/users/' . $guest->id);
207         $resp->assertSee('Guest');
208         $html = $this->withHtml($resp);
209
210         $html->assertElementNotExists('#password');
211         $html->assertElementNotExists('[name="language"]');
212     }
213
214     public function test_guest_profile_cannot_be_deleted()
215     {
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');
221
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');
226     }
227
228     public function test_user_create_language_reflects_default_system_locale()
229     {
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]');
235         }
236     }
237
238     public function test_user_creation_is_not_performed_if_the_invitation_sending_fails()
239     {
240         /** @var User $user */
241         $user = User::factory()->make();
242         $adminRole = Role::getRole('admin');
243
244         // Simulate an invitation sending failure
245         $this->mock(UserInviteService::class, function (MockInterface $mock) {
246             $mock->shouldReceive('sendInvitation')->once()->andThrow(UserInviteException::class);
247         });
248
249         $this->asAdmin()->post('/settings/users/create', [
250             'name'                          => $user->name,
251             'email'                         => $user->email,
252             'send_invite'                   => 'true',
253             'roles[' . $adminRole->id . ']' => 'true',
254         ]);
255
256         // Since the invitation failed, the user should not exist in the database
257         $this->assertDatabaseMissing('users', $user->only('name', 'email'));
258     }
259
260     public function test_user_create_activity_is_not_persisted_if_the_invitation_sending_fails()
261     {
262         /** @var User $user */
263         $user = User::factory()->make();
264
265         $this->mock(UserInviteService::class, function (MockInterface $mock) {
266             $mock->shouldReceive('sendInvitation')->once()->andThrow(UserInviteException::class);
267         });
268
269         $this->asAdmin()->post('/settings/users/create', [
270             'name'                          => $user->name,
271             'email'                         => $user->email,
272             'send_invite'                   => 'true',
273         ]);
274
275         $this->assertDatabaseMissing('activities', ['type' => 'USER_CREATE']);
276     }
277
278     public function test_return_to_form_with_warning_if_the_invitation_sending_fails()
279     {
280         $logger = $this->withTestLogger();
281         /** @var User $user */
282         $user = User::factory()->make();
283
284         $this->mock(UserInviteService::class, function (MockInterface $mock) {
285             $mock->shouldReceive('sendInvitation')->once()->andThrow(UserInviteException::class);
286         });
287
288         $resp = $this->asAdmin()->post('/settings/users/create', [
289             'name'                          => $user->name,
290             'email'                         => $user->email,
291             'send_invite'                   => 'true',
292         ]);
293
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:'));
298     }
299
300     public function test_user_create_update_fails_if_locale_is_invalid()
301     {
302         $user = $this->users->editor();
303
304         // Too long
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.']);
307         session()->flush();
308
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.']);
312         session()->flush();
313
314         // Both on create
315         $resp = $this->post('/settings/users/create', [
316             'language' => 'en<GB_and_this_is_longer',
317             'name'     => 'My name',
318             'email'    => '[email protected]',
319         ]);
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.']);
322     }
323
324     public function test_user_avatar_update_and_reset()
325     {
326         $user = $this->users->viewer();
327         $avatarFile = $this->files->uploadedImage('avatar-icon.png');
328
329         $this->assertEquals(0, $user->image_id);
330
331         $upload = $this->asAdmin()->call('PUT', "/settings/users/{$user->id}", [
332             'name' => 'Barry Scott',
333         ], [], ['profile_image' => $avatarFile], []);
334         $upload->assertRedirect('/settings/users');
335
336         $user->refresh();
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));
341
342         $reset = $this->put("/settings/users/{$user->id}", [
343             'name' => 'Barry Scott',
344             'profile_image_reset' => 'true',
345         ]);
346         $upload->assertRedirect('/settings/users');
347
348         $user->refresh();
349         $this->assertFileDoesNotExist(public_path($image->path));
350         $this->assertEquals(0, $user->image_id);
351     }
352 }