feat: 支持登录、个人信息存储
This commit is contained in:
45
src/common/guards/jwt-auth.guard.ts
Normal file
45
src/common/guards/jwt-auth.guard.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { Request } from 'express';
|
||||
|
||||
export interface JwtPayload {
|
||||
sub: string; // user id
|
||||
openid: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class JwtAuthGuard implements CanActivate {
|
||||
constructor(private readonly jwtService: JwtService) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest<Request>();
|
||||
const token = this.extractToken(request);
|
||||
|
||||
if (!token) {
|
||||
throw new UnauthorizedException('未提供访问令牌');
|
||||
}
|
||||
|
||||
try {
|
||||
const payload = await this.jwtService.verifyAsync<JwtPayload>(token);
|
||||
// 将用户信息挂载到 request 上
|
||||
(request as any).user = payload;
|
||||
} catch {
|
||||
throw new UnauthorizedException('访问令牌无效或已过期');
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private extractToken(request: Request): string | null {
|
||||
const authorization = request.headers.authorization;
|
||||
if (!authorization) return null;
|
||||
|
||||
const [type, token] = authorization.split(' ');
|
||||
return type === 'Bearer' ? token : null;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user