emilsoftware-utilities 1.3.87 → 1.3.89

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.
@@ -16,7 +16,6 @@ const PermissionService_1 = require("./Services/PermissionService/PermissionServ
16
16
  const UserService_1 = require("./Services/UserService/UserService");
17
17
  let AccessiModule = AccessiModule_1 = class AccessiModule {
18
18
  static forRoot(options) {
19
- console.log("✅ AccessiModule inizializzato con opzioni:", options);
20
19
  return {
21
20
  module: AccessiModule_1,
22
21
  providers: [
@@ -4,6 +4,7 @@ import { AuthService } from '../Services/AuthService/AuthService';
4
4
  import { PermissionService } from '../Services/PermissionService/PermissionService';
5
5
  import { UserService } from '../Services/UserService/UserService';
6
6
  import { EmailService } from '../Services/EmailService/EmailService';
7
+ import { IUser } from '../Services/UserService/IUserService';
7
8
  export declare class AccessiController {
8
9
  private readonly userService;
9
10
  private readonly authService;
@@ -11,6 +12,8 @@ export declare class AccessiController {
11
12
  private readonly permissionService;
12
13
  private readonly options;
13
14
  constructor(userService: UserService, authService: AuthService, emailService: EmailService, permissionService: PermissionService, options: AccessiOptions);
15
+ serveResetPasswordPage(res: Response, token: string): Promise<void>;
16
+ resetPassword(res: Response, token: string, newPassword: string): Promise<Response<any, Record<string, any>>>;
14
17
  getUserByToken(token: string, res: Response): Promise<Response<any, Record<string, any>>>;
15
18
  login(loginDto: {
16
19
  username: string;
@@ -18,7 +21,7 @@ export declare class AccessiController {
18
21
  }, res: Response): Promise<Response<any, Record<string, any>>>;
19
22
  getUsers(res: Response): Promise<Response<any, Record<string, any>>>;
20
23
  deleteUser(codiceUtente: string, res: Response): Promise<Response<any, Record<string, any>>>;
21
- register(request: any, res: Response): Promise<Response<any, Record<string, any>>>;
24
+ register(request: Request, registrationData: IUser, res: Response): Promise<Response<any, Record<string, any>>>;
22
25
  encrypt(data: string, res: Response): Promise<Response<any, Record<string, any>>>;
23
26
  decrypt(data: string, res: Response): Promise<Response<any, Record<string, any>>>;
24
27
  resetAbilitazioni(codiceUtente: string, res: Response): Promise<Response<any, Record<string, any>>>;
@@ -64,6 +64,7 @@ const AuthService_1 = require("../Services/AuthService/AuthService");
64
64
  const PermissionService_1 = require("../Services/PermissionService/PermissionService");
65
65
  const UserService_1 = require("../Services/UserService/UserService");
66
66
  const EmailService_1 = require("../Services/EmailService/EmailService");
67
+ const path_1 = require("path");
67
68
  let AccessiController = AccessiController_1 = class AccessiController {
68
69
  constructor(userService, authService, emailService, permissionService, options) {
69
70
  this.userService = userService;
@@ -72,6 +73,22 @@ let AccessiController = AccessiController_1 = class AccessiController {
72
73
  this.permissionService = permissionService;
73
74
  this.options = options;
74
75
  }
76
+ serveResetPasswordPage(res, token) {
77
+ return __awaiter(this, void 0, void 0, function* () {
78
+ return res.sendFile((0, path_1.join)(__dirname, '..', 'Views', 'reset-password.html'));
79
+ });
80
+ }
81
+ resetPassword(res, token, newPassword) {
82
+ return __awaiter(this, void 0, void 0, function* () {
83
+ try {
84
+ yield this.authService.resetPassword(token, newPassword);
85
+ return Utilities_1.RestUtilities.sendOKMessage(res, 'Password aggiornata con successo!');
86
+ }
87
+ catch (error) {
88
+ return Utilities_1.RestUtilities.sendErrorMessage(res, error, AccessiController_1.name);
89
+ }
90
+ });
91
+ }
75
92
  getUserByToken(token, res) {
76
93
  return __awaiter(this, void 0, void 0, function* () {
77
94
  try {
@@ -129,11 +146,17 @@ let AccessiController = AccessiController_1 = class AccessiController {
129
146
  }
130
147
  });
131
148
  }
132
- register(request, res) {
149
+ register(request, registrationData, res) {
133
150
  return __awaiter(this, void 0, void 0, function* () {
134
151
  try {
135
- yield this.userService.register(request);
136
- return Utilities_1.RestUtilities.sendOKMessage(res, 'L\'utente è stato registrato con successo.');
152
+ let protocol = request["protocol"];
153
+ let host = request.headers["host"];
154
+ if (!protocol || !host) {
155
+ return Utilities_1.RestUtilities.sendErrorMessage(res, "Impossibile procedere: protocollo e host non impostati negli header della richiesta.", AccessiController_1.name);
156
+ }
157
+ let confirmationEmailPrefix = protocol + "://" + host;
158
+ yield this.userService.register(registrationData, confirmationEmailPrefix);
159
+ return Utilities_1.RestUtilities.sendOKMessage(res, "L'utente è stato registrato con successo.");
137
160
  }
138
161
  catch (error) {
139
162
  return Utilities_1.RestUtilities.sendErrorMessage(res, error, AccessiController_1.name);
@@ -210,6 +233,23 @@ let AccessiController = AccessiController_1 = class AccessiController {
210
233
  exports.AccessiController = AccessiController;
211
234
  __decorate([
212
235
  (0, swagger_1.ApiOperation)({ summary: 'Recupera le informazioni utente dal token JWT' }),
236
+ (0, common_1.Get)('reset-password/:token'),
237
+ __param(0, (0, common_1.Res)()),
238
+ __param(1, (0, common_1.Param)('token')),
239
+ __metadata("design:type", Function),
240
+ __metadata("design:paramtypes", [Object, String]),
241
+ __metadata("design:returntype", Promise)
242
+ ], AccessiController.prototype, "serveResetPasswordPage", null);
243
+ __decorate([
244
+ (0, common_1.Post)('reset-password/:token'),
245
+ __param(0, (0, common_1.Res)()),
246
+ __param(1, (0, common_1.Param)('token')),
247
+ __param(2, (0, common_1.Body)("newPassword")),
248
+ __metadata("design:type", Function),
249
+ __metadata("design:paramtypes", [Object, String, String]),
250
+ __metadata("design:returntype", Promise)
251
+ ], AccessiController.prototype, "resetPassword", null);
252
+ __decorate([
213
253
  (0, common_1.Post)('get-user-by-token'),
214
254
  __param(0, (0, common_1.Body)('token')),
215
255
  __param(1, (0, common_1.Res)()),
@@ -228,7 +268,7 @@ __decorate([
228
268
  ], AccessiController.prototype, "login", null);
229
269
  __decorate([
230
270
  (0, swagger_1.ApiOperation)({ summary: 'Recupera la lista degli utenti' }),
231
- (0, common_1.Get)('users'),
271
+ (0, common_1.Post)('get-users'),
232
272
  __param(0, (0, common_1.Res)()),
233
273
  __metadata("design:type", Function),
234
274
  __metadata("design:paramtypes", [Object]),
@@ -246,10 +286,11 @@ __decorate([
246
286
  __decorate([
247
287
  (0, swagger_1.ApiOperation)({ summary: 'Registra un nuovo utente' }),
248
288
  (0, common_1.Post)('register'),
249
- __param(0, (0, common_1.Body)()),
250
- __param(1, (0, common_1.Res)()),
289
+ __param(0, (0, common_1.Req)()),
290
+ __param(1, (0, common_1.Body)()),
291
+ __param(2, (0, common_1.Res)()),
251
292
  __metadata("design:type", Function),
252
- __metadata("design:paramtypes", [Object, Object]),
293
+ __metadata("design:paramtypes", [Request, Object, Object]),
253
294
  __metadata("design:returntype", Promise)
254
295
  ], AccessiController.prototype, "register", null);
255
296
  __decorate([
@@ -73,7 +73,8 @@ let AuthService = class AuthService {
73
73
  return __awaiter(this, void 0, void 0, function* () {
74
74
  try {
75
75
  const query = `UPDATE OR INSERT INTO UTENTI_PWD (CODUTE, PWD) VALUES (?, ?)`;
76
- return yield Orm_1.Orm.execute(this.accessiOptions.databaseOptions, query, [codiceUtente, nuovaPassword]);
76
+ const hashedPassword = Utilities_1.CryptUtilities.encrypt(nuovaPassword, this.accessiOptions.encryptionKey);
77
+ return yield Orm_1.Orm.execute(this.accessiOptions.databaseOptions, query, [codiceUtente, hashedPassword]);
77
78
  }
78
79
  catch (error) {
79
80
  throw error;
@@ -132,18 +133,18 @@ let AuthService = class AuthService {
132
133
  return __awaiter(this, void 0, void 0, function* () {
133
134
  try {
134
135
  // Controlliamo se il token esiste
135
- const result = yield Orm_1.Orm.query({}, "SELECT CODUTE FROM UTENTI WHERE KEYREG = ?", [token]);
136
+ const result = yield Orm_1.Orm.query(this.accessiOptions.databaseOptions, "SELECT CODUTE FROM UTENTI WHERE KEYREG = ?", [token]);
136
137
  if (result.length === 0) {
137
138
  throw new Error("Token non valido o già usato.");
138
139
  }
139
140
  // Hashiamo la nuova password
140
141
  const hashedPassword = Utilities_1.CryptUtilities.encrypt(newPassword, this.accessiOptions.encryptionKey);
141
142
  // Aggiorniamo la password e rimuoviamo il token di reset
142
- yield Orm_1.Orm.query({}, "UPDATE UTENTI SET PASSWORD = ?, KEYREG = NULL WHERE CODUTE = ?", [hashedPassword, result[0].CODUTE]);
143
+ yield Orm_1.Orm.query(this.accessiOptions.databaseOptions, "UPDATE UTENTI SET KEYREG = NULL, STAREG = ? WHERE CODUTE = ?", [StatoRegistrazione_1.StatoRegistrazione.CONF, result[0].CODUTE]);
144
+ yield Orm_1.Orm.query(this.accessiOptions.databaseOptions, "UPDATE OR INSERT INTO UTENTI_PWD (CODUTE, PWD) VALUES (?, ?)", [result[0].CODUTE, hashedPassword]);
143
145
  }
144
146
  catch (error) {
145
- console.error("Errore nel reset della password:", error);
146
- throw new Error("Errore durante il reset della password.");
147
+ throw error;
147
148
  }
148
149
  });
149
150
  }
@@ -6,5 +6,4 @@ export declare class EmailService implements IEmailService {
6
6
  sendAccountUpdateEmail(email: string, message: string): Promise<void>;
7
7
  private transporter;
8
8
  sendPasswordResetEmail(email: string, baseUrl: string): Promise<void>;
9
- sendVerificationEmail(email: string, codiceUtente: string, baseUrl: string): Promise<void>;
10
9
  }
@@ -42,11 +42,11 @@ let EmailService = class EmailService {
42
42
  try {
43
43
  const resetToken = (0, uuid_1.v4)(); // Generiamo un nuovo token unico
44
44
  // Aggiorna il campo keyReg nel database
45
- const result = yield Orm_1.Orm.query({}, "UPDATE UTENTI SET KEYREG = ? WHERE USRNAME = ? RETURNING CODUTE", [resetToken, email]);
45
+ const result = yield Orm_1.Orm.query(this.accessiOptions.databaseOptions, "UPDATE UTENTI SET KEYREG = ? WHERE USRNAME = ? RETURNING CODUTE", [resetToken, email]);
46
46
  if (result.length === 0) {
47
47
  throw new Error("Email non trovata.");
48
48
  }
49
- const resetUrl = `${baseUrl}/reset-password/${resetToken}`;
49
+ const resetUrl = `${baseUrl}/api/accessi/reset-password/${resetToken}`;
50
50
  const mailOptions = {
51
51
  from: this.accessiOptions.emailOptions.from,
52
52
  to: email,
@@ -62,27 +62,6 @@ let EmailService = class EmailService {
62
62
  }
63
63
  });
64
64
  }
65
- sendVerificationEmail(email, codiceUtente, baseUrl) {
66
- return __awaiter(this, void 0, void 0, function* () {
67
- try {
68
- const userKey = (0, uuid_1.v4)();
69
- yield Orm_1.Orm.query(this.accessiOptions.databaseOptions, "UPDATE UTENTI SET KEYREG = ? WHERE CODUTE = ?", [userKey, codiceUtente]);
70
- const verificationUrl = `${baseUrl}/${userKey}`;
71
- const mailOptions = {
72
- from: '"Supporto" <noreply@example.com>',
73
- to: email,
74
- subject: 'Verifica la tua email',
75
- text: `Clicca sul seguente link per verificare il tuo account: ${verificationUrl}`,
76
- html: `<p>Clicca sul seguente link per verificare il tuo account:</p><a href="${verificationUrl}">${verificationUrl}</a>`
77
- };
78
- yield this.transporter.sendMail(mailOptions);
79
- }
80
- catch (error) {
81
- console.error("Errore nell'invio dell'email di verifica:", error);
82
- throw new Error("Errore durante l'invio dell'email di verifica.");
83
- }
84
- });
85
- }
86
65
  };
87
66
  exports.EmailService = EmailService;
88
67
  exports.EmailService = EmailService = __decorate([
@@ -1,14 +1,4 @@
1
1
  export interface IEmailService {
2
- /**
3
- * Invia un'email di verifica all'utente e aggiorna la chiave di registrazione nel database.
4
- *
5
- * @param {string} email - Email del destinatario.
6
- * @param {string} codiceUtente - Codice utente per il database.
7
- * @param {string} baseUrl - URL base per il link di verifica.
8
- * @returns {Promise<void>} Una Promise che si risolve al completamento dell'invio.
9
- * @throws {Error} Se l'invio dell'email fallisce.
10
- */
11
- sendVerificationEmail(email: string, codiceUtente: string, baseUrl: string): Promise<void>;
12
2
  /**
13
3
  * Invia un'email di recupero password con un link per reimpostarla.
14
4
  *
@@ -42,7 +42,7 @@ export interface IUserService {
42
42
  * @returns {Promise<void>} Una Promise che si risolve al completamento dell'operazione.
43
43
  * @throws {Error} Se l'inserimento fallisce per qualsiasi motivo.
44
44
  */
45
- register(request: UserQueryResult): Promise<void>;
45
+ register(request: UserQueryResult, confirmationEmailPrefix: string): Promise<void>;
46
46
  /**
47
47
  * Recupera un utente in base al suo username.
48
48
  *
@@ -2,16 +2,18 @@ import { AccessiOptions } from "../../AccessiModule";
2
2
  import { UserQueryResult } from "../../models/QueryResults/UserQueryResult";
3
3
  import { StatoRegistrazione } from "../../models/StatoRegistrazione";
4
4
  import { IFiltriUtente, IUser, IUserService } from "./IUserService";
5
+ import { EmailService } from "../EmailService/EmailService";
5
6
  export declare class UserService implements IUserService {
6
7
  private readonly accessiOptions;
7
- constructor(accessiOptions: AccessiOptions);
8
+ private readonly emailService;
9
+ constructor(accessiOptions: AccessiOptions, emailService: EmailService);
8
10
  getUsers(): Promise<UserQueryResult[]>;
9
11
  getCodiceUtenteByUsername(username: string): Promise<{
10
12
  codiceUtente: string;
11
13
  }>;
12
14
  getUserByUsername(username: string): Promise<IUser | null>;
13
15
  getUserFilters(codiceUtente: string): Promise<IFiltriUtente[]>;
14
- register(request: IUser): Promise<void>;
16
+ register(request: IUser, confirmationEmailPrefix: string): Promise<void>;
15
17
  setRegistrazioneConfermata(userKey: string): Promise<void>;
16
18
  updateUser(user: UserQueryResult): Promise<void>;
17
19
  deleteUser(codiceCliente: string): Promise<void>;
@@ -27,9 +27,11 @@ const autobind_1 = require("../../../autobind");
27
27
  const Orm_1 = require("../../../Orm");
28
28
  const Utilities_1 = require("../../../Utilities");
29
29
  const StatoRegistrazione_1 = require("../../models/StatoRegistrazione");
30
+ const EmailService_1 = require("../EmailService/EmailService");
30
31
  let UserService = class UserService {
31
- constructor(accessiOptions) {
32
+ constructor(accessiOptions, emailService) {
32
33
  this.accessiOptions = accessiOptions;
34
+ this.emailService = emailService;
33
35
  }
34
36
  getUsers() {
35
37
  return __awaiter(this, void 0, void 0, function* () {
@@ -119,16 +121,20 @@ let UserService = class UserService {
119
121
  .then(results => results.map(Utilities_1.RestUtilities.convertKeysToCamelCase));
120
122
  });
121
123
  }
122
- register(request) {
124
+ register(request, confirmationEmailPrefix) {
123
125
  return __awaiter(this, void 0, void 0, function* () {
124
126
  try {
125
- const queryUtenti = `INSERT INTO UTENTI (USRNAME, STAREG, FLGGDPR) VALUES (?,?,?,?) RETURNING CODUTE`;
126
- const paramsUtenti = [request.username, request.statoRegistrazione, false];
127
+ const existingUser = yield Orm_1.Orm.query(this.accessiOptions.databaseOptions, "SELECT CODUTE FROM UTENTI WHERE USRNAME = ?", [request.username]);
128
+ if (existingUser.length > 0) {
129
+ throw new Error("Utente già esistente!");
130
+ }
131
+ const queryUtenti = `INSERT INTO UTENTI (USRNAME, STAREG) VALUES (?,?) RETURNING CODUTE`;
132
+ const paramsUtenti = [request.username, StatoRegistrazione_1.StatoRegistrazione.INVIO];
127
133
  const codiceUtente = (yield Orm_1.Orm.query(this.accessiOptions.databaseOptions, queryUtenti, paramsUtenti)).CODUTE;
128
- const queryUtentiConfig = `INSERT INTO UTENTI_CONFIG (CODUTE,COGNOME,NOME,CODLINGUA,FLGSUPER) VALUES (?,?,?,?,?)`;
129
- const paramsUtentiConfig = [codiceUtente, request.cognome, request.nome, request.codiceLingua, request.flagSuper];
130
- //await this.sendVerificationEmail(request.username, codiceUtente, "");
134
+ const queryUtentiConfig = `INSERT INTO UTENTI_CONFIG (CODUTE,COGNOME,NOME,CODLINGUA) VALUES (?,?,?,?)`;
135
+ const paramsUtentiConfig = [codiceUtente, request.cognome, request.nome, request.codiceLingua];
131
136
  yield Orm_1.Orm.execute(this.accessiOptions.databaseOptions, queryUtentiConfig, paramsUtentiConfig);
137
+ yield this.emailService.sendPasswordResetEmail(request.username, confirmationEmailPrefix);
132
138
  }
133
139
  catch (error) {
134
140
  throw error;
@@ -233,5 +239,5 @@ exports.UserService = UserService = __decorate([
233
239
  autobind_1.autobind,
234
240
  (0, common_1.Injectable)(),
235
241
  __param(0, (0, common_1.Inject)('ACCESSI_OPTIONS')),
236
- __metadata("design:paramtypes", [Object])
242
+ __metadata("design:paramtypes", [Object, EmailService_1.EmailService])
237
243
  ], UserService);
@@ -8,6 +8,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  step((generator = generator.apply(thisArg, _arguments || [])).next());
9
9
  });
10
10
  };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
11
14
  Object.defineProperty(exports, "__esModule", { value: true });
12
15
  exports.StatoRegistrazione = exports.AccessiModule = void 0;
13
16
  exports.initializeAccessiModule = initializeAccessiModule;
@@ -15,6 +18,7 @@ const core_1 = require("@nestjs/core");
15
18
  const platform_express_1 = require("@nestjs/platform-express");
16
19
  const SwaggerConfig_1 = require("./swagger/SwaggerConfig");
17
20
  const AccessiModule_1 = require("./AccessiModule");
21
+ const express_1 = __importDefault(require("express"));
18
22
  function initializeAccessiModule(app, options) {
19
23
  return __awaiter(this, void 0, void 0, function* () {
20
24
  try {
@@ -49,11 +53,47 @@ function initializeAccessiModule(app, options) {
49
53
  console.log(availableRoutes);
50
54
  }
51
55
  catch (error) {
52
- console.error("Errore in initializeAccessiModule:", error);
56
+ console.error("Errore in initialize AccessiModule:", error);
53
57
  throw error;
54
58
  }
55
59
  });
56
60
  }
61
+ function start() {
62
+ return __awaiter(this, void 0, void 0, function* () {
63
+ const app = (0, express_1.default)();
64
+ yield initializeAccessiModule(app, {
65
+ databaseOptions: {
66
+ host: '127.0.0.1',
67
+ port: 3050,
68
+ database: 'C:/Siti/Autoclub/ACCESSI.GDB',
69
+ user: "SYSDBA",
70
+ password: "masterkey",
71
+ },
72
+ encryptionKey: "BNB_KIT7GRP2023!",
73
+ mockDemoUser: true,
74
+ jwtOptions: {
75
+ expiresIn: "24h",
76
+ secret: "fabriziocorona",
77
+ },
78
+ emailOptions: {
79
+ auth: {
80
+ user: "form@emilsoftware.it",
81
+ pass: "ForES713",
82
+ },
83
+ from: "noreply@emilsoftware.it",
84
+ host: "smtp.qboxmail.com",
85
+ port: 587,
86
+ secure: false,
87
+ },
88
+ baseUrl: "http://localhost:3000"
89
+ });
90
+ const PORT = 3000;
91
+ app.listen(PORT, () => {
92
+ console.log(`Server avviato su http://localhost:${PORT}`);
93
+ });
94
+ });
95
+ }
96
+ start();
57
97
  var AccessiModule_2 = require("./AccessiModule");
58
98
  Object.defineProperty(exports, "AccessiModule", { enumerable: true, get: function () { return AccessiModule_2.AccessiModule; } });
59
99
  var StatoRegistrazione_1 = require("./models/StatoRegistrazione");
@@ -7,9 +7,8 @@ function serveSwaggerDocs(app) {
7
7
  .setTitle('Accessi API')
8
8
  .setDescription('Documentazione delle API per la gestione degli accessi')
9
9
  .setVersion('1.0')
10
- .addServer('/')
11
10
  .build();
12
- const document = swagger_1.SwaggerModule.createDocument(app, config);
13
- swagger_1.SwaggerModule.setup('swagger/accessi', app, document);
11
+ const documentFactory = () => swagger_1.SwaggerModule.createDocument(app, config);
12
+ swagger_1.SwaggerModule.setup('swagger', app, documentFactory);
14
13
  console.log('Swagger UI disponibile su http://localhost:3000/swagger/accessi');
15
14
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "emilsoftware-utilities",
3
- "version": "1.3.87",
3
+ "version": "1.3.89",
4
4
  "description": "Utilities for EmilSoftware",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.js",
@@ -30,7 +30,7 @@
30
30
  "class-transformer": "^0.5.1",
31
31
  "class-validator": "^0.14.1",
32
32
  "colorette": "^2.0.20",
33
- "es-node-firebird": "^1.2.6",
33
+ "es-node-firebird": "^1.2.7",
34
34
  "jsonwebtoken": "^9.0.2",
35
35
  "jspdf": "^3.0.0",
36
36
  "jspdf-autotable": "^5.0.2",