book_manage/apps/server/src/auth/auth.guard.ts

37 lines
1016 B
TypeScript
Executable File

import {
CanActivate,
ExecutionContext,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { env } from '@server/env';
import { JwtPayload } from '@nice/common';
import { extractTokenFromHeader } from './utils';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private jwtService: JwtService) { }
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const token = extractTokenFromHeader(request);
if (!token) {
throw new UnauthorizedException();
}
try {
const payload: JwtPayload = await this.jwtService.verifyAsync(
token,
{
secret: env.JWT_SECRET
}
);
request['user'] = payload;
} catch {
throw new UnauthorizedException();
}
return true;
}
}