@flusys/nestjs-auth 6.0.1 → 6.1.0

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.
Files changed (83) hide show
  1. package/cjs/controllers/authentication.controller.spec.js +219 -0
  2. package/cjs/controllers/branch.controller.spec.js +134 -0
  3. package/cjs/controllers/company-selection.controller.spec.js +84 -0
  4. package/cjs/controllers/company.controller.spec.js +131 -0
  5. package/cjs/controllers/email-verification.controller.spec.js +142 -0
  6. package/cjs/controllers/user-permission.controller.spec.js +138 -0
  7. package/cjs/controllers/user.controller.spec.js +204 -0
  8. package/cjs/docs/auth-swagger.config.spec.js +130 -0
  9. package/cjs/entities/company-branch.entity.js +2 -3
  10. package/cjs/entities/index.spec.js +73 -0
  11. package/cjs/helpers/auth-response.mapper.js +46 -0
  12. package/cjs/helpers/auth-response.mapper.spec.js +139 -0
  13. package/cjs/helpers/index.js +19 -0
  14. package/cjs/helpers/token.helper.js +58 -0
  15. package/cjs/helpers/token.helper.spec.js +86 -0
  16. package/cjs/index.js +1 -0
  17. package/cjs/interceptors/clear-token.interceptor.spec.js +107 -0
  18. package/cjs/interceptors/set-token.interceptor.spec.js +165 -0
  19. package/cjs/modules/auth.module.spec.js +243 -0
  20. package/cjs/services/auth-config.service.spec.js +97 -0
  21. package/cjs/services/auth-datasource.provider.spec.js +161 -0
  22. package/cjs/services/auth-email.service.spec.js +404 -0
  23. package/cjs/services/authentication.service.js +37 -109
  24. package/cjs/services/authentication.service.spec.js +904 -0
  25. package/cjs/services/branch.service.js +30 -3
  26. package/cjs/services/branch.service.spec.js +154 -0
  27. package/cjs/services/company-selection-session.service.spec.js +90 -0
  28. package/cjs/services/company.service.js +34 -3
  29. package/cjs/services/company.service.spec.js +113 -0
  30. package/cjs/services/user-permission.service.js +35 -4
  31. package/cjs/services/user-permission.service.spec.js +202 -0
  32. package/cjs/services/user.service.spec.js +704 -0
  33. package/cjs/strategies/jwt.strategy.js +1 -1
  34. package/cjs/strategies/jwt.strategy.spec.js +166 -0
  35. package/cjs/validators/password.validator.spec.js +161 -0
  36. package/entities/company-branch.entity.d.ts +1 -1
  37. package/entities/pending-registration.entity.d.ts +2 -7
  38. package/fesm/controllers/authentication.controller.spec.js +215 -0
  39. package/fesm/controllers/branch.controller.spec.js +130 -0
  40. package/fesm/controllers/company-selection.controller.spec.js +80 -0
  41. package/fesm/controllers/company.controller.spec.js +127 -0
  42. package/fesm/controllers/email-verification.controller.spec.js +138 -0
  43. package/fesm/controllers/user-permission.controller.spec.js +134 -0
  44. package/fesm/controllers/user.controller.spec.js +200 -0
  45. package/fesm/docs/auth-swagger.config.spec.js +126 -0
  46. package/fesm/entities/company-branch.entity.js +2 -3
  47. package/fesm/entities/index.spec.js +69 -0
  48. package/fesm/helpers/auth-response.mapper.js +25 -0
  49. package/fesm/helpers/auth-response.mapper.spec.js +135 -0
  50. package/fesm/helpers/index.js +2 -0
  51. package/fesm/helpers/token.helper.js +40 -0
  52. package/fesm/helpers/token.helper.spec.js +82 -0
  53. package/fesm/index.js +1 -0
  54. package/fesm/interceptors/clear-token.interceptor.spec.js +103 -0
  55. package/fesm/interceptors/set-token.interceptor.spec.js +161 -0
  56. package/fesm/interfaces/authentication.interface.js +1 -1
  57. package/fesm/modules/auth.module.spec.js +239 -0
  58. package/fesm/services/auth-config.service.spec.js +93 -0
  59. package/fesm/services/auth-datasource.provider.spec.js +157 -0
  60. package/fesm/services/auth-email.service.spec.js +359 -0
  61. package/fesm/services/authentication.service.js +37 -109
  62. package/fesm/services/authentication.service.spec.js +859 -0
  63. package/fesm/services/branch.service.js +32 -5
  64. package/fesm/services/branch.service.spec.js +150 -0
  65. package/fesm/services/company-selection-session.service.spec.js +86 -0
  66. package/fesm/services/company.service.js +36 -5
  67. package/fesm/services/company.service.spec.js +109 -0
  68. package/fesm/services/user-permission.service.js +36 -5
  69. package/fesm/services/user-permission.service.spec.js +198 -0
  70. package/fesm/services/user.service.spec.js +659 -0
  71. package/fesm/strategies/jwt.strategy.js +1 -1
  72. package/fesm/strategies/jwt.strategy.spec.js +162 -0
  73. package/fesm/validators/password.validator.spec.js +157 -0
  74. package/helpers/auth-response.mapper.d.ts +22 -0
  75. package/helpers/index.d.ts +2 -0
  76. package/helpers/token.helper.d.ts +8 -0
  77. package/index.d.ts +1 -0
  78. package/interfaces/authentication.interface.d.ts +7 -0
  79. package/package.json +8 -3
  80. package/services/authentication.service.d.ts +1 -8
  81. package/services/branch.service.d.ts +7 -5
  82. package/services/company.service.d.ts +7 -4
  83. package/services/user-permission.service.d.ts +4 -1
@@ -0,0 +1,82 @@
1
+ import { generateTokens, parseExpiryToMs } from './token.helper';
2
+ describe('token.helper', ()=>{
3
+ describe('generateTokens', ()=>{
4
+ let mockJwtService;
5
+ let mockAuthConfig;
6
+ beforeEach(()=>{
7
+ mockJwtService = {
8
+ sign: jest.fn()
9
+ };
10
+ mockAuthConfig = {
11
+ getJwtSecret: jest.fn().mockReturnValue('jwt-secret'),
12
+ getJwtExpiration: jest.fn().mockReturnValue('1h'),
13
+ getRefreshTokenSecret: jest.fn().mockReturnValue('refresh-secret'),
14
+ getRefreshTokenExpiration: jest.fn().mockReturnValue('7d')
15
+ };
16
+ });
17
+ it('signs an access token and a refresh token with distinct secrets', ()=>{
18
+ mockJwtService.sign.mockReturnValueOnce('access-token-value').mockReturnValueOnce('refresh-token-value');
19
+ const result = generateTokens(mockJwtService, mockAuthConfig, {
20
+ id: 'user-1',
21
+ email: 'user@example.com',
22
+ type: 'access'
23
+ });
24
+ expect(result).toEqual({
25
+ accessToken: 'access-token-value',
26
+ refreshToken: 'refresh-token-value'
27
+ });
28
+ expect(mockJwtService.sign).toHaveBeenNthCalledWith(1, expect.objectContaining({
29
+ id: 'user-1',
30
+ email: 'user@example.com',
31
+ type: 'access'
32
+ }), expect.objectContaining({
33
+ secret: 'jwt-secret',
34
+ expiresIn: '1h',
35
+ algorithm: 'HS256'
36
+ }));
37
+ expect(mockJwtService.sign).toHaveBeenNthCalledWith(2, expect.objectContaining({
38
+ id: 'user-1',
39
+ email: 'user@example.com',
40
+ type: 'refresh'
41
+ }), expect.objectContaining({
42
+ secret: 'refresh-secret',
43
+ expiresIn: '7d',
44
+ algorithm: 'HS256'
45
+ }));
46
+ });
47
+ it('includes companyId and branchId in the signed payload when provided', ()=>{
48
+ mockJwtService.sign.mockReturnValue('token');
49
+ generateTokens(mockJwtService, mockAuthConfig, {
50
+ id: 'user-1',
51
+ email: 'user@example.com',
52
+ type: 'access',
53
+ companyId: 'company-1',
54
+ branchId: 'branch-1'
55
+ });
56
+ expect(mockJwtService.sign).toHaveBeenCalledWith(expect.objectContaining({
57
+ companyId: 'company-1',
58
+ branchId: 'branch-1'
59
+ }), expect.anything());
60
+ });
61
+ });
62
+ describe('parseExpiryToMs', ()=>{
63
+ it('parses seconds', ()=>{
64
+ expect(parseExpiryToMs('30s')).toBe(30 * 1000);
65
+ });
66
+ it('parses minutes', ()=>{
67
+ expect(parseExpiryToMs('15m')).toBe(15 * 60 * 1000);
68
+ });
69
+ it('parses hours', ()=>{
70
+ expect(parseExpiryToMs('2h')).toBe(2 * 60 * 60 * 1000);
71
+ });
72
+ it('parses days', ()=>{
73
+ expect(parseExpiryToMs('7d')).toBe(7 * 24 * 60 * 60 * 1000);
74
+ });
75
+ it('falls back to 7 days for an unparsable value', ()=>{
76
+ expect(parseExpiryToMs('not-a-duration')).toBe(7 * 24 * 60 * 60 * 1000);
77
+ });
78
+ it('falls back to 7 days for an unknown unit', ()=>{
79
+ expect(parseExpiryToMs('5y')).toBe(7 * 24 * 60 * 60 * 1000);
80
+ });
81
+ });
82
+ });
package/fesm/index.js CHANGED
@@ -4,6 +4,7 @@ export * from './docs';
4
4
  export * from './dtos';
5
5
  export * from './entities';
6
6
  export * from './enums';
7
+ export * from './helpers';
7
8
  export * from './interceptors';
8
9
  export * from './interfaces';
9
10
  export * from './modules';
@@ -0,0 +1,103 @@
1
+ import { of } from 'rxjs';
2
+ import { ClearToken } from './clear-token.interceptor';
3
+ import { DEFAULT_COOKIE_NAME } from '../config';
4
+ function buildContext(req, res) {
5
+ return {
6
+ switchToHttp: ()=>({
7
+ getRequest: ()=>req,
8
+ getResponse: ()=>res
9
+ })
10
+ };
11
+ }
12
+ function buildCallHandler(value) {
13
+ return {
14
+ handle: ()=>of(value)
15
+ };
16
+ }
17
+ describe('ClearToken', ()=>{
18
+ let mockAuthConfig;
19
+ beforeEach(()=>{
20
+ mockAuthConfig = {
21
+ getRefreshTokenCookieName: jest.fn().mockReturnValue('custom_refresh_token')
22
+ };
23
+ });
24
+ it('clears the cookie for a browser request', (done)=>{
25
+ const interceptor = new ClearToken(mockAuthConfig);
26
+ const clearCookie = jest.fn();
27
+ const req = {
28
+ headers: {
29
+ 'user-agent': 'Mozilla/5.0 Chrome/1.0'
30
+ }
31
+ };
32
+ const res = {
33
+ clearCookie
34
+ };
35
+ interceptor.intercept(buildContext(req, res), buildCallHandler({
36
+ success: true
37
+ })).subscribe((result)=>{
38
+ expect(clearCookie).toHaveBeenCalledWith('custom_refresh_token', expect.objectContaining({
39
+ httpOnly: true,
40
+ path: '/'
41
+ }));
42
+ expect(result).toEqual({
43
+ success: true
44
+ });
45
+ done();
46
+ });
47
+ });
48
+ it('does not clear the cookie for a non-browser (API) request', (done)=>{
49
+ const interceptor = new ClearToken(mockAuthConfig);
50
+ const clearCookie = jest.fn();
51
+ const req = {
52
+ headers: {
53
+ 'user-agent': 'PostmanRuntime/7.0'
54
+ }
55
+ };
56
+ const res = {
57
+ clearCookie
58
+ };
59
+ interceptor.intercept(buildContext(req, res), buildCallHandler({
60
+ success: true
61
+ })).subscribe(()=>{
62
+ expect(clearCookie).not.toHaveBeenCalled();
63
+ done();
64
+ });
65
+ });
66
+ it('falls back to the default cookie name when authConfig is unavailable', (done)=>{
67
+ const interceptor = new ClearToken(undefined);
68
+ const clearCookie = jest.fn();
69
+ const req = {
70
+ headers: {
71
+ 'user-agent': 'Mozilla/5.0 Chrome/1.0'
72
+ }
73
+ };
74
+ const res = {
75
+ clearCookie
76
+ };
77
+ interceptor.intercept(buildContext(req, res), buildCallHandler({
78
+ success: true
79
+ })).subscribe(()=>{
80
+ expect(clearCookie).toHaveBeenCalledWith(DEFAULT_COOKIE_NAME, expect.anything());
81
+ done();
82
+ });
83
+ });
84
+ it('passes through the emitted value unchanged', (done)=>{
85
+ const interceptor = new ClearToken(mockAuthConfig);
86
+ const req = {
87
+ headers: {
88
+ 'user-agent': 'PostmanRuntime/7.0'
89
+ }
90
+ };
91
+ const res = {
92
+ clearCookie: jest.fn()
93
+ };
94
+ const payload = {
95
+ success: true,
96
+ message: 'Logged out successfully'
97
+ };
98
+ interceptor.intercept(buildContext(req, res), buildCallHandler(payload)).subscribe((result)=>{
99
+ expect(result).toBe(payload);
100
+ done();
101
+ });
102
+ });
103
+ });
@@ -0,0 +1,161 @@
1
+ import { PayloadTooLargeException } from '@nestjs/common';
2
+ import { of } from 'rxjs';
3
+ import { SetToken } from './set-token.interceptor';
4
+ import { DEFAULT_COOKIE_NAME } from '../config';
5
+ function buildContext(req, res) {
6
+ return {
7
+ switchToHttp: ()=>({
8
+ getRequest: ()=>req,
9
+ getResponse: ()=>res
10
+ })
11
+ };
12
+ }
13
+ function buildCallHandler(value) {
14
+ return {
15
+ handle: ()=>of(value)
16
+ };
17
+ }
18
+ const browserReq = {
19
+ headers: {
20
+ 'user-agent': 'Mozilla/5.0 Chrome/1.0'
21
+ }
22
+ };
23
+ const apiReq = {
24
+ headers: {
25
+ 'user-agent': 'PostmanRuntime/7.0'
26
+ }
27
+ };
28
+ describe('SetToken', ()=>{
29
+ let mockAuthConfig;
30
+ beforeEach(()=>{
31
+ mockAuthConfig = {
32
+ getRefreshTokenCookieName: jest.fn().mockReturnValue('custom_refresh_token'),
33
+ getRefreshTokenExpiration: jest.fn().mockReturnValue('7d')
34
+ };
35
+ });
36
+ it('sets a refresh token cookie and strips refreshToken from data for browser requests', (done)=>{
37
+ const interceptor = new SetToken(mockAuthConfig);
38
+ const cookie = jest.fn();
39
+ const res = {
40
+ cookie
41
+ };
42
+ const payload = {
43
+ success: true,
44
+ data: {
45
+ accessToken: 'access-1',
46
+ refreshToken: 'refresh-1',
47
+ user: {
48
+ id: 'u1'
49
+ }
50
+ }
51
+ };
52
+ interceptor.intercept(buildContext(browserReq, res), buildCallHandler(payload)).subscribe((result)=>{
53
+ expect(cookie).toHaveBeenCalledWith('custom_refresh_token', 'refresh-1', expect.objectContaining({
54
+ httpOnly: true,
55
+ path: '/'
56
+ }));
57
+ expect(result).toEqual({
58
+ success: true,
59
+ data: {
60
+ accessToken: 'access-1',
61
+ user: {
62
+ id: 'u1'
63
+ }
64
+ }
65
+ });
66
+ expect(result.data.refreshToken).toBeUndefined();
67
+ done();
68
+ });
69
+ });
70
+ it('does not set a cookie or modify data for non-browser (API) requests', (done)=>{
71
+ const interceptor = new SetToken(mockAuthConfig);
72
+ const cookie = jest.fn();
73
+ const res = {
74
+ cookie
75
+ };
76
+ const payload = {
77
+ success: true,
78
+ data: {
79
+ accessToken: 'access-1',
80
+ refreshToken: 'refresh-1'
81
+ }
82
+ };
83
+ interceptor.intercept(buildContext(apiReq, res), buildCallHandler(payload)).subscribe((result)=>{
84
+ expect(cookie).not.toHaveBeenCalled();
85
+ expect(result).toBe(payload);
86
+ done();
87
+ });
88
+ });
89
+ it('passes through non-object values unchanged', (done)=>{
90
+ const interceptor = new SetToken(mockAuthConfig);
91
+ const res = {
92
+ cookie: jest.fn()
93
+ };
94
+ interceptor.intercept(buildContext(browserReq, res), buildCallHandler('plain-string')).subscribe((result)=>{
95
+ expect(result).toBe('plain-string');
96
+ done();
97
+ });
98
+ });
99
+ it('passes through null values unchanged', (done)=>{
100
+ const interceptor = new SetToken(mockAuthConfig);
101
+ const res = {
102
+ cookie: jest.fn()
103
+ };
104
+ interceptor.intercept(buildContext(browserReq, res), buildCallHandler(null)).subscribe((result)=>{
105
+ expect(result).toBeNull();
106
+ done();
107
+ });
108
+ });
109
+ it('passes through values without a refreshToken in data unchanged', (done)=>{
110
+ const interceptor = new SetToken(mockAuthConfig);
111
+ const cookie = jest.fn();
112
+ const res = {
113
+ cookie
114
+ };
115
+ const payload = {
116
+ success: true,
117
+ data: {
118
+ accessToken: 'access-1'
119
+ }
120
+ };
121
+ interceptor.intercept(buildContext(browserReq, res), buildCallHandler(payload)).subscribe((result)=>{
122
+ expect(cookie).not.toHaveBeenCalled();
123
+ expect(result).toBe(payload);
124
+ done();
125
+ });
126
+ });
127
+ it('falls back to the default cookie name when authConfig is unavailable', (done)=>{
128
+ const interceptor = new SetToken(undefined);
129
+ const cookie = jest.fn();
130
+ const res = {
131
+ cookie
132
+ };
133
+ const payload = {
134
+ data: {
135
+ refreshToken: 'refresh-1'
136
+ }
137
+ };
138
+ interceptor.intercept(buildContext(browserReq, res), buildCallHandler(payload)).subscribe(()=>{
139
+ expect(cookie).toHaveBeenCalledWith(DEFAULT_COOKIE_NAME, 'refresh-1', expect.anything());
140
+ done();
141
+ });
142
+ });
143
+ it('throws PayloadTooLargeException when the refresh token exceeds the max cookie size', (done)=>{
144
+ const interceptor = new SetToken(mockAuthConfig);
145
+ const res = {
146
+ cookie: jest.fn()
147
+ };
148
+ const oversizedToken = 'a'.repeat(4000);
149
+ const payload = {
150
+ data: {
151
+ refreshToken: oversizedToken
152
+ }
153
+ };
154
+ interceptor.intercept(buildContext(browserReq, res), buildCallHandler(payload)).subscribe({
155
+ error: (err)=>{
156
+ expect(err).toBeInstanceOf(PayloadTooLargeException);
157
+ done();
158
+ }
159
+ });
160
+ });
161
+ });
@@ -1 +1 @@
1
- /** Login Response when email verification is required */ export { };
1
+ /** Company/branch selection or creation data supplied during registration */ export { };
@@ -0,0 +1,239 @@
1
+ function _define_property(obj, key, value) {
2
+ if (key in obj) {
3
+ Object.defineProperty(obj, key, {
4
+ value: value,
5
+ enumerable: true,
6
+ configurable: true,
7
+ writable: true
8
+ });
9
+ } else {
10
+ obj[key] = value;
11
+ }
12
+ return obj;
13
+ }
14
+ import { AuthModule } from './auth.module';
15
+ import { AUTH_MODULE_OPTIONS } from '../config/auth.constants';
16
+ import { AuthenticationController, BranchController, CompanyController, CompanySelectionController, EmailVerificationController, UserController, UserPermissionController } from '../controllers';
17
+ import { AuthEmailService, BranchService, CompanySelectionSessionService, CompanyService, UserPermissionService } from '../services';
18
+ function providerTokens(providers) {
19
+ return providers.map((p)=>typeof p === 'function' ? p : p.provide);
20
+ }
21
+ describe('AuthModule', ()=>{
22
+ describe('forRoot', ()=>{
23
+ it('should build a non-global module by default with the minimal feature set', ()=>{
24
+ const dynamicModule = AuthModule.forRoot({
25
+ bootstrapAppConfig: {
26
+ enableEmailVerification: false
27
+ }
28
+ });
29
+ expect(dynamicModule.module).toBe(AuthModule);
30
+ expect(dynamicModule.global).toBe(false);
31
+ expect(dynamicModule.controllers).toEqual([
32
+ AuthenticationController,
33
+ UserController
34
+ ]);
35
+ expect(providerTokens(dynamicModule.providers)).not.toContain(AuthEmailService);
36
+ expect(providerTokens(dynamicModule.providers)).not.toContain(CompanyService);
37
+ });
38
+ it('should respect global: true', ()=>{
39
+ const dynamicModule = AuthModule.forRoot({
40
+ global: true
41
+ });
42
+ expect(dynamicModule.global).toBe(true);
43
+ });
44
+ it('should register no controllers when includeController is false', ()=>{
45
+ const dynamicModule = AuthModule.forRoot({
46
+ includeController: false
47
+ });
48
+ expect(dynamicModule.controllers).toEqual([]);
49
+ });
50
+ it('should enable email verification by default (bootstrapAppConfig omitted)', ()=>{
51
+ const dynamicModule = AuthModule.forRoot({});
52
+ expect(dynamicModule.controllers).toContain(EmailVerificationController);
53
+ expect(providerTokens(dynamicModule.providers)).toContain(AuthEmailService);
54
+ expect(dynamicModule.exports).toContain(AuthEmailService);
55
+ });
56
+ it('should omit email verification controller/provider/export when explicitly disabled', ()=>{
57
+ const dynamicModule = AuthModule.forRoot({
58
+ bootstrapAppConfig: {
59
+ enableEmailVerification: false
60
+ }
61
+ });
62
+ expect(dynamicModule.controllers).not.toContain(EmailVerificationController);
63
+ expect(providerTokens(dynamicModule.providers)).not.toContain(AuthEmailService);
64
+ expect(dynamicModule.exports).not.toContain(AuthEmailService);
65
+ });
66
+ it('should add company controllers/providers/exports when enableCompanyFeature is true', ()=>{
67
+ const dynamicModule = AuthModule.forRoot({
68
+ bootstrapAppConfig: {
69
+ enableCompanyFeature: true
70
+ }
71
+ });
72
+ expect(dynamicModule.controllers).toEqual(expect.arrayContaining([
73
+ CompanySelectionController,
74
+ CompanyController,
75
+ BranchController,
76
+ UserPermissionController
77
+ ]));
78
+ expect(providerTokens(dynamicModule.providers)).toEqual(expect.arrayContaining([
79
+ CompanySelectionSessionService,
80
+ CompanyService,
81
+ BranchService,
82
+ UserPermissionService
83
+ ]));
84
+ expect(dynamicModule.exports).toEqual(expect.arrayContaining([
85
+ CompanyService,
86
+ BranchService,
87
+ UserPermissionService
88
+ ]));
89
+ });
90
+ it('should register an AUTH_MODULE_OPTIONS provider carrying the given options', ()=>{
91
+ const options = {
92
+ bootstrapAppConfig: {
93
+ enableCompanyFeature: true
94
+ }
95
+ };
96
+ const dynamicModule = AuthModule.forRoot(options);
97
+ const optionsProvider = dynamicModule.providers.find((p)=>p.provide === AUTH_MODULE_OPTIONS);
98
+ expect(optionsProvider.useValue).toBe(options);
99
+ });
100
+ it('should append any caller-supplied extra providers', ()=>{
101
+ const extraProvider = {
102
+ provide: 'EXTRA',
103
+ useValue: 'x'
104
+ };
105
+ const dynamicModule = AuthModule.forRoot({
106
+ providers: [
107
+ extraProvider
108
+ ]
109
+ });
110
+ expect(dynamicModule.providers).toEqual(expect.arrayContaining([
111
+ extraProvider
112
+ ]));
113
+ });
114
+ });
115
+ describe('forRootAsync', ()=>{
116
+ it('should default AUTH_MODULE_OPTIONS to the static options when no useFactory/useClass/useExisting is given', async ()=>{
117
+ const dynamicModule = AuthModule.forRootAsync({
118
+ bootstrapAppConfig: {},
119
+ global: true
120
+ });
121
+ const optionsProvider = dynamicModule.providers.find((p)=>p.provide === AUTH_MODULE_OPTIONS);
122
+ expect(optionsProvider.useValue).toEqual({
123
+ global: true,
124
+ includeController: undefined,
125
+ bootstrapAppConfig: {}
126
+ });
127
+ });
128
+ it('should resolve config via useFactory and merge it with the static options', async ()=>{
129
+ const useFactory = jest.fn().mockResolvedValue({
130
+ jwtSecret: 'from-factory'
131
+ });
132
+ const dynamicModule = AuthModule.forRootAsync({
133
+ bootstrapAppConfig: {},
134
+ useFactory,
135
+ inject: [
136
+ 'SOME_TOKEN'
137
+ ]
138
+ });
139
+ const optionsProvider = dynamicModule.providers.find((p)=>p.provide === AUTH_MODULE_OPTIONS);
140
+ expect(optionsProvider.inject).toEqual([
141
+ 'SOME_TOKEN'
142
+ ]);
143
+ const resolved = await optionsProvider.useFactory('injected-value');
144
+ expect(useFactory).toHaveBeenCalledWith('injected-value');
145
+ expect(resolved).toEqual({
146
+ global: undefined,
147
+ includeController: undefined,
148
+ bootstrapAppConfig: {},
149
+ config: {
150
+ jwtSecret: 'from-factory'
151
+ }
152
+ });
153
+ });
154
+ it('should resolve config via a useClass factory', async ()=>{
155
+ let MyOptionsFactory = class MyOptionsFactory {
156
+ constructor(){
157
+ _define_property(this, "createAuthOptions", jest.fn().mockResolvedValue({
158
+ jwtSecret: 'from-class'
159
+ }));
160
+ }
161
+ };
162
+ const dynamicModule = AuthModule.forRootAsync({
163
+ bootstrapAppConfig: {},
164
+ useClass: MyOptionsFactory
165
+ });
166
+ const classProvider = dynamicModule.providers.find((p)=>p.provide === MyOptionsFactory);
167
+ expect(classProvider.useClass).toBe(MyOptionsFactory);
168
+ const optionsProvider = dynamicModule.providers.find((p)=>p.provide === AUTH_MODULE_OPTIONS);
169
+ expect(optionsProvider.inject).toEqual([
170
+ MyOptionsFactory
171
+ ]);
172
+ const factoryInstance = new MyOptionsFactory();
173
+ const resolved = await optionsProvider.useFactory(factoryInstance);
174
+ expect(factoryInstance.createAuthOptions).toHaveBeenCalled();
175
+ expect(resolved.config).toEqual({
176
+ jwtSecret: 'from-class'
177
+ });
178
+ });
179
+ it('should resolve config via a useExisting factory', async ()=>{
180
+ let MyOptionsFactory = class MyOptionsFactory {
181
+ constructor(){
182
+ _define_property(this, "createAuthOptions", jest.fn().mockResolvedValue({
183
+ jwtSecret: 'from-existing'
184
+ }));
185
+ }
186
+ };
187
+ const dynamicModule = AuthModule.forRootAsync({
188
+ bootstrapAppConfig: {},
189
+ useExisting: MyOptionsFactory
190
+ });
191
+ const optionsProvider = dynamicModule.providers.find((p)=>p.provide === AUTH_MODULE_OPTIONS);
192
+ expect(optionsProvider.inject).toEqual([
193
+ MyOptionsFactory
194
+ ]);
195
+ const factoryInstance = new MyOptionsFactory();
196
+ const resolved = await optionsProvider.useFactory(factoryInstance);
197
+ expect(resolved.config).toEqual({
198
+ jwtSecret: 'from-existing'
199
+ });
200
+ });
201
+ it('should forward the async `imports` array into the built module', ()=>{
202
+ let FakeImportedModule = class FakeImportedModule {
203
+ };
204
+ const dynamicModule = AuthModule.forRootAsync({
205
+ bootstrapAppConfig: {},
206
+ imports: [
207
+ FakeImportedModule
208
+ ]
209
+ });
210
+ expect(dynamicModule.imports).toEqual(expect.arrayContaining([
211
+ FakeImportedModule
212
+ ]));
213
+ });
214
+ it('should append any caller-supplied extra providers alongside the async options provider', ()=>{
215
+ const extraProvider = {
216
+ provide: 'EXTRA',
217
+ useValue: 'x'
218
+ };
219
+ const dynamicModule = AuthModule.forRootAsync({
220
+ bootstrapAppConfig: {},
221
+ providers: [
222
+ extraProvider
223
+ ]
224
+ });
225
+ expect(dynamicModule.providers).toEqual(expect.arrayContaining([
226
+ extraProvider
227
+ ]));
228
+ });
229
+ });
230
+ describe('getEntities', ()=>{
231
+ it('should delegate to getAuthEntitiesByConfig with the bootstrap flags', ()=>{
232
+ const entitiesWithDefaults = AuthModule.getEntities({});
233
+ const entitiesWithCompany = AuthModule.getEntities({
234
+ enableCompanyFeature: true
235
+ });
236
+ expect(entitiesWithDefaults.length).toBeLessThan(entitiesWithCompany.length);
237
+ });
238
+ });
239
+ });
@@ -0,0 +1,93 @@
1
+ import { InternalServerErrorException } from '@nestjs/common';
2
+ import { envConfig } from '@flusys/nestjs-core/config';
3
+ import { AuthConfigService } from './auth-config.service';
4
+ jest.mock('@flusys/nestjs-core/config', ()=>({
5
+ envConfig: {
6
+ isProduction: jest.fn().mockReturnValue(false)
7
+ }
8
+ }));
9
+ describe('AuthConfigService', ()=>{
10
+ afterEach(()=>{
11
+ jest.clearAllMocks();
12
+ });
13
+ describe('with no injected options', ()=>{
14
+ it('defaults database mode to single and company feature to disabled', ()=>{
15
+ const service = new AuthConfigService();
16
+ expect(service.getDatabaseMode()).toBe('single');
17
+ expect(service.isMultiTenant()).toBe(false);
18
+ expect(service.isCompanyFeatureEnabled()).toBe(false);
19
+ expect(service.isEmailVerificationEnabled()).toBe(true);
20
+ expect(service.isPermissionModeFound()).toBe(false);
21
+ });
22
+ it('throws when reading the JWT secret without configuration', ()=>{
23
+ const service = new AuthConfigService();
24
+ expect(()=>service.getJwtSecret()).toThrow(InternalServerErrorException);
25
+ });
26
+ it('falls back to the JWT secret for refresh token secret outside production', ()=>{
27
+ const service = new AuthConfigService({
28
+ global: false,
29
+ includeController: true,
30
+ config: {
31
+ jwtSecret: 'shared-secret'
32
+ }
33
+ });
34
+ expect(service.getRefreshTokenSecret()).toBe('shared-secret');
35
+ });
36
+ it('returns default JWT expiration and refresh token expiration', ()=>{
37
+ const service = new AuthConfigService();
38
+ expect(service.getJwtExpiration()).toBe('1h');
39
+ expect(service.getRefreshTokenExpiration()).toBe('7d');
40
+ expect(service.getRefreshTokenCookieName()).toBe('fsn_refresh_token');
41
+ });
42
+ });
43
+ describe('with injected options', ()=>{
44
+ function buildOptions(overrides = {}) {
45
+ return {
46
+ global: false,
47
+ includeController: true,
48
+ bootstrapAppConfig: {
49
+ databaseMode: 'multi-tenant',
50
+ enableCompanyFeature: true,
51
+ enableEmailVerification: false,
52
+ permissionMode: 'RBAC'
53
+ },
54
+ config: {
55
+ jwtSecret: 'jwt-secret',
56
+ jwtExpiration: '30m',
57
+ refreshTokenSecret: 'refresh-secret',
58
+ refreshTokenExpiration: '14d',
59
+ refreshTokenCookieName: 'custom_cookie'
60
+ },
61
+ ...overrides
62
+ };
63
+ }
64
+ it('reflects multi-tenant database mode', ()=>{
65
+ const service = new AuthConfigService(buildOptions());
66
+ expect(service.getDatabaseMode()).toBe('multi-tenant');
67
+ expect(service.isMultiTenant()).toBe(true);
68
+ });
69
+ it('reflects enabled company feature and email verification flags', ()=>{
70
+ const service = new AuthConfigService(buildOptions());
71
+ expect(service.isCompanyFeatureEnabled()).toBe(true);
72
+ expect(service.isEmailVerificationEnabled()).toBe(false);
73
+ expect(service.isPermissionModeFound()).toBe(true);
74
+ });
75
+ it('returns configured JWT and refresh token values', ()=>{
76
+ const service = new AuthConfigService(buildOptions());
77
+ expect(service.getJwtSecret()).toBe('jwt-secret');
78
+ expect(service.getJwtExpiration()).toBe('30m');
79
+ expect(service.getRefreshTokenSecret()).toBe('refresh-secret');
80
+ expect(service.getRefreshTokenExpiration()).toBe('14d');
81
+ expect(service.getRefreshTokenCookieName()).toBe('custom_cookie');
82
+ });
83
+ it('throws in production when refresh token secret is missing (security: prevents shared-secret fallback)', ()=>{
84
+ envConfig.isProduction.mockReturnValue(true);
85
+ const service = new AuthConfigService(buildOptions({
86
+ config: {
87
+ jwtSecret: 'jwt-secret'
88
+ }
89
+ }));
90
+ expect(()=>service.getRefreshTokenSecret()).toThrow(InternalServerErrorException);
91
+ });
92
+ });
93
+ });