/opt/mawid/apps/api/src/auth
Edit: /opt/mawid/apps/api/src/auth/jwt-auth.guard.ts (1100B)
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { JwtService } from '@nestjs/jwt';
import { IS_PUBLIC_KEY } from './public.decorator';
@Injectable()
export class JwtAuthGuard implements CanActivate {
constructor(
private readonly jwtService: JwtService,
private readonly reflector: Reflector,
) {}
async canActivate(context: ExecutionContext): Promise
{
const isPublic = this.reflector.getAllAndOverride(IS_PUBLIC_KEY, [
context.getHandler(),
context.getClass(),
]);
if (isPublic) return true;
const request = context.switchToHttp().getRequest();
const header: string | undefined = request.headers?.authorization;
if (!header?.startsWith('Bearer ')) {
throw new UnauthorizedException('Missing bearer token');
}
try {
request.user = await this.jwtService.verifyAsync(header.slice('Bearer '.length));
} catch {
throw new UnauthorizedException('Invalid or expired token');
}
return true;
}
}