@flusys/nestjs-auth 1.0.0-beta → 1.0.0-rc
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/README.md +274 -291
- package/cjs/config/auth.constants.js +12 -0
- package/cjs/controllers/authentication.controller.js +219 -10
- package/cjs/controllers/branch.controller.js +44 -1
- package/cjs/controllers/company-selection.controller.js +27 -20
- package/cjs/controllers/company.controller.js +44 -1
- package/cjs/controllers/user-permission.controller.js +40 -25
- package/cjs/controllers/user.controller.js +211 -7
- package/cjs/dtos/authentication.dto.js +119 -13
- package/cjs/dtos/user-permission.dto.js +28 -0
- package/cjs/dtos/user.dto.js +19 -4
- package/cjs/entities/index.js +5 -1
- package/cjs/entities/pending-registration.entity.js +125 -0
- package/cjs/entities/user-company-permission.entity.js +0 -6
- package/cjs/entities/user-token.entity.js +129 -0
- package/cjs/guards/auth-throttler.guard.js +53 -0
- package/cjs/interceptors/clear-token.interceptor.js +3 -6
- package/cjs/interceptors/set-token.interceptor.js +38 -31
- package/cjs/interfaces/auth-email-provider.interface.js +45 -0
- package/cjs/interfaces/index.js +2 -0
- package/cjs/interfaces/user-enricher.interface.js +4 -0
- package/cjs/modules/auth.module.js +8 -20
- package/cjs/services/auth-config.service.js +23 -2
- package/cjs/services/auth-datasource.provider.js +5 -3
- package/cjs/services/auth-email.service.js +471 -0
- package/cjs/services/authentication.service.js +169 -77
- package/cjs/services/branch.service.js +6 -5
- package/cjs/services/company-selection-session.service.js +1 -1
- package/cjs/services/index.js +1 -0
- package/cjs/services/user-permission.service.js +0 -2
- package/cjs/services/user.service.js +213 -34
- package/cjs/validators/password.validator.js +45 -0
- package/config/auth.constants.d.ts +3 -0
- package/controllers/authentication.controller.d.ts +13 -9
- package/controllers/company-selection.controller.d.ts +6 -2
- package/controllers/user.controller.d.ts +33 -0
- package/dtos/authentication.dto.d.ts +21 -3
- package/dtos/company-branch.dto.d.ts +0 -1
- package/dtos/company.dto.d.ts +0 -1
- package/dtos/user-permission.dto.d.ts +4 -0
- package/dtos/user.dto.d.ts +1 -2
- package/entities/index.d.ts +7 -3
- package/entities/pending-registration.entity.d.ts +17 -0
- package/entities/user-company-permission.entity.d.ts +0 -2
- package/entities/user-token.entity.d.ts +15 -0
- package/fesm/config/auth.constants.js +6 -2
- package/fesm/controllers/authentication.controller.js +221 -12
- package/fesm/controllers/branch.controller.js +45 -2
- package/fesm/controllers/company-selection.controller.js +28 -21
- package/fesm/controllers/company.controller.js +45 -2
- package/fesm/controllers/user-permission.controller.js +41 -26
- package/fesm/controllers/user.controller.js +214 -10
- package/fesm/dtos/authentication.dto.js +106 -14
- package/fesm/dtos/user-permission.dto.js +28 -0
- package/fesm/dtos/user.dto.js +20 -5
- package/fesm/entities/index.js +7 -1
- package/fesm/entities/pending-registration.entity.js +115 -0
- package/fesm/entities/user-company-permission.entity.js +0 -6
- package/fesm/entities/user-token.entity.js +113 -0
- package/fesm/guards/auth-throttler.guard.js +43 -0
- package/fesm/interceptors/clear-token.interceptor.js +2 -5
- package/fesm/interceptors/set-token.interceptor.js +37 -30
- package/fesm/interfaces/auth-email-provider.interface.js +38 -0
- package/fesm/interfaces/authentication.interface.js +1 -1
- package/fesm/interfaces/index.js +2 -0
- package/fesm/interfaces/user-enricher.interface.js +26 -0
- package/fesm/modules/auth.module.js +10 -22
- package/fesm/services/auth-config.service.js +24 -3
- package/fesm/services/auth-datasource.provider.js +6 -4
- package/fesm/services/auth-email.service.js +420 -0
- package/fesm/services/authentication.service.js +169 -77
- package/fesm/services/branch.service.js +6 -5
- package/fesm/services/company-selection-session.service.js +1 -1
- package/fesm/services/index.js +1 -0
- package/fesm/services/user-permission.service.js +1 -3
- package/fesm/services/user.service.js +215 -36
- package/fesm/validators/password.validator.js +48 -0
- package/guards/auth-throttler.guard.d.ts +7 -0
- package/interceptors/set-token.interceptor.d.ts +1 -0
- package/interfaces/auth-email-provider.interface.d.ts +6 -0
- package/interfaces/auth-module-options.interface.d.ts +4 -1
- package/interfaces/authentication.interface.d.ts +14 -0
- package/interfaces/index.d.ts +2 -0
- package/interfaces/user-enricher.interface.d.ts +64 -0
- package/interfaces/user.interface.d.ts +1 -0
- package/modules/auth.module.d.ts +0 -1
- package/package.json +4 -4
- package/services/auth-config.service.d.ts +5 -1
- package/services/auth-email.service.d.ts +51 -0
- package/services/authentication.service.d.ts +16 -11
- package/services/company-selection-session.service.d.ts +1 -1
- package/services/index.d.ts +1 -0
- package/services/user-permission.service.d.ts +0 -1
- package/services/user.service.d.ts +19 -3
- package/validators/password.validator.d.ts +10 -0
|
@@ -12,7 +12,6 @@ const _modules = require("@flusys/nestjs-shared/modules");
|
|
|
12
12
|
const _common = require("@nestjs/common");
|
|
13
13
|
const _jwt = require("@nestjs/jwt");
|
|
14
14
|
const _passport = require("@nestjs/passport");
|
|
15
|
-
const _typeorm = require("@nestjs/typeorm");
|
|
16
15
|
const _authconfigservice = require("../services/auth-config.service");
|
|
17
16
|
const _authdatasourceprovider = require("../services/auth-datasource.provider");
|
|
18
17
|
const _authconstants = require("../config/auth.constants");
|
|
@@ -34,7 +33,7 @@ let AuthModule = class AuthModule {
|
|
|
34
33
|
return this.buildDynamicModule(options);
|
|
35
34
|
}
|
|
36
35
|
static forRootAsync(asyncOptions) {
|
|
37
|
-
const { global = false, includeController = true, bootstrapAppConfig: { enableCompanyFeature } = {}, imports: externalImports = [] } = asyncOptions;
|
|
36
|
+
const { global = false, includeController = true, bootstrapAppConfig: { enableCompanyFeature } = {}, imports: externalImports = [], providers: additionalProviders = [] } = asyncOptions;
|
|
38
37
|
const asyncProviders = this.createAsyncProviders(asyncOptions);
|
|
39
38
|
// Build imports
|
|
40
39
|
const imports = [
|
|
@@ -61,6 +60,7 @@ let AuthModule = class AuthModule {
|
|
|
61
60
|
// Build providers
|
|
62
61
|
const providers = [
|
|
63
62
|
...asyncProviders,
|
|
63
|
+
...additionalProviders,
|
|
64
64
|
// Config & Infrastructure
|
|
65
65
|
_authconfigservice.AuthConfigService,
|
|
66
66
|
_authdatasourceprovider.AuthDataSourceProvider,
|
|
@@ -68,6 +68,7 @@ let AuthModule = class AuthModule {
|
|
|
68
68
|
_jwtstrategy.JwtStrategy,
|
|
69
69
|
_guards.JwtAuthGuard,
|
|
70
70
|
_services.AuthenticationService,
|
|
71
|
+
_services.AuthEmailService,
|
|
71
72
|
// Interceptors
|
|
72
73
|
_settokeninterceptor.SetToken,
|
|
73
74
|
_cleartokeninterceptor.ClearToken,
|
|
@@ -87,6 +88,7 @@ let AuthModule = class AuthModule {
|
|
|
87
88
|
_jwtstrategy.JwtStrategy,
|
|
88
89
|
_guards.JwtAuthGuard,
|
|
89
90
|
_services.AuthenticationService,
|
|
91
|
+
_services.AuthEmailService,
|
|
90
92
|
_services.UserService
|
|
91
93
|
];
|
|
92
94
|
if (enableCompanyFeature) {
|
|
@@ -102,7 +104,7 @@ let AuthModule = class AuthModule {
|
|
|
102
104
|
};
|
|
103
105
|
}
|
|
104
106
|
static buildDynamicModule(options) {
|
|
105
|
-
const { bootstrapAppConfig: { enableCompanyFeature } = {}, includeController = true, global = false } = options;
|
|
107
|
+
const { bootstrapAppConfig: { enableCompanyFeature } = {}, includeController = true, global = false, providers: additionalProviders = [] } = options;
|
|
106
108
|
const imports = [
|
|
107
109
|
_passport.PassportModule.register({
|
|
108
110
|
defaultStrategy: 'jwt'
|
|
@@ -128,6 +130,7 @@ let AuthModule = class AuthModule {
|
|
|
128
130
|
provide: _authconstants.AUTH_MODULE_OPTIONS,
|
|
129
131
|
useValue: options
|
|
130
132
|
},
|
|
133
|
+
...additionalProviders,
|
|
131
134
|
// Config & Infrastructure
|
|
132
135
|
_authconfigservice.AuthConfigService,
|
|
133
136
|
_authdatasourceprovider.AuthDataSourceProvider,
|
|
@@ -135,6 +138,7 @@ let AuthModule = class AuthModule {
|
|
|
135
138
|
_jwtstrategy.JwtStrategy,
|
|
136
139
|
_guards.JwtAuthGuard,
|
|
137
140
|
_services.AuthenticationService,
|
|
141
|
+
_services.AuthEmailService,
|
|
138
142
|
// Interceptors
|
|
139
143
|
_settokeninterceptor.SetToken,
|
|
140
144
|
_cleartokeninterceptor.ClearToken,
|
|
@@ -153,6 +157,7 @@ let AuthModule = class AuthModule {
|
|
|
153
157
|
_jwtstrategy.JwtStrategy,
|
|
154
158
|
_guards.JwtAuthGuard,
|
|
155
159
|
_services.AuthenticationService,
|
|
160
|
+
_services.AuthEmailService,
|
|
156
161
|
_services.UserService
|
|
157
162
|
];
|
|
158
163
|
if (enableCompanyFeature) {
|
|
@@ -233,23 +238,6 @@ let AuthModule = class AuthModule {
|
|
|
233
238
|
}
|
|
234
239
|
];
|
|
235
240
|
}
|
|
236
|
-
/**
|
|
237
|
-
* Create repository providers that use AuthDataSourceProvider
|
|
238
|
-
* This replaces TypeOrmModule.forFeature() functionality
|
|
239
|
-
* Note: Must be REQUEST-scoped since AuthDataSourceProvider is REQUEST-scoped
|
|
240
|
-
*/ static getRepositoryProviders(enableCompanyFeature) {
|
|
241
|
-
const entities = this.getEntities(enableCompanyFeature);
|
|
242
|
-
return entities.map((entity)=>({
|
|
243
|
-
provide: (0, _typeorm.getRepositoryToken)(entity),
|
|
244
|
-
scope: _common.Scope.REQUEST,
|
|
245
|
-
useFactory: async (dataSourceProvider)=>{
|
|
246
|
-
return await dataSourceProvider.getRepository(entity);
|
|
247
|
-
},
|
|
248
|
-
inject: [
|
|
249
|
-
_authdatasourceprovider.AuthDataSourceProvider
|
|
250
|
-
]
|
|
251
|
-
}));
|
|
252
|
-
}
|
|
253
241
|
static getEntities(enableCompanyFeature = false) {
|
|
254
242
|
const coreEntities = [
|
|
255
243
|
_entities.User
|
|
@@ -52,13 +52,28 @@ let AuthConfigService = class AuthConfigService {
|
|
|
52
52
|
}
|
|
53
53
|
// JWT Configuration
|
|
54
54
|
/** Get JWT secret key */ getJwtSecret() {
|
|
55
|
-
|
|
55
|
+
if (!this.config.jwtSecret) {
|
|
56
|
+
throw new _common.InternalServerErrorException('[AuthModule] JWT_SECRET is required - set via environment or module config');
|
|
57
|
+
}
|
|
58
|
+
return this.config.jwtSecret;
|
|
56
59
|
}
|
|
57
60
|
/** Get JWT expiration time */ getJwtExpiration() {
|
|
58
61
|
return this.config.jwtExpiration ?? '1h';
|
|
59
62
|
}
|
|
60
63
|
/** Get refresh token secret key */ getRefreshTokenSecret() {
|
|
61
|
-
|
|
64
|
+
if (this.config.refreshTokenSecret) {
|
|
65
|
+
return this.config.refreshTokenSecret;
|
|
66
|
+
}
|
|
67
|
+
// Production: require separate refresh token secret for security
|
|
68
|
+
if (process.env.NODE_ENV === 'production') {
|
|
69
|
+
throw new _common.InternalServerErrorException('[AuthModule] REFRESH_TOKEN_SECRET is required in production - ' + 'using the same secret for access and refresh tokens is a security risk');
|
|
70
|
+
}
|
|
71
|
+
// Development: warn once about fallback to JWT secret
|
|
72
|
+
if (!this.refreshTokenSecretWarned) {
|
|
73
|
+
this.refreshTokenSecretWarned = true;
|
|
74
|
+
this.logger.warn('REFRESH_TOKEN_SECRET not configured - using JWT_SECRET as fallback. ' + 'For better security, configure a separate refresh token secret.');
|
|
75
|
+
}
|
|
76
|
+
return this.config.jwtSecret ?? this.getJwtSecret();
|
|
62
77
|
}
|
|
63
78
|
/** Get refresh token expiration time */ getRefreshTokenExpiration() {
|
|
64
79
|
return this.config.refreshTokenExpiration ?? '7d';
|
|
@@ -66,6 +81,10 @@ let AuthConfigService = class AuthConfigService {
|
|
|
66
81
|
/** Get refresh token cookie name */ getRefreshTokenCookieName() {
|
|
67
82
|
return this.config.refreshTokenCookieName ?? 'fsn_refresh_token';
|
|
68
83
|
}
|
|
84
|
+
// Frontend Configuration
|
|
85
|
+
/** Get frontend URL for email links */ getFrontendUrl() {
|
|
86
|
+
return this.config.frontendUrl;
|
|
87
|
+
}
|
|
69
88
|
// Database Configuration
|
|
70
89
|
/** Get default database config */ getDefaultDatabaseConfig() {
|
|
71
90
|
return this.config.defaultDatabaseConfig ?? this.config.tenantDefaultDatabaseConfig;
|
|
@@ -88,8 +107,10 @@ let AuthConfigService = class AuthConfigService {
|
|
|
88
107
|
};
|
|
89
108
|
}
|
|
90
109
|
constructor(injectedOptions){
|
|
110
|
+
_define_property(this, "logger", new _common.Logger(AuthConfigService.name));
|
|
91
111
|
_define_property(this, "options", void 0);
|
|
92
112
|
_define_property(this, "config", void 0);
|
|
113
|
+
_define_property(this, "refreshTokenSecretWarned", false);
|
|
93
114
|
this.options = injectedOptions ?? {
|
|
94
115
|
global: false,
|
|
95
116
|
includeController: true
|
|
@@ -92,7 +92,7 @@ let AuthDataSourceProvider = class AuthDataSourceProvider extends _modules.Multi
|
|
|
92
92
|
const lockPromise = (async ()=>{
|
|
93
93
|
const config = this.getDefaultDatabaseConfig();
|
|
94
94
|
if (!config) {
|
|
95
|
-
throw new
|
|
95
|
+
throw new _common.InternalServerErrorException('Default database config is not available');
|
|
96
96
|
}
|
|
97
97
|
const ds = await this.createDataSourceFromConfig(config);
|
|
98
98
|
AuthDataSourceProvider.singleDataSource = ds;
|
|
@@ -153,9 +153,11 @@ let AuthDataSourceProvider = class AuthDataSourceProvider extends _modules.Multi
|
|
|
153
153
|
// Entity Management
|
|
154
154
|
/** Get auth entities based on company feature flag */ async getAuthEntities(enableCompanyFeature) {
|
|
155
155
|
const enable = enableCompanyFeature ?? this.getEnableCompanyFeature();
|
|
156
|
-
const { Company, CompanyBranch, User, UserCompanyPermission } = await Promise.resolve().then(()=>/*#__PURE__*/ _interop_require_wildcard(require("../entities")));
|
|
156
|
+
const { Company, CompanyBranch, User, UserCompanyPermission, UserToken, PendingRegistration } = await Promise.resolve().then(()=>/*#__PURE__*/ _interop_require_wildcard(require("../entities")));
|
|
157
157
|
const coreEntities = [
|
|
158
|
-
User
|
|
158
|
+
User,
|
|
159
|
+
UserToken,
|
|
160
|
+
PendingRegistration
|
|
159
161
|
];
|
|
160
162
|
const companyEntities = enable ? [
|
|
161
163
|
Company,
|
|
@@ -0,0 +1,471 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", {
|
|
3
|
+
value: true
|
|
4
|
+
});
|
|
5
|
+
Object.defineProperty(exports, "AuthEmailService", {
|
|
6
|
+
enumerable: true,
|
|
7
|
+
get: function() {
|
|
8
|
+
return AuthEmailService;
|
|
9
|
+
}
|
|
10
|
+
});
|
|
11
|
+
const _common = require("@nestjs/common");
|
|
12
|
+
const _bcrypt = /*#__PURE__*/ _interop_require_wildcard(require("bcrypt"));
|
|
13
|
+
const _crypto = /*#__PURE__*/ _interop_require_wildcard(require("crypto"));
|
|
14
|
+
const _typeorm = require("typeorm");
|
|
15
|
+
const _authdatasourceprovider = require("./auth-datasource.provider");
|
|
16
|
+
const _pendingregistrationentity = require("../entities/pending-registration.entity");
|
|
17
|
+
const _usertokenentity = require("../entities/user-token.entity");
|
|
18
|
+
const _userentity = require("../entities/user.entity");
|
|
19
|
+
const _interfaces = require("../interfaces");
|
|
20
|
+
const _config = require("../config");
|
|
21
|
+
function _define_property(obj, key, value) {
|
|
22
|
+
if (key in obj) {
|
|
23
|
+
Object.defineProperty(obj, key, {
|
|
24
|
+
value: value,
|
|
25
|
+
enumerable: true,
|
|
26
|
+
configurable: true,
|
|
27
|
+
writable: true
|
|
28
|
+
});
|
|
29
|
+
} else {
|
|
30
|
+
obj[key] = value;
|
|
31
|
+
}
|
|
32
|
+
return obj;
|
|
33
|
+
}
|
|
34
|
+
function _getRequireWildcardCache(nodeInterop) {
|
|
35
|
+
if (typeof WeakMap !== "function") return null;
|
|
36
|
+
var cacheBabelInterop = new WeakMap();
|
|
37
|
+
var cacheNodeInterop = new WeakMap();
|
|
38
|
+
return (_getRequireWildcardCache = function(nodeInterop) {
|
|
39
|
+
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
|
|
40
|
+
})(nodeInterop);
|
|
41
|
+
}
|
|
42
|
+
function _interop_require_wildcard(obj, nodeInterop) {
|
|
43
|
+
if (!nodeInterop && obj && obj.__esModule) {
|
|
44
|
+
return obj;
|
|
45
|
+
}
|
|
46
|
+
if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
|
|
47
|
+
return {
|
|
48
|
+
default: obj
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
var cache = _getRequireWildcardCache(nodeInterop);
|
|
52
|
+
if (cache && cache.has(obj)) {
|
|
53
|
+
return cache.get(obj);
|
|
54
|
+
}
|
|
55
|
+
var newObj = {
|
|
56
|
+
__proto__: null
|
|
57
|
+
};
|
|
58
|
+
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
|
|
59
|
+
for(var key in obj){
|
|
60
|
+
if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
|
|
61
|
+
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
|
|
62
|
+
if (desc && (desc.get || desc.set)) {
|
|
63
|
+
Object.defineProperty(newObj, key, desc);
|
|
64
|
+
} else {
|
|
65
|
+
newObj[key] = obj[key];
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
newObj.default = obj;
|
|
70
|
+
if (cache) {
|
|
71
|
+
cache.set(obj, newObj);
|
|
72
|
+
}
|
|
73
|
+
return newObj;
|
|
74
|
+
}
|
|
75
|
+
function _ts_decorate(decorators, target, key, desc) {
|
|
76
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
77
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
78
|
+
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;
|
|
79
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
80
|
+
}
|
|
81
|
+
function _ts_metadata(k, v) {
|
|
82
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
83
|
+
}
|
|
84
|
+
function _ts_param(paramIndex, decorator) {
|
|
85
|
+
return function(target, key) {
|
|
86
|
+
decorator(target, key, paramIndex);
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
let AuthEmailService = class AuthEmailService {
|
|
90
|
+
async getUserRepository() {
|
|
91
|
+
if (this.dataSourceProvider) {
|
|
92
|
+
return this.dataSourceProvider.getRepository(_userentity.User);
|
|
93
|
+
}
|
|
94
|
+
throw new _common.InternalServerErrorException('User repository not available');
|
|
95
|
+
}
|
|
96
|
+
async getUserTokenRepository() {
|
|
97
|
+
if (this.dataSourceProvider) {
|
|
98
|
+
return this.dataSourceProvider.getRepository(_usertokenentity.UserToken);
|
|
99
|
+
}
|
|
100
|
+
throw new _common.InternalServerErrorException('UserToken repository not available');
|
|
101
|
+
}
|
|
102
|
+
async getPendingRegistrationRepository() {
|
|
103
|
+
if (this.dataSourceProvider) {
|
|
104
|
+
return this.dataSourceProvider.getRepository(_pendingregistrationentity.PendingRegistration);
|
|
105
|
+
}
|
|
106
|
+
throw new _common.InternalServerErrorException('PendingRegistration repository not available');
|
|
107
|
+
}
|
|
108
|
+
isEmailEnabled() {
|
|
109
|
+
return !!this.emailProvider;
|
|
110
|
+
}
|
|
111
|
+
generateToken() {
|
|
112
|
+
return _crypto.randomBytes(32).toString('hex');
|
|
113
|
+
}
|
|
114
|
+
/** Hash token for secure storage - prevents token theft if database is compromised */ hashToken(token) {
|
|
115
|
+
return _crypto.createHash('sha256').update(token).digest('hex');
|
|
116
|
+
}
|
|
117
|
+
// ============================================
|
|
118
|
+
// Pending Registration (New Users)
|
|
119
|
+
// ============================================
|
|
120
|
+
/**
|
|
121
|
+
* Create pending registration - stores data until email verified
|
|
122
|
+
*/ async createPendingRegistration(data) {
|
|
123
|
+
if (!this.emailProvider) {
|
|
124
|
+
throw new _common.BadRequestException('Email service is not configured');
|
|
125
|
+
}
|
|
126
|
+
const userRepository = await this.getUserRepository();
|
|
127
|
+
const pendingRepository = await this.getPendingRegistrationRepository();
|
|
128
|
+
// Check if user already exists
|
|
129
|
+
const existingUser = await userRepository.findOne({
|
|
130
|
+
where: {
|
|
131
|
+
email: data.email
|
|
132
|
+
}
|
|
133
|
+
});
|
|
134
|
+
if (existingUser) {
|
|
135
|
+
throw new _common.BadRequestException('Registration failed. Please try again or contact support.');
|
|
136
|
+
}
|
|
137
|
+
// Delete any existing pending registration for this email
|
|
138
|
+
await pendingRepository.delete({
|
|
139
|
+
email: data.email
|
|
140
|
+
});
|
|
141
|
+
// Create pending registration with hashed token for secure storage
|
|
142
|
+
const token = this.generateToken();
|
|
143
|
+
const tokenHash = this.hashToken(token);
|
|
144
|
+
const passwordHash = await _bcrypt.hash(data.password, _config.BCRYPT_SALT_ROUNDS);
|
|
145
|
+
const expiresAt = new Date(Date.now() + this.EMAIL_VERIFICATION_EXPIRY);
|
|
146
|
+
const pending = pendingRepository.create({
|
|
147
|
+
email: data.email,
|
|
148
|
+
name: data.name ?? null,
|
|
149
|
+
phone: data.phone ?? null,
|
|
150
|
+
passwordHash,
|
|
151
|
+
token: tokenHash,
|
|
152
|
+
expiresAt,
|
|
153
|
+
companyData: data.companyData ?? null
|
|
154
|
+
});
|
|
155
|
+
await pendingRepository.save(pending);
|
|
156
|
+
// Send verification email with raw token (user receives this)
|
|
157
|
+
const verifyUrl = `${data.verifyUrlBase}?token=${token}`;
|
|
158
|
+
try {
|
|
159
|
+
await this.emailProvider.sendVerificationEmail(data.email, token, verifyUrl);
|
|
160
|
+
this.logger.log(`Registration verification email sent to: ${data.email}`);
|
|
161
|
+
} catch (error) {
|
|
162
|
+
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
|
|
163
|
+
this.logger.error(`Failed to send verification email: ${errorMessage}`);
|
|
164
|
+
throw new _common.BadRequestException('Failed to send verification email. Please try again.');
|
|
165
|
+
}
|
|
166
|
+
return {
|
|
167
|
+
success: true,
|
|
168
|
+
message: 'Please check your email to verify your registration.'
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
// ============================================
|
|
172
|
+
// Password Reset (Existing Users)
|
|
173
|
+
// ============================================
|
|
174
|
+
/**
|
|
175
|
+
* Request password reset - sends reset email
|
|
176
|
+
*/ async forgotPassword(email, resetUrlBase) {
|
|
177
|
+
if (!this.emailProvider) {
|
|
178
|
+
throw new _common.BadRequestException('Email service is not configured');
|
|
179
|
+
}
|
|
180
|
+
const userRepository = await this.getUserRepository();
|
|
181
|
+
const tokenRepository = await this.getUserTokenRepository();
|
|
182
|
+
const user = await userRepository.findOne({
|
|
183
|
+
where: {
|
|
184
|
+
email
|
|
185
|
+
}
|
|
186
|
+
});
|
|
187
|
+
// Always return success to prevent email enumeration
|
|
188
|
+
if (!user || !user.isActive) {
|
|
189
|
+
this.logger.warn(`Password reset requested for non-existent/inactive email: ${email}`);
|
|
190
|
+
return {
|
|
191
|
+
success: true,
|
|
192
|
+
message: 'If the email exists, a password reset link has been sent.'
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
// Invalidate existing password reset tokens for this user
|
|
196
|
+
await tokenRepository.delete({
|
|
197
|
+
userId: user.id,
|
|
198
|
+
type: _usertokenentity.TokenType.PASSWORD_RESET
|
|
199
|
+
});
|
|
200
|
+
// Create new token with hashed storage
|
|
201
|
+
const token = this.generateToken();
|
|
202
|
+
const tokenHash = this.hashToken(token);
|
|
203
|
+
const userToken = tokenRepository.create({
|
|
204
|
+
userId: user.id,
|
|
205
|
+
type: _usertokenentity.TokenType.PASSWORD_RESET,
|
|
206
|
+
token: tokenHash,
|
|
207
|
+
expiresAt: new Date(Date.now() + this.PASSWORD_RESET_EXPIRY)
|
|
208
|
+
});
|
|
209
|
+
await tokenRepository.save(userToken);
|
|
210
|
+
// Send email with raw token
|
|
211
|
+
const resetUrl = `${resetUrlBase}?token=${token}`;
|
|
212
|
+
try {
|
|
213
|
+
await this.emailProvider.sendPasswordResetEmail(email, token, resetUrl);
|
|
214
|
+
this.logger.log(`Password reset email sent to: ${email}`);
|
|
215
|
+
} catch (error) {
|
|
216
|
+
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
|
|
217
|
+
this.logger.error(`Failed to send password reset email: ${errorMessage}`);
|
|
218
|
+
// Don't silently fail - but still use same message to prevent enumeration
|
|
219
|
+
throw new _common.BadRequestException('Failed to process request. Please try again later.');
|
|
220
|
+
}
|
|
221
|
+
return {
|
|
222
|
+
success: true,
|
|
223
|
+
message: 'If the email exists, a password reset link has been sent.'
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Reset password using token
|
|
228
|
+
*/ async resetPassword(token, newPassword) {
|
|
229
|
+
const userRepository = await this.getUserRepository();
|
|
230
|
+
const tokenRepository = await this.getUserTokenRepository();
|
|
231
|
+
// Hash the incoming token to compare with stored hash
|
|
232
|
+
const tokenHash = this.hashToken(token);
|
|
233
|
+
const userToken = await tokenRepository.findOne({
|
|
234
|
+
where: {
|
|
235
|
+
token: tokenHash,
|
|
236
|
+
type: _usertokenentity.TokenType.PASSWORD_RESET
|
|
237
|
+
}
|
|
238
|
+
});
|
|
239
|
+
if (!userToken) {
|
|
240
|
+
throw new _common.BadRequestException('Invalid or expired reset token');
|
|
241
|
+
}
|
|
242
|
+
if (userToken.expiresAt < new Date()) {
|
|
243
|
+
await tokenRepository.delete({
|
|
244
|
+
id: userToken.id
|
|
245
|
+
});
|
|
246
|
+
throw new _common.BadRequestException('Reset token has expired. Please request a new one.');
|
|
247
|
+
}
|
|
248
|
+
if (userToken.usedAt) {
|
|
249
|
+
throw new _common.BadRequestException('This reset token has already been used.');
|
|
250
|
+
}
|
|
251
|
+
const user = await userRepository.findOne({
|
|
252
|
+
where: {
|
|
253
|
+
id: userToken.userId
|
|
254
|
+
}
|
|
255
|
+
});
|
|
256
|
+
if (!user) {
|
|
257
|
+
throw new _common.BadRequestException('User not found');
|
|
258
|
+
}
|
|
259
|
+
// Update password
|
|
260
|
+
user.password = await _bcrypt.hash(newPassword, _config.BCRYPT_SALT_ROUNDS);
|
|
261
|
+
await userRepository.save(user);
|
|
262
|
+
// Mark token as used
|
|
263
|
+
userToken.usedAt = new Date();
|
|
264
|
+
await tokenRepository.save(userToken);
|
|
265
|
+
this.logger.log(`Password reset successful for user: ${user.email}`);
|
|
266
|
+
return {
|
|
267
|
+
success: true,
|
|
268
|
+
message: 'Password has been reset successfully.'
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
// ============================================
|
|
272
|
+
// Email Verification
|
|
273
|
+
// ============================================
|
|
274
|
+
/**
|
|
275
|
+
* Verify email using token
|
|
276
|
+
* Handles both pending registration and existing user verification
|
|
277
|
+
*/ async verifyEmail(token) {
|
|
278
|
+
const pendingRepository = await this.getPendingRegistrationRepository();
|
|
279
|
+
const userRepository = await this.getUserRepository();
|
|
280
|
+
const tokenRepository = await this.getUserTokenRepository();
|
|
281
|
+
// Hash the incoming token to compare with stored hash
|
|
282
|
+
const tokenHash = this.hashToken(token);
|
|
283
|
+
// Check for pending registration first
|
|
284
|
+
const pending = await pendingRepository.findOne({
|
|
285
|
+
where: {
|
|
286
|
+
token: tokenHash
|
|
287
|
+
}
|
|
288
|
+
});
|
|
289
|
+
if (pending) {
|
|
290
|
+
if (pending.expiresAt < new Date()) {
|
|
291
|
+
await pendingRepository.delete({
|
|
292
|
+
id: pending.id
|
|
293
|
+
});
|
|
294
|
+
throw new _common.BadRequestException('Verification token has expired. Please register again.');
|
|
295
|
+
}
|
|
296
|
+
// Delete pending registration (will be consumed by caller to create user)
|
|
297
|
+
await pendingRepository.delete({
|
|
298
|
+
id: pending.id
|
|
299
|
+
});
|
|
300
|
+
return {
|
|
301
|
+
type: 'pending',
|
|
302
|
+
pending
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
// Check for existing user email verification token (token already hashed above)
|
|
306
|
+
const userToken = await tokenRepository.findOne({
|
|
307
|
+
where: {
|
|
308
|
+
token: tokenHash,
|
|
309
|
+
type: _usertokenentity.TokenType.EMAIL_VERIFICATION
|
|
310
|
+
}
|
|
311
|
+
});
|
|
312
|
+
if (!userToken) {
|
|
313
|
+
throw new _common.BadRequestException('Invalid or expired verification token');
|
|
314
|
+
}
|
|
315
|
+
if (userToken.expiresAt < new Date()) {
|
|
316
|
+
await tokenRepository.delete({
|
|
317
|
+
id: userToken.id
|
|
318
|
+
});
|
|
319
|
+
throw new _common.BadRequestException('Verification token has expired. Please request a new one.');
|
|
320
|
+
}
|
|
321
|
+
if (userToken.usedAt) {
|
|
322
|
+
return {
|
|
323
|
+
type: 'verified',
|
|
324
|
+
message: 'Email has already been verified.'
|
|
325
|
+
};
|
|
326
|
+
}
|
|
327
|
+
const user = await userRepository.findOne({
|
|
328
|
+
where: {
|
|
329
|
+
id: userToken.userId
|
|
330
|
+
}
|
|
331
|
+
});
|
|
332
|
+
if (!user) {
|
|
333
|
+
throw new _common.BadRequestException('User not found');
|
|
334
|
+
}
|
|
335
|
+
// Mark email as verified
|
|
336
|
+
user.emailVerified = true;
|
|
337
|
+
await userRepository.save(user);
|
|
338
|
+
// Mark token as used
|
|
339
|
+
userToken.usedAt = new Date();
|
|
340
|
+
await tokenRepository.save(userToken);
|
|
341
|
+
this.logger.log(`Email verified for user: ${user.email}`);
|
|
342
|
+
return {
|
|
343
|
+
type: 'verified',
|
|
344
|
+
message: 'Email has been verified successfully.'
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
/**
|
|
348
|
+
* Resend verification email - handles both pending registrations and existing users
|
|
349
|
+
*/ async resendVerificationEmail(email, verifyUrlBase) {
|
|
350
|
+
if (!this.emailProvider) {
|
|
351
|
+
throw new _common.BadRequestException('Email service is not configured');
|
|
352
|
+
}
|
|
353
|
+
const pendingRepository = await this.getPendingRegistrationRepository();
|
|
354
|
+
const userRepository = await this.getUserRepository();
|
|
355
|
+
const tokenRepository = await this.getUserTokenRepository();
|
|
356
|
+
// Check pending registration first
|
|
357
|
+
const pending = await pendingRepository.findOne({
|
|
358
|
+
where: {
|
|
359
|
+
email
|
|
360
|
+
}
|
|
361
|
+
});
|
|
362
|
+
if (pending) {
|
|
363
|
+
const token = this.generateToken();
|
|
364
|
+
const tokenHash = this.hashToken(token);
|
|
365
|
+
pending.token = tokenHash; // Store hashed token
|
|
366
|
+
pending.expiresAt = new Date(Date.now() + this.EMAIL_VERIFICATION_EXPIRY);
|
|
367
|
+
await pendingRepository.save(pending);
|
|
368
|
+
const verifyUrl = `${verifyUrlBase}?token=${token}`;
|
|
369
|
+
try {
|
|
370
|
+
await this.emailProvider.sendVerificationEmail(email, token, verifyUrl);
|
|
371
|
+
this.logger.log(`Re-sent registration verification email to: ${email}`);
|
|
372
|
+
} catch (error) {
|
|
373
|
+
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
|
|
374
|
+
this.logger.error(`Failed to resend verification email: ${errorMessage}`);
|
|
375
|
+
throw new _common.BadRequestException('Failed to send verification email. Please try again.');
|
|
376
|
+
}
|
|
377
|
+
return {
|
|
378
|
+
success: true,
|
|
379
|
+
message: 'If the email requires verification, a link has been sent.'
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
// Check existing user
|
|
383
|
+
const user = await userRepository.findOne({
|
|
384
|
+
where: {
|
|
385
|
+
email
|
|
386
|
+
}
|
|
387
|
+
});
|
|
388
|
+
if (!user || user.emailVerified) {
|
|
389
|
+
return {
|
|
390
|
+
success: true,
|
|
391
|
+
message: 'If the email requires verification, a link has been sent.'
|
|
392
|
+
};
|
|
393
|
+
}
|
|
394
|
+
// Invalidate existing tokens and create new one
|
|
395
|
+
await tokenRepository.delete({
|
|
396
|
+
userId: user.id,
|
|
397
|
+
type: _usertokenentity.TokenType.EMAIL_VERIFICATION
|
|
398
|
+
});
|
|
399
|
+
const token = this.generateToken();
|
|
400
|
+
const tokenHash = this.hashToken(token);
|
|
401
|
+
const userToken = tokenRepository.create({
|
|
402
|
+
userId: user.id,
|
|
403
|
+
type: _usertokenentity.TokenType.EMAIL_VERIFICATION,
|
|
404
|
+
token: tokenHash,
|
|
405
|
+
expiresAt: new Date(Date.now() + this.EMAIL_VERIFICATION_EXPIRY)
|
|
406
|
+
});
|
|
407
|
+
await tokenRepository.save(userToken);
|
|
408
|
+
const verifyUrl = `${verifyUrlBase}?token=${token}`;
|
|
409
|
+
try {
|
|
410
|
+
await this.emailProvider.sendVerificationEmail(user.email, token, verifyUrl);
|
|
411
|
+
this.logger.log(`Verification email sent to: ${user.email}`);
|
|
412
|
+
} catch (error) {
|
|
413
|
+
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
|
|
414
|
+
this.logger.error(`Failed to send verification email: ${errorMessage}`);
|
|
415
|
+
throw new _common.BadRequestException('Failed to send verification email. Please try again.');
|
|
416
|
+
}
|
|
417
|
+
return {
|
|
418
|
+
success: true,
|
|
419
|
+
message: 'If the email requires verification, a link has been sent.'
|
|
420
|
+
};
|
|
421
|
+
}
|
|
422
|
+
// ============================================
|
|
423
|
+
// Cleanup
|
|
424
|
+
// ============================================
|
|
425
|
+
/**
|
|
426
|
+
* Clean up expired tokens and pending registrations
|
|
427
|
+
*/ async cleanupExpired() {
|
|
428
|
+
const tokenRepository = await this.getUserTokenRepository();
|
|
429
|
+
const pendingRepository = await this.getPendingRegistrationRepository();
|
|
430
|
+
const now = new Date();
|
|
431
|
+
const tokenResult = await tokenRepository.delete({
|
|
432
|
+
expiresAt: (0, _typeorm.LessThan)(now)
|
|
433
|
+
});
|
|
434
|
+
const pendingResult = await pendingRepository.delete({
|
|
435
|
+
expiresAt: (0, _typeorm.LessThan)(now)
|
|
436
|
+
});
|
|
437
|
+
const deletedTokens = tokenResult.affected ?? 0;
|
|
438
|
+
const deletedPending = pendingResult.affected ?? 0;
|
|
439
|
+
this.logger.log(`Cleaned up ${deletedTokens} expired tokens and ${deletedPending} expired pending registrations`);
|
|
440
|
+
return {
|
|
441
|
+
deletedTokens,
|
|
442
|
+
deletedPending
|
|
443
|
+
};
|
|
444
|
+
}
|
|
445
|
+
constructor(dataSourceProvider, emailProvider){
|
|
446
|
+
_define_property(this, "dataSourceProvider", void 0);
|
|
447
|
+
_define_property(this, "emailProvider", void 0);
|
|
448
|
+
_define_property(this, "logger", void 0);
|
|
449
|
+
_define_property(this, "PASSWORD_RESET_EXPIRY", void 0); // 1 hour
|
|
450
|
+
_define_property(this, "EMAIL_VERIFICATION_EXPIRY", void 0); // 24 hours
|
|
451
|
+
this.dataSourceProvider = dataSourceProvider;
|
|
452
|
+
this.emailProvider = emailProvider;
|
|
453
|
+
this.logger = new _common.Logger(AuthEmailService.name);
|
|
454
|
+
this.PASSWORD_RESET_EXPIRY = 60 * 60 * 1000;
|
|
455
|
+
this.EMAIL_VERIFICATION_EXPIRY = 24 * 60 * 60 * 1000;
|
|
456
|
+
}
|
|
457
|
+
};
|
|
458
|
+
AuthEmailService = _ts_decorate([
|
|
459
|
+
(0, _common.Injectable)({
|
|
460
|
+
scope: _common.Scope.REQUEST
|
|
461
|
+
}),
|
|
462
|
+
_ts_param(0, (0, _common.Optional)()),
|
|
463
|
+
_ts_param(0, (0, _common.Inject)(_authdatasourceprovider.AuthDataSourceProvider)),
|
|
464
|
+
_ts_param(1, (0, _common.Optional)()),
|
|
465
|
+
_ts_param(1, (0, _common.Inject)(_interfaces.AUTH_EMAIL_PROVIDER)),
|
|
466
|
+
_ts_metadata("design:type", Function),
|
|
467
|
+
_ts_metadata("design:paramtypes", [
|
|
468
|
+
typeof _authdatasourceprovider.AuthDataSourceProvider === "undefined" ? Object : _authdatasourceprovider.AuthDataSourceProvider,
|
|
469
|
+
typeof _interfaces.IAuthEmailProvider === "undefined" ? Object : _interfaces.IAuthEmailProvider
|
|
470
|
+
])
|
|
471
|
+
], AuthEmailService);
|