11import type { CanActivate , ExecutionContext } from '@nestjs/common'
2- import { Injectable , UnauthorizedException } from '@nestjs/common'
2+ import { Injectable , Logger } from '@nestjs/common'
3+ import { ErrorCodeEnum } from '~/constants/error-code.constant'
34import { AuthService } from '~/modules/auth/auth.service'
4- import { ConfigsService } from '~/modules/configs/configs.service'
5- import type { UserModel } from '~/modules/user/user.model'
6- import { UserService } from '~/modules/user/user.service'
5+ import type { SessionUser } from '~/modules/auth/auth.types'
76import type { FastifyBizRequest } from '~/transformers/get-req.transformer'
87import { getNestExecutionContextRequest } from '~/transformers/get-req.transformer'
9- import { isJWT } from '~/utils/validator.util '
8+ import { BizException } from '../exceptions/biz.exception '
109
1110/**
12- * JWT auth guard
11+ * Better Auth (cookie + API key) guard
1312 */
1413
1514@Injectable ( )
1615export class AuthGuard implements CanActivate {
17- constructor (
18- protected readonly authService : AuthService ,
19- protected readonly configs : ConfigsService ,
20-
21- protected readonly userService : UserService ,
22- ) { }
16+ protected readonly logger = new Logger ( AuthGuard . name )
17+ constructor ( protected readonly authService : AuthService ) { }
2318 async canActivate ( context : ExecutionContext ) : Promise < any > {
2419 const request = this . getRequest ( context )
2520
26- const query = request . query as any
27- const headers = request . headers
28-
2921 const session = await this . authService . getSessionUser ( request . raw )
3022
31- const Authorization : string =
32- headers . authorization || headers . Authorization || query . token
33-
3423 if ( session ) {
35- const isOwner = ! ! session . user ?. isOwner
24+ const isOwner = session . user ?. role === 'owner'
3625
3726 if ( isOwner ) {
3827 this . attachUserAndToken (
3928 request ,
40- await this . userService . getMaster ( ) ,
41- Authorization ,
29+ session . user as SessionUser ,
30+ session . session ?. token || '' ,
4231 )
4332 return true
4433 }
4534 }
4635
47- if ( ! Authorization ) {
48- throw new UnauthorizedException ( '未登录' )
36+ const apiKey = this . authService . getApiKeyFromRequest ( {
37+ headers : request . headers ,
38+ query : request . query as any ,
39+ } )
40+
41+ if ( ! apiKey ) {
42+ throw new BizException ( ErrorCodeEnum . AuthNotLoggedIn )
4943 }
5044
51- if ( this . authService . isCustomToken ( Authorization ) ) {
52- const [ isValid , userModel ] =
53- await this . authService . verifyCustomToken ( Authorization )
54- if ( ! isValid ) {
55- throw new UnauthorizedException ( '令牌无效' )
56- }
45+ if ( apiKey . deprecated ) {
46+ // this.logger.warn(
47+ // '[Auth] Authorization bearer token is deprecated. Use x-api-key instead.',
48+ // )
49+ }
5750
58- this . attachUserAndToken ( request , userModel , Authorization )
59- return true
51+ if ( ! this . authService . isCustomToken ( apiKey . key ) ) {
52+ throw new BizException ( ErrorCodeEnum . AuthTokenInvalid )
6053 }
6154
62- const jwt = Authorization . replace ( / [ B b ] e a r e r / , '' )
55+ const result = await this . authService . verifyApiKey ( apiKey . key )
56+ if ( ! result ?. userId ) {
57+ throw new BizException ( ErrorCodeEnum . AuthTokenInvalid )
58+ }
6359
64- if ( ! isJWT ( jwt ) ) {
65- throw new UnauthorizedException ( '令牌无效' )
60+ const isOwner = await this . authService . isOwnerReaderId ( result . userId )
61+ if ( ! isOwner ) {
62+ throw new BizException ( ErrorCodeEnum . AuthTokenInvalid )
6663 }
67- const valid = await this . authService . jwtServicePublic . verify ( jwt )
6864
69- if ( ! valid ) throw new UnauthorizedException ( '身份过期' )
70- this . attachUserAndToken (
71- request ,
72- await this . userService . getMaster ( ) ,
73- Authorization ,
74- )
65+ const readerUser = await this . authService . getReaderById ( result . userId )
66+ if ( ! readerUser ) {
67+ throw new BizException ( ErrorCodeEnum . AuthTokenInvalid )
68+ }
69+ this . attachUserAndToken ( request , readerUser , apiKey . key )
7570 return true
7671 }
7772
@@ -81,7 +76,7 @@ export class AuthGuard implements CanActivate {
8176
8277 attachUserAndToken (
8378 request : FastifyBizRequest ,
84- user : UserModel ,
79+ user : SessionUser ,
8580 token : string ,
8681 ) {
8782 request . user = user
0 commit comments