@next-nest-auth/nestauth 1.2.5 → 1.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@next-nest-auth/nestauth",
3
- "version": "1.2.5",
3
+ "version": "1.2.7",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "scripts": {
@@ -32,8 +32,8 @@
32
32
  "type": "commonjs",
33
33
  "description": "NestAuth is an authentication solution for NestJS applications, designed to handle user login, session management, and token-based authentication (JWT). It integrates seamlessly with Next.js and other frontends to provide a unified authentication system, supporting features like refresh tokens, secure cookie handling, and multi-provider authentication.",
34
34
  "dependencies": {
35
- "@nestjs/common": "^11.1.11",
36
- "@nestjs/config": "^4.0.2",
35
+ "@nestjs/common": "^11.1.13",
36
+ "@nestjs/config": "^4.0.3",
37
37
  "@nestjs/jwt": "^11.0.2",
38
38
  "@nestjs/passport": "^11.0.5",
39
39
  "bcryptjs": "^3.0.3",
@@ -48,7 +48,7 @@
48
48
  },
49
49
  "devDependencies": {
50
50
  "@nestjs/schematics": "^11.0.9",
51
- "@nestjs/testing": "^11.1.11",
51
+ "@nestjs/testing": "^11.1.13",
52
52
  "@types/bcryptjs": "^3.0.0",
53
53
  "@types/passport-facebook": "^3.0.4",
54
54
  "@types/passport-google-oauth20": "^2.0.17",
@@ -1,5 +1,12 @@
1
1
  import { Injectable } from "@nestjs/common";
2
2
  import { AuthGuard } from "@nestjs/passport";
3
3
 
4
- @Injectable()
5
- export class NestAuthLocalGuard extends AuthGuard("nestauth-local") {}
4
+ // @Injectable()
5
+ // export class NestAuthLocalGuard extends AuthGuard("nestauth-local") {}
6
+
7
+ export function createLocalGuard(strategyName: string) {
8
+ @Injectable()
9
+ class NestAuthLocalGuard extends AuthGuard(strategyName) {}
10
+
11
+ return NestAuthLocalGuard;
12
+ }
@@ -4,23 +4,51 @@ import { Inject, Injectable, UnauthorizedException } from "@nestjs/common";
4
4
  import { NestAuthInterface } from "./nestauth.interface";
5
5
  import * as macaddress from "macaddress";
6
6
 
7
- @Injectable()
8
- export class NestAuthLocalStrategy extends PassportStrategy(
9
- Strategy,
10
- "nestauth-local"
7
+ // @Injectable()
8
+ // export class NestAuthLocalStrategy extends PassportStrategy(
9
+ // Strategy,
10
+ // "nestauth-local",
11
+ // ) {
12
+ // constructor(private readonly userService: NestAuthInterface) {
13
+ // super();
14
+ // }
15
+
16
+ // async validate(req: Request): Promise<any> {
17
+ // console.log
18
+ // const user = await this.userService.validateUser(req.body);
19
+ // if (!user) {
20
+ // throw new UnauthorizedException("Invalid credentials");
21
+ // }
22
+ // user.macId = await macaddress.one();
23
+ // return user;
24
+ // }
25
+ // }
26
+
27
+ export function createLocalStrategy(
28
+ strategyName: string,
29
+ userServiceToken: string,
11
30
  ) {
12
- constructor(
13
- @Inject("UserService") private readonly userService: NestAuthInterface
31
+ @Injectable()
32
+ class NestAuthLocalStrategy extends PassportStrategy(
33
+ Strategy,
34
+ strategyName,
14
35
  ) {
15
- super();
16
- }
36
+ constructor(
37
+ @Inject(userServiceToken)
38
+ readonly userService: NestAuthInterface,
39
+ ) {
40
+ super();
41
+ }
17
42
 
18
- async validate(req: Request): Promise<any> {
19
- const user = await this.userService.validateUser(req.body);
20
- if (!user) {
21
- throw new UnauthorizedException("Invalid credentials");
43
+ async validate(req: Request): Promise<any> {
44
+ const user = await this.userService.validateUser(req.body);
45
+ if (!user) {
46
+ throw new UnauthorizedException("Invalid credentials");
47
+ }
48
+ user.macId = await macaddress.one();
49
+ return user;
22
50
  }
23
- user.macId = await macaddress.one();
24
- return user;
25
51
  }
52
+
53
+ return NestAuthLocalStrategy;
26
54
  }
@@ -1,71 +1,93 @@
1
1
  import {
2
2
  Request,
3
+ Controller,
3
4
  Get,
4
5
  Post,
5
6
  UseGuards,
6
7
  Body,
7
8
  UnauthorizedException,
8
9
  HttpStatus,
10
+ All,
9
11
  BadRequestException,
12
+ UseFilters,
13
+ Inject,
10
14
  } from "@nestjs/common";
11
15
  import { NestAuthService } from "./nestauth.service";
12
- import { NestAuthLocalGuard } from "./nestauth-local.guard";
13
16
  import { NestAuthGoogleGuard } from "./nestauth-google.guard";
14
17
  import { NestAuthFacebookGuard } from "./nestauth-facebook.guard";
18
+ import { HttpExceptionFilter } from "./http-exception.filter";
15
19
 
16
- export class NestAuthController {
17
- constructor(private readonly nestAuthService: NestAuthService) {}
20
+ export function createDynamicController(
21
+ prefix: string,
22
+ nestAuthServiceToken: string,
23
+ localGuard: any,
24
+ ) {
25
+ @UseFilters(HttpExceptionFilter)
26
+ @Controller(prefix)
27
+ class NestAuthController {
28
+ constructor(
29
+ @Inject(nestAuthServiceToken)
30
+ readonly nestAuthService: NestAuthService,
31
+ ) {}
18
32
 
19
- @Get()
20
- async greetings(): Promise<string> {
21
- return "Welcome to NestAuth. Please check our documentation for more information.";
22
- }
33
+ @All()
34
+ async greetings(): Promise<string> {
35
+ return "Welcome to NestAuth. Please check our documentation for more information.";
36
+ }
23
37
 
24
- @UseGuards(NestAuthLocalGuard)
25
- @Post("login")
26
- async login(@Request() req): Promise<any> {
27
- return this.nestAuthService.login(req.user);
28
- }
38
+ @UseGuards(localGuard)
39
+ @Post("login")
40
+ async login(@Request() req: any): Promise<any> {
41
+ console.log("nestAuthServiceToken", nestAuthServiceToken);
42
+ return this.nestAuthService.login(req.user);
43
+ }
29
44
 
30
- @Post("refresh-token")
31
- refreshToken(@Body() params: { refresh_token: string }): Promise<any> {
32
- if (!params.refresh_token) {
33
- throw new BadRequestException("Invalid or expired refresh token");
45
+ @Post("refresh-token")
46
+ refreshToken(@Body() params: { refresh_token: string }): Promise<any> {
47
+ if (!params.refresh_token) {
48
+ throw new BadRequestException(
49
+ "Invalid or expired refresh token",
50
+ );
51
+ }
52
+ return this.nestAuthService.refreshToken(params.refresh_token);
34
53
  }
35
- return this.nestAuthService.refreshToken(params.refresh_token);
36
- }
37
54
 
38
- @UseGuards(NestAuthGoogleGuard)
39
- @Get("google")
40
- async googleAuth(@Request() req): Promise<any> {}
55
+ @UseGuards(NestAuthGoogleGuard)
56
+ @Get("google")
57
+ async googleAuth(@Request() req: any): Promise<any> {}
41
58
 
42
- @Get("google-redirect")
43
- @UseGuards(NestAuthGoogleGuard)
44
- googleAuthRedirect(@Request() req) {
45
- if (!req.user) {
46
- throw new UnauthorizedException("Unable to login with Google");
59
+ @Get("google-redirect")
60
+ @UseGuards(NestAuthGoogleGuard)
61
+ googleAuthRedirect(@Request() req) {
62
+ if (!req.user) {
63
+ throw new UnauthorizedException("Unable to login with Google");
64
+ }
65
+ return this.nestAuthService.google(req.user);
47
66
  }
48
- return this.nestAuthService.google(req.user);
49
- }
50
67
 
51
- @Get("/facebook")
52
- @UseGuards(NestAuthFacebookGuard)
53
- async facebookLogin(): Promise<any> {
54
- return HttpStatus.OK;
55
- }
68
+ @Get("/facebook")
69
+ @UseGuards(NestAuthFacebookGuard)
70
+ async facebookLogin(): Promise<any> {
71
+ return HttpStatus.OK;
72
+ }
56
73
 
57
- @Get("/facebook-redirect")
58
- @UseGuards(NestAuthFacebookGuard)
59
- async facebookLoginRedirect(@Request() req): Promise<any> {
60
- if (!req.user) {
61
- throw new UnauthorizedException("Unable to login with Facebook");
74
+ @Get("/facebook-redirect")
75
+ @UseGuards(NestAuthFacebookGuard)
76
+ async facebookLoginRedirect(@Request() req): Promise<any> {
77
+ if (!req.user) {
78
+ throw new UnauthorizedException(
79
+ "Unable to login with Facebook",
80
+ );
81
+ }
82
+ return this.nestAuthService.facebook(req.user);
62
83
  }
63
- return this.nestAuthService.facebook(req.user);
64
- }
65
84
 
66
- @UseGuards(NestAuthLocalGuard)
67
- @Get("logout")
68
- async logout(@Request() req) {
69
- return req.logout();
85
+ @UseGuards(localGuard)
86
+ @Get("logout")
87
+ async logout(@Request() req: any) {
88
+ return req.logout();
89
+ }
70
90
  }
91
+
92
+ return NestAuthController;
71
93
  }
@@ -1,47 +1,68 @@
1
- import {
2
- Module,
3
- DynamicModule,
4
- forwardRef,
5
- UseFilters,
6
- Controller,
7
- Inject,
8
- } from "@nestjs/common";
1
+ import { Module, DynamicModule, Provider, forwardRef } from "@nestjs/common";
9
2
  import { ConfigModule } from "@nestjs/config";
10
3
  import { NestAuthService } from "./nestauth.service";
11
- import { NestAuthController } from "./nestauth.controller";
12
- import { NestAuthModuleOptions } from "./nestauth.interface";
4
+ import { createDynamicController } from "./nestauth.controller";
5
+ import { NestAuthInterface, NestAuthModuleOptions } from "./nestauth.interface";
13
6
  import { PassportModule } from "@nestjs/passport";
14
- import { JwtModule } from "@nestjs/jwt";
7
+ import { JwtModule, JwtService } from "@nestjs/jwt";
15
8
  import { NestAuthJwtStrategy } from "./nestauth-jwt.strategy";
16
- import { NestAuthLocalStrategy } from "./nestauth-local.strategy";
9
+ // import { NestAuthLocalStrategy } from "./nestauth-local.strategy";
17
10
  import { NestAuthGoogleStrategy } from "./nestauth-google.strategy";
18
11
  import { NestAuthFacebookStrategy } from "./nestauth-facebook.strategy";
19
12
  import { StringValue } from "ms";
20
- import { HttpExceptionFilter } from "./http-exception.filter";
13
+ import { createLocalStrategy } from "./nestauth-local.strategy";
14
+ import { createLocalGuard } from "./nestauth-local.guard";
21
15
 
22
16
  @Module({
23
17
  imports: [PassportModule, ConfigModule.forRoot({})],
24
18
  })
25
19
  export class NestAuthModule {
26
- static register(options: NestAuthModuleOptions): DynamicModule {
27
- // Create unique tokens for each module instance
28
- const moduleId = options.routePrefix || "default";
29
- const AUTH_SERVICE_TOKEN = Symbol(`NestAuthService_${moduleId}`);
30
- const USER_SERVICE_TOKEN = Symbol(`UserService_${moduleId}`);
20
+ static forRoot(options: NestAuthModuleOptions): DynamicModule {
21
+ const JwtSecretProvider: Provider = {
22
+ provide: "JWT_SECRET",
23
+ useValue: options.jwtSecret || "60s",
24
+ };
25
+
26
+ const JwtExpiresInProvider: Provider = {
27
+ provide: "JWT_EXPIRES_IN",
28
+ useValue: options.jwtExpiresIn,
29
+ };
30
+
31
+ const JwtRefreshTokenExpiresInProvider: Provider = {
32
+ provide: "JWT_REFRESH_TOKEN_EXPIRES_IN",
33
+ useValue: options.jwtRefreshTokenExpiresIn,
34
+ };
31
35
 
32
36
  const controllerPath = options.routePrefix
33
37
  ? `${options.routePrefix.replace(/^\/|\/$/g, "")}/nestauth`
34
38
  : "nestauth";
35
39
 
36
- @UseFilters(HttpExceptionFilter)
37
- @Controller(controllerPath)
38
- class DynamicNestAuthController extends NestAuthController {
39
- constructor(
40
- @Inject(AUTH_SERVICE_TOKEN) nestAuthService: NestAuthService,
41
- ) {
42
- super(nestAuthService);
43
- }
44
- }
40
+ const pathKey = controllerPath.replaceAll("/", "_").toUpperCase();
41
+
42
+ const userServiceToken = `NEST_AUTH_USER_SERVICE_${pathKey}`;
43
+ const nestAuthServiceToken = `NEST_AUTH_SERVICE_${pathKey}`;
44
+
45
+ const strategyName = `${pathKey}-local`;
46
+
47
+ const LocalStrategy = createLocalStrategy(
48
+ strategyName,
49
+ userServiceToken,
50
+ );
51
+
52
+ const LocalGuard = createLocalGuard(strategyName);
53
+
54
+ console.log("controllerPath", controllerPath);
55
+ console.log("pathKey", pathKey);
56
+ console.log("userServiceToken", userServiceToken);
57
+ console.log("nestAuthServiceToken", nestAuthServiceToken);
58
+
59
+ console.log("------------------------------------------");
60
+
61
+ const controller = createDynamicController(
62
+ controllerPath,
63
+ nestAuthServiceToken,
64
+ LocalGuard,
65
+ );
45
66
 
46
67
  return {
47
68
  module: NestAuthModule,
@@ -61,41 +82,47 @@ export class NestAuthModule {
61
82
  forwardRef(() => options.UserModule),
62
83
  ],
63
84
  providers: [
64
- // NestAuthService with unique token
65
- {
66
- provide: AUTH_SERVICE_TOKEN,
67
- useClass: NestAuthService,
68
- },
69
- // UserService with unique token
70
85
  {
71
- provide: USER_SERVICE_TOKEN,
86
+ provide: userServiceToken,
72
87
  useExisting: options.UserService,
73
88
  },
74
- // Alias for backward compatibility
75
- {
76
- provide: "UserService",
77
- useFactory: (userService) => userService,
78
- inject: [USER_SERVICE_TOKEN],
79
- },
80
89
  {
81
- provide: "JWT_SECRET",
82
- useValue: options.jwtSecret,
83
- },
84
- {
85
- provide: "JWT_EXPIRES_IN",
86
- useValue: options.jwtExpiresIn,
87
- },
88
- {
89
- provide: "JWT_REFRESH_TOKEN_EXPIRES_IN",
90
- useValue: options.jwtRefreshTokenExpiresIn,
90
+ provide: nestAuthServiceToken,
91
+ useFactory: (
92
+ jwtService: JwtService,
93
+ userService: NestAuthInterface,
94
+ jwtExpiresIn: StringValue | number,
95
+ jwtRefreshTokenExpiresIn: StringValue | number,
96
+ ) =>
97
+ new NestAuthService(
98
+ jwtService,
99
+ userService,
100
+ jwtExpiresIn,
101
+ jwtRefreshTokenExpiresIn,
102
+ ),
103
+ inject: [
104
+ JwtService,
105
+ userServiceToken,
106
+ "JWT_EXPIRES_IN",
107
+ "JWT_REFRESH_TOKEN_EXPIRES_IN",
108
+ ],
91
109
  },
92
110
  NestAuthJwtStrategy,
93
- NestAuthLocalStrategy,
94
111
  NestAuthGoogleStrategy,
95
112
  NestAuthFacebookStrategy,
113
+ JwtSecretProvider,
114
+ JwtExpiresInProvider,
115
+ JwtRefreshTokenExpiresInProvider,
116
+ LocalStrategy,
117
+ LocalGuard,
118
+
119
+ // {
120
+ // provide: APP_FILTER,
121
+ // useClass: HttpExceptionFilter,
122
+ // },
96
123
  ],
97
- exports: [AUTH_SERVICE_TOKEN, "UserService"],
98
- controllers: [DynamicNestAuthController],
124
+ exports: [nestAuthServiceToken],
125
+ controllers: [controller],
99
126
  };
100
127
  }
101
128
  }
@@ -12,11 +12,11 @@ import { StringValue } from "ms";
12
12
  export class NestAuthService {
13
13
  constructor(
14
14
  private jwtService: JwtService,
15
- @Inject("UserService") private readonly userService: NestAuthInterface,
15
+ readonly userService: NestAuthInterface,
16
16
  @Inject("JWT_EXPIRES_IN")
17
17
  private readonly jwtExpiresIn: StringValue | number = "15m",
18
18
  @Inject("JWT_REFRESH_TOKEN_EXPIRES_IN")
19
- private readonly jwtRefreshTokenExpiresIn: StringValue | number = "7d"
19
+ private readonly jwtRefreshTokenExpiresIn: StringValue | number = "7d",
20
20
  ) {}
21
21
 
22
22
  async login(user: any): Promise<any> {
@@ -58,7 +58,7 @@ export class NestAuthService {
58
58
  const user = await this.userService.getUserById(payload.sub);
59
59
  if (!user) {
60
60
  throw new UnauthorizedException(
61
- "Invalid or expired refresh token"
61
+ "Invalid or expired refresh token",
62
62
  );
63
63
  }
64
64
  return this.login(user);