• 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

92.78
/src/Controllers/JwtController.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\HTTP\ResponseInterface;
17
use CodeIgniter\I18n\Time;
18
use Daycry\Auth\Entities\User;
19
use Daycry\Auth\Interfaces\JWTAdapterInterface;
20
use Daycry\Auth\Validation\ValidationRules;
21

22
/**
23
 * JwtController
24
 *
25
 * Stateless JWT authentication with refresh token rotation.
26
 * Access tokens are short-lived JWTs; refresh tokens are
27
 * long-lived opaque tokens stored in the identities table.
28
 *
29
 * Routes (add to your app):
30
 *   $routes->post('auth/jwt/login',   'Daycry\Auth\Controllers\JwtController::login',   ['as' => 'jwt-login']);
31
 *   $routes->post('auth/jwt/refresh', 'Daycry\Auth\Controllers\JwtController::refresh', ['as' => 'jwt-refresh']);
32
 *   $routes->post('auth/jwt/logout',  'Daycry\Auth\Controllers\JwtController::logout',  ['as' => 'jwt-logout']);
33
 */
34
class JwtController extends BaseAuthController
35
{
36
    /**
37
     * {@inheritDoc}
38
     */
39
    protected function getValidationRules(): array
17 ✔
40
    {
41
        $rules = new ValidationRules();
17 ✔
42

43
        return $rules->getLoginRules();
17 ✔
44
    }
45

46
    /**
47
     * Authenticate with email+password.
48
     *
49
     * Returns a short-lived JWT access token and a long-lived refresh token.
50
     *
51
     * POST body: email, password
52
     * Response JSON: access_token, refresh_token, token_type
53
     */
54
    public function login(): ResponseInterface
17 ✔
55
    {
56
        $rules    = $this->getValidationRules();
17 ✔
57
        $postData = $this->authRequestData();
17 ✔
58

59
        if (! $this->validateRequest($postData, $rules)) {
17 ✔
60
            return $this->response->setStatusCode(422)->setJSON([
×
61
                'message' => $this->validator->getErrors(),
×
62
            ]);
×
63
        }
64

65
        $credentials = $this->extractLoginCredentials();
17 ✔
66

67
        $authenticator = $this->getSessionAuthenticator();
17 ✔
68
        $result        = $authenticator->check($credentials);
17 ✔
69

70
        if (! $result->isOK()) {
17 ✔
71
            return $this->response->setStatusCode(401)->setJSON([
2 ✔
72
                'message' => $result->reason(),
2 ✔
73
            ]);
2 ✔
74
        }
75

76
        $user = $result->extraInfo();
16 ✔
77

78
        $mfaVerified = $this->verifyLoginMfa($user);
16 ✔
79
        if (($denied = $this->mandatoryMfaDenial($user, $mfaVerified)) !== null) {
16 ✔
80
            return $denied;
4 ✔
81
        }
82

83
        $authenticator->getLockoutManager()->resetOnSuccess($user);
14 ✔
84

85
        return $this->response->setJSON($this->buildTokenResponse($user, null, $mfaVerified));
14 ✔
86
    }
87

88
    /**
89
     * Exchange a valid refresh token for a new access token and rotated refresh token.
90
     *
91
     * POST body: user_id, refresh_token
92
     * Response JSON: access_token, refresh_token, token_type
93
     */
94
    public function refresh(): ResponseInterface
11 ✔
95
    {
96
        $userId       = (int) $this->authInput('user_id');
11 ✔
97
        $refreshToken = (string) $this->authInput('refresh_token');
11 ✔
98

99
        if ($userId === 0 || $refreshToken === '') {
11 ✔
100
            return $this->response->setStatusCode(401)->setJSON([
×
101
                'message' => lang('Auth.invalidRefreshToken'),
×
102
            ]);
×
103
        }
104

105
        $user = auth()->getProvider()->findById($userId);
11 ✔
106

107
        // A banned user must not obtain new tokens, even if a refresh token
108
        // survived the ban (e.g. the status was changed outside User::ban()).
109
        if ($user === null || $user->isBanned()) {
11 ✔
110
            return $this->response->setStatusCode(401)->setJSON([
3 ✔
111
                'message' => lang('Auth.invalidUser'),
3 ✔
112
            ]);
3 ✔
113
        }
114

115
        $repository  = service('jwtTokenRepository');
8 ✔
116
        $identity    = $repository->getRefreshToken($userId, $refreshToken);
8 ✔
117
        $metadata    = $identity === null ? [] : json_decode((string) $identity->extra, true);
8 ✔
118
        $mfaVerified = is_array($metadata) && ($metadata['mfa_verified'] ?? false) === true;
8 ✔
119
        if ($identity !== null && ($denied = $this->mandatoryMfaDenial($user, $mfaVerified)) !== null) {
8 ✔
120
            return $denied;
1 ✔
121
        }
122

123
        $replacement = bin2hex(random_bytes(32));
7 ✔
124
        $expiresAt   = Time::now()->addSeconds((int) setting('AuthSecurity.jwtRefreshLifetime'))->format('Y-m-d H:i:s');
7 ✔
125
        if (! service('jwtTokenRepository')->rotateRefreshToken($userId, $refreshToken, $replacement, $expiresAt)) {
7 ✔
126
            return $this->response->setStatusCode(401)->setJSON(['message' => lang('Auth.invalidRefreshToken')]);
5 ✔
127
        }
128

129
        return $this->response->setJSON($this->buildTokenResponse($user, $replacement, $mfaVerified));
5 ✔
130
    }
131

132
    /**
133
     * Revoke the refresh token (stateless logout).
134
     *
135
     * POST body: user_id, refresh_token
136
     * Response JSON: message
137
     */
138
    public function logout(): ResponseInterface
1 ✔
139
    {
140
        $userId       = (int) $this->authInput('user_id');
1 ✔
141
        $refreshToken = (string) $this->authInput('refresh_token');
1 ✔
142

143
        if ($userId > 0 && $refreshToken !== '') {
1 ✔
144
            $repository = service('jwtTokenRepository');
1 ✔
145
            $identity   = $repository->getRefreshToken($userId, $refreshToken);
1 ✔
146

147
            if ($identity !== null) {
1 ✔
148
                $repository->softRevokeRefreshToken((int) $identity->id, $userId, 'logout');
1 ✔
149
            }
150
        }
151

152
        return $this->response->setJSON(['message' => lang('Auth.successLogout')]);
1 ✔
153
    }
154

155
    /**
156
     * Password-only JWT grants cannot satisfy a mandatory second factor.
157
     */
158
    protected function mandatoryMfaDenial(User $user, bool $verified): ?ResponseInterface
16 ✔
159
    {
160
        $policy = service('mfaPolicy');
16 ✔
161
        if (! $policy->requires($user) || $verified) {
16 ✔
162
            return null;
14 ✔
163
        }
164

165
        return $this->response->setStatusCode(403)->setJSON([
5 ✔
166
            'message' => lang('Auth.passwordConfirmRequired'),
5 ✔
167
            'error'   => $policy->hasFactor($user) ? 'mfa_required' : 'mfa_enrollment_required',
5 ✔
168
        ]);
5 ✔
169
    }
170

171
    /**
172
     * Verify a code or a second-factor proof bound to this same live session.
173
     */
174
    protected function verifyLoginMfa(User $user): bool
16 ✔
175
    {
176
        $session = $this->getSessionAuthenticator();
16 ✔
177
        $policy  = service('mfaPolicy');
16 ✔
178
        if (! $policy->hasFactor($user)) {
16 ✔
179
            return false;
13 ✔
180
        }
181
        if ($session->loggedIn() && (string) $session->getUser()?->id === (string) $user->id && $policy->verified($user)) {
4 ✔
182
            return true;
1 ✔
183
        }
184

185
        $code = (string) $this->authInput('mfa_code');
3 ✔
186
        if ($code === '') {
3 ✔
NEW
187
            return false;
×
188
        }
189
        if (($user->hasTotpEnabled() && $user->verifyTotpCode($code)) || $user->consumeBackupCode($code)) {
3 ✔
190
            return true;
2 ✔
191
        }
192
        $session->getLockoutManager()->recordFailedAttempt($user);
2 ✔
193

194
        return false;
2 ✔
195
    }
196

197
    /**
198
     * Builds the token pair response for a given user.
199
     *
200
     * Generates a JWT access token (via the configured adapter) and a new
201
     * opaque refresh token stored in the identities table.
202
     *
203
     * @param User $user
204
     *
205
     * @return array<string, mixed>
206
     */
207
    private function buildTokenResponse(object $user, ?string $rotatedRefresh = null, bool $mfaVerified = false): array
14 ✔
208
    {
209
        // Generate access token via the configured JWT adapter. The payload
210
        // embeds the user's current token_version so the token can be revoked
211
        // wholesale (ban / password change) without a per-token denylist.
212
        $adapterClass = setting('Auth.jwtAdapter');
14 ✔
213
        /** @var JWTAdapterInterface $adapter */
214
        $adapter     = new $adapterClass();
14 ✔
215
        $accessToken = $adapter->encode([
14 ✔
216
            'uid' => $user->id,
14 ✔
217
            'tv'  => (int) ($user->token_version ?? 0),
14 ✔
218
            'mfa' => $mfaVerified,
14 ✔
219
        ]);
14 ✔
220

221
        // Generate and persist a new refresh token
222
        $rawRefresh = $rotatedRefresh ?? bin2hex(random_bytes(32));
14 ✔
223
        $expiresAt  = Time::now()
14 ✔
224
            ->addSeconds((int) setting('AuthSecurity.jwtRefreshLifetime'))
14 ✔
225
            ->format('Y-m-d H:i:s');
14 ✔
226

227
        if ($rotatedRefresh === null) {
14 ✔
228
            service('jwtTokenRepository')->createRefreshToken((int) $user->id, $rawRefresh, $expiresAt, $mfaVerified);
14 ✔
229
        }
230

231
        return [
14 ✔
232
            'access_token'  => $accessToken,
14 ✔
233
            'refresh_token' => $rawRefresh,
14 ✔
234
            'user_id'       => $user->id,
14 ✔
235
            'token_type'    => 'Bearer',
14 ✔
236
        ];
14 ✔
237
    }
238
}
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