|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace CodeIgniter\Shield\Authentication\Authenticators; |
| 4 | + |
| 5 | +use CodeIgniter\HTTP\IncomingRequest; |
| 6 | +use CodeIgniter\I18n\Time; |
| 7 | +use CodeIgniter\Shield\Authentication\AuthenticationException; |
| 8 | +use CodeIgniter\Shield\Authentication\AuthenticatorInterface; |
| 9 | +use CodeIgniter\Shield\Authentication\Authenticators\JWT\Firebase; |
| 10 | +use CodeIgniter\Shield\Authentication\Authenticators\JWT\JWTDecoderInterface; |
| 11 | +use CodeIgniter\Shield\Entities\User; |
| 12 | +use CodeIgniter\Shield\Exceptions\RuntimeException; |
| 13 | +use CodeIgniter\Shield\Models\TokenLoginModel; |
| 14 | +use CodeIgniter\Shield\Models\UserModel; |
| 15 | +use CodeIgniter\Shield\Result; |
| 16 | +use InvalidArgumentException; |
| 17 | +use stdClass; |
| 18 | + |
| 19 | +/** |
| 20 | + * Stateless JWT Authenticator |
| 21 | + */ |
| 22 | +class JWT implements AuthenticatorInterface |
| 23 | +{ |
| 24 | + /** |
| 25 | + * @var string Special ID Type. |
| 26 | + * This Authenticator is stateless, so no `auth_identities` record. |
| 27 | + */ |
| 28 | + public const ID_TYPE_JWT = 'jwt'; |
| 29 | + |
| 30 | + /** |
| 31 | + * The persistence engine |
| 32 | + */ |
| 33 | + protected UserModel $provider; |
| 34 | + |
| 35 | + protected ?User $user = null; |
| 36 | + protected JWTDecoderInterface $jwtDecoder; |
| 37 | + protected TokenLoginModel $loginModel; |
| 38 | + protected ?stdClass $payload = null; |
| 39 | + |
| 40 | + public function __construct(UserModel $provider, ?JWTDecoderInterface $jwtDecoder = null) |
| 41 | + { |
| 42 | + $this->provider = $provider; |
| 43 | + $this->jwtDecoder = $jwtDecoder ?? new Firebase(); |
| 44 | + |
| 45 | + $this->loginModel = model(TokenLoginModel::class); // @phpstan-ignore-line |
| 46 | + } |
| 47 | + |
| 48 | + /** |
| 49 | + * Attempts to authenticate a user with the given $credentials. |
| 50 | + * Logs the user in with a successful check. |
| 51 | + * |
| 52 | + * @param array{token?: string} $credentials |
| 53 | + */ |
| 54 | + public function attempt(array $credentials): Result |
| 55 | + { |
| 56 | + /** @var IncomingRequest $request */ |
| 57 | + $request = service('request'); |
| 58 | + |
| 59 | + $ipAddress = $request->getIPAddress(); |
| 60 | + $userAgent = $request->getUserAgent(); |
| 61 | + |
| 62 | + $result = $this->check($credentials); |
| 63 | + |
| 64 | + if (! $result->isOK()) { |
| 65 | + // Always record a login attempt, whether success or not. |
| 66 | + $this->loginModel->recordLoginAttempt( |
| 67 | + self::ID_TYPE_JWT, |
| 68 | + $credentials['token'] ?? '', |
| 69 | + false, |
| 70 | + $ipAddress, |
| 71 | + $userAgent |
| 72 | + ); |
| 73 | + |
| 74 | + return $result; |
| 75 | + } |
| 76 | + |
| 77 | + $user = $result->extraInfo(); |
| 78 | + |
| 79 | + $this->login($user); |
| 80 | + |
| 81 | + $this->loginModel->recordLoginAttempt( |
| 82 | + self::ID_TYPE_JWT, |
| 83 | + $credentials['token'] ?? '', |
| 84 | + true, |
| 85 | + $ipAddress, |
| 86 | + $userAgent, |
| 87 | + $this->user->id |
| 88 | + ); |
| 89 | + |
| 90 | + return $result; |
| 91 | + } |
| 92 | + |
| 93 | + /** |
| 94 | + * Checks a user's $credentials to see if they match an |
| 95 | + * existing user. |
| 96 | + * |
| 97 | + * In this case, $credentials has only a single valid value: token, |
| 98 | + * which is the plain text token to return. |
| 99 | + * |
| 100 | + * @param array{token?: string} $credentials |
| 101 | + */ |
| 102 | + public function check(array $credentials): Result |
| 103 | + { |
| 104 | + if (! array_key_exists('token', $credentials) || $credentials['token'] === '') { |
| 105 | + return new Result([ |
| 106 | + 'success' => false, |
| 107 | + 'reason' => lang('Auth.noToken'), |
| 108 | + ]); |
| 109 | + } |
| 110 | + |
| 111 | + if (strpos($credentials['token'], 'Bearer') === 0) { |
| 112 | + $credentials['token'] = trim(substr($credentials['token'], 6)); |
| 113 | + } |
| 114 | + |
| 115 | + // Check JWT |
| 116 | + try { |
| 117 | + $this->payload = $this->decodeJWT($credentials['token']); |
| 118 | + } catch (RuntimeException $e) { |
| 119 | + return new Result([ |
| 120 | + 'success' => false, |
| 121 | + 'reason' => $e->getMessage(), |
| 122 | + ]); |
| 123 | + } |
| 124 | + |
| 125 | + $userId = $this->payload->sub ?? null; |
| 126 | + |
| 127 | + if ($userId === null) { |
| 128 | + return new Result([ |
| 129 | + 'success' => false, |
| 130 | + 'reason' => 'Invalid JWT: no user_id', |
| 131 | + ]); |
| 132 | + } |
| 133 | + |
| 134 | + // Find User |
| 135 | + $user = $this->provider->findById($userId); |
| 136 | + |
| 137 | + if ($user === null) { |
| 138 | + return new Result([ |
| 139 | + 'success' => false, |
| 140 | + 'reason' => lang('Auth.invalidUser'), |
| 141 | + ]); |
| 142 | + } |
| 143 | + |
| 144 | + return new Result([ |
| 145 | + 'success' => true, |
| 146 | + 'extraInfo' => $user, |
| 147 | + ]); |
| 148 | + } |
| 149 | + |
| 150 | + /** |
| 151 | + * Checks if the user is currently logged in. |
| 152 | + * Since AccessToken usage is inherently stateless, |
| 153 | + * it runs $this->attempt on each usage. |
| 154 | + */ |
| 155 | + public function loggedIn(): bool |
| 156 | + { |
| 157 | + if ($this->user !== null) { |
| 158 | + return true; |
| 159 | + } |
| 160 | + |
| 161 | + /** @var IncomingRequest $request */ |
| 162 | + $request = service('request'); |
| 163 | + |
| 164 | + return $this->attempt([ |
| 165 | + 'token' => $request->getHeaderLine(config('Auth')->authenticatorHeader['jwt']), |
| 166 | + ])->isOK(); |
| 167 | + } |
| 168 | + |
| 169 | + /** |
| 170 | + * Logs the given user in by saving them to the class. |
| 171 | + */ |
| 172 | + public function login(User $user): void |
| 173 | + { |
| 174 | + $this->user = $user; |
| 175 | + } |
| 176 | + |
| 177 | + /** |
| 178 | + * Logs a user in based on their ID. |
| 179 | + * |
| 180 | + * @param int|string $userId |
| 181 | + * |
| 182 | + * @throws AuthenticationException |
| 183 | + */ |
| 184 | + public function loginById($userId): void |
| 185 | + { |
| 186 | + $user = $this->provider->findById($userId); |
| 187 | + |
| 188 | + if ($user === null) { |
| 189 | + throw AuthenticationException::forInvalidUser(); |
| 190 | + } |
| 191 | + |
| 192 | + $this->login($user); |
| 193 | + } |
| 194 | + |
| 195 | + /** |
| 196 | + * Logs the current user out. |
| 197 | + */ |
| 198 | + public function logout(): bool |
| 199 | + { |
| 200 | + $this->user = null; |
| 201 | + |
| 202 | + return true; |
| 203 | + } |
| 204 | + |
| 205 | + /** |
| 206 | + * Returns the currently logged in user. |
| 207 | + */ |
| 208 | + public function getUser(): ?User |
| 209 | + { |
| 210 | + return $this->user; |
| 211 | + } |
| 212 | + |
| 213 | + /** |
| 214 | + * Updates the user's last active date. |
| 215 | + */ |
| 216 | + public function recordActiveDate(): void |
| 217 | + { |
| 218 | + if (! $this->user instanceof User) { |
| 219 | + throw new InvalidArgumentException( |
| 220 | + __METHOD__ . '() requires logged in user before calling.' |
| 221 | + ); |
| 222 | + } |
| 223 | + |
| 224 | + $this->user->last_active = Time::now(); |
| 225 | + |
| 226 | + $this->provider->save($this->user); |
| 227 | + } |
| 228 | + |
| 229 | + /** |
| 230 | + * Returns payload of the JWT |
| 231 | + */ |
| 232 | + public function decodeJWT(string $encodedToken): stdClass |
| 233 | + { |
| 234 | + return $this->jwtDecoder->decode($encodedToken); |
| 235 | + } |
| 236 | + |
| 237 | + /** |
| 238 | + * Returns payload |
| 239 | + */ |
| 240 | + public function getPayload(): ?stdClass |
| 241 | + { |
| 242 | + return $this->payload; |
| 243 | + } |
| 244 | +} |
0 commit comments