• 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

69.62
/src/Controllers/MagicLinkController.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\Events\Events;
17
use CodeIgniter\Exceptions\RuntimeException;
18
use CodeIgniter\HTTP\RedirectResponse;
19
use CodeIgniter\HTTP\ResponseInterface;
20
use CodeIgniter\I18n\Time;
21
use Daycry\Auth\Authentication\Authenticators\Session;
22
use Daycry\Auth\Entities\User;
23
use Daycry\Auth\Libraries\Utils;
24
use Daycry\Auth\Models\UserIdentityModel;
25
use Daycry\Auth\Models\UserModel;
26

27
/**
28
 * Handles "Magic Link" logins - an email-based
29
 * no-password login protocol. This works much
30
 * like password reset would, but Shield provides
31
 * this in place of password reset. It can also
32
 * be used on it's own without an email/password
33
 * login strategy.
34
 */
35
class MagicLinkController extends BaseAuthController
36
{
37
    /**
38
     * @var UserModel
39
     */
40
    protected $provider;
41

42
    public function __construct()
22 ✔
43
    {
44
        /** @var class-string<UserModel> $providerClass */
45
        $providerClass = setting('Auth.userProvider');
22 ✔
46

47
        $this->provider = new $providerClass();
22 ✔
48
    }
49

50
    /**
51
     * Displays the view to enter their email address
52
     * so an email can be sent to them.
53
     */
54
    public function loginView(): ResponseInterface
×
55
    {
NEW
56
        if ($this->magicLinkDisabled()) {
×
NEW
57
            return $this->handleFailure(
×
58
                config('Auth')->loginRoute(),
×
59
                lang('Auth.magicLinkDisabled'),
×
NEW
60
                true,
×
NEW
61
                403,
×
UNCOV
62
            );
×
63
        }
64

65
        if (($redirect = $this->redirectIfLoggedIn()) instanceof RedirectResponse) {
×
66
            return $redirect;
×
67
        }
68

69
        $content = $this->view(setting('Auth.views')['magic-link-login']);
×
70

71
        return $this->response->setBody($content);
×
72
    }
73

74
    /**
75
     * Receives the email from the user, creates the hash
76
     * to a user identity, and sends an email to the given
77
     * email address.
78
     */
79
    public function loginAction(): ResponseInterface
4 ✔
80
    {
81
        if ($this->magicLinkDisabled()) {
4 ✔
NEW
82
            return $this->handleFailure(
×
83
                config('Auth')->loginRoute(),
×
84
                lang('Auth.magicLinkDisabled'),
×
NEW
85
                true,
×
NEW
86
                403,
×
UNCOV
87
            );
×
88
        }
89

90
        $rules    = $this->getValidationRules();
4 ✔
91
        $postData = $this->authInput();
4 ✔
92

93
        // Resolve the form URL once. The 'magic-link' route is login/magic-link,
94
        // so redirecting to the literal 'magic-link' path would 404 — use the
95
        // named route.
96
        $formUrl = route_to('magic-link');
4 ✔
97

98
        if (! $this->validateRequest($postData, $rules)) {
4 ✔
99
            return $this->handleValidationError($formUrl);
×
100
        }
101

102
        $delivery = $this->authInput('delivery') === 'code' ? 'code' : 'link';
4 ✔
103

104
        if ($delivery === 'link' && ! setting('AuthSecurity.magicLinkEnableLink')) {
4 ✔
NEW
105
            return $this->handleFailure($formUrl, lang('Auth.magicLinkDisabled'), true, 403);
×
106
        }
107
        if ($delivery === 'code' && ! setting('AuthSecurity.magicLinkEnableCode')) {
4 ✔
108
            return $this->handleFailure($formUrl, lang('Auth.magicLinkDisabled'), true, 403);
1 ✔
109
        }
110

111
        $email = $this->authInput('email');
3 ✔
112
        $user  = $this->provider->findByCredentials(['email' => $email]);
3 ✔
113

114
        if ($delivery === 'code') {
3 ✔
115
            // Session-bound: remember the requested email regardless of whether
116
            // it exists (anti-enumeration), then show the code form.
117
            session()->set('magicCodeEmail', $email);
2 ✔
118

119
            if ($user !== null) {
2 ✔
120
                try {
121
                    service('tokenEmailSender')->sendTokenEmail(
1 ✔
122
                        $user,
1 ✔
123
                        Session::ID_TYPE_MAGIC_CODE,
1 ✔
124
                        setting('AuthSecurity.magicCodeLifetime'),
1 ✔
125
                        lang('Auth.magicCodeSubject'),
1 ✔
126
                        setting('Auth.views')['magic-link-code-email'],
1 ✔
127
                        [],
1 ✔
128
                        static fn (): string => Utils::generateNumericCode(6),
1 ✔
129
                    );
1 ✔
130
                } catch (RuntimeException $e) {
×
131
                    // Swallow send failures so the response can't be used to
132
                    // distinguish existing from non-existing accounts.
133
                    log_message('error', 'Magic code email failed: {m}', ['m' => $e->getMessage()]);
×
134
                }
135
            }
136

137
            return $this->handleSuccess(url_to('magic-link-code'));
2 ✔
138
        }
139

140
        // Link mode (existing behaviour, now anti-enumeration: unknown emails
141
        // and send failures both fall through to the generic message page).
142
        if ($user !== null) {
1 ✔
143
            try {
NEW
144
                service('tokenEmailSender')->sendTokenEmail(
×
145
                    $user,
×
146
                    Session::ID_TYPE_MAGIC_LINK,
×
147
                    setting('AuthSecurity.magicLinkLifetime'),
×
148
                    lang('Auth.magicLinkSubject'),
×
149
                    setting('Auth.views')['magic-link-email'],
×
150
                );
×
151
            } catch (RuntimeException $e) {
×
152
                log_message('error', 'Magic link email failed: {m}', ['m' => $e->getMessage()]);
×
153
            }
154
        }
155

156
        return $this->handleSuccess(url_to('magic-link-message'));
1 ✔
157
    }
158

159
    /**
160
     * Display the "What's happening/next" message to the user.
161
     */
162
    protected function displayMessage(): string
×
163
    {
164
        return $this->view(setting('Auth.views')['magic-link-message']);
×
165
    }
166

167
    /**
168
     * Shows the message view (public route)
169
     */
170
    public function messageView(): ResponseInterface
×
171
    {
NEW
172
        return $this->response->setBody($this->displayMessage());
×
173
    }
174

175
    /**
176
     * Shows the 6-digit code entry form. Only reachable after a code has been
177
     * requested (the pending email is in the session).
178
     */
179
    public function codeView(): ResponseInterface
2 ✔
180
    {
181
        if ($this->magicLinkDisabled(true)) {
2 ✔
NEW
182
            return $this->handleFailure(
×
183
                config('Auth')->loginRoute(),
×
184
                lang('Auth.magicLinkDisabled'),
×
NEW
185
                true,
×
NEW
186
                403,
×
UNCOV
187
            );
×
188
        }
189

190
        if (! session()->has('magicCodeEmail')) {
2 ✔
191
            return redirect()->route('magic-link');
1 ✔
192
        }
193

194
        $content = $this->view(setting('Auth.views')['magic-link-code']);
1 ✔
195

196
        return $this->response->setBody($content);
1 ✔
197
    }
198

199
    /**
200
     * Handles the GET request from the email
201
     */
202
    public function verify(): ResponseInterface
6 ✔
203
    {
204
        if ($this->magicLinkDisabled()) {
6 ✔
NEW
205
            return $this->handleFailure(route_to('login'), lang('Auth.magicLinkDisabled'), true, 403);
×
206
        }
207

208
        $token = $this->request->getGet('token');
6 ✔
209
        // A malformed query (e.g. token[]=x) is just an unknown token.
210
        $token = is_string($token) ? $token : null;
6 ✔
211

212
        /** @var UserIdentityModel $identityModel */
213
        $identityModel = model(UserIdentityModel::class);
6 ✔
214

215
        $identity = $identityModel->getIdentityBySecret(Session::ID_TYPE_MAGIC_LINK, $token);
6 ✔
216

217
        // No token found?
218
        if ($identity === null) {
6 ✔
219
            return $this->failLinkVerification($token, lang('Auth.magicTokenNotFound'));
2 ✔
220
        }
221

222
        // Delete the db entry so it cannot be used again.
223
        $identityModel->delete($identity->id);
5 ✔
224

225
        // Token expired?
226
        if (Time::now()->isAfter($identity->expires)) {
5 ✔
227
            return $this->failLinkVerification($token, lang('Auth.magicLinkExpired'));
1 ✔
228
        }
229

230
        $user = $this->provider->findById($identity->user_id);
4 ✔
231

232
        // The account behind the token no longer exists.
233
        if ($user === null) {
4 ✔
NEW
234
            return $this->failLinkVerification($token, lang('Auth.magicTokenNotFound'));
×
235
        }
236

237
        // A banned user must not get a session (password login refuses them
238
        // in checkLogin(); loginById() does not check).
239
        if ($user->isBanned()) {
4 ✔
240
            return $this->failLinkVerification($token, $this->banMessage($user), $user->id);
1 ✔
241
        }
242

243
        /** @var Session $authenticator */
244
        $authenticator = auth('session')->getAuthenticator();
3 ✔
245

246
        // If an action has been defined
247
        if ($authenticator->hasAction($user->id)) {
3 ✔
NEW
248
            return $this->redirectToAuthAction();
×
249
        }
250

251
        $response = $this->completeMagicLogin($authenticator, $user);
3 ✔
252

253
        // Recorded after the login: SuspiciousLoginDetector must only see the
254
        // previous successful logins when it checks for a new IP.
255
        $this->recordLoginAttempt(Session::ID_TYPE_MAGIC_LINK, $token ?? '', true, $user->id);
3 ✔
256

257
        return $response;
3 ✔
258
    }
259

260
    /**
261
     * Verifies the 6-digit code (code delivery mode). The pending email is read
262
     * from the session, the code is matched against that user's own MAGIC_CODE
263
     * identity (never a global lookup), and the account's brute-force lockout
264
     * applies. Generic errors throughout (anti-enumeration).
265
     */
266
    public function verifyCode(): ResponseInterface
10 ✔
267
    {
268
        if ($this->magicLinkDisabled(true)) {
10 ✔
NEW
269
            return $this->handleFailure(route_to('login'), lang('Auth.magicLinkDisabled'), true, 403);
×
270
        }
271

272
        $email = session()->get('magicCodeEmail');
10 ✔
273
        if (empty($email)) {
10 ✔
274
            if ($this->expectsJsonResponse()) {
1 ✔
NEW
275
                return $this->authJsonResponse(['status' => 'error', 'message' => lang('Auth.magicCodeInvalid')], 401);
×
276
            }
277

278
            return redirect()->route('magic-link');
1 ✔
279
        }
280

281
        $code = (string) $this->authInput('token');
9 ✔
282
        $user = $this->provider->findByCredentials(['email' => $email]);
9 ✔
283

284
        /** @var Session $authenticator */
285
        $authenticator = auth('session')->getAuthenticator();
9 ✔
286

287
        if ($user !== null) {
9 ✔
288
            $lockout       = $authenticator->getLockoutManager();
8 ✔
289
            $lockoutResult = $lockout->isLockedOut($user);
8 ✔
290

291
            if ($lockoutResult !== null) {
8 ✔
292
                // Generic message even while locked out: surfacing the lockout
293
                // reason here would confirm the account exists (a non-existent
294
                // email is never locked out and always gets the generic error),
295
                // breaking anti-enumeration.
296
                return $this->handleFailure(route_to('magic-link-code'), lang('Auth.magicCodeInvalid'), true, 401);
1 ✔
297
            }
298

299
            /** @var UserIdentityModel $identityModel */
300
            $identityModel = model(UserIdentityModel::class);
8 ✔
301
            $identities    = $identityModel->getIdentitiesByTypes($user, [Session::ID_TYPE_MAGIC_CODE]);
8 ✔
302
            $identity      = $identities[0] ?? null;
8 ✔
303

304
            if (
305
                $identity !== null
8 ✔
306
                && $code !== ''
8 ✔
307
                && hash_equals((string) $identity->secret, hash('sha256', $code))
8 ✔
308
                && Time::now()->isBefore($identity->expires)
8 ✔
309
            ) {
310
                // Success — consume the code (single-use) and clear state.
311
                $identityModel->delete($identity->id);
4 ✔
312
                $lockout->resetOnSuccess($user);
4 ✔
313
                session()->remove('magicCodeEmail');
4 ✔
314

315
                if ($user->isBanned()) {
4 ✔
316
                    $this->recordLoginAttempt(Session::ID_TYPE_MAGIC_CODE, (string) $email, false, $user->id);
1 ✔
317
                    Events::trigger('failedLogin', ['magicCode' => $code]);
1 ✔
318

319
                    return $this->handleFailure(route_to('magic-link'), $this->banMessage($user), true, 401);
1 ✔
320
                }
321

322
                // Respect any pending post-auth action (mirrors verify()).
323
                if ($authenticator->hasAction($user->id)) {
3 ✔
NEW
324
                    $this->recordLoginAttempt(Session::ID_TYPE_MAGIC_CODE, (string) $email, true, $user->id);
×
325

NEW
326
                    return $this->redirectToAuthAction();
×
327
                }
328

329
                $response = $this->completeMagicLogin($authenticator, $user);
3 ✔
330

331
                // After the login, as in verify(): keeps the new-IP check working.
332
                $this->recordLoginAttempt(Session::ID_TYPE_MAGIC_CODE, (string) $email, true, $user->id);
3 ✔
333

334
                return $response;
3 ✔
335
            }
336

337
            // Existing user, bad/expired code → count the failed attempt.
338
            $lockout->recordFailedAttempt($user);
5 ✔
339
        }
340

341
        // Generic failure path (unknown email OR bad/expired code).
342
        $this->recordLoginAttempt(Session::ID_TYPE_MAGIC_CODE, (string) $email, false);
6 ✔
343
        Events::trigger('failedLogin', ['magicCode' => $code]);
6 ✔
344

345
        return $this->handleFailure(route_to('magic-link-code'), lang('Auth.magicCodeInvalid'), true, 401);
6 ✔
346
    }
347

348
    /**
349
     * Whether magic-link logins are off (or, with $code, the code mode).
350
     */
351
    protected function magicLinkDisabled(bool $code = false): bool
22 ✔
352
    {
353
        return ! setting('AuthSecurity.allowMagicLinkLogins')
22 ✔
354
            || ($code && ! setting('AuthSecurity.magicLinkEnableCode'));
22 ✔
355
    }
356

357
    /**
358
     * Records the failed link verification, fires `failedLogin` and sends the
359
     * user back to the magic-link form with $error.
360
     */
361
    protected function failLinkVerification(?string $token, string $error, ?int $userId = null): ResponseInterface
4 ✔
362
    {
363
        $this->recordLoginAttempt(Session::ID_TYPE_MAGIC_LINK, $token ?? '', false, $userId);
4 ✔
364

365
        Events::trigger('failedLogin', ['magicLinkToken' => $token]);
4 ✔
366

367
        return $this->handleFailure(route_to('magic-link'), $error, true, 401);
4 ✔
368
    }
369

370
    /**
371
     * Signs the verified user in and flags the session as a magic login.
372
     */
373
    protected function completeMagicLogin(Session $authenticator, User $user): ResponseInterface
6 ✔
374
    {
375
        $authenticator->loginById($user->id);
6 ✔
376

377
        // Give the developer a way to know the user
378
        // logged in via a magic link.
379
        session()->setTempdata('magicLogin', true);
6 ✔
380

381
        Events::trigger('magicLogin', $user);
6 ✔
382

383
        return $this->handleSuccess(config('Auth')->loginRedirect());
6 ✔
384
    }
385

386
    /**
387
     * The message shown to a banned user.
388
     */
389
    protected function banMessage(User $user): string
2 ✔
390
    {
391
        return $user->getBanMessage() ?? lang('Auth.bannedUser');
2 ✔
392
    }
393

394
    /**
395
     * Returns the rules that should be used for validation.
396
     *
397
     * @return         array<string, array<string, list<string>|string>>
398
     * @phpstan-return array<string, array<string, string|list<string>>>
399
     */
400
    protected function getValidationRules(): array
4 ✔
401
    {
402
        return [
4 ✔
403
            'email' => config('Auth')->emailValidationRules,
4 ✔
404
        ];
4 ✔
405
    }
406
}
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