• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

daycry / auth / 44317717916

18 Nov 2026 01:49PM UTC coverage: 82.894% (+4.4%) from 78.462%
44317717916

Pull #79

github

web-flow
Merge 7c781daeb into 55dbf61d2
Pull Request #79: feat: security fixes, extension points and auth completion

1214 of 1370 new or added lines in 67 files covered. (88.61%)

12 existing lines in 5 files now uncovered.

6663 of 8038 relevant lines covered (82.89%)

97.52 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

80.19
/src/Controllers/UserSecurityController.php
1
<?php
2

3
declare(strict_types=1);
4

5
/**
6
 * This file is part of Daycry Auth.
7
 *
8
 * (c) Daycry <daycry9@proton.me>
9
 *
10
 * For the full copyright and license information, please view
11
 * the LICENSE file that was distributed with this source code.
12
 */
13

14
namespace Daycry\Auth\Controllers;
15

16
use CodeIgniter\Database\Exceptions\DatabaseException as FrameworkDatabaseException;
17
use CodeIgniter\Events\Events;
18
use CodeIgniter\Exceptions\RuntimeException;
19
use CodeIgniter\HTTP\RedirectResponse;
20
use CodeIgniter\HTTP\ResponseInterface;
21
use CodeIgniter\I18n\Time;
22
use Daycry\Auth\Authentication\Authenticators\Session;
23
use Daycry\Auth\Authentication\Passwords;
24
use Daycry\Auth\Entities\User;
25
use Daycry\Auth\Entities\UserIdentity;
26
use Daycry\Auth\Enums\IdentityType;
27
use Daycry\Auth\Exceptions\DatabaseException;
28
use Daycry\Auth\Exceptions\DataExportLimitException;
29
use Daycry\Auth\Interfaces\MfaPolicyInterface;
30
use Daycry\Auth\Libraries\TOTP;
31
use Daycry\Auth\Models\DeviceSessionModel;
32
use Daycry\Auth\Models\LoginModel;
33
use Daycry\Auth\Models\RememberModel;
34
use Daycry\Auth\Models\UserIdentityModel;
35
use Daycry\Auth\Models\UserModel;
36
use Daycry\Auth\Services\AuditLogger;
37
use Throwable;
38

39
/**
40
 * UserSecurityController
41
 *
42
 * Lets authenticated users manage their own account and security settings:
43
 *   - device sessions (list + revoke), TOTP 2FA (setup / disable), login activity
44
 *   - password change (or set a first password on a password-less account)
45
 *   - e-mail change (confirmed through a link sent to the new address)
46
 *   - unlink an OAuth provider (never the last way to sign in)
47
 *   - account deletion (GDPR anonymisation)
48
 *
49
 * Password-less accounts (OAuth-created) re-authenticate with a recent
50
 * interactive sign-in (AuthSecurity::$passwordConfirmationLifetime) instead
51
 * of a current password; their deletion is confirmed by e-mail.
52
 *
53
 * Routes to add in your app. Keep CSRF protection on (CI4 `csrf` filter) for
54
 * every POST, and consider the `rates` filter for the mutating routes:
55
 *
56
 *   $c = '\Daycry\Auth\Controllers\UserSecurityController::';
57
 *   $routes->group('account/security', ['filter' => 'auth:session'], static function ($routes) use ($c): void {
58
 *       $routes->get('/',                       $c . 'index',                    ['as' => 'security']);
59
 *       $routes->post('sessions/revoke',        $c . 'revokeSession',            ['as' => 'security-revoke-session']);
60
 *       $routes->post('sessions/revoke-all',    $c . 'revokeAllSessions',        ['as' => 'security-revoke-all']);
61
 *       $routes->get('totp/setup',              $c . 'totpSetup',                ['as' => 'totp-setup']);
62
 *       $routes->post('totp/setup/confirm',     $c . 'totpSetupConfirm',         ['as' => 'totp-setup-confirm']);
63
 *       $routes->post('totp/disable',           $c . 'totpDisable',              ['as' => 'totp-disable']);
64
 *       $routes->get('activity',                $c . 'loginActivity',            ['as' => 'security-activity']);
65
 *       $routes->get('password',                $c . 'changePasswordView',       ['as' => 'security-change-password']);
66
 *       $routes->post('password',               $c . 'changePassword',           ['as' => 'security-change-password-action']);
67
 *       $routes->get('email',                   $c . 'changeEmailView',          ['as' => 'security-change-email']);
68
 *       $routes->post('email',                  $c . 'changeEmail',              ['as' => 'security-change-email-action']);
69
 *       $routes->get('email/confirm',           $c . 'confirmEmailChangeView',   ['as' => 'security-confirm-email']);
70
 *       $routes->post('email/confirm',          $c . 'confirmEmailChange',       ['as' => 'security-confirm-email-action']);
71
 *       $routes->post('oauth/(:segment)/unlink', $c . 'unlinkOauth/$1',          ['as' => 'security-unlink-oauth']);
72
 *       $routes->get('delete',                  $c . 'deleteAccountView',        ['as' => 'security-delete-account']);
73
 *       $routes->post('delete',                 $c . 'deleteAccount',            ['as' => 'security-delete-account-action']);
74
 *       $routes->get('delete/confirm',          $c . 'confirmDeleteAccountView', ['as' => 'security-confirm-delete']);
75
 *       $routes->post('delete/confirm',         $c . 'confirmDeleteAccount',     ['as' => 'security-confirm-delete-action']);
76
 *   });
77
 *
78
 * The e-mailed links point at `security-confirm-email` / `security-confirm-delete`,
79
 * so those route names must exist.
80
 */
81
class UserSecurityController extends BaseAuthController
82
{
83
    protected function getValidationRules(): array
×
84
    {
85
        return [];
×
86
    }
87

88
    /**
89
     * Security overview: device sessions + TOTP status.
90
     */
91
    public function index(): string
1 ✔
92
    {
93
        $user = auth()->user();
1 ✔
94

95
        /** @var DeviceSessionModel $deviceModel */
96
        $deviceModel = model(DeviceSessionModel::class);
1 ✔
97

98
        $sessions   = $deviceModel->getActiveForUser($user);
1 ✔
99
        $currentSid = session_id();
1 ✔
100

101
        return $this->view(setting('Auth.views')['security_overview'], [
1 ✔
102
            'sessions'            => $sessions,
1 ✔
103
            'currentSid'          => $currentSid,
1 ✔
104
            'totpEnabled'         => $user->hasTotpEnabled(),
1 ✔
105
            'webAuthnCredentials' => $user->webAuthnCredentials(),
1 ✔
106
            'webauthnEnabled'     => (bool) (setting('AuthSecurity.webauthnEnabled') ?? false),
1 ✔
107
        ]);
1 ✔
108
    }
109

110
    /**
111
     * Revoke a single device session.
112
     */
113
    public function revokeSession(): RedirectResponse
×
114
    {
115
        $sessionId = (string) $this->request->getPost('session_id');
×
116

117
        if ($sessionId === '') {
×
118
            return redirect()->back()->with('error', 'Invalid session.');
×
119
        }
120

121
        $user = auth()->user();
×
122

123
        /** @var DeviceSessionModel $deviceModel */
124
        $deviceModel = model(DeviceSessionModel::class);
×
125

126
        // Safety check: ensure the session belongs to the current user
127
        $session = $deviceModel->findBySessionId($sessionId);
×
128

129
        if ($session === null || $session->user_id !== $user->id) {
×
130
            return redirect()->back()->with('error', 'Session not found.');
×
131
        }
132

133
        $deviceModel->terminateSession($sessionId);
×
134

135
        return redirect()->back()->with('message', 'Session revoked successfully.');
×
136
    }
137

138
    /**
139
     * Revoke all other active sessions (keep current one).
140
     */
141
    public function revokeAllSessions(): RedirectResponse
×
142
    {
143
        $user = auth()->user();
×
144

145
        /** @var DeviceSessionModel $deviceModel */
146
        $deviceModel = model(DeviceSessionModel::class);
×
147
        $deviceModel->terminateAllForUser($user, session_id());
×
148

149
        return redirect()->back()->with('message', 'All other sessions have been revoked.');
×
150
    }
151

152
    /**
153
     * Show the TOTP setup page with QR code.
154
     *
155
     * Always generates a fresh secret. If the user navigates away before
156
     * confirming, a new QR code will be issued on their next visit.
157
     */
158
    public function totpSetup(): RedirectResponse|string
3 ✔
159
    {
160
        $user = auth()->user();
3 ✔
161

162
        if (($denied = $this->requireEnrollmentAuthentication($user)) !== null) {
3 ✔
163
            return $denied;
1 ✔
164
        }
165

166
        if ($user->hasTotpEnabled()) {
2 ✔
167
            return redirect()->route('security')->with('error', 'TOTP is already enabled.');
×
168
        }
169

170
        $otpAuthUrl = $user->enableTotp();
2 ✔
171
        $secret     = $user->getTotpSecret();
2 ✔
172

173
        return $this->view(setting('Auth.views')['action_totp_setup_show'], [
2 ✔
174
            'otpAuthUrl' => $otpAuthUrl,
2 ✔
175
            'secret'     => $secret ?? '',
2 ✔
176
            'qrCodeUrl'  => TOTP::getQRCodeUrl($otpAuthUrl),
2 ✔
177
            'confirmUrl' => url_to('totp-setup-confirm'),
2 ✔
178
        ]);
2 ✔
179
    }
180

181
    /**
182
     * Confirm TOTP setup by verifying the first code.
183
     *
184
     * On failure the pending secret is kept so the user can retry with the same
185
     * QR code already in their authenticator app.
186
     */
187
    public function totpSetupConfirm(): RedirectResponse|string
1 ✔
188
    {
189
        $user = auth()->user();
1 ✔
190
        if (($denied = $this->requireEnrollmentAuthentication($user)) !== null) {
1 ✔
NEW
191
            return $denied;
×
192
        }
193
        $code = (string) $this->request->getPost('token');
1 ✔
194

195
        if (! $user->verifyTotpCode($code)) {
1 ✔
196
            return redirect()->route('totp-setup')
×
197
                ->with('error', lang('Auth.totpSetupInvalidCode'));
×
198
        }
199

200
        // Mark the secret as confirmed — from this point hasTotpEnabled() returns true.
201
        $user->confirmTotp();
1 ✔
202
        service('mfaPolicy')->markVerified($user);
1 ✔
203

204
        // Generate backup codes — shown to the user once on this page.
205
        $backupCodes = $user->generateBackupCodes();
1 ✔
206

207
        return $this->view(setting('Auth.views')['action_totp_setup_success'], [
1 ✔
208
            'redirectUrl' => url_to('security'),
1 ✔
209
            'backupCodes' => $backupCodes,
1 ✔
210
        ]);
1 ✔
211
    }
212

213
    /**
214
     * Disable TOTP for the current user.
215
     */
216
    public function totpDisable(): RedirectResponse
3 ✔
217
    {
218
        $code = (string) $this->request->getPost('token');
3 ✔
219
        $user = auth()->user();
3 ✔
220

221
        /** @var MfaPolicyInterface $policy */
222
        $policy = service('mfaPolicy');
3 ✔
223
        if ($policy->requires($user) && (! (bool) setting('AuthSecurity.webauthnEnabled') || ! $user->hasWebAuthnCredentials())) {
3 ✔
224
            return redirect()->route('security')->with('error', lang('Auth.mfaLastFactorRequired'));
1 ✔
225
        }
226

227
        if (! $user->verifyTotpCode($code)) {
2 ✔
228
            return redirect()->back()->with('error', lang('Auth.invalidTotpToken'));
1 ✔
229
        }
230

231
        $user->disableTotp();
1 ✔
232
        service('securityNotifier')->totpDisabled($user);
1 ✔
233

234
        return redirect()->route('security')->with('message', 'Two-factor authentication has been disabled.');
1 ✔
235
    }
236

237
    /**
238
     * User-facing login activity feed: lists the user's recent login attempts
239
     * (success + failure) so they can spot suspicious activity targeting
240
     * their account.
241
     *
242
     * Add the route, e.g.:
243
     *     $routes->get('account/security/activity',
244
     *         'Daycry\Auth\Controllers\UserSecurityController::loginActivity',
245
     *         ['as' => 'security-activity']);
246
     */
247
    public function loginActivity(): string
×
248
    {
249
        $user = auth()->user();
×
250

251
        /** @var LoginModel $loginModel */
252
        $loginModel = model(LoginModel::class);
×
253

254
        $limit = max(1, (int) ($this->request->getGet('limit') ?? 25));
×
255
        $limit = min($limit, 100);
×
256

257
        $entries = $loginModel->recentForUser($user, $limit);
×
258

259
        $views    = setting('Auth.views');
×
260
        $viewName = $views['security_login_activity'] ?? 'Daycry\Auth\Views\security\login_activity';
×
261

262
        return $this->view($viewName, [
×
263
            'entries' => $entries,
×
264
            'limit'   => $limit,
×
265
        ]);
×
266
    }
267

268
    /**
269
     * Renders the password confirmation form.
270
     *
271
     * Wire as:
272
     *     $routes->get('auth/confirm-password',
273
     *         'Daycry\Auth\Controllers\UserSecurityController::confirmPasswordView',
274
     *         ['filter' => 'session', 'as' => 'password-confirm-show']);
275
     */
276
    public function confirmPasswordView(): ResponseInterface
×
277
    {
278
        $views    = setting('Auth.views');
×
279
        $viewName = $views['confirm_password'] ?? 'Daycry\Auth\Views\confirm_password';
×
280

NEW
281
        $user    = auth()->user();
×
NEW
282
        $content = $this->view($viewName, [
×
NEW
283
            'hasPassword' => $user !== null && $this->hasUsablePassword($user),
×
NEW
284
            'hasTotp'     => $user !== null && $user->hasTotpEnabled(),
×
NEW
285
            'hasRecovery' => $user !== null && $user->backupCodesRemaining() > 0,
×
NEW
286
            'hasPasskey'  => $user !== null && (bool) setting('AuthSecurity.webauthnEnabled') && $user->hasWebAuthnCredentials(),
×
NEW
287
        ]);
×
288

289
        return $this->response->setBody($content);
×
290
    }
291

292
    /**
293
     * Verifies the submitted password against the logged-in user, stamps
294
     * `password_confirmed_at` in the session, then redirects to the URL
295
     * the user was originally trying to reach (or to a fallback).
296
     *
297
     * Wire as:
298
     *     $routes->post('auth/confirm-password',
299
     *         'Daycry\Auth\Controllers\UserSecurityController::confirmPasswordAction',
300
     *         ['filter' => 'session', 'as' => 'password-confirm']);
301
     */
302
    public function confirmPasswordAction(): ResponseInterface
7 ✔
303
    {
304
        $user   = auth()->user();
7 ✔
305
        $factor = (string) ($this->authInput('factor') ?? 'password');
7 ✔
306

307
        if ($user === null) {
7 ✔
NEW
308
            if ($this->expectsJsonResponse()) {
×
NEW
309
                return $this->authJsonResponse(['status' => 'error', 'confirmed' => false, 'message' => lang('Auth.stepUpInvalid')], 401);
×
310
            }
311

312
            return redirect()->route('password-confirm-show')
×
NEW
313
                ->with('error', lang('Auth.stepUpInvalid'));
×
314
        }
315

316
        $lockout = $this->getSessionAuthenticator()->getLockoutManager();
7 ✔
317
        if (($locked = $lockout->isLockedOut($user)) !== null) {
7 ✔
NEW
318
            if ($this->expectsJsonResponse()) {
×
NEW
319
                return $this->authJsonResponse(['status' => 'error', 'confirmed' => false, 'message' => $locked->reason()], 429);
×
320
            }
321

NEW
322
            return redirect()->route('password-confirm-show')->with('error', $locked->reason());
×
323
        }
324

325
        /** @var Passwords $passwords */
326
        $passwords  = service('passwords');
7 ✔
327
        $credential = $this->authRequestData()['credential'] ?? '';
7 ✔
328
        $credential = is_array($credential) ? json_encode($credential, JSON_THROW_ON_ERROR) : (is_string($credential) ? $credential : '');
7 ✔
329
        $verified   = match ($factor) {
7 ✔
330
            'recovery' => ($user->hasTotpEnabled() || $user->hasWebAuthnCredentials()) && $user->consumeBackupCode((string) $this->authInput('token')),
1 ✔
331
            'totp'     => $user->hasTotpEnabled() && $user->verifyTotpCode((string) $this->authInput('token')),
3 ✔
332
            'passkey'  => (bool) setting('AuthSecurity.webauthnEnabled') && $user->hasWebAuthnCredentials()
2 ✔
333
                && service('webAuthnManager')->finishStepUp($user, $credential),
2 ✔
334
            'password' => $this->hasUsablePassword($user)
1 ✔
335
                && $passwords->verify((string) $this->authInput('password'), $user->getPasswordHash()),
1 ✔
NEW
336
            default => false,
×
337
        };
7 ✔
338

339
        if (! $verified) {
7 ✔
340
            $lockout->recordFailedAttempt($user);
4 ✔
341
            if ($this->expectsJsonResponse()) {
4 ✔
342
                return $this->authJsonResponse(['status' => 'error', 'confirmed' => false, 'message' => lang('Auth.stepUpInvalid')], 422);
1 ✔
343
            }
344

345
            return redirect()->route('password-confirm-show')
3 ✔
346
                ->with('error', lang('Auth.stepUpInvalid'));
3 ✔
347
        }
348

349
        $lockout->resetOnSuccess($user);
5 ✔
350
        session()->set('password_confirmed_at', time());
5 ✔
351
        session()->set('auth_step_up_user', (string) $user->id);
5 ✔
352

353
        if (in_array($factor, ['totp', 'passkey', 'recovery'], true)) {
5 ✔
354
            /** @var MfaPolicyInterface $policy */
355
            $policy = service('mfaPolicy');
4 ✔
356
            $policy->markVerified($user);
4 ✔
357
        }
358

359
        service('auditLogger')->record(AuditLogger::EVENT_PASSWORD_CONFIRMED, (int) $user->id, ['factor' => $factor]);
5 ✔
360

361
        $intended = (string) (session()->getTempdata('passwordConfirmIntendedUrl') ?? '');
5 ✔
362
        session()->removeTempdata('passwordConfirmIntendedUrl');
5 ✔
363

364
        if ($intended === '') {
5 ✔
365
            $intended = config('Auth')->loginRedirect();
4 ✔
366
        }
367

368
        if ($this->expectsJsonResponse()) {
5 ✔
369
            return $this->authJsonResponse(['status' => 'success', 'confirmed' => true, 'redirect' => $intended]);
2 ✔
370
        }
371

372
        return redirect()->to($intended);
3 ✔
373
    }
374

375
    /**
376
     * A remembered session alone cannot enroll a mandatory first factor.
377
     */
378
    protected function requireEnrollmentAuthentication(User $user): ?RedirectResponse
3 ✔
379
    {
380
        /** @var MfaPolicyInterface $policy */
381
        $policy = service('mfaPolicy');
3 ✔
382
        if (! $policy->requires($user)) {
3 ✔
NEW
383
            return null;
×
384
        }
385

386
        $primaryAt   = (int) session(Session::AUTHENTICATED_AT_KEY);
3 ✔
387
        $confirmedAt = (string) session('auth_step_up_user') === (string) $user->id
3 ✔
388
            ? (int) session('password_confirmed_at') : 0;
3 ✔
389
        $latest   = max($primaryAt, $confirmedAt);
3 ✔
390
        $lifetime = max(0, (int) setting('AuthSecurity.passwordConfirmationLifetime'));
3 ✔
391
        if ($latest > 0 && $latest <= time() && time() - $latest <= $lifetime) {
3 ✔
392
            return null;
2 ✔
393
        }
394

395
        session()->setTempdata('passwordConfirmIntendedUrl', url_to('totp-setup'), 300);
1 ✔
396

397
        return redirect()->route('password-confirm-show')->with('error', lang('Auth.passwordConfirmRequired'));
1 ✔
398
    }
399

400
    /**
401
     * Starts a single-use passkey ceremony bound to the signed-in user.
402
     */
403
    public function passwordConfirmOptions(): ResponseInterface
1 ✔
404
    {
405
        $user = auth()->user();
1 ✔
406
        if ($user === null) {
1 ✔
NEW
407
            return $this->response->setStatusCode(401)->setJSON(['message' => lang('Auth.stepUpInvalid')]);
×
408
        }
409
        if (! (bool) setting('AuthSecurity.webauthnEnabled') || ! $user->hasWebAuthnCredentials()) {
1 ✔
NEW
410
            return $this->response->setStatusCode(404)->setJSON(['message' => lang('Auth.stepUpInvalid')]);
×
411
        }
412
        if (($locked = $this->getSessionAuthenticator()->getLockoutManager()->isLockedOut($user)) !== null) {
1 ✔
NEW
413
            return $this->response->setStatusCode(429)->setJSON(['message' => $locked->reason()]);
×
414
        }
415

416
        $options          = service('webAuthnManager')->startStepUp($user);
1 ✔
417
        $options['token'] = csrf_hash();
1 ✔
418

419
        return $this->response->setJSON($options);
1 ✔
420
    }
421

422
    /**
423
     * Shows only a regeneration form; stored recovery codes are never read back.
424
     */
NEW
425
    public function recoveryCodesView(): RedirectResponse|string
×
426
    {
NEW
427
        $user = auth()->user();
×
NEW
428
        if ($user === null || (! $user->hasTotpEnabled() && ! $user->hasWebAuthnCredentials())) {
×
NEW
429
            return redirect()->route('security')->with('error', lang('Auth.recoveryCodesUnavailable'));
×
430
        }
431

NEW
432
        return $this->view(setting('Auth.views')['security_recovery_codes'] ?? 'Daycry\\Auth\\Views\\security\\recovery_codes', ['backupCodes' => []]);
×
433
    }
434

435
    /**
436
     * Replaces recovery codes only after a recent, user-bound step-up proof.
437
     */
438
    public function regenerateRecoveryCodes(): ResponseInterface
1 ✔
439
    {
440
        $user = auth()->user();
1 ✔
441
        if ($user === null || (! $user->hasTotpEnabled() && ! $user->hasWebAuthnCredentials())) {
1 ✔
NEW
442
            return redirect()->route('security')->with('error', lang('Auth.recoveryCodesUnavailable'));
×
443
        }
444

445
        $confirmedAt = (int) session('password_confirmed_at');
1 ✔
446
        $lifetime    = max(0, (int) setting('AuthSecurity.passwordConfirmationLifetime'));
1 ✔
447
        if ((string) session('auth_step_up_user') !== (string) $user->id || $confirmedAt <= 0
1 ✔
448
                                                                         || $confirmedAt > time() || $lifetime <= 0 || time() - $confirmedAt > $lifetime) {
1 ✔
449
            session()->setTempdata('passwordConfirmIntendedUrl', url_to('security-recovery-codes'), 300);
1 ✔
450

451
            return redirect()->route('password-confirm-show')->with('error', lang('Auth.passwordConfirmRequired'));
1 ✔
452
        }
453

454
        $codes = $user->generateBackupCodes();
1 ✔
455

456
        return $this->response->setHeader('Cache-Control', 'no-store')->setBody($this->view(
1 ✔
457
            setting('Auth.views')['security_recovery_codes'] ?? 'Daycry\\Auth\\Views\\security\\recovery_codes',
1 ✔
458
            ['backupCodes' => $codes],
1 ✔
459
        ));
1 ✔
460
    }
461

462
    /**
463
     * Change-password form, or the set-password form for an account that has
464
     * no usable password yet (e.g. created through OAuth).
465
     */
466
    public function changePasswordView(): string
2 ✔
467
    {
468
        return $this->view($this->viewFor('security-change-password'), [
2 ✔
469
            'hasPassword' => $this->hasUsablePassword(auth()->user()),
2 ✔
470
        ]);
2 ✔
471
    }
472

473
    /**
474
     * Changes the password (requires the current one), or sets a first
475
     * password on a password-less account (requires an e-mail address and a
476
     * recent interactive sign-in instead).
477
     *
478
     * Every other device session and remember-me token is revoked, issued
479
     * JWTs are invalidated; the current session stays signed in.
480
     */
481
    public function changePassword(): RedirectResponse
8 ✔
482
    {
483
        $user        = auth()->user();
8 ✔
484
        $hasPassword = $this->hasUsablePassword($user);
8 ✔
485

486
        /** @var Passwords $passwords */
487
        $passwords = service('passwords');
8 ✔
488

489
        if (! $hasPassword && (string) $user->email === '') {
8 ✔
490
            return redirect()->back()->with('error', lang('Auth.changePasswordNeedsEmail'));
1 ✔
491
        }
492

493
        $denied = $this->reauthenticate($user);
7 ✔
494
        if ($denied instanceof RedirectResponse) {
7 ✔
495
            return $denied;
2 ✔
496
        }
497

498
        $newPassword = (string) $this->request->getPost('new_password');
5 ✔
499

500
        if ($newPassword !== (string) $this->request->getPost('new_password_confirm')) {
5 ✔
501
            return redirect()->back()->with('error', lang('Auth.changePasswordMismatch'));
1 ✔
502
        }
503

504
        $check = $passwords->check($newPassword, $user);
4 ✔
505

506
        if (! $check->isOK()) {
4 ✔
507
            return redirect()->back()->with('error', $check->reason());
1 ✔
508
        }
509

510
        $previousHash = $user->getPasswordHash();
3 ✔
511

512
        $user->setPassword($newPassword);
3 ✔
513
        model(UserModel::class)->save($user);
3 ✔
514

515
        // History, password_changed_at, JWT access + refresh revocation.
516
        service('passwordChangeRecorder')->record($user, $previousHash);
3 ✔
517

518
        // Sign out everywhere else; keep this session.
519
        model(DeviceSessionModel::class)->terminateAllForUser($user, session_id());
3 ✔
520
        model(RememberModel::class)->purgeRememberTokensByUserId($user->id);
3 ✔
521

522
        service('auditLogger')->record(AuditLogger::EVENT_PASSWORD_CHANGED, (int) $user->id);
3 ✔
523
        service('securityNotifier')->passwordChanged($user);
3 ✔
524
        Events::trigger('password-changed', $user);
3 ✔
525

526
        return redirect()->route('security')
3 ✔
527
            ->with('message', lang($hasPassword ? 'Auth.changePasswordSuccess' : 'Auth.setPasswordSuccess'));
3 ✔
528
    }
529

530
    /**
531
     * Form to request an e-mail address change.
532
     */
533
    public function changeEmailView(): string
×
534
    {
535
        $user = auth()->user();
×
536

537
        return $this->view($this->viewFor('security-change-email'), [
×
538
            'hasPassword'  => $this->hasUsablePassword($user),
×
539
            'currentEmail' => (string) $user->email,
×
540
        ]);
×
541
    }
542

543
    /**
544
     * Requests an e-mail change: re-authenticates (current password, or a
545
     * recent sign-in on a password-less account), e-mails a single-use
546
     * confirmation link to the NEW address and warns the CURRENT one.
547
     * Nothing changes until the link is confirmed.
548
     */
549
    public function changeEmail(): RedirectResponse
7 ✔
550
    {
551
        $user = auth()->user();
7 ✔
552

553
        $denied = $this->reauthenticate($user);
7 ✔
554
        if ($denied instanceof RedirectResponse) {
7 ✔
555
            return $denied;
2 ✔
556
        }
557

558
        $newEmail = strtolower(trim((string) $this->request->getPost('new_email')));
6 ✔
559

560
        if (filter_var($newEmail, FILTER_VALIDATE_EMAIL) === false) {
6 ✔
561
            return redirect()->back()->with('error', lang('Auth.changeEmailInvalid'));
1 ✔
562
        }
563

564
        if ($newEmail === strtolower((string) $user->email)) {
6 ✔
565
            return redirect()->back()->with('error', lang('Auth.changeEmailUnchanged'));
1 ✔
566
        }
567

568
        // Authenticated-only, low-severity enumeration surface (session +
569
        // CSRF; add the `rates` filter to the route).
570
        if ($this->emailBelongsToAnotherAccount($newEmail, $user)) {
6 ✔
571
            return redirect()->back()->with('error', lang('Auth.changeEmailAlreadyUsed'));
1 ✔
572
        }
573

574
        try {
575
            service('tokenEmailSender')->sendTokenEmail(
5 ✔
576
                $user,
5 ✔
577
                IdentityType::EMAIL_CHANGE->value,
5 ✔
578
                (int) setting('AuthSecurity.emailChangeLifetime'),
5 ✔
579
                lang('Auth.changeEmailSubject'),
5 ✔
580
                $this->viewFor('email-change-email'),
5 ✔
581
                [],
5 ✔
582
                null,
5 ✔
583
                $newEmail,
5 ✔
584
                ['new_email' => $newEmail],
5 ✔
585
            );
5 ✔
586
        } catch (RuntimeException $e) {
×
587
            log_message('error', 'E-mail change confirmation could not be sent: {message}', ['message' => $e->getMessage()]);
×
588

589
            return redirect()->back()->with('error', lang('Auth.unableSendEmailToUser', [$newEmail]));
×
590
        }
591

592
        service('securityNotifier')->emailChangeRequested($user, $newEmail);
5 ✔
593
        service('auditLogger')->record(AuditLogger::EVENT_EMAIL_CHANGE_REQUEST, (int) $user->id);
5 ✔
594

595
        return redirect()->back()->with('message', lang('Auth.changeEmailSent'));
5 ✔
596
    }
597

598
    /**
599
     * Confirmation page for the e-mailed link. GET never mutates (mail
600
     * scanners and link prefetchers follow GET links); it renders a form that
601
     * POSTs the token to confirmEmailChange().
602
     */
603
    public function confirmEmailChangeView(): RedirectResponse|string
2 ✔
604
    {
605
        $token = (string) $this->request->getGet('token');
2 ✔
606

607
        [$identity, $error] = $this->pendingToken(IdentityType::EMAIL_CHANGE, $token, 'changeEmail');
2 ✔
608
        if ($identity === null) {
2 ✔
609
            return redirect()->route('security')->with('error', $error);
1 ✔
610
        }
611

612
        return $this->view($this->viewFor('security-confirm-email-change'), [
1 ✔
613
            'token'    => $token,
1 ✔
614
            'newEmail' => (string) ($this->identityExtra($identity)['new_email'] ?? ''),
1 ✔
615
        ]);
1 ✔
616
    }
617

618
    /**
619
     * Applies a confirmed e-mail change. The token is single-use and must
620
     * belong to the signed-in user; the new address is re-checked.
621
     */
622
    public function confirmEmailChange(): RedirectResponse
4 ✔
623
    {
624
        $user = auth()->user();
4 ✔
625

626
        [$identity, $error] = $this->pendingToken(IdentityType::EMAIL_CHANGE, (string) $this->request->getPost('token'), 'changeEmail');
4 ✔
627
        if ($identity === null) {
4 ✔
628
            return redirect()->route('security')->with('error', $error);
2 ✔
629
        }
630

631
        // Consume first: the link is single-use whatever happens next.
632
        model(UserIdentityModel::class)->delete($identity->id);
3 ✔
633

634
        $newEmail = (string) ($this->identityExtra($identity)['new_email'] ?? '');
3 ✔
635

636
        if (filter_var($newEmail, FILTER_VALIDATE_EMAIL) === false) {
3 ✔
637
            return redirect()->route('security')->with('error', lang('Auth.changeEmailTokenInvalid'));
×
638
        }
639

640
        if ($this->emailBelongsToAnotherAccount($newEmail, $user)) {
3 ✔
641
            return redirect()->route('security')->with('error', lang('Auth.changeEmailAlreadyUsed'));
1 ✔
642
        }
643

644
        $oldEmail = (string) $user->email;
2 ✔
645

646
        // Save the ENTITY: UserModel syncs the login identity (an array update
647
        // would skip saveEmailIdentity and leave the old login address).
648
        $user->setEmail($newEmail);
2 ✔
649

650
        try {
651
            model(UserModel::class)->save($user);
2 ✔
652
        } catch (DatabaseException|FrameworkDatabaseException) {
×
653
            // Lost a race on the unique (type, secret) index.
654
            return redirect()->route('security')->with('error', lang('Auth.changeEmailAlreadyUsed'));
×
655
        }
656

657
        service('auditLogger')->record(AuditLogger::EVENT_EMAIL_CHANGED, (int) $user->id);
2 ✔
658

659
        if ($oldEmail !== '') {
2 ✔
660
            service('securityNotifier')->emailChanged($user, $oldEmail);
1 ✔
661
        }
662

663
        Events::trigger('email-changed', $user, $oldEmail);
2 ✔
664

665
        return redirect()->route('security')->with('message', lang('Auth.changeEmailSuccess'));
2 ✔
666
    }
667

668
    /**
669
     * Disconnects an OAuth provider from the account. Refused when it is the
670
     * last way to sign in: a usable password, another linked provider or a
671
     * passkey (stored in its own table) must remain.
672
     */
673
    public function unlinkOauth(string $provider): RedirectResponse
5 ✔
674
    {
675
        $user          = auth()->user();
5 ✔
676
        $type          = IdentityType::oauthProvider($provider);
5 ✔
677
        $identityModel = model(UserIdentityModel::class);
5 ✔
678
        $identity      = $identityModel->getIdentityByType($user, $type);
5 ✔
679

680
        if ($identity === null) {
5 ✔
681
            return redirect()->back()->with('error', lang('Auth.unlinkOauthNotFound', [$provider]));
1 ✔
682
        }
683

684
        $otherProviders = array_filter(
4 ✔
685
            $identityModel->getIdentities($user),
4 ✔
686
            static fn (UserIdentity $i): bool => str_starts_with((string) $i->type, 'oauth_') && $i->type !== $type,
4 ✔
687
        );
4 ✔
688

689
        if (! $this->hasUsablePassword($user) && $otherProviders === [] && ! $user->hasWebAuthnCredentials()) {
4 ✔
690
            return redirect()->back()->with('error', lang('Auth.unlinkOauthLastMethod'));
2 ✔
691
        }
692

693
        $identityModel->delete($identity->id);
2 ✔
694

695
        service('auditLogger')->record(AuditLogger::EVENT_OAUTH_UNLINKED, (int) $user->id, ['provider' => $provider]);
2 ✔
696
        Events::trigger('oauth-unlinked', $user, $provider);
2 ✔
697

698
        return redirect()->back()->with('message', lang('Auth.unlinkOauthSuccess', [$provider]));
2 ✔
699
    }
700

701
    /**
702
     * Account deletion form: password re-auth, or "send me a confirmation
703
     * link" on a password-less account.
704
     */
705
    public function deleteAccountView(): string
1 ✔
706
    {
707
        $user = auth()->user();
1 ✔
708

709
        return $this->view($this->viewFor('security-delete-account'), [
1 ✔
710
            'hasPassword' => $this->hasUsablePassword($user),
1 ✔
711
            'hasEmail'    => (string) $user->email !== '',
1 ✔
712
        ]);
1 ✔
713
    }
714

715
    /**
716
     * Deletes (anonymises) the account. A password account is deleted right
717
     * after its current password is verified; a password-less account gets a
718
     * single-use confirmation link by e-mail instead (the link is the re-auth).
719
     */
720
    public function deleteAccount(): RedirectResponse
6 ✔
721
    {
722
        $user = auth()->user();
6 ✔
723

724
        if ($this->hasUsablePassword($user)) {
6 ✔
725
            $denied = $this->reauthenticate($user);
3 ✔
726

727
            return $denied ?? $this->performAccountDeletion($user);
3 ✔
728
        }
729

730
        if ((string) $user->email === '') {
3 ✔
731
            return redirect()->back()->with('error', lang('Auth.deleteAccountNeedsEmail'));
1 ✔
732
        }
733

734
        try {
735
            service('tokenEmailSender')->sendTokenEmail(
2 ✔
736
                $user,
2 ✔
737
                IdentityType::ACCOUNT_DELETE->value,
2 ✔
738
                (int) setting('AuthSecurity.emailChangeLifetime'),
2 ✔
739
                lang('Auth.deleteAccountSubject'),
2 ✔
740
                $this->viewFor('security-account-delete-email'),
2 ✔
741
            );
2 ✔
742
        } catch (RuntimeException $e) {
×
743
            log_message('error', 'Account deletion confirmation could not be sent: {message}', ['message' => $e->getMessage()]);
×
744

745
            return redirect()->back()->with('error', lang('Auth.unableSendEmailToUser', [(string) $user->email]));
×
746
        }
747

748
        return redirect()->back()->with('message', lang('Auth.deleteAccountEmailSent'));
2 ✔
749
    }
750

751
    /**
752
     * Confirmation page for the e-mailed deletion link (GET never mutates).
753
     */
754
    public function confirmDeleteAccountView(): RedirectResponse|string
1 ✔
755
    {
756
        $token = (string) $this->request->getGet('token');
1 ✔
757

758
        [$identity, $error] = $this->pendingToken(IdentityType::ACCOUNT_DELETE, $token, 'deleteAccount');
1 ✔
759
        if ($identity === null) {
1 ✔
760
            return redirect()->route('security')->with('error', $error);
×
761
        }
762

763
        return $this->view($this->viewFor('security-confirm-delete-account'), ['token' => $token]);
1 ✔
764
    }
765

766
    /**
767
     * Deletes a password-less account from its confirmed link.
768
     */
769
    public function confirmDeleteAccount(): RedirectResponse
2 ✔
770
    {
771
        [$identity, $error] = $this->pendingToken(IdentityType::ACCOUNT_DELETE, (string) $this->request->getPost('token'), 'deleteAccount');
2 ✔
772
        if ($identity === null) {
2 ✔
773
            return redirect()->route('security')->with('error', $error);
1 ✔
774
        }
775

776
        return $this->performAccountDeletion(auth()->user());
1 ✔
777
    }
778

779
    /**
780
     * Anonymises the account first (one transaction), then — only once it
781
     * succeeded — sends the farewell notice and signs the user out.
782
     */
783
    protected function performAccountDeletion(User $user): RedirectResponse
3 ✔
784
    {
785
        $userId = (int) $user->id;
3 ✔
786

787
        // Load the address now: the anonymizer removes the identity holding it.
788
        $user->getEmail();
3 ✔
789

790
        try {
791
            service('userAnonymizer')->anonymize($user, 'self-service', $userId);
3 ✔
792
        } catch (Throwable $e) {
1 ✔
793
            log_message('error', 'Self-service account deletion failed for user {id}: {message}', ['id' => $userId, 'message' => $e->getMessage()]);
1 ✔
794

795
            return redirect()->back()->with('error', lang('Auth.deleteAccountFailed'));
1 ✔
796
        }
797

798
        service('securityNotifier')->accountDeleted($user);
2 ✔
799

800
        auth('session')->logout();
2 ✔
801

802
        Events::trigger('account-deleted', $userId);
2 ✔
803

804
        return redirect()->to(config('Auth')->logoutRedirect())->with('message', lang('Auth.deleteAccountSuccess'));
2 ✔
805
    }
806

807
    /**
808
     * Re-authentication for a sensitive change: the current password on a
809
     * password account, a recent interactive sign-in on a password-less one.
810
     *
811
     * @return RedirectResponse|null Null when the user is re-authenticated
812
     */
813
    protected function reauthenticate(User $user): ?RedirectResponse
17 ✔
814
    {
815
        if ($this->hasUsablePassword($user)) {
17 ✔
816
            /** @var Passwords $passwords */
817
            $passwords = service('passwords');
14 ✔
818

819
            if (! $passwords->verify((string) $this->request->getPost('current_password'), (string) $user->getPasswordHash())) {
14 ✔
820
                return redirect()->back()->with('error', lang('Auth.changePasswordCurrentInvalid'));
3 ✔
821
            }
822

823
            return null;
11 ✔
824
        }
825

826
        if (! $this->recentlyAuthenticated()) {
3 ✔
827
            return redirect()->back()->with('error', lang('Auth.reauthRequired'));
2 ✔
828
        }
829

830
        return null;
2 ✔
831
    }
832

833
    /**
834
     * Resolves a self-service confirmation token of the signed-in user.
835
     *
836
     * @param string $langPrefix 'changeEmail' | 'deleteAccount' (selects the *TokenInvalid / *TokenExpired line)
837
     *
838
     * @return array{0: UserIdentity|null, 1: string|null} [identity, error message]
839
     */
840
    protected function pendingToken(IdentityType $type, string $token, string $langPrefix): array
6 ✔
841
    {
842
        $identityModel = model(UserIdentityModel::class);
6 ✔
843
        $identity      = $token === '' ? null : $identityModel->getIdentityBySecret($type->value, $token);
6 ✔
844

845
        if ($identity === null || (int) $identity->user_id !== (int) auth()->id()) {
6 ✔
846
            return [null, lang('Auth.' . $langPrefix . 'TokenInvalid')];
3 ✔
847
        }
848

849
        if ($identity->expires !== null && Time::now()->isAfter($identity->expires)) {
5 ✔
850
            $identityModel->delete($identity->id);
1 ✔
851

852
            return [null, lang('Auth.' . $langPrefix . 'TokenExpired')];
1 ✔
853
        }
854

855
        return [$identity, null];
4 ✔
856
    }
857

858
    /**
859
     * @return array<string, mixed>
860
     */
861
    protected function identityExtra(UserIdentity $identity): array
3 ✔
862
    {
863
        $extra = json_decode((string) $identity->extra, true);
3 ✔
864

865
        return is_array($extra) ? $extra : [];
3 ✔
866
    }
867

868
    /**
869
     * Whether $email is the login address of an account other than $user.
870
     */
871
    protected function emailBelongsToAnotherAccount(string $email, User $user): bool
6 ✔
872
    {
873
        return model(UserIdentityModel::class)
6 ✔
874
            ->where('type', IdentityType::EMAIL_PASSWORD->value)
6 ✔
875
            ->where('secret', strtolower($email))
6 ✔
876
            ->where('user_id !=', $user->id)
6 ✔
877
            ->countAllResults() > 0;
6 ✔
878
    }
879

880
    /**
881
     * Whether the user can sign in with a password: an e-mail identity whose
882
     * hash is not the empty password (OAuth accounts that later confirm an
883
     * e-mail get an identity without a usable password).
884
     */
885
    protected function hasUsablePassword(User $user): bool
27 ✔
886
    {
887
        $hash = (string) $user->getPasswordHash();
27 ✔
888

889
        if ($hash === '') {
27 ✔
890
            return false;
5 ✔
891
        }
892

893
        /** @var Passwords $passwords */
894
        $passwords = service('passwords');
22 ✔
895

896
        return ! $passwords->verify('', $hash);
22 ✔
897
    }
898

899
    /**
900
     * Whether the user proved who they are recently: an interactive sign-in or
901
     * a password confirmation within AuthSecurity::$passwordConfirmationLifetime.
902
     * Gates sensitive changes on password-less accounts, where there is no
903
     * current password to ask for.
904
     */
905
    protected function recentlyAuthenticated(): bool
3 ✔
906
    {
907
        $lifetime = (int) (setting('AuthSecurity.passwordConfirmationLifetime') ?? 0);
3 ✔
908
        $latest   = max(
3 ✔
909
            (int) session(Session::AUTHENTICATED_AT_KEY),
3 ✔
910
            (int) session('password_confirmed_at'),
3 ✔
911
        );
3 ✔
912

913
        return $latest > 0 && time() - $latest <= $lifetime;
3 ✔
914
    }
915

916
    /**
917
     * View name for a self-service screen, with a fallback for published
918
     * Config\Auth::$views arrays that predate the key.
919
     */
920
    public function exportData(): ResponseInterface
4 ✔
921
    {
922
        $user = auth('session')->user();
4 ✔
923
        if ($user === null) {
4 ✔
NEW
924
            return $this->response->setStatusCode(401)->setJSON(['code' => 'unauthenticated']);
×
925
        }
926

927
        $confirmedAt = (int) session('password_confirmed_at');
4 ✔
928
        $lifetime    = max(0, (int) setting('AuthSecurity.passwordConfirmationLifetime'));
4 ✔
929
        if ((string) session('auth_step_up_user') !== (string) $user->id || $confirmedAt <= 0
4 ✔
930
                                                                         || $confirmedAt > time() || $lifetime <= 0 || time() - $confirmedAt >= $lifetime) {
4 ✔
931
            if ($this->expectsJsonResponse()) {
2 ✔
932
                return $this->response->setStatusCode(403)->setHeader('Cache-Control', 'no-store')->setJSON([
2 ✔
933
                    'code'     => 'confirmation_required',
2 ✔
934
                    'message'  => lang('Auth.passwordConfirmRequired'),
2 ✔
935
                    'redirect' => url_to('password-confirm-show'),
2 ✔
936
                ]);
2 ✔
937
            }
NEW
938
            session()->setTempdata('passwordConfirmIntendedUrl', url_to('security'), 300);
×
939

NEW
940
            return redirect()->route('password-confirm-show')->with('error', lang('Auth.passwordConfirmRequired'));
×
941
        }
942

943
        try {
944
            $data = service('userDataExporter')->export($user);
2 ✔
945
        } catch (DataExportLimitException $e) {
1 ✔
946
            return $this->response->setStatusCode(413)->setHeader('Cache-Control', 'no-store')
1 ✔
947
                ->setJSON(['code' => 'export_too_large', 'message' => $e->getMessage()]);
1 ✔
948
        }
949

950
        return $this->response->setHeader('Cache-Control', 'no-store')
1 ✔
951
            ->setHeader('Content-Disposition', 'attachment; filename="account-data.json"')
1 ✔
952
            ->setJSON($data);
1 ✔
953
    }
954

955
    protected function viewFor(string $key): string
10 ✔
956
    {
957
        $defaults = [
10 ✔
958
            'security-change-password'        => '\Daycry\Auth\Views\security\change_password',
10 ✔
959
            'security-change-email'           => '\Daycry\Auth\Views\security\change_email',
10 ✔
960
            'security-confirm-email-change'   => '\Daycry\Auth\Views\security\confirm_email_change',
10 ✔
961
            'security-delete-account'         => '\Daycry\Auth\Views\security\delete_account',
10 ✔
962
            'security-confirm-delete-account' => '\Daycry\Auth\Views\security\confirm_delete_account',
10 ✔
963
            'security-account-delete-email'   => '\Daycry\Auth\Views\Email\account_delete_email',
10 ✔
964
            'email-change-email'              => '\Daycry\Auth\Views\Email\email_change_email',
10 ✔
965
        ];
10 ✔
966

967
        return setting('Auth.views')[$key] ?? $defaults[$key];
10 ✔
968
    }
969
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc