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