validate([ 'grant_type' => ['required', 'in:authorization_code'], 'client_id' => ['required', 'string'], 'code' => ['required', 'string'], 'redirect_uri' => ['required', 'string'], 'code_verifier' => [ 'required', 'string', 'regex:/^[A-Za-z0-9._~-]{43,128}$/', ], ]); $challenge = rtrim( strtr( base64_encode(hash('sha256', $data['code_verifier'], true)), '+/', '-_' ), '=' ); $result = DB::transaction(function () use ($data, $challenge): ?array { $authorization = DB::table('helpdesk_native_authorization_codes') ->where('code_hash', hash('sha256', $data['code'])) ->lockForUpdate() ->first(); if (! $authorization) { return null; } if ( $authorization->consumed_at !== null || now()->greaterThanOrEqualTo($authorization->expires_at) || ! hash_equals($authorization->client_id, $data['client_id']) || ! hash_equals($authorization->redirect_uri, $data['redirect_uri']) || $authorization->code_challenge_method !== 'S256' || ! hash_equals($authorization->code_challenge, $challenge) ) { return null; } $user = User::query()->find($authorization->user_id); if (! $user) { return null; } DB::table('helpdesk_native_authorization_codes') ->where('id', $authorization->id) ->update([ 'consumed_at' => now(), 'updated_at' => now(), ]); $token = $user->createToken( 'HelpdeskMac', ['helpdesk:native'], now()->addDays( (int) config('helpdesk-native.access_token_lifetime_days', 30) ) ); return [ 'access_token' => $token->plainTextToken, 'token_type' => 'Bearer', 'expires_at' => $token->accessToken->expires_at?->toIso8601String(), 'user' => [ 'id' => $user->getKey(), 'name' => $user->name, 'email' => $user->email, ], ]; }); if ($result === null) { throw ValidationException::withMessages([ 'code' => ['Invalid or expired authorization code.'], ]); } return response()->json($result) ->header('Cache-Control', 'no-store') ->header('Pragma', 'no-cache'); } }