hospital-log/backend/api/src/modules/auth/guard/auth.guard.ts

52 lines
1.3 KiB
TypeScript
Raw Normal View History

import {
CanActivate,
ExecutionContext,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
import { Request } from 'express';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(
private jwtService: JwtService,
private configService: ConfigService,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const jwtToken = this.extractTokenFromCookie(request);
const csrfToken = this.extractTokenFromHeader(request);
if (!jwtToken || !csrfToken) {
throw new UnauthorizedException();
}
try {
const payload = await this.jwtService.verifyAsync(jwtToken, {
secret: this.configService.get<string>('JWT_SECRET'),
});
if (payload.csrf !== csrfToken) {
throw new UnauthorizedException('Invalid CSRF token');
}
request['user'] = payload;
} catch {
throw new UnauthorizedException();
}
return true;
}
private extractTokenFromHeader(request: any): string | undefined {
const token = request.headers['x-csrf-token'];
return token;
}
private extractTokenFromCookie(request: Request): string | undefined {
return request.cookies?.access_token;
}
}