Files
yara724api/src/common/auth/guards/auth.guard.ts
2026-06-15 11:27:25 +03:30

36 lines
1.1 KiB
TypeScript

import {
CanActivate,
ExecutionContext,
Injectable,
UnauthorizedException,
} from "@nestjs/common";
import { JwtService } from "@nestjs/jwt";
import { Request } from "express";
import { JwtPayload } from "../types/payload.types";
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private readonly jwtService: JwtService) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<Request>();
const token = this.extractTokenFromHeader(request);
if (!token) {
throw new UnauthorizedException("No token provided");
}
try {
const payload: JwtPayload =
await this.jwtService.verifyAsync<JwtPayload>(token);
request["user"] = payload;
} catch {
throw new UnauthorizedException("Invalid or expired token");
}
return true;
}
private extractTokenFromHeader(request: Request): string | undefined {
const [type, token] = request.headers.authorization?.split(" ") ?? [];
return type === "Bearer" ? token : undefined;
}
}