forked from ZyntariHQ/Invoisio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.guard.ts
More file actions
41 lines (35 loc) · 1.11 KB
/
Copy pathauth.guard.ts
File metadata and controls
41 lines (35 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import {
CanActivate,
ExecutionContext,
Injectable,
UnauthorizedException,
} from "@nestjs/common";
import { JwtService } from "@nestjs/jwt";
import type { Request } from "express";
/**
* JWT authentication guard
* Validates Bearer tokens on protected endpoints
*/
@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.extractBearerToken(request);
if (!token) {
throw new UnauthorizedException("No token provided");
}
try {
const payload = await this.jwtService.verifyAsync(token);
// Attach decoded payload to request for downstream use
request["user"] = payload;
} catch {
throw new UnauthorizedException("Invalid or expired token");
}
return true;
}
private extractBearerToken(request: Request): string | null {
const [type, token] = request.headers.authorization?.split(" ") ?? [];
return type === "Bearer" ? token : null;
}
}