34 lines
1.0 KiB
TypeScript
34 lines
1.0 KiB
TypeScript
import { ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
|
|
import { Reflector } from '@nestjs/core';
|
|
import { AuthGuard } from '@nestjs/passport';
|
|
import { Observable } from 'rxjs';
|
|
import { SKIP_AUTH_KEY } from 'src/common/decorators/skip-auth.decorator';
|
|
import { AuthMessages } from 'src/common/enums/messages.enum';
|
|
import { JWT_STRATEGY_NAME } from 'src/constants';
|
|
|
|
@Injectable()
|
|
export class JwtAuthGuard extends AuthGuard(JWT_STRATEGY_NAME) {
|
|
constructor(private reflector: Reflector) {
|
|
super();
|
|
}
|
|
|
|
canActivate(
|
|
context: ExecutionContext,
|
|
): boolean | Promise<boolean> | Observable<boolean> {
|
|
const skipAuth = this.reflector.getAllAndOverride<boolean>(SKIP_AUTH_KEY, [
|
|
context.getHandler(),
|
|
context.getClass(),
|
|
]);
|
|
|
|
if (skipAuth) return true;
|
|
|
|
return super.canActivate(context);
|
|
}
|
|
|
|
handleRequest(err: unknown, user: any, _info: unknown) {
|
|
if (err || !user)
|
|
throw new UnauthorizedException(AuthMessages.TOKEN_EXPIRED_OR_INVALID);
|
|
return user;
|
|
}
|
|
}
|