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