实现博客评论
This commit is contained in:
@@ -9,6 +9,7 @@ import { PassportModule } from '@nestjs/passport';
|
||||
import { JwtStrategy } from './strategies/jwt.strategy';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { VerificationModule } from 'src/verification/verification.module';
|
||||
import { OptionalAuthGuard } from './strategies/OptionalAuthGuard';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -32,11 +33,13 @@ import { VerificationModule } from 'src/verification/verification.module';
|
||||
providers: [
|
||||
AuthService,
|
||||
JwtStrategy,
|
||||
OptionalAuthGuard,
|
||||
],
|
||||
exports: [
|
||||
PassportModule,
|
||||
JwtStrategy,
|
||||
AuthService,
|
||||
OptionalAuthGuard,
|
||||
]
|
||||
})
|
||||
export class AuthModule { }
|
||||
|
||||
22
tone-page-server/src/auth/strategies/OptionalAuthGuard.ts
Normal file
22
tone-page-server/src/auth/strategies/OptionalAuthGuard.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { CanActivate, ExecutionContext, Injectable } from "@nestjs/common";
|
||||
import { AuthGuard } from "@nestjs/passport";
|
||||
import { Observable, retry } from "rxjs";
|
||||
|
||||
@Injectable()
|
||||
export class OptionalAuthGuard extends AuthGuard('jwt') implements CanActivate {
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
try {
|
||||
await super.canActivate(context);
|
||||
return true;
|
||||
} catch (error) {
|
||||
return true;// 如果验证失败,仍然允许访问
|
||||
}
|
||||
}
|
||||
|
||||
handleRequest<TUser = any>(err: any, user: any, info: any, context: ExecutionContext, status?: any): TUser {
|
||||
if (err || !user) {
|
||||
return null; // 如果没有用户信息,返回null
|
||||
}
|
||||
return user; // 如果有用户信息,返回用户对象
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user