1<?php
2
3// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
4// See the LICENCE file in the repository root for full licence text.
5
6declare(strict_types=1);
7
8namespace App\Libraries\OAuth;
9
10use App\Models\OAuth\Token;
11use Defuse\Crypto\Crypto;
12use Firebase\JWT\JWT;
13use Laravel\Passport\Passport;
14use Laravel\Passport\RefreshToken;
15
16class EncodeToken
17{
18 public static function encodeAccessToken(Token $token): string
19 {
20 $privateKey = $GLOBALS['cfg']['passport']['private_key']
21 ?? file_get_contents(Passport::keyPath('oauth-private.key'));
22
23 return JWT::encode([
24 'aud' => $token->client_id,
25 'exp' => $token->expires_at->timestamp,
26 'iat' => $token->created_at->timestamp, // issued at
27 'jti' => $token->getKey(),
28 'nbf' => $token->created_at->timestamp, // valid after
29 'sub' => $token->user_id,
30 'scopes' => $token->scopes,
31 ], $privateKey, 'RS256');
32 }
33
34 public static function encodeRefreshToken(RefreshToken $refreshToken, Token $accessToken): string
35 {
36 return Crypto::encryptWithPassword(json_encode([
37 'client_id' => (string) $accessToken->client_id,
38 'refresh_token_id' => $refreshToken->getKey(),
39 'access_token_id' => $accessToken->getKey(),
40 'scopes' => $accessToken->scopes,
41 'user_id' => $accessToken->user_id,
42 'expire_time' => $refreshToken->expires_at->timestamp,
43 ]), \Crypt::getKey());
44 }
45}