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