@flusys/nestjs-auth 6.0.2 → 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 (71) 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/index.spec.js +73 -0
  10. package/cjs/helpers/auth-response.mapper.js +46 -0
  11. package/cjs/helpers/auth-response.mapper.spec.js +139 -0
  12. package/cjs/helpers/index.js +19 -0
  13. package/cjs/helpers/token.helper.js +58 -0
  14. package/cjs/helpers/token.helper.spec.js +86 -0
  15. package/cjs/index.js +1 -0
  16. package/cjs/interceptors/clear-token.interceptor.spec.js +107 -0
  17. package/cjs/interceptors/set-token.interceptor.spec.js +165 -0
  18. package/cjs/modules/auth.module.spec.js +243 -0
  19. package/cjs/services/auth-config.service.spec.js +97 -0
  20. package/cjs/services/auth-datasource.provider.spec.js +161 -0
  21. package/cjs/services/auth-email.service.spec.js +404 -0
  22. package/cjs/services/authentication.service.js +37 -109
  23. package/cjs/services/authentication.service.spec.js +904 -0
  24. package/cjs/services/branch.service.spec.js +154 -0
  25. package/cjs/services/company-selection-session.service.spec.js +90 -0
  26. package/cjs/services/company.service.spec.js +113 -0
  27. package/cjs/services/user-permission.service.spec.js +202 -0
  28. package/cjs/services/user.service.spec.js +704 -0
  29. package/cjs/strategies/jwt.strategy.js +1 -1
  30. package/cjs/strategies/jwt.strategy.spec.js +166 -0
  31. package/cjs/validators/password.validator.spec.js +161 -0
  32. package/entities/pending-registration.entity.d.ts +2 -7
  33. package/fesm/controllers/authentication.controller.spec.js +215 -0
  34. package/fesm/controllers/branch.controller.spec.js +130 -0
  35. package/fesm/controllers/company-selection.controller.spec.js +80 -0
  36. package/fesm/controllers/company.controller.spec.js +127 -0
  37. package/fesm/controllers/email-verification.controller.spec.js +138 -0
  38. package/fesm/controllers/user-permission.controller.spec.js +134 -0
  39. package/fesm/controllers/user.controller.spec.js +200 -0
  40. package/fesm/docs/auth-swagger.config.spec.js +126 -0
  41. package/fesm/entities/index.spec.js +69 -0
  42. package/fesm/helpers/auth-response.mapper.js +25 -0
  43. package/fesm/helpers/auth-response.mapper.spec.js +135 -0
  44. package/fesm/helpers/index.js +2 -0
  45. package/fesm/helpers/token.helper.js +40 -0
  46. package/fesm/helpers/token.helper.spec.js +82 -0
  47. package/fesm/index.js +1 -0
  48. package/fesm/interceptors/clear-token.interceptor.spec.js +103 -0
  49. package/fesm/interceptors/set-token.interceptor.spec.js +161 -0
  50. package/fesm/interfaces/authentication.interface.js +1 -1
  51. package/fesm/modules/auth.module.spec.js +239 -0
  52. package/fesm/services/auth-config.service.spec.js +93 -0
  53. package/fesm/services/auth-datasource.provider.spec.js +157 -0
  54. package/fesm/services/auth-email.service.spec.js +359 -0
  55. package/fesm/services/authentication.service.js +37 -109
  56. package/fesm/services/authentication.service.spec.js +859 -0
  57. package/fesm/services/branch.service.spec.js +150 -0
  58. package/fesm/services/company-selection-session.service.spec.js +86 -0
  59. package/fesm/services/company.service.spec.js +109 -0
  60. package/fesm/services/user-permission.service.spec.js +198 -0
  61. package/fesm/services/user.service.spec.js +659 -0
  62. package/fesm/strategies/jwt.strategy.js +1 -1
  63. package/fesm/strategies/jwt.strategy.spec.js +162 -0
  64. package/fesm/validators/password.validator.spec.js +157 -0
  65. package/helpers/auth-response.mapper.d.ts +22 -0
  66. package/helpers/index.d.ts +2 -0
  67. package/helpers/token.helper.d.ts +8 -0
  68. package/index.d.ts +1 -0
  69. package/interfaces/authentication.interface.d.ts +7 -0
  70. package/package.json +8 -3
  71. package/services/authentication.service.d.ts +1 -8
@@ -41,7 +41,7 @@ function _ts_metadata(k, v) {
41
41
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
42
42
  }
43
43
  function hasCompanyContext(payload) {
44
- return 'companyId' in payload && 'branchId' in payload;
44
+ return 'companyId' in payload && payload.companyId != null;
45
45
  }
46
46
  let JwtStrategy = class JwtStrategy extends (0, _passport.PassportStrategy)(_passportjwt.Strategy, 'jwt') {
47
47
  async validate(_req, payload) {
@@ -0,0 +1,166 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ const _common = require("@nestjs/common");
6
+ const _repositorymock = require("@test-utils/mocks/repository.mock");
7
+ const _jwtstrategy = require("./jwt.strategy");
8
+ const _authdatasourceprovider = require("../services/auth-datasource.provider");
9
+ const _authenticationservice = require("../services/authentication.service");
10
+ describe('JwtStrategy', ()=>{
11
+ let strategy;
12
+ let userRepo;
13
+ let mockAuthConfig;
14
+ let mockModuleRef;
15
+ let mockDataSourceProvider;
16
+ let mockAuthService;
17
+ beforeEach(()=>{
18
+ userRepo = (0, _repositorymock.createMockRepository)();
19
+ mockAuthConfig = {
20
+ getJwtSecret: jest.fn().mockReturnValue('jwt-secret')
21
+ };
22
+ mockDataSourceProvider = {
23
+ getRepository: jest.fn().mockResolvedValue(userRepo)
24
+ };
25
+ mockAuthService = {
26
+ isTokenRevoked: jest.fn().mockResolvedValue(false)
27
+ };
28
+ mockModuleRef = {
29
+ resolve: jest.fn().mockImplementation(async (token)=>{
30
+ if (token === _authdatasourceprovider.AuthDataSourceProvider) return mockDataSourceProvider;
31
+ if (token === _authenticationservice.AuthenticationService) return mockAuthService;
32
+ return null;
33
+ })
34
+ };
35
+ strategy = new _jwtstrategy.JwtStrategy(mockAuthConfig, mockModuleRef);
36
+ });
37
+ describe('validate', ()=>{
38
+ const req = {};
39
+ it('returns basic user info for a payload without company context', async ()=>{
40
+ userRepo.findOne.mockResolvedValue({
41
+ id: 'user-1',
42
+ isActive: true
43
+ });
44
+ const result = await strategy.validate(req, {
45
+ id: 'user-1',
46
+ email: 'user@example.com',
47
+ type: 'access'
48
+ });
49
+ expect(result).toEqual({
50
+ id: 'user-1',
51
+ email: 'user@example.com'
52
+ });
53
+ });
54
+ it('includes companyId and branchId when present in the payload', async ()=>{
55
+ userRepo.findOne.mockResolvedValue({
56
+ id: 'user-1',
57
+ isActive: true
58
+ });
59
+ const result = await strategy.validate(req, {
60
+ id: 'user-1',
61
+ email: 'user@example.com',
62
+ type: 'access',
63
+ companyId: 'company-1',
64
+ branchId: 'branch-1'
65
+ });
66
+ expect(result).toEqual({
67
+ id: 'user-1',
68
+ email: 'user@example.com',
69
+ companyId: 'company-1',
70
+ branchId: 'branch-1'
71
+ });
72
+ });
73
+ it('omits branchId when only companyId is present', async ()=>{
74
+ userRepo.findOne.mockResolvedValue({
75
+ id: 'user-1',
76
+ isActive: true
77
+ });
78
+ const result = await strategy.validate(req, {
79
+ id: 'user-1',
80
+ email: 'user@example.com',
81
+ type: 'access',
82
+ companyId: 'company-1'
83
+ });
84
+ expect(result).toEqual({
85
+ id: 'user-1',
86
+ email: 'user@example.com',
87
+ companyId: 'company-1'
88
+ });
89
+ });
90
+ it('throws UnauthorizedException when the user is not found or inactive', async ()=>{
91
+ userRepo.findOne.mockResolvedValue(null);
92
+ await expect(strategy.validate(req, {
93
+ id: 'missing-user',
94
+ email: 'x@example.com',
95
+ type: 'access'
96
+ })).rejects.toThrow(_common.UnauthorizedException);
97
+ });
98
+ it('throws UnauthorizedException when the token has been revoked', async ()=>{
99
+ userRepo.findOne.mockResolvedValue({
100
+ id: 'user-1',
101
+ isActive: true
102
+ });
103
+ mockAuthService.isTokenRevoked.mockResolvedValue(true);
104
+ await expect(strategy.validate(req, {
105
+ id: 'user-1',
106
+ email: 'user@example.com',
107
+ type: 'access',
108
+ iat: 1000
109
+ })).rejects.toThrow(_common.UnauthorizedException);
110
+ });
111
+ it('skips revocation check when the payload has no iat', async ()=>{
112
+ userRepo.findOne.mockResolvedValue({
113
+ id: 'user-1',
114
+ isActive: true
115
+ });
116
+ await strategy.validate(req, {
117
+ id: 'user-1',
118
+ email: 'user@example.com',
119
+ type: 'access'
120
+ });
121
+ expect(mockAuthService.isTokenRevoked).not.toHaveBeenCalled();
122
+ });
123
+ it('throws UnauthorizedException when the data source provider cannot be resolved', async ()=>{
124
+ mockModuleRef.resolve.mockImplementation(async (token)=>{
125
+ if (token === _authdatasourceprovider.AuthDataSourceProvider) return null;
126
+ return mockAuthService;
127
+ });
128
+ await expect(strategy.validate(req, {
129
+ id: 'user-1',
130
+ email: 'user@example.com',
131
+ type: 'access'
132
+ })).rejects.toThrow(_common.UnauthorizedException);
133
+ });
134
+ it('propagates an UnauthorizedException raised while resolving the data source provider', async ()=>{
135
+ mockModuleRef.resolve.mockImplementation(async (token)=>{
136
+ if (token === _authdatasourceprovider.AuthDataSourceProvider) throw new Error('resolution failed');
137
+ return mockAuthService;
138
+ });
139
+ await expect(strategy.validate(req, {
140
+ id: 'user-1',
141
+ email: 'user@example.com',
142
+ type: 'access'
143
+ })).rejects.toThrow(_common.UnauthorizedException);
144
+ });
145
+ it('does not fail validation when the authentication service cannot be resolved for revocation checks', async ()=>{
146
+ userRepo.findOne.mockResolvedValue({
147
+ id: 'user-1',
148
+ isActive: true
149
+ });
150
+ mockModuleRef.resolve.mockImplementation(async (token)=>{
151
+ if (token === _authdatasourceprovider.AuthDataSourceProvider) return mockDataSourceProvider;
152
+ return null;
153
+ });
154
+ const result = await strategy.validate(req, {
155
+ id: 'user-1',
156
+ email: 'user@example.com',
157
+ type: 'access',
158
+ iat: 1000
159
+ });
160
+ expect(result).toEqual({
161
+ id: 'user-1',
162
+ email: 'user@example.com'
163
+ });
164
+ });
165
+ });
166
+ });
@@ -0,0 +1,161 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ const _classvalidator = require("class-validator");
6
+ const _passwordvalidator = require("./password.validator");
7
+ function _define_property(obj, key, value) {
8
+ if (key in obj) {
9
+ Object.defineProperty(obj, key, {
10
+ value: value,
11
+ enumerable: true,
12
+ configurable: true,
13
+ writable: true
14
+ });
15
+ } else {
16
+ obj[key] = value;
17
+ }
18
+ return obj;
19
+ }
20
+ function _ts_decorate(decorators, target, key, desc) {
21
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
22
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
23
+ else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
24
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
25
+ }
26
+ function _ts_metadata(k, v) {
27
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
28
+ }
29
+ let DefaultPasswordDto = class DefaultPasswordDto {
30
+ constructor(){
31
+ _define_property(this, "password", void 0);
32
+ }
33
+ };
34
+ _ts_decorate([
35
+ (0, _passwordvalidator.IsStrongPassword)(),
36
+ _ts_metadata("design:type", String)
37
+ ], DefaultPasswordDto.prototype, "password", void 0);
38
+ let CustomPasswordDto = class CustomPasswordDto {
39
+ constructor(){
40
+ _define_property(this, "password", void 0);
41
+ }
42
+ };
43
+ _ts_decorate([
44
+ (0, _passwordvalidator.IsStrongPassword)({
45
+ minLength: 12,
46
+ requireSpecialChar: false
47
+ }),
48
+ _ts_metadata("design:type", String)
49
+ ], CustomPasswordDto.prototype, "password", void 0);
50
+ let NoComplexityPasswordDto = class NoComplexityPasswordDto {
51
+ constructor(){
52
+ _define_property(this, "password", void 0);
53
+ }
54
+ };
55
+ _ts_decorate([
56
+ (0, _passwordvalidator.IsStrongPassword)({
57
+ requireUppercase: false,
58
+ requireLowercase: false,
59
+ requireNumber: false,
60
+ requireSpecialChar: false,
61
+ minLength: 4
62
+ }),
63
+ _ts_metadata("design:type", String)
64
+ ], NoComplexityPasswordDto.prototype, "password", void 0);
65
+ async function validatePassword(dto) {
66
+ const errors = await (0, _classvalidator.validate)(dto);
67
+ return errors.length === 0;
68
+ }
69
+ describe('IsStrongPassword', ()=>{
70
+ describe('default options', ()=>{
71
+ it('accepts a password meeting all default complexity rules', async ()=>{
72
+ const dto = new DefaultPasswordDto();
73
+ dto.password = 'StrongP@ss1';
74
+ expect(await validatePassword(dto)).toBe(true);
75
+ });
76
+ it('rejects a password shorter than the minimum length', async ()=>{
77
+ const dto = new DefaultPasswordDto();
78
+ dto.password = 'Sh0rt!';
79
+ expect(await validatePassword(dto)).toBe(false);
80
+ });
81
+ it('accepts a password at exactly the minimum length boundary', async ()=>{
82
+ const dto = new DefaultPasswordDto();
83
+ dto.password = 'Ab1!Ab1!'; // 8 chars
84
+ expect(await validatePassword(dto)).toBe(true);
85
+ });
86
+ it('rejects a password longer than the maximum length', async ()=>{
87
+ const dto = new DefaultPasswordDto();
88
+ dto.password = 'A1!' + 'a'.repeat(127); // 130 chars total
89
+ expect(await validatePassword(dto)).toBe(false);
90
+ });
91
+ it('accepts a password at exactly the maximum length boundary', async ()=>{
92
+ const dto = new DefaultPasswordDto();
93
+ dto.password = 'A1!' + 'a'.repeat(125); // 128 chars total
94
+ expect(await validatePassword(dto)).toBe(true);
95
+ });
96
+ it('rejects a password missing an uppercase letter', async ()=>{
97
+ const dto = new DefaultPasswordDto();
98
+ dto.password = 'lowercase1!';
99
+ expect(await validatePassword(dto)).toBe(false);
100
+ });
101
+ it('rejects a password missing a lowercase letter', async ()=>{
102
+ const dto = new DefaultPasswordDto();
103
+ dto.password = 'UPPERCASE1!';
104
+ expect(await validatePassword(dto)).toBe(false);
105
+ });
106
+ it('rejects a password missing a number', async ()=>{
107
+ const dto = new DefaultPasswordDto();
108
+ dto.password = 'NoNumbers!';
109
+ expect(await validatePassword(dto)).toBe(false);
110
+ });
111
+ it('rejects a password missing a special character', async ()=>{
112
+ const dto = new DefaultPasswordDto();
113
+ dto.password = 'NoSpecial1';
114
+ expect(await validatePassword(dto)).toBe(false);
115
+ });
116
+ it('rejects a non-string value', async ()=>{
117
+ const dto = new DefaultPasswordDto();
118
+ dto.password = 12345678;
119
+ expect(await validatePassword(dto)).toBe(false);
120
+ });
121
+ it('rejects an empty string', async ()=>{
122
+ const dto = new DefaultPasswordDto();
123
+ dto.password = '';
124
+ expect(await validatePassword(dto)).toBe(false);
125
+ });
126
+ it('produces a descriptive default error message', async ()=>{
127
+ const dto = new DefaultPasswordDto();
128
+ dto.password = 'bad';
129
+ const errors = await (0, _classvalidator.validate)(dto);
130
+ expect(errors).toHaveLength(1);
131
+ const message = Object.values(errors[0].constraints ?? {})[0];
132
+ expect(message).toContain('at least 8 characters');
133
+ expect(message).toContain('one uppercase letter');
134
+ expect(message).toContain('one lowercase letter');
135
+ expect(message).toContain('one number');
136
+ expect(message).toContain('one special character');
137
+ });
138
+ });
139
+ describe('custom options', ()=>{
140
+ it('enforces a custom minimum length', async ()=>{
141
+ const dto = new CustomPasswordDto();
142
+ dto.password = 'Short1Aa';
143
+ expect(await validatePassword(dto)).toBe(false);
144
+ });
145
+ it('accepts a password without special chars when requireSpecialChar is false', async ()=>{
146
+ const dto = new CustomPasswordDto();
147
+ dto.password = 'LongEnoughPassword1';
148
+ expect(await validatePassword(dto)).toBe(true);
149
+ });
150
+ it('allows fully relaxed complexity requirements', async ()=>{
151
+ const dto = new NoComplexityPasswordDto();
152
+ dto.password = 'abcd';
153
+ expect(await validatePassword(dto)).toBe(true);
154
+ });
155
+ it('still enforces minLength when complexity checks are disabled', async ()=>{
156
+ const dto = new NoComplexityPasswordDto();
157
+ dto.password = 'abc';
158
+ expect(await validatePassword(dto)).toBe(false);
159
+ });
160
+ });
161
+ });
@@ -1,3 +1,4 @@
1
+ import { CompanyRegistrationData } from '../interfaces/authentication.interface';
1
2
  export declare class PendingRegistration {
2
3
  id: string;
3
4
  email: string;
@@ -6,13 +7,7 @@ export declare class PendingRegistration {
6
7
  passwordHash: string;
7
8
  token: string;
8
9
  expiresAt: Date;
9
- companyData: {
10
- companySlug?: string;
11
- branchSlug?: string;
12
- newCompanyName?: string;
13
- newCompanyPhone?: string;
14
- newCompanyAddress?: string;
15
- } | null;
10
+ companyData: CompanyRegistrationData | null;
16
11
  additionalFields: Record<string, any> | null;
17
12
  createdAt: Date;
18
13
  }
@@ -0,0 +1,215 @@
1
+ import { UnauthorizedException } from '@nestjs/common';
2
+ import { buildMockUser } from '@test-utils/mocks/logged-user.mock';
3
+ import { AuthenticationController } from './authentication.controller';
4
+ describe('AuthenticationController', ()=>{
5
+ let controller;
6
+ let mockAuthService;
7
+ let mockAuthConfig;
8
+ beforeEach(()=>{
9
+ mockAuthService = {
10
+ login: jest.fn(),
11
+ register: jest.fn(),
12
+ refreshToken: jest.fn(),
13
+ getUserInfo: jest.fn(),
14
+ logout: jest.fn(),
15
+ changePassword: jest.fn()
16
+ };
17
+ mockAuthConfig = {
18
+ getRefreshTokenCookieName: jest.fn().mockReturnValue('fsn_refresh_token')
19
+ };
20
+ controller = new AuthenticationController(mockAuthService, mockAuthConfig);
21
+ });
22
+ describe('login', ()=>{
23
+ it('wraps a standard login response', async ()=>{
24
+ mockAuthService.login.mockResolvedValue({
25
+ accessToken: 'a',
26
+ refreshToken: 'r',
27
+ user: {
28
+ id: 'u1',
29
+ email: 'u@example.com'
30
+ }
31
+ });
32
+ const result = await controller.login({
33
+ email: 'u@example.com',
34
+ password: 'pw'
35
+ });
36
+ expect(result).toEqual(expect.objectContaining({
37
+ success: true,
38
+ data: expect.objectContaining({
39
+ accessToken: 'a'
40
+ })
41
+ }));
42
+ expect(mockAuthService.login).toHaveBeenCalledWith('u@example.com', 'pw');
43
+ });
44
+ it('wraps a company-selection-required response', async ()=>{
45
+ mockAuthService.login.mockResolvedValue({
46
+ requiresSelection: true,
47
+ sessionId: 'sess-1'
48
+ });
49
+ const result = await controller.login({
50
+ email: 'u@example.com',
51
+ password: 'pw'
52
+ });
53
+ expect(result.message).toBe('Company selection required');
54
+ expect(result.data).toEqual(expect.objectContaining({
55
+ requiresSelection: true
56
+ }));
57
+ });
58
+ it('wraps an email-verification-required response', async ()=>{
59
+ mockAuthService.login.mockResolvedValue({
60
+ requiresEmailVerification: true,
61
+ email: 'u@example.com'
62
+ });
63
+ const result = await controller.login({
64
+ email: 'u@example.com',
65
+ password: 'pw'
66
+ });
67
+ expect(result.message).toBe('Email verification required');
68
+ expect(result.data).toEqual(expect.objectContaining({
69
+ requiresEmailVerification: true
70
+ }));
71
+ });
72
+ it('propagates errors thrown by the service', async ()=>{
73
+ mockAuthService.login.mockRejectedValue(new UnauthorizedException('bad creds'));
74
+ await expect(controller.login({
75
+ email: 'u@example.com',
76
+ password: 'wrong'
77
+ })).rejects.toThrow(UnauthorizedException);
78
+ });
79
+ });
80
+ describe('register', ()=>{
81
+ it('reports success message when registration completes without verification', async ()=>{
82
+ mockAuthService.register.mockResolvedValue({
83
+ accessToken: 'a',
84
+ user: {
85
+ id: 'u1'
86
+ },
87
+ requiresEmailVerification: false
88
+ });
89
+ const req = {
90
+ headers: {},
91
+ get: jest.fn((h)=>h === 'host' ? 'app.example.com' : undefined),
92
+ protocol: 'https'
93
+ };
94
+ const result = await controller.register(req, {
95
+ name: 'New',
96
+ email: 'new@example.com',
97
+ password: 'Password1!'
98
+ });
99
+ expect(result.message).toBe('Registration successful');
100
+ expect(result.success).toBe(true);
101
+ });
102
+ it('reports verification-sent message when email verification is required', async ()=>{
103
+ mockAuthService.register.mockResolvedValue({
104
+ requiresEmailVerification: true,
105
+ user: {
106
+ id: 'u1'
107
+ }
108
+ });
109
+ const req = {
110
+ headers: {},
111
+ get: jest.fn((h)=>h === 'host' ? 'app.example.com' : undefined),
112
+ protocol: 'https'
113
+ };
114
+ const result = await controller.register(req, {
115
+ name: 'New',
116
+ email: 'new@example.com',
117
+ password: 'Password1!'
118
+ });
119
+ expect(result.message).toBe('Verification email sent');
120
+ });
121
+ });
122
+ describe('refreshToken', ()=>{
123
+ it('reads the refresh token from the cookie first', async ()=>{
124
+ mockAuthService.refreshToken.mockResolvedValue({
125
+ accessToken: 'new-token'
126
+ });
127
+ const req = {
128
+ cookies: {
129
+ fsn_refresh_token: 'cookie-token'
130
+ }
131
+ };
132
+ await controller.refreshToken(req, {
133
+ refreshToken: 'body-token'
134
+ });
135
+ expect(mockAuthService.refreshToken).toHaveBeenCalledWith('cookie-token');
136
+ });
137
+ it('falls back to the request body when no cookie is present', async ()=>{
138
+ mockAuthService.refreshToken.mockResolvedValue({
139
+ accessToken: 'new-token'
140
+ });
141
+ const req = {
142
+ cookies: {}
143
+ };
144
+ await controller.refreshToken(req, {
145
+ refreshToken: 'body-token'
146
+ });
147
+ expect(mockAuthService.refreshToken).toHaveBeenCalledWith('body-token');
148
+ });
149
+ it('throws UnauthorizedException when no refresh token is available', async ()=>{
150
+ const req = {
151
+ cookies: {}
152
+ };
153
+ await expect(controller.refreshToken(req, {})).rejects.toThrow(UnauthorizedException);
154
+ expect(mockAuthService.refreshToken).not.toHaveBeenCalled();
155
+ });
156
+ it('uses the default cookie name when authConfig is unavailable', async ()=>{
157
+ controller = new AuthenticationController(mockAuthService, undefined);
158
+ mockAuthService.refreshToken.mockResolvedValue({
159
+ accessToken: 'new-token'
160
+ });
161
+ const req = {
162
+ cookies: {
163
+ fsn_refresh_token: 'cookie-token'
164
+ }
165
+ };
166
+ await controller.refreshToken(req, {});
167
+ expect(mockAuthService.refreshToken).toHaveBeenCalledWith('cookie-token');
168
+ });
169
+ });
170
+ describe('getCurrentUser', ()=>{
171
+ it('delegates to authService.getUserInfo with the current user context', async ()=>{
172
+ mockAuthService.getUserInfo.mockResolvedValue({
173
+ user: {
174
+ id: 'u1'
175
+ }
176
+ });
177
+ const user = buildMockUser();
178
+ const result = await controller.getCurrentUser(user);
179
+ expect(mockAuthService.getUserInfo).toHaveBeenCalledWith(user.id, user.companyId, user.branchId);
180
+ expect(result.data).toEqual({
181
+ user: {
182
+ id: 'u1'
183
+ }
184
+ });
185
+ });
186
+ });
187
+ describe('logout', ()=>{
188
+ it('delegates to authService.logout and returns a success message', async ()=>{
189
+ const result = await controller.logout('user-1');
190
+ expect(mockAuthService.logout).toHaveBeenCalledWith('user-1');
191
+ expect(result).toEqual(expect.objectContaining({
192
+ success: true
193
+ }));
194
+ });
195
+ });
196
+ describe('changePassword', ()=>{
197
+ it('delegates to authService.changePassword', async ()=>{
198
+ const result = await controller.changePassword('user-1', {
199
+ currentPassword: 'old',
200
+ newPassword: 'New1!aaaa'
201
+ });
202
+ expect(mockAuthService.changePassword).toHaveBeenCalledWith('user-1', 'old', 'New1!aaaa');
203
+ expect(result).toEqual(expect.objectContaining({
204
+ success: true
205
+ }));
206
+ });
207
+ it('propagates errors from an invalid current password', async ()=>{
208
+ mockAuthService.changePassword.mockRejectedValue(new UnauthorizedException());
209
+ await expect(controller.changePassword('user-1', {
210
+ currentPassword: 'wrong',
211
+ newPassword: 'New1!aaaa'
212
+ })).rejects.toThrow(UnauthorizedException);
213
+ });
214
+ });
215
+ });