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