Files
qztool/backend/app/Services/OAuthService.php
T
DevandCursor 60daff2365 搭建轻舟一期门户、后台和统一登录。
让分类、会员和示例工具共用同一账号,本地即可跑通登录与授权。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-09 16:46:35 +08:00

289 lines
10 KiB
PHP

<?php
namespace App\Services;
use App\Models\OauthAccessToken;
use App\Models\OauthAuthCode;
use App\Models\OauthClient;
use App\Models\OauthRefreshToken;
use App\Models\Tool;
use App\Models\ToolOpenLog;
use App\Models\User;
use App\Models\UserToolOpen;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class OAuthService
{
public function __construct(private readonly MembershipService $membership) {}
public function clientFromRequest(Request $request): ?OauthClient
{
$clientId = (string) $request->input('client_id');
$client = OauthClient::query()->where('client_id', $clientId)->where('status', 'active')->first();
if (! $client) {
return null;
}
if ($client->is_public) {
return $client;
}
$secret = (string) $request->input('client_secret');
if ($secret === '' || ! hash_equals((string) $client->secret_hash, hash('sha256', $secret))) {
return null;
}
return $client;
}
/** @return list<string> */
public function scopes(string $scope): array
{
$allowed = ['openid', 'profile', 'membership'];
$items = array_values(array_filter(explode(' ', trim($scope))));
if ($items === []) {
$items = ['openid'];
}
foreach ($items as $item) {
if (! in_array($item, $allowed, true)) {
abort(400, '不支持的 scope');
}
}
if (! in_array('openid', $items, true)) {
array_unshift($items, 'openid');
}
return $items;
}
public function issueCode(OauthClient $client, User $user, array $input, array $scopes): string
{
$code = $this->random();
OauthAuthCode::query()->create([
'code_hash' => hash('sha256', $code),
'oauth_client_id' => $client->id,
'user_id' => $user->id,
'redirect_uri' => $input['redirect_uri'],
'scopes' => $scopes,
'nonce' => $input['nonce'] ?? null,
'code_challenge' => $input['code_challenge'],
'code_challenge_method' => 'S256',
'expires_at' => now()->addSeconds((int) config('qz.code_ttl')),
]);
if ($client->tool_id) {
$this->recordOpen($user, $client->tool_id);
}
return $code;
}
public function exchange(Request $request, OauthClient $client): array
{
$code = OauthAuthCode::query()->where('code_hash', hash('sha256', (string) $request->input('code')))->first();
if (! $code || $code->oauth_client_id !== $client->id) {
return $this->error('invalid_grant', '授权码无效');
}
if ($code->consumed_at) {
$this->revokeClientUser($client->id, $code->user_id);
return $this->error('invalid_grant', '授权码已使用');
}
if ($code->expires_at->isPast() || ! hash_equals($code->redirect_uri, (string) $request->input('redirect_uri'))) {
return $this->error('invalid_grant', '授权码已过期或回调不匹配');
}
if (! $this->pkce($code->code_challenge, (string) $request->input('code_verifier'))) {
return $this->error('invalid_grant', 'PKCE 校验失败');
}
$code->update(['consumed_at' => now()]);
$user = $code->user;
if (! $user || $user->status !== 'active') {
return $this->error('access_denied', '用户不可用');
}
return $this->mint($client, $user, $code->scopes ?? [], $code->nonce);
}
public function refresh(Request $request, OauthClient $client): array
{
$row = OauthRefreshToken::query()->where('token_hash', hash('sha256', (string) $request->input('refresh_token')))->first();
if (! $row || $row->oauth_client_id !== $client->id) {
return $this->error('invalid_grant', '刷新令牌无效');
}
if ($row->revoked_at) {
$this->revokeClientUser($client->id, $row->user_id);
return $this->error('invalid_grant', '刷新令牌已失效');
}
if ($row->expires_at->isPast()) {
return $this->error('invalid_grant', '刷新令牌已过期');
}
$user = $row->user;
if (! $user || $user->status !== 'active') {
return $this->error('access_denied', '用户不可用');
}
$scopes = $row->accessToken?->scopes ?? ['openid'];
$row->update(['revoked_at' => now()]);
$row->accessToken?->update(['revoked_at' => now()]);
return $this->mint($client, $user, $scopes, null);
}
public function userinfo(string $token): ?array
{
$access = $this->access($token);
if (! $access) {
return null;
}
$user = $access->user;
$client = $access->client;
$scopes = $access->scopes ?? [];
$slug = $client?->tool?->slug;
$payload = ['sub' => (string) $user->id];
if (in_array('profile', $scopes, true)) {
$payload['name'] = $user->nickname;
$payload['picture'] = null;
}
if (in_array('membership', $scopes, true)) {
$payload['membership'] = $this->membership->snapshot($user, $slug);
}
return $payload;
}
public function introspect(string $token): array
{
$access = $this->access($token);
if (! $access) {
return ['active' => false];
}
$user = $access->user;
return [
'active' => true,
'sub' => (string) $user->id,
'entitlement_version' => $access->entitlement_version,
'current_entitlement_version' => $user->entitlement_version,
'stale' => $access->entitlement_version !== $user->entitlement_version,
'exp' => $access->expires_at->timestamp,
];
}
public function revoke(string $token): void
{
$hash = hash('sha256', $token);
OauthAccessToken::query()->where('token_hash', $hash)->update(['revoked_at' => now()]);
$refresh = OauthRefreshToken::query()->where('token_hash', $hash)->first();
if ($refresh) {
$refresh->update(['revoked_at' => now()]);
$refresh->accessToken?->update(['revoked_at' => now()]);
}
}
private function mint(OauthClient $client, User $user, array $scopes, ?string $nonce): array
{
$accessPlain = $this->random();
$refreshPlain = $this->random();
$access = OauthAccessToken::query()->create([
'token_hash' => hash('sha256', $accessPlain),
'oauth_client_id' => $client->id,
'user_id' => $user->id,
'scopes' => $scopes,
'entitlement_version' => $user->entitlement_version,
'expires_at' => now()->addMinutes((int) config('qz.access_ttl')),
]);
OauthRefreshToken::query()->create([
'token_hash' => hash('sha256', $refreshPlain),
'oauth_access_token_id' => $access->id,
'oauth_client_id' => $client->id,
'user_id' => $user->id,
'expires_at' => now()->addDays((int) config('qz.refresh_ttl_days')),
]);
$now = time();
$idPayload = [
'iss' => config('app.url'),
'sub' => (string) $user->id,
'aud' => $client->client_id,
'exp' => $now + ((int) config('qz.access_ttl') * 60),
'iat' => $now,
'nonce' => $nonce,
'name' => in_array('profile', $scopes, true) ? $user->nickname : null,
];
return [
'token_type' => 'Bearer',
'access_token' => $accessPlain,
'expires_in' => (int) config('qz.access_ttl') * 60,
'refresh_token' => $refreshPlain,
'id_token' => $this->jwt($idPayload),
'scope' => implode(' ', $scopes),
];
}
private function access(string $token): ?OauthAccessToken
{
$row = OauthAccessToken::query()->with(['user', 'client.tool'])->where('token_hash', hash('sha256', $token))->first();
if (! $row || $row->revoked_at || $row->expires_at->isPast() || ! $row->user || $row->user->status !== 'active') {
return null;
}
return $row;
}
private function pkce(string $challenge, string $verifier): bool
{
if ($verifier === '') {
return false;
}
$computed = rtrim(strtr(base64_encode(hash('sha256', $verifier, true)), '+/', '-_'), '=');
return hash_equals($challenge, $computed);
}
private function revokeClientUser(int $clientId, int $userId): void
{
OauthAccessToken::query()->where('oauth_client_id', $clientId)->where('user_id', $userId)->update(['revoked_at' => now()]);
OauthRefreshToken::query()->where('oauth_client_id', $clientId)->where('user_id', $userId)->update(['revoked_at' => now()]);
}
private function recordOpen(User $user, int $toolId): void
{
DB::transaction(function () use ($user, $toolId) {
$open = UserToolOpen::query()->firstOrNew(['user_id' => $user->id, 'tool_id' => $toolId]);
$open->open_count = ($open->open_count ?? 0) + 1;
$open->last_opened_at = now();
$open->save();
ToolOpenLog::query()->create(['user_id' => $user->id, 'tool_id' => $toolId]);
Tool::query()->whereKey($toolId)->increment('clicks');
});
}
private function jwt(array $payload): string
{
$header = $this->b64(json_encode(['alg' => 'RS256', 'typ' => 'JWT'], JSON_UNESCAPED_UNICODE));
$body = $this->b64(json_encode($payload, JSON_UNESCAPED_UNICODE));
$data = $header.'.'.$body;
$private = file_get_contents(storage_path('app/keys/login-private.pem'));
if (! is_string($private) || $private === '') {
app(AuthService::class)->publicKeyPem();
$private = (string) file_get_contents(storage_path('app/keys/login-private.pem'));
}
openssl_sign($data, $signature, $private, OPENSSL_ALGO_SHA256);
return $data.'.'.$this->b64($signature);
}
private function b64(string $raw): string
{
return rtrim(strtr(base64_encode($raw), '+/', '-_'), '=');
}
private function random(): string
{
return rtrim(strtr(base64_encode(random_bytes(32)), '+/', '-_'), '=');
}
private function error(string $error, string $description): array
{
return ['error' => $error, 'error_description' => $description];
}
}