50 lines
1.2 KiB
TypeScript
50 lines
1.2 KiB
TypeScript
|
|
import {
|
||
|
|
CanActivate,
|
||
|
|
ExecutionContext,
|
||
|
|
Injectable,
|
||
|
|
UnauthorizedException,
|
||
|
|
} from '@nestjs/common';
|
||
|
|
import { Reflector } from '@nestjs/core';
|
||
|
|
import { IS_PUBLIC_KEY } from '../decorators/public.decorator';
|
||
|
|
import { AuthTokenService } from '../auth-token.service';
|
||
|
|
|
||
|
|
@Injectable()
|
||
|
|
export class JwtAuthGuard implements CanActivate {
|
||
|
|
constructor(
|
||
|
|
private readonly reflector: Reflector,
|
||
|
|
private readonly authToken: AuthTokenService,
|
||
|
|
) {}
|
||
|
|
|
||
|
|
canActivate(context: ExecutionContext) {
|
||
|
|
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
|
||
|
|
context.getHandler(),
|
||
|
|
context.getClass(),
|
||
|
|
]);
|
||
|
|
|
||
|
|
if (isPublic) {
|
||
|
|
return true;
|
||
|
|
}
|
||
|
|
|
||
|
|
const request = context.switchToHttp().getRequest();
|
||
|
|
const token = this.extractBearerToken(request.headers?.authorization);
|
||
|
|
|
||
|
|
if (!token) {
|
||
|
|
throw new UnauthorizedException('Token de autenticação não informado');
|
||
|
|
}
|
||
|
|
|
||
|
|
request.user = this.authToken.verifyToken(token);
|
||
|
|
|
||
|
|
return true;
|
||
|
|
}
|
||
|
|
|
||
|
|
private extractBearerToken(authorization?: string) {
|
||
|
|
const [type, token] = String(authorization || '').split(' ');
|
||
|
|
|
||
|
|
if (type?.toLowerCase() !== 'bearer' || !token) {
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
|
||
|
|
return token;
|
||
|
|
}
|
||
|
|
}
|