Files
zod-backend/src/common/guards/access-token.guard.ts
2024-12-22 10:47:59 +03:00

35 lines
994 B
TypeScript

import { ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { AuthGuard } from '@nestjs/passport';
import { IS_PUBLIC_KEY } from '../decorators';
import { CacheService } from '../modules/cache/services';
@Injectable()
export class AccessTokenGuard extends AuthGuard('access-token') {
constructor(protected reflector: Reflector, private readonly cacheService: CacheService) {
super();
}
async canActivate(context: ExecutionContext) {
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
context.getHandler(),
context.getClass(),
]);
if (isPublic) {
return true;
}
await super.canActivate(context);
const token = context.switchToHttp().getRequest().headers['authorization']?.split(' ')[1];
const isRevoked = await this.cacheService.get(token);
if (isRevoked) {
throw new UnauthorizedException();
}
return true;
}
}