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
54 lines (48 loc) · 1.36 KB
/
Copy pathauth.guard.ts
File metadata and controls
54 lines (48 loc) · 1.36 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
42
43
44
45
46
47
48
49
50
51
52
53
54
import {
Injectable,
CanActivate,
ExecutionContext,
SetMetadata,
applyDecorators,
UseGuards,
createParamDecorator,
} from "@nestjs/common";
import { AuthGuard } from "@nestjs/passport";
import { Reflector } from "@nestjs/core";
import { User } from "../../users/user.entity";
export const IS_PUBLIC_KEY = "isPublic";
/** Mark a route as publicly accessible (no JWT required). */
export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);
/**
* JWT authentication guard.
* Apply globally or per-controller; use @Public() to opt out.
*/
@Injectable()
export class JwtAuthGuard extends AuthGuard("jwt") implements CanActivate {
constructor(protected readonly reflector: Reflector) {
super();
}
canActivate(context: ExecutionContext) {
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
context.getHandler(),
context.getClass(),
]);
if (isPublic) return true;
return super.canActivate(context);
}
}
/**
* Convenience decorator that applies JWT guard to a route.
*
* Usage:
* @Auth()
* @Get('profile')
* getProfile(@Req() req) { ... }
*/
export const Auth = () => applyDecorators(UseGuards(JwtAuthGuard));
export const CurrentUser = createParamDecorator(
(_data: unknown, ctx: ExecutionContext): User => {
const request = ctx.switchToHttp().getRequest();
return request.user;
},
);