Skip to content

Commit 39ff851

Browse files
committed
feat: enhance authentication with JWT strategy and user decorators
- Implemented JwtStrategy for handling JWT authentication, extracting user payload from tokens. - Created JwtAuthGuard to manage access control based on public metadata. - Introduced user decorators to simplify access to authenticated user data in controllers. - Updated EmailController to utilize user information for email operations. - Added public health check endpoint to allow unauthenticated access. - Included new JWT payload DTO for structured token data handling. - Added unit tests for JwtStrategy to ensure correct payload validation.
1 parent 990bf15 commit 39ff851

13 files changed

Lines changed: 416 additions & 44 deletions

package-lock.json

Lines changed: 221 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@
3434
"@nestjs/config": "^4.0.3",
3535
"@nestjs/core": "^11.1.15",
3636
"@nestjs/event-emitter": "^3.0.1",
37+
"@nestjs/jwt": "^11.0.2",
38+
"@nestjs/passport": "^11.0.5",
3739
"@nestjs/platform-express": "^11.1.15",
3840
"@nestjs/sequelize": "^11.0.1",
3941
"@nestjs/swagger": "^11.2.6",
@@ -43,6 +45,8 @@
4345
"helmet": "^8.1.0",
4446
"nanoid": "^5.1.5",
4547
"nestjs-pino": "^4.6.0",
48+
"passport": "^0.7.0",
49+
"passport-jwt": "^4.0.1",
4650
"pg": "^8.20.0",
4751
"pino-http": "^11.0.0",
4852
"pino-pretty": "^13.1.3",
@@ -64,6 +68,7 @@
6468
"@types/chance": "^1.1.7",
6569
"@types/express": "^5.0.6",
6670
"@types/node": "^22.15.0",
71+
"@types/passport-jwt": "^4.0.1",
6772
"@vitest/coverage-v8": "^3.2.4",
6873
"chance": "^1.1.13",
6974
"eslint": "^9.18.0",

src/modules/auth/auth.guard.ts

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,24 @@
1-
import {
2-
type CanActivate,
3-
type ExecutionContext,
4-
Injectable,
5-
} from '@nestjs/common';
1+
import { Injectable, type ExecutionContext } from '@nestjs/common';
2+
import { Reflector } from '@nestjs/core';
3+
import { AuthGuard } from '@nestjs/passport';
4+
import { IS_PUBLIC_KEY } from './decorators/public.decorator.js';
65

76
@Injectable()
8-
export class AuthGuard implements CanActivate {
9-
canActivate(_context: ExecutionContext): boolean {
10-
return true;
7+
export class JwtAuthGuard extends AuthGuard('jwt') {
8+
constructor(private readonly reflector: Reflector) {
9+
super();
10+
}
11+
12+
canActivate(context: ExecutionContext) {
13+
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
14+
context.getHandler(),
15+
context.getClass(),
16+
]);
17+
18+
if (isPublic) {
19+
return true;
20+
}
21+
22+
return super.canActivate(context);
1123
}
1224
}

0 commit comments

Comments
 (0)