feat: auth guard 增加
This commit is contained in:
1 parent
346742b157
commit
a2ee53f83a
11 files changed
+245
-6
No files matched your search
@@ -0,0 +1,61 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { UserService } from '../service/user.service';
|
||||
import { NO_AUTH_KEY } from '../decorators/no-auth.decorator';
|
||||
import { JWT_SECRET } from '../constants/jwt';
|
||||
|
||||
@Injectable()
|
||||
export class AuthGuard implements CanActivate {
|
||||
constructor(
|
||||
private readonly reflector: Reflector,
|
||||
private readonly jwtService: JwtService,
|
||||
private readonly userService: UserService, // 注入 UserService
|
||||
) {}
|
||||
async canActivate(context: ExecutionContext) {
|
||||
const isNoAuth = this.reflector.getAllAndOverride<boolean>(NO_AUTH_KEY, [
|
||||
context.getHandler(),
|
||||
context.getClass(),
|
||||
]);
|
||||
|
||||
if (isNoAuth) {
|
||||
return true;
|
||||
}
|
||||
// 获取请求对象
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const token = this.extractTokenFromHeader(request);
|
||||
if (!token) {
|
||||
throw new UnauthorizedException('Missing authorization token');
|
||||
}
|
||||
try {
|
||||
// 验证并解析 JWT
|
||||
const payload = await this.jwtService.verifyAsync(token, {
|
||||
secret: JWT_SECRET,
|
||||
});
|
||||
|
||||
// 从 UserService 加载用户
|
||||
const user = await this.userService.findById(payload.sub);
|
||||
if (!user) {
|
||||
throw new UnauthorizedException('User not found');
|
||||
}
|
||||
|
||||
// 将用户信息附加到请求对象
|
||||
request.user = user;
|
||||
return true;
|
||||
} catch (error) {
|
||||
throw new UnauthorizedException('Invalid token');
|
||||
}
|
||||
}
|
||||
private extractTokenFromHeader(request: any): string | null {
|
||||
const authHeader = request.headers['Authorization'];
|
||||
if (!authHeader || !authHeader.startsWith('Bearer ')) {
|
||||
return null;
|
||||
}
|
||||
return authHeader.split(' ')[1];
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user