]> BookStack Code Mirror - bookstack/blob - tests/Auth/AuthTest.php
Reviewed and refactored additional editor draft save warnings
[bookstack] / tests / Auth / AuthTest.php
1 <?php
2
3 namespace Tests\Auth;
4
5 use BookStack\Auth\Access\Mfa\MfaSession;
6 use BookStack\Auth\User;
7 use BookStack\Entities\Models\Page;
8 use BookStack\Notifications\ConfirmEmail;
9 use BookStack\Notifications\ResetPassword;
10 use Illuminate\Support\Facades\DB;
11 use Illuminate\Support\Facades\Notification;
12 use Tests\TestCase;
13 use Tests\TestResponse;
14
15 class AuthTest extends TestCase
16 {
17     public function test_auth_working()
18     {
19         $this->get('/')->assertRedirect('/login');
20     }
21
22     public function test_login()
23     {
24         $this->login('[email protected]', 'password')->assertRedirect('/');
25     }
26
27     public function test_public_viewing()
28     {
29         $this->setSettings(['app-public' => 'true']);
30         $this->get('/')
31             ->assertOk()
32             ->assertSee('Log in');
33     }
34
35     public function test_registration_showing()
36     {
37         // Ensure registration form is showing
38         $this->setSettings(['registration-enabled' => 'true']);
39         $this->get('/login')
40             ->assertElementContains('a[href="' . url('/register') . '"]', 'Sign up');
41     }
42
43     public function test_normal_registration()
44     {
45         // Set settings and get user instance
46         $this->setSettings(['registration-enabled' => 'true']);
47         $user = factory(User::class)->make();
48
49         // Test form and ensure user is created
50         $this->get('/register')
51             ->assertSee('Sign Up')
52             ->assertElementContains('form[action="' . url('/register') . '"]', 'Create Account');
53
54         $resp = $this->post('/register', $user->only('password', 'name', 'email'));
55         $resp->assertRedirect('/');
56
57         $resp = $this->get('/');
58         $resp->assertOk();
59         $resp->assertSee($user->name);
60         $this->assertDatabaseHas('users', ['name' => $user->name, 'email' => $user->email]);
61     }
62
63     public function test_empty_registration_redirects_back_with_errors()
64     {
65         // Set settings and get user instance
66         $this->setSettings(['registration-enabled' => 'true']);
67
68         // Test form and ensure user is created
69         $this->get('/register');
70         $this->post('/register', [])->assertRedirect('/register');
71         $this->get('/register')->assertSee('The name field is required');
72     }
73
74     public function test_registration_validation()
75     {
76         $this->setSettings(['registration-enabled' => 'true']);
77
78         $this->get('/register');
79         $resp = $this->followingRedirects()->post('/register', [
80             'name'     => '1',
81             'email'    => '1',
82             'password' => '1',
83         ]);
84         $resp->assertSee('The name must be at least 2 characters.');
85         $resp->assertSee('The email must be a valid email address.');
86         $resp->assertSee('The password must be at least 8 characters.');
87     }
88
89     public function test_sign_up_link_on_login()
90     {
91         $this->get('/login')->assertDontSee('Sign up');
92
93         $this->setSettings(['registration-enabled' => 'true']);
94
95         $this->get('/login')->assertSee('Sign up');
96     }
97
98     public function test_confirmed_registration()
99     {
100         // Fake notifications
101         Notification::fake();
102
103         // Set settings and get user instance
104         $this->setSettings(['registration-enabled' => 'true', 'registration-confirmation' => 'true']);
105         $user = factory(User::class)->make();
106
107         // Go through registration process
108         $resp = $this->post('/register', $user->only('name', 'email', 'password'));
109         $resp->assertRedirect('/register/confirm');
110         $this->assertDatabaseHas('users', ['name' => $user->name, 'email' => $user->email, 'email_confirmed' => false]);
111
112         // Ensure notification sent
113         /** @var User $dbUser */
114         $dbUser = User::query()->where('email', '=', $user->email)->first();
115         Notification::assertSentTo($dbUser, ConfirmEmail::class);
116
117         // Test access and resend confirmation email
118         $resp = $this->login($user->email, $user->password);
119         $resp->assertRedirect('/register/confirm/awaiting');
120
121         $resp = $this->get('/register/confirm/awaiting');
122         $resp->assertElementContains('form[action="' . url('/register/confirm/resend') . '"]', 'Resend');
123
124         $this->get('/books')->assertRedirect('/login');
125         $this->post('/register/confirm/resend', $user->only('email'));
126
127         // Get confirmation and confirm notification matches
128         $emailConfirmation = DB::table('email_confirmations')->where('user_id', '=', $dbUser->id)->first();
129         Notification::assertSentTo($dbUser, ConfirmEmail::class, function ($notification, $channels) use ($emailConfirmation) {
130             return $notification->token === $emailConfirmation->token;
131         });
132
133         // Check confirmation email confirmation activation.
134         $this->get('/register/confirm/' . $emailConfirmation->token)->assertRedirect('/');
135         $this->get('/')->assertSee($user->name);
136         $this->assertDatabaseMissing('email_confirmations', ['token' => $emailConfirmation->token]);
137         $this->assertDatabaseHas('users', ['name' => $dbUser->name, 'email' => $dbUser->email, 'email_confirmed' => true]);
138     }
139
140     public function test_restricted_registration()
141     {
142         $this->setSettings(['registration-enabled' => 'true', 'registration-confirmation' => 'true', 'registration-restrict' => 'example.com']);
143         $user = factory(User::class)->make();
144
145         // Go through registration process
146         $this->post('/register', $user->only('name', 'email', 'password'))
147             ->assertRedirect('/register');
148         $resp = $this->get('/register');
149         $resp->assertSee('That email domain does not have access to this application');
150         $this->assertDatabaseMissing('users', $user->only('email'));
151
152         $user->email = '[email protected]';
153
154         $this->post('/register', $user->only('name', 'email', 'password'))
155             ->assertRedirect('/register/confirm');
156         $this->assertDatabaseHas('users', ['name' => $user->name, 'email' => $user->email, 'email_confirmed' => false]);
157
158         $this->assertNull(auth()->user());
159
160         $this->get('/')->assertRedirect('/login');
161         $resp = $this->followingRedirects()->post('/login', $user->only('email', 'password'));
162         $resp->assertSee('Email Address Not Confirmed');
163         $this->assertNull(auth()->user());
164     }
165
166     public function test_restricted_registration_with_confirmation_disabled()
167     {
168         $this->setSettings(['registration-enabled' => 'true', 'registration-confirmation' => 'false', 'registration-restrict' => 'example.com']);
169         $user = factory(User::class)->make();
170
171         // Go through registration process
172         $this->post('/register', $user->only('name', 'email', 'password'))
173             ->assertRedirect('/register');
174         $this->assertDatabaseMissing('users', $user->only('email'));
175         $this->get('/register')->assertSee('That email domain does not have access to this application');
176
177         $user->email = '[email protected]';
178
179         $this->post('/register', $user->only('name', 'email', 'password'))
180             ->assertRedirect('/register/confirm');
181         $this->assertDatabaseHas('users', ['name' => $user->name, 'email' => $user->email, 'email_confirmed' => false]);
182
183         $this->assertNull(auth()->user());
184
185         $this->get('/')->assertRedirect('/login');
186         $resp = $this->post('/login', $user->only('email', 'password'));
187         $resp->assertRedirect('/register/confirm/awaiting');
188         $this->get('/register/confirm/awaiting')->assertSee('Email Address Not Confirmed');
189         $this->assertNull(auth()->user());
190     }
191
192     public function test_logout()
193     {
194         $this->asAdmin()->get('/')->assertOk();
195         $this->get('/logout')->assertRedirect('/');
196         $this->get('/')->assertRedirect('/login');
197     }
198
199     public function test_mfa_session_cleared_on_logout()
200     {
201         $user = $this->getEditor();
202         $mfaSession = $this->app->make(MfaSession::class);
203
204         $mfaSession->markVerifiedForUser($user);
205         $this->assertTrue($mfaSession->isVerifiedForUser($user));
206
207         $this->asAdmin()->get('/logout');
208         $this->assertFalse($mfaSession->isVerifiedForUser($user));
209     }
210
211     public function test_reset_password_flow()
212     {
213         Notification::fake();
214
215         $this->get('/login')
216             ->assertElementContains('a[href="' . url('/password/email') . '"]', 'Forgot Password?');
217
218         $this->get('/password/email')
219             ->assertElementContains('form[action="' . url('/password/email') . '"]', 'Send Reset Link');
220
221         $resp = $this->post('/password/email', [
222             'email' => '[email protected]',
223         ]);
224         $resp->assertRedirect('/password/email');
225
226         $resp = $this->get('/password/email');
227         $resp->assertSee('A password reset link will be sent to [email protected] if that email address is found in the system.');
228
229         $this->assertDatabaseHas('password_resets', [
230             'email' => '[email protected]',
231         ]);
232
233         /** @var User $user */
234         $user = User::query()->where('email', '=', '[email protected]')->first();
235
236         Notification::assertSentTo($user, ResetPassword::class);
237         $n = Notification::sent($user, ResetPassword::class);
238
239         $this->get('/password/reset/' . $n->first()->token)
240             ->assertOk()
241             ->assertSee('Reset Password');
242
243         $resp = $this->post('/password/reset', [
244             'email'                 => '[email protected]',
245             'password'              => 'randompass',
246             'password_confirmation' => 'randompass',
247             'token'                 => $n->first()->token,
248         ]);
249         $resp->assertRedirect('/');
250
251         $this->get('/')->assertSee('Your password has been successfully reset');
252     }
253
254     public function test_reset_password_flow_shows_success_message_even_if_wrong_password_to_prevent_user_discovery()
255     {
256         $this->get('/password/email');
257         $resp = $this->followingRedirects()->post('/password/email', [
258             'email' => '[email protected]',
259         ]);
260         $resp->assertSee('A password reset link will be sent to [email protected] if that email address is found in the system.');
261         $resp->assertDontSee('We can\'t find a user');
262
263         $this->get('/password/reset/arandometokenvalue')->assertSee('Reset Password');
264         $resp = $this->post('/password/reset', [
265             'email'                 => '[email protected]',
266             'password'              => 'randompass',
267             'password_confirmation' => 'randompass',
268             'token'                 => 'arandometokenvalue',
269         ]);
270         $resp->assertRedirect('/password/reset/arandometokenvalue');
271
272         $this->get('/password/reset/arandometokenvalue')
273             ->assertDontSee('We can\'t find a user')
274             ->assertSee('The password reset token is invalid for this email address.');
275     }
276
277     public function test_reset_password_page_shows_sign_links()
278     {
279         $this->setSettings(['registration-enabled' => 'true']);
280         $this->get('/password/email')
281             ->assertElementContains('a', 'Log in')
282             ->assertElementContains('a', 'Sign up');
283     }
284
285     public function test_login_redirects_to_initially_requested_url_correctly()
286     {
287         config()->set('app.url', 'http://localhost');
288         /** @var Page $page */
289         $page = Page::query()->first();
290
291         $this->get($page->getUrl())->assertRedirect(url('/login'));
292         $this->login('[email protected]', 'password')
293             ->assertRedirect($page->getUrl());
294     }
295
296     public function test_login_intended_redirect_does_not_redirect_to_external_pages()
297     {
298         config()->set('app.url', 'http://localhost');
299         $this->setSettings(['app-public' => true]);
300
301         $this->get('/login', ['referer' => 'https://example.com']);
302         $login = $this->post('/login', ['email' => '[email protected]', 'password' => 'password']);
303
304         $login->assertRedirect('http://localhost');
305     }
306
307     public function test_login_intended_redirect_does_not_factor_mfa_routes()
308     {
309         $this->get('/books')->assertRedirect('/login');
310         $this->get('/mfa/setup')->assertRedirect('/login');
311         $login = $this->post('/login', ['email' => '[email protected]', 'password' => 'password']);
312         $login->assertRedirect('/books');
313     }
314
315     public function test_login_authenticates_admins_on_all_guards()
316     {
317         $this->post('/login', ['email' => '[email protected]', 'password' => 'password']);
318         $this->assertTrue(auth()->check());
319         $this->assertTrue(auth('ldap')->check());
320         $this->assertTrue(auth('saml2')->check());
321     }
322
323     public function test_login_authenticates_nonadmins_on_default_guard_only()
324     {
325         $editor = $this->getEditor();
326         $editor->password = bcrypt('password');
327         $editor->save();
328
329         $this->post('/login', ['email' => $editor->email, 'password' => 'password']);
330         $this->assertTrue(auth()->check());
331         $this->assertFalse(auth('ldap')->check());
332         $this->assertFalse(auth('saml2')->check());
333     }
334
335     public function test_failed_logins_are_logged_when_message_configured()
336     {
337         $log = $this->withTestLogger();
338         config()->set(['logging.failed_login.message' => 'Failed login for %u']);
339
340         $this->post('/login', ['email' => '[email protected]', 'password' => 'cattreedog']);
341         $this->assertTrue($log->hasWarningThatContains('Failed login for [email protected]'));
342
343         $this->post('/login', ['email' => '[email protected]', 'password' => 'password']);
344         $this->assertFalse($log->hasWarningThatContains('Failed login for [email protected]'));
345     }
346
347     public function test_logged_in_user_with_unconfirmed_email_is_logged_out()
348     {
349         $this->setSettings(['registration-confirmation' => 'true']);
350         $user = $this->getEditor();
351         $user->email_confirmed = false;
352         $user->save();
353
354         auth()->login($user);
355         $this->assertTrue(auth()->check());
356
357         $this->get('/books')->assertRedirect('/');
358         $this->assertFalse(auth()->check());
359     }
360
361     /**
362      * Perform a login.
363      */
364     protected function login(string $email, string $password): TestResponse
365     {
366         return $this->post('/login', compact('email', 'password'));
367     }
368 }