Files
api_directorio/src/auth/auth.guard.ts
T

43 lines
1.2 KiB
TypeScript
Raw Normal View History

2024-06-06 20:32:46 -06:00
import {
CanActivate,
ExecutionContext,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { Request } from 'express';
import { ConfigService } from '@nestjs/config';
@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 token = this.extractTokenFromHeader(request);
if (!token) {
2024-06-25 20:11:55 -06:00
throw new UnauthorizedException('token faltante');
2024-06-06 20:32:46 -06:00
}
try {
const payload = await this.jwtService.verifyAsync(
token,
{
secret: this.configService.get('JWT_SECRET'),
}
);
request['user'] = payload;
} catch {
2024-06-25 20:11:55 -06:00
throw new UnauthorizedException('algo fallo');
2024-06-06 20:32:46 -06:00
}
return true;
}
private extractTokenFromHeader(request: Request): string | undefined {
const [type, token] = request.headers.authorization?.split(' ') ?? [];
return type === 'Bearer' ? token : undefined;
}
}