@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
@@ -0,0 +1,162 @@
1
+ import { UnauthorizedException } from '@nestjs/common';
2
+ import { createMockRepository } from '@test-utils/mocks/repository.mock';
3
+ import { JwtStrategy } from './jwt.strategy';
4
+ import { AuthDataSourceProvider } from '../services/auth-datasource.provider';
5
+ import { AuthenticationService } from '../services/authentication.service';
6
+ describe('JwtStrategy', ()=>{
7
+ let strategy;
8
+ let userRepo;
9
+ let mockAuthConfig;
10
+ let mockModuleRef;
11
+ let mockDataSourceProvider;
12
+ let mockAuthService;
13
+ beforeEach(()=>{
14
+ userRepo = createMockRepository();
15
+ mockAuthConfig = {
16
+ getJwtSecret: jest.fn().mockReturnValue('jwt-secret')
17
+ };
18
+ mockDataSourceProvider = {
19
+ getRepository: jest.fn().mockResolvedValue(userRepo)
20
+ };
21
+ mockAuthService = {
22
+ isTokenRevoked: jest.fn().mockResolvedValue(false)
23
+ };
24
+ mockModuleRef = {
25
+ resolve: jest.fn().mockImplementation(async (token)=>{
26
+ if (token === AuthDataSourceProvider) return mockDataSourceProvider;
27
+ if (token === AuthenticationService) return mockAuthService;
28
+ return null;
29
+ })
30
+ };
31
+ strategy = new JwtStrategy(mockAuthConfig, mockModuleRef);
32
+ });
33
+ describe('validate', ()=>{
34
+ const req = {};
35
+ it('returns basic user info for a payload without company context', async ()=>{
36
+ userRepo.findOne.mockResolvedValue({
37
+ id: 'user-1',
38
+ isActive: true
39
+ });
40
+ const result = await strategy.validate(req, {
41
+ id: 'user-1',
42
+ email: 'user@example.com',
43
+ type: 'access'
44
+ });
45
+ expect(result).toEqual({
46
+ id: 'user-1',
47
+ email: 'user@example.com'
48
+ });
49
+ });
50
+ it('includes companyId and branchId when present in the payload', async ()=>{
51
+ userRepo.findOne.mockResolvedValue({
52
+ id: 'user-1',
53
+ isActive: true
54
+ });
55
+ const result = await strategy.validate(req, {
56
+ id: 'user-1',
57
+ email: 'user@example.com',
58
+ type: 'access',
59
+ companyId: 'company-1',
60
+ branchId: 'branch-1'
61
+ });
62
+ expect(result).toEqual({
63
+ id: 'user-1',
64
+ email: 'user@example.com',
65
+ companyId: 'company-1',
66
+ branchId: 'branch-1'
67
+ });
68
+ });
69
+ it('omits branchId when only companyId is present', async ()=>{
70
+ userRepo.findOne.mockResolvedValue({
71
+ id: 'user-1',
72
+ isActive: true
73
+ });
74
+ const result = await strategy.validate(req, {
75
+ id: 'user-1',
76
+ email: 'user@example.com',
77
+ type: 'access',
78
+ companyId: 'company-1'
79
+ });
80
+ expect(result).toEqual({
81
+ id: 'user-1',
82
+ email: 'user@example.com',
83
+ companyId: 'company-1'
84
+ });
85
+ });
86
+ it('throws UnauthorizedException when the user is not found or inactive', async ()=>{
87
+ userRepo.findOne.mockResolvedValue(null);
88
+ await expect(strategy.validate(req, {
89
+ id: 'missing-user',
90
+ email: 'x@example.com',
91
+ type: 'access'
92
+ })).rejects.toThrow(UnauthorizedException);
93
+ });
94
+ it('throws UnauthorizedException when the token has been revoked', async ()=>{
95
+ userRepo.findOne.mockResolvedValue({
96
+ id: 'user-1',
97
+ isActive: true
98
+ });
99
+ mockAuthService.isTokenRevoked.mockResolvedValue(true);
100
+ await expect(strategy.validate(req, {
101
+ id: 'user-1',
102
+ email: 'user@example.com',
103
+ type: 'access',
104
+ iat: 1000
105
+ })).rejects.toThrow(UnauthorizedException);
106
+ });
107
+ it('skips revocation check when the payload has no iat', async ()=>{
108
+ userRepo.findOne.mockResolvedValue({
109
+ id: 'user-1',
110
+ isActive: true
111
+ });
112
+ await strategy.validate(req, {
113
+ id: 'user-1',
114
+ email: 'user@example.com',
115
+ type: 'access'
116
+ });
117
+ expect(mockAuthService.isTokenRevoked).not.toHaveBeenCalled();
118
+ });
119
+ it('throws UnauthorizedException when the data source provider cannot be resolved', async ()=>{
120
+ mockModuleRef.resolve.mockImplementation(async (token)=>{
121
+ if (token === AuthDataSourceProvider) return null;
122
+ return mockAuthService;
123
+ });
124
+ await expect(strategy.validate(req, {
125
+ id: 'user-1',
126
+ email: 'user@example.com',
127
+ type: 'access'
128
+ })).rejects.toThrow(UnauthorizedException);
129
+ });
130
+ it('propagates an UnauthorizedException raised while resolving the data source provider', async ()=>{
131
+ mockModuleRef.resolve.mockImplementation(async (token)=>{
132
+ if (token === AuthDataSourceProvider) throw new Error('resolution failed');
133
+ return mockAuthService;
134
+ });
135
+ await expect(strategy.validate(req, {
136
+ id: 'user-1',
137
+ email: 'user@example.com',
138
+ type: 'access'
139
+ })).rejects.toThrow(UnauthorizedException);
140
+ });
141
+ it('does not fail validation when the authentication service cannot be resolved for revocation checks', async ()=>{
142
+ userRepo.findOne.mockResolvedValue({
143
+ id: 'user-1',
144
+ isActive: true
145
+ });
146
+ mockModuleRef.resolve.mockImplementation(async (token)=>{
147
+ if (token === AuthDataSourceProvider) return mockDataSourceProvider;
148
+ return null;
149
+ });
150
+ const result = await strategy.validate(req, {
151
+ id: 'user-1',
152
+ email: 'user@example.com',
153
+ type: 'access',
154
+ iat: 1000
155
+ });
156
+ expect(result).toEqual({
157
+ id: 'user-1',
158
+ email: 'user@example.com'
159
+ });
160
+ });
161
+ });
162
+ });
@@ -0,0 +1,157 @@
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
+ function _ts_decorate(decorators, target, key, desc) {
15
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
16
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
17
+ 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;
18
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
19
+ }
20
+ function _ts_metadata(k, v) {
21
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
22
+ }
23
+ import { validate } from 'class-validator';
24
+ import { IsStrongPassword } from './password.validator';
25
+ let DefaultPasswordDto = class DefaultPasswordDto {
26
+ constructor(){
27
+ _define_property(this, "password", void 0);
28
+ }
29
+ };
30
+ _ts_decorate([
31
+ IsStrongPassword(),
32
+ _ts_metadata("design:type", String)
33
+ ], DefaultPasswordDto.prototype, "password", void 0);
34
+ let CustomPasswordDto = class CustomPasswordDto {
35
+ constructor(){
36
+ _define_property(this, "password", void 0);
37
+ }
38
+ };
39
+ _ts_decorate([
40
+ IsStrongPassword({
41
+ minLength: 12,
42
+ requireSpecialChar: false
43
+ }),
44
+ _ts_metadata("design:type", String)
45
+ ], CustomPasswordDto.prototype, "password", void 0);
46
+ let NoComplexityPasswordDto = class NoComplexityPasswordDto {
47
+ constructor(){
48
+ _define_property(this, "password", void 0);
49
+ }
50
+ };
51
+ _ts_decorate([
52
+ IsStrongPassword({
53
+ requireUppercase: false,
54
+ requireLowercase: false,
55
+ requireNumber: false,
56
+ requireSpecialChar: false,
57
+ minLength: 4
58
+ }),
59
+ _ts_metadata("design:type", String)
60
+ ], NoComplexityPasswordDto.prototype, "password", void 0);
61
+ async function validatePassword(dto) {
62
+ const errors = await validate(dto);
63
+ return errors.length === 0;
64
+ }
65
+ describe('IsStrongPassword', ()=>{
66
+ describe('default options', ()=>{
67
+ it('accepts a password meeting all default complexity rules', async ()=>{
68
+ const dto = new DefaultPasswordDto();
69
+ dto.password = 'StrongP@ss1';
70
+ expect(await validatePassword(dto)).toBe(true);
71
+ });
72
+ it('rejects a password shorter than the minimum length', async ()=>{
73
+ const dto = new DefaultPasswordDto();
74
+ dto.password = 'Sh0rt!';
75
+ expect(await validatePassword(dto)).toBe(false);
76
+ });
77
+ it('accepts a password at exactly the minimum length boundary', async ()=>{
78
+ const dto = new DefaultPasswordDto();
79
+ dto.password = 'Ab1!Ab1!'; // 8 chars
80
+ expect(await validatePassword(dto)).toBe(true);
81
+ });
82
+ it('rejects a password longer than the maximum length', async ()=>{
83
+ const dto = new DefaultPasswordDto();
84
+ dto.password = 'A1!' + 'a'.repeat(127); // 130 chars total
85
+ expect(await validatePassword(dto)).toBe(false);
86
+ });
87
+ it('accepts a password at exactly the maximum length boundary', async ()=>{
88
+ const dto = new DefaultPasswordDto();
89
+ dto.password = 'A1!' + 'a'.repeat(125); // 128 chars total
90
+ expect(await validatePassword(dto)).toBe(true);
91
+ });
92
+ it('rejects a password missing an uppercase letter', async ()=>{
93
+ const dto = new DefaultPasswordDto();
94
+ dto.password = 'lowercase1!';
95
+ expect(await validatePassword(dto)).toBe(false);
96
+ });
97
+ it('rejects a password missing a lowercase letter', async ()=>{
98
+ const dto = new DefaultPasswordDto();
99
+ dto.password = 'UPPERCASE1!';
100
+ expect(await validatePassword(dto)).toBe(false);
101
+ });
102
+ it('rejects a password missing a number', async ()=>{
103
+ const dto = new DefaultPasswordDto();
104
+ dto.password = 'NoNumbers!';
105
+ expect(await validatePassword(dto)).toBe(false);
106
+ });
107
+ it('rejects a password missing a special character', async ()=>{
108
+ const dto = new DefaultPasswordDto();
109
+ dto.password = 'NoSpecial1';
110
+ expect(await validatePassword(dto)).toBe(false);
111
+ });
112
+ it('rejects a non-string value', async ()=>{
113
+ const dto = new DefaultPasswordDto();
114
+ dto.password = 12345678;
115
+ expect(await validatePassword(dto)).toBe(false);
116
+ });
117
+ it('rejects an empty string', async ()=>{
118
+ const dto = new DefaultPasswordDto();
119
+ dto.password = '';
120
+ expect(await validatePassword(dto)).toBe(false);
121
+ });
122
+ it('produces a descriptive default error message', async ()=>{
123
+ const dto = new DefaultPasswordDto();
124
+ dto.password = 'bad';
125
+ const errors = await validate(dto);
126
+ expect(errors).toHaveLength(1);
127
+ const message = Object.values(errors[0].constraints ?? {})[0];
128
+ expect(message).toContain('at least 8 characters');
129
+ expect(message).toContain('one uppercase letter');
130
+ expect(message).toContain('one lowercase letter');
131
+ expect(message).toContain('one number');
132
+ expect(message).toContain('one special character');
133
+ });
134
+ });
135
+ describe('custom options', ()=>{
136
+ it('enforces a custom minimum length', async ()=>{
137
+ const dto = new CustomPasswordDto();
138
+ dto.password = 'Short1Aa';
139
+ expect(await validatePassword(dto)).toBe(false);
140
+ });
141
+ it('accepts a password without special chars when requireSpecialChar is false', async ()=>{
142
+ const dto = new CustomPasswordDto();
143
+ dto.password = 'LongEnoughPassword1';
144
+ expect(await validatePassword(dto)).toBe(true);
145
+ });
146
+ it('allows fully relaxed complexity requirements', async ()=>{
147
+ const dto = new NoComplexityPasswordDto();
148
+ dto.password = 'abcd';
149
+ expect(await validatePassword(dto)).toBe(true);
150
+ });
151
+ it('still enforces minLength when complexity checks are disabled', async ()=>{
152
+ const dto = new NoComplexityPasswordDto();
153
+ dto.password = 'abc';
154
+ expect(await validatePassword(dto)).toBe(false);
155
+ });
156
+ });
157
+ });
@@ -0,0 +1,22 @@
1
+ import { AppUser } from '../entities/app-user.entity';
2
+ import { CompanyBranch } from '../entities/company-branch.entity';
3
+ import { Company } from '../entities/company.entity';
4
+ export declare function toUserInfo(user: AppUser): {
5
+ id: string;
6
+ email: string;
7
+ name: string | undefined;
8
+ phone: string | null;
9
+ profilePictureId: string | null;
10
+ };
11
+ export declare function toCompanyInfo(company: Company): {
12
+ id: string;
13
+ name: string;
14
+ slug: string;
15
+ logoId: string | null;
16
+ };
17
+ export declare function toBranchInfo(branch: CompanyBranch): {
18
+ id: string;
19
+ name: string;
20
+ slug: string;
21
+ logoId: string | null;
22
+ };
@@ -0,0 +1,2 @@
1
+ export * from './auth-response.mapper';
2
+ export * from './token.helper';
@@ -0,0 +1,8 @@
1
+ import { JwtService } from '@nestjs/jwt';
2
+ import { TokenPayload, TokenPayloadWithCompany } from '../interfaces/authentication.interface';
3
+ import { AuthConfigService } from '../services/auth-config.service';
4
+ export declare function generateTokens(jwtService: JwtService, authConfig: AuthConfigService, payload: TokenPayload | TokenPayloadWithCompany): {
5
+ accessToken: string;
6
+ refreshToken: string;
7
+ };
8
+ export declare function parseExpiryToMs(expiry: string): number;
package/index.d.ts 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';
@@ -62,3 +62,10 @@ export interface LoginResponseRequiresEmailVerification {
62
62
  message: string;
63
63
  messageKey: string;
64
64
  }
65
+ export interface CompanyRegistrationData {
66
+ companySlug?: string;
67
+ branchSlug?: string;
68
+ newCompanyName?: string;
69
+ newCompanyPhone?: string;
70
+ newCompanyAddress?: string;
71
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flusys/nestjs-auth",
3
- "version": "6.0.2",
3
+ "version": "6.1.0",
4
4
  "description": "Authentication and authorization infrastructure for NestJS applications",
5
5
  "main": "cjs/index.js",
6
6
  "module": "fesm/index.js",
@@ -52,6 +52,11 @@
52
52
  "import": "./fesm/enums/index.js",
53
53
  "require": "./cjs/enums/index.js"
54
54
  },
55
+ "./helpers": {
56
+ "types": "./helpers/index.d.ts",
57
+ "import": "./fesm/helpers/index.js",
58
+ "require": "./cjs/helpers/index.js"
59
+ },
55
60
  "./interceptors": {
56
61
  "types": "./interceptors/index.d.ts",
57
62
  "import": "./fesm/interceptors/index.js",
@@ -93,7 +98,7 @@
93
98
  "rxjs": "^7.8.0"
94
99
  },
95
100
  "dependencies": {
96
- "@flusys/nestjs-core": "6.0.2",
97
- "@flusys/nestjs-shared": "6.0.2"
101
+ "@flusys/nestjs-core": "6.1.0",
102
+ "@flusys/nestjs-shared": "6.1.0"
98
103
  }
99
104
  }
@@ -24,9 +24,7 @@ export declare class AuthenticationService {
24
24
  private isCompanyFeatureEnabled;
25
25
  private isEmailVerificationEnabled;
26
26
  private getUserRepository;
27
- private getPermissionRepository;
28
- private getCompanyRepository;
29
- private getBranchRepository;
27
+ private getCompanyScopedRepository;
30
28
  login(email: string, password: string): Promise<LoginResponse | LoginResponseRequiresSelection | LoginResponseRequiresEmailVerification>;
31
29
  private handleCompanyBasedLogin;
32
30
  register(dto: RegistrationDto, verifyUrlBase?: string): Promise<RegistrationResponse | {
@@ -50,7 +48,6 @@ export declare class AuthenticationService {
50
48
  changePassword(userId: string, currentPassword: string, newPassword: string): Promise<void>;
51
49
  logout(userId: string): Promise<void>;
52
50
  isTokenRevoked(userId: string, tokenIssuedAt?: number): Promise<boolean>;
53
- private parseExpiryToMs;
54
51
  getUserCompanies(userId: string): Promise<Company[]>;
55
52
  getUserBranches(userId: string, companyId: string): Promise<CompanyBranch[]>;
56
53
  getCompanyById(companyId: string): Promise<Company | null>;
@@ -58,10 +55,6 @@ export declare class AuthenticationService {
58
55
  getUserInfo(userId: string, companyId?: string, branchId?: string): Promise<MeResponse>;
59
56
  private ensureCompanyFeatureEnabled;
60
57
  private validateUser;
61
- private toUserInfo;
62
- private toCompanyInfo;
63
- private toBranchInfo;
64
- private generateTokens;
65
58
  private generateLoginResponse;
66
59
  private generateLoginResponseWithCompany;
67
60
  private sendLoginNotification;