emilsoftware-utilities 2.0.0-dev.60 → 2.0.0-dev.62

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 (79) hide show
  1. package/dist/accessi-module/AccessiModule.d.ts +6 -0
  2. package/dist/accessi-module/AccessiModule.js.map +1 -1
  3. package/dist/accessi-module/Console/console.js +163 -4
  4. package/dist/accessi-module/Console/console.js.map +1 -1
  5. package/dist/accessi-module/Console/generated/accessiApi.d.ts +68 -5
  6. package/dist/accessi-module/Console/generated/accessiApi.js +84 -10
  7. package/dist/accessi-module/Console/generated/accessiApi.js.map +1 -1
  8. package/dist/accessi-module/Console/generated/model/createScopeRequest.d.ts +18 -0
  9. package/dist/accessi-module/Console/generated/model/createScopeRequest.js +9 -0
  10. package/dist/accessi-module/Console/generated/model/createScopeRequest.js.map +1 -0
  11. package/dist/accessi-module/Console/generated/model/getGroupsWithMenusParams.d.ts +4 -0
  12. package/dist/accessi-module/Console/generated/model/getGroupsWithMenusParams.js.map +1 -1
  13. package/dist/accessi-module/Console/generated/model/getMenuScopesResponse.d.ts +14 -0
  14. package/dist/accessi-module/Console/generated/model/getMenuScopesResponse.js +3 -0
  15. package/dist/accessi-module/Console/generated/model/getMenuScopesResponse.js.map +1 -0
  16. package/dist/accessi-module/Console/generated/model/getMenusParams.d.ts +12 -0
  17. package/dist/accessi-module/Console/generated/model/getMenusParams.js +9 -0
  18. package/dist/accessi-module/Console/generated/model/getMenusParams.js.map +1 -0
  19. package/dist/accessi-module/Console/generated/model/getScopesResponse.d.ts +14 -0
  20. package/dist/accessi-module/Console/generated/model/getScopesResponse.js +3 -0
  21. package/dist/accessi-module/Console/generated/model/getScopesResponse.js.map +1 -0
  22. package/dist/accessi-module/Console/generated/model/getUserRolesAndGrantsParams.d.ts +12 -0
  23. package/dist/accessi-module/Console/generated/model/getUserRolesAndGrantsParams.js +9 -0
  24. package/dist/accessi-module/Console/generated/model/getUserRolesAndGrantsParams.js.map +1 -0
  25. package/dist/accessi-module/Console/generated/model/index.d.ts +9 -0
  26. package/dist/accessi-module/Console/generated/model/index.js +9 -0
  27. package/dist/accessi-module/Console/generated/model/index.js.map +1 -1
  28. package/dist/accessi-module/Console/generated/model/loginRequest.d.ts +2 -0
  29. package/dist/accessi-module/Console/generated/model/loginRequest.js.map +1 -1
  30. package/dist/accessi-module/Console/generated/model/scopeEntity.d.ts +12 -0
  31. package/dist/accessi-module/Console/generated/model/scopeEntity.js +9 -0
  32. package/dist/accessi-module/Console/generated/model/scopeEntity.js.map +1 -0
  33. package/dist/accessi-module/Console/generated/model/setMenuScopesRequest.d.ts +10 -0
  34. package/dist/accessi-module/Console/generated/model/setMenuScopesRequest.js +9 -0
  35. package/dist/accessi-module/Console/generated/model/setMenuScopesRequest.js.map +1 -0
  36. package/dist/accessi-module/Console/generated/model/setScopeMenusRequest.d.ts +10 -0
  37. package/dist/accessi-module/Console/generated/model/setScopeMenusRequest.js +9 -0
  38. package/dist/accessi-module/Console/generated/model/setScopeMenusRequest.js.map +1 -0
  39. package/dist/accessi-module/Console/generated/model/updateScopeRequest.d.ts +13 -0
  40. package/dist/accessi-module/Console/generated/model/updateScopeRequest.js +9 -0
  41. package/dist/accessi-module/Console/generated/model/updateScopeRequest.js.map +1 -0
  42. package/dist/accessi-module/Console/index.html +1 -0
  43. package/dist/accessi-module/Controllers/PermissionController.d.ts +11 -3
  44. package/dist/accessi-module/Controllers/PermissionController.js +208 -12
  45. package/dist/accessi-module/Controllers/PermissionController.js.map +1 -1
  46. package/dist/accessi-module/Dtos/LoginRequest.d.ts +2 -0
  47. package/dist/accessi-module/Dtos/LoginRequest.js +10 -0
  48. package/dist/accessi-module/Dtos/LoginRequest.js.map +1 -1
  49. package/dist/accessi-module/Dtos/ScopeDtos.d.ts +28 -0
  50. package/dist/accessi-module/Dtos/ScopeDtos.js +103 -0
  51. package/dist/accessi-module/Dtos/ScopeDtos.js.map +1 -0
  52. package/dist/accessi-module/Dtos/index.d.ts +1 -0
  53. package/dist/accessi-module/Dtos/index.js +1 -0
  54. package/dist/accessi-module/Dtos/index.js.map +1 -1
  55. package/dist/accessi-module/Services/AuthService/AuthService.d.ts +1 -1
  56. package/dist/accessi-module/Services/AuthService/AuthService.js +3 -3
  57. package/dist/accessi-module/Services/AuthService/AuthService.js.map +1 -1
  58. package/dist/accessi-module/Services/PermissionService/PermissionService.d.ts +27 -4
  59. package/dist/accessi-module/Services/PermissionService/PermissionService.js +177 -24
  60. package/dist/accessi-module/Services/PermissionService/PermissionService.js.map +1 -1
  61. package/dist/accessi-module/Services/UserService/UserService.d.ts +1 -0
  62. package/dist/accessi-module/Services/UserService/UserService.js +1 -1
  63. package/dist/accessi-module/Services/UserService/UserService.js.map +1 -1
  64. package/dist/accessi-module/database-updates/AccessiDatabaseUpdater.js +2 -0
  65. package/dist/accessi-module/database-updates/AccessiDatabaseUpdater.js.map +1 -1
  66. package/dist/accessi-module/database-updates/accessiSchema.d.ts +1 -1
  67. package/dist/accessi-module/database-updates/accessiSchema.js +12 -1
  68. package/dist/accessi-module/database-updates/accessiSchema.js.map +1 -1
  69. package/dist/accessi-module/database-updates/menuScopeSeed.d.ts +15 -0
  70. package/dist/accessi-module/database-updates/menuScopeSeed.js +338 -0
  71. package/dist/accessi-module/database-updates/menuScopeSeed.js.map +1 -0
  72. package/dist/accessi-module/database-updates/menuScopeSeeder.d.ts +8 -0
  73. package/dist/accessi-module/database-updates/menuScopeSeeder.js +131 -0
  74. package/dist/accessi-module/database-updates/menuScopeSeeder.js.map +1 -0
  75. package/dist/accessi-module/database-updates/runAccessiDbUpdate.js +4 -1
  76. package/dist/accessi-module/database-updates/runAccessiDbUpdate.js.map +1 -1
  77. package/dist/emilsoftware-utilities-2.0.0-dev.62.tgz +0 -0
  78. package/package.json +3 -3
  79. package/dist/emilsoftware-utilities-2.0.0-dev.60.tgz +0 -0
@@ -0,0 +1,103 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ 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;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.GetMenuScopesResponse = exports.SetScopeMenusRequest = exports.SetMenuScopesRequest = exports.UpdateScopeRequest = exports.CreateScopeRequest = exports.GetScopesResponse = exports.ScopeEntity = void 0;
13
+ const swagger_1 = require("@nestjs/swagger");
14
+ const class_transformer_1 = require("class-transformer");
15
+ const class_validator_1 = require("class-validator");
16
+ const BaseResponse_1 = require("./BaseResponse");
17
+ /**
18
+ * Scope applicativi: etichette che decidono in quali applicazioni un menu e
19
+ * visibile. Il codice e la chiave stabile usata dalle API (`?scope=STEX`).
20
+ */
21
+ class ScopeEntity {
22
+ }
23
+ exports.ScopeEntity = ScopeEntity;
24
+ __decorate([
25
+ (0, swagger_1.ApiProperty)({ description: 'Codice dello scope.', example: 'STEX' }),
26
+ __metadata("design:type", String)
27
+ ], ScopeEntity.prototype, "codice", void 0);
28
+ __decorate([
29
+ (0, swagger_1.ApiProperty)({ description: 'Nome leggibile dello scope.', example: 'SteX' }),
30
+ __metadata("design:type", String)
31
+ ], ScopeEntity.prototype, "nome", void 0);
32
+ class GetScopesResponse extends BaseResponse_1.BaseResponse {
33
+ }
34
+ exports.GetScopesResponse = GetScopesResponse;
35
+ __decorate([
36
+ (0, swagger_1.ApiProperty)({ type: [ScopeEntity] }),
37
+ (0, class_validator_1.ValidateNested)({ each: true }),
38
+ (0, class_transformer_1.Type)(() => ScopeEntity),
39
+ __metadata("design:type", Array)
40
+ ], GetScopesResponse.prototype, "Result", void 0);
41
+ class CreateScopeRequest {
42
+ }
43
+ exports.CreateScopeRequest = CreateScopeRequest;
44
+ __decorate([
45
+ (0, swagger_1.ApiProperty)({ description: 'Codice univoco dello scope.', example: 'STEX', maxLength: 20 }),
46
+ (0, class_validator_1.IsString)({ message: 'Il codice scope deve essere una stringa.' }),
47
+ (0, class_validator_1.IsNotEmpty)({ message: 'Il codice scope e obbligatorio.' }),
48
+ (0, class_validator_1.MaxLength)(20, { message: 'Il codice scope non puo superare 20 caratteri.' }),
49
+ __metadata("design:type", String)
50
+ ], CreateScopeRequest.prototype, "codice", void 0);
51
+ __decorate([
52
+ (0, swagger_1.ApiProperty)({ description: 'Nome leggibile dello scope.', example: 'SteX', maxLength: 100 }),
53
+ (0, class_validator_1.IsString)({ message: 'Il nome scope deve essere una stringa.' }),
54
+ (0, class_validator_1.IsNotEmpty)({ message: 'Il nome scope e obbligatorio.' }),
55
+ (0, class_validator_1.MaxLength)(100, { message: 'Il nome scope non puo superare 100 caratteri.' }),
56
+ __metadata("design:type", String)
57
+ ], CreateScopeRequest.prototype, "nome", void 0);
58
+ class UpdateScopeRequest {
59
+ }
60
+ exports.UpdateScopeRequest = UpdateScopeRequest;
61
+ __decorate([
62
+ (0, swagger_1.ApiPropertyOptional)({ description: 'Nome leggibile dello scope.', example: 'SteX', maxLength: 100 }),
63
+ (0, class_validator_1.IsString)({ message: 'Il nome scope deve essere una stringa.' }),
64
+ (0, class_validator_1.IsOptional)(),
65
+ (0, class_validator_1.MaxLength)(100, { message: 'Il nome scope non puo superare 100 caratteri.' }),
66
+ __metadata("design:type", String)
67
+ ], UpdateScopeRequest.prototype, "nome", void 0);
68
+ class SetMenuScopesRequest {
69
+ }
70
+ exports.SetMenuScopesRequest = SetMenuScopesRequest;
71
+ __decorate([
72
+ (0, swagger_1.ApiProperty)({
73
+ description: 'Elenco completo degli scope associati al menu.',
74
+ example: ['STEX', 'TINTEMIX'],
75
+ type: [String],
76
+ }),
77
+ (0, class_validator_1.IsArray)({ message: 'Gli scope devono essere un array.' }),
78
+ (0, class_validator_1.ArrayUnique)({ message: 'Gli scope non devono contenere duplicati.' }),
79
+ (0, class_validator_1.IsString)({ each: true, message: 'Ogni scope deve essere una stringa.' }),
80
+ __metadata("design:type", Array)
81
+ ], SetMenuScopesRequest.prototype, "scopes", void 0);
82
+ class SetScopeMenusRequest {
83
+ }
84
+ exports.SetScopeMenusRequest = SetScopeMenusRequest;
85
+ __decorate([
86
+ (0, swagger_1.ApiProperty)({
87
+ description: 'Elenco completo dei menu associati allo scope.',
88
+ example: ['MNUMAIN', 'MNUUTENTI'],
89
+ type: [String],
90
+ }),
91
+ (0, class_validator_1.IsArray)({ message: 'I menu devono essere un array.' }),
92
+ (0, class_validator_1.ArrayUnique)({ message: 'I menu non devono contenere duplicati.' }),
93
+ (0, class_validator_1.IsString)({ each: true, message: 'Ogni menu deve essere una stringa.' }),
94
+ __metadata("design:type", Array)
95
+ ], SetScopeMenusRequest.prototype, "menu", void 0);
96
+ class GetMenuScopesResponse extends BaseResponse_1.BaseResponse {
97
+ }
98
+ exports.GetMenuScopesResponse = GetMenuScopesResponse;
99
+ __decorate([
100
+ (0, swagger_1.ApiProperty)({ type: [String], description: 'Codici degli scope associati al menu.' }),
101
+ __metadata("design:type", Array)
102
+ ], GetMenuScopesResponse.prototype, "Result", void 0);
103
+ //# sourceMappingURL=ScopeDtos.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ScopeDtos.js","sourceRoot":"","sources":["../../../src/accessi-module/Dtos/ScopeDtos.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,6CAAmE;AACnE,yDAAyC;AACzC,qDAQyB;AACzB,iDAA8C;AAE9C;;;GAGG;AACH,MAAa,WAAW;CAMvB;AAND,kCAMC;AAJC;IADC,IAAA,qBAAW,EAAC,EAAE,WAAW,EAAE,qBAAqB,EAAE,OAAO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ty, ApiPropertyOptional } from '@nestjs/swagger';\nimport { Type } from 'class-transformer';\nimport {\n ArrayUnique,\n IsArray,\n IsNotEmpty,\n IsOptional,\n IsString,\n MaxLength,\n ValidateNested,\n} from 'class-validator';\nimport { BaseResponse } from './BaseResponse';\n\n/**\n * Scope applicativi: etichette che decidono in quali applicazioni un menu e\n * visibile. Il codice e la chiave stabile usata dalle API (`?scope=STEX`).\n */\nexport class ScopeEntity {\n @ApiProperty({ description: 'Codice dello scope.', example: 'STEX' })\n codice!: string;\n\n @ApiProperty({ description: 'Nome leggibile dello scope.', example: 'SteX' })\n nome!: string;\n}\n\nexport class GetScopesResponse extends BaseResponse {\n @ApiProperty({ type: [ScopeEntity] })\n @ValidateNested({ each: true })\n @Type(() => ScopeEntity)\n Result!: ScopeEntity[];\n}\n\nexport class CreateScopeRequest {\n @ApiProperty({ description: 'Codice univoco dello scope.', example: 'STEX', maxLength: 20 })\n @IsString({ message: 'Il codice scope deve essere una stringa.' })\n @IsNotEmpty({ message: 'Il codice scope e obbligatorio.' })\n @MaxLength(20, { message: 'Il codice scope non puo superare 20 caratteri.' })\n codice!: string;\n\n @ApiProperty({ description: 'Nome leggibile dello scope.', example: 'SteX', maxLength: 100 })\n @IsString({ message: 'Il nome scope deve essere una stringa.' })\n @IsNotEmpty({ message: 'Il nome scope e obbligatorio.' })\n @MaxLength(100, { message: 'Il nome scope non puo superare 100 caratteri.' })\n nome!: string;\n}\n\nexport class UpdateScopeRequest {\n @ApiPropertyOptional({ description: 'Nome leggibile dello scope.', example: 'SteX', maxLength: 100 })\n @IsString({ message: 'Il nome scope deve essere una stringa.' })\n @IsOptional()\n @MaxLength(100, { message: 'Il nome scope non puo superare 100 caratteri.' })\n nome?: string;\n}\n\nexport class SetMenuScopesRequest {\n @ApiProperty({\n description: 'Elenco completo degli scope associati al menu.',\n example: ['STEX', 'TINTEMIX'],\n type: [String],\n })\n @IsArray({ message: 'Gli scope devono essere un array.' })\n @ArrayUnique({ message: 'Gli scope non devono contenere duplicati.' })\n @IsString({ each: true, message: 'Ogni scope deve essere una stringa.' })\n scopes!: string[];\n}\n\nexport class SetScopeMenusRequest {\n @ApiProperty({\n description: 'Elenco completo dei menu associati allo scope.',\n example: ['MNUMAIN', 'MNUUTENTI'],\n type: [String],\n })\n @IsArray({ message: 'I menu devono essere un array.' })\n @ArrayUnique({ message: 'I menu non devono contenere duplicati.' })\n @IsString({ each: true, message: 'Ogni menu deve essere una stringa.' })\n menu!: string[];\n}\n\nexport class GetMenuScopesResponse extends BaseResponse {\n @ApiProperty({ type: [String], description: 'Codici degli scope associati al menu.' })\n Result!: string[];\n}\n"]}
@@ -19,6 +19,7 @@ export * from "./Permission";
19
19
  export * from "./PublicRegisterRequest";
20
20
  export * from "./Role";
21
21
  export * from "./SchemaDtos";
22
+ export * from "./ScopeDtos";
22
23
  export * from "./SendResetPasswordEmailRequest";
23
24
  export * from "./StatoRegistrazione";
24
25
  export * from "./TipoAbilitazione";
@@ -35,6 +35,7 @@ __exportStar(require("./Permission"), exports);
35
35
  __exportStar(require("./PublicRegisterRequest"), exports);
36
36
  __exportStar(require("./Role"), exports);
37
37
  __exportStar(require("./SchemaDtos"), exports);
38
+ __exportStar(require("./ScopeDtos"), exports);
38
39
  __exportStar(require("./SendResetPasswordEmailRequest"), exports);
39
40
  __exportStar(require("./StatoRegistrazione"), exports);
40
41
  __exportStar(require("./TipoAbilitazione"), exports);
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/accessi-module/Dtos/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,iDAA+B;AAC/B,uDAAqC;AACrC,qDAAmC;AACnC,mEAAiD;AACjD,6DAA2C;AAC3C,gEAA8C;AAC9C,iDAA+B;AAC/B,gDAA8B;AAC9B,gEAA8C;AAC9C,+DAA4C;AAE5C,iDAA+B;AAC/B,0DAAwC;AACxC,0DAAwC;AACxC,2DAAyC;AACzC,gDAA8B;AAC9B,iDAA+B;AAC/B,kDAAgC;AAChC,+CAA6B;AAC7B,0DAAwC;AACxC,yCAAuB;AACvB,+CAA6B;AAC7B,kEAAgD;AAChD,uDAAqC;AACrC,qDAAmC;AACnC,gDAA8B;AAC9B,4CAA0B;AAC1B,uDAAqC;AAErC,8CAA2B;AAE3B,iDAA+B;AAE/B,kDAAgC","sourcesContent":["export * from \"./Abilitazione\";\nexport * from \"./AdminBootstrapDtos\";\nexport * from \"./AbilitazioneMenu\";\nexport * from \"./AssignPermissionsToUserRequest\";\nexport * from \"./AssignRolesToUserRequest\";\nexport * from \"./AuthenticatedUserPayloadDto\";\nexport * from \"./BaseResponse\";\nexport * from \"./CatalogDtos\";\nexport * from \"./ConfirmResetPasswordRequest\";\nexport * from \"./UpdateEnabledStatusRequest\"\n\nexport * from \"./FiltriUtente\";\nexport * from \"./FederatedIdentityDtos\";\nexport * from \"./GetUserByTokenRequest\";\nexport * from \"./GetUserByTokenResponse\";\nexport * from \"./LoginAsDtos\";\nexport * from \"./LoginRequest\";\nexport * from \"./LoginResponse\";\nexport * from \"./Permission\";\nexport * from \"./PublicRegisterRequest\";\nexport * from \"./Role\";\nexport * from \"./SchemaDtos\";\nexport * from \"./SendResetPasswordEmailRequest\";\nexport * from \"./StatoRegistrazione\";\nexport * from \"./TipoAbilitazione\";\nexport * from \"./TokenResult\";\nexport * from \"./UserDto\";\nexport * from \"./UserGrantsResponse\";\n\nexport * from \"./RuoliMenu\"\n\nexport * from \"./ServiceToken\";\n\nexport * from './TwoFactorDtos';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/accessi-module/Dtos/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,iDAA+B;AAC/B,uDAAqC;AACrC,qDAAmC;AACnC,mEAAiD;AACjD,6DAA2C;AAC3C,gEAA8C;AAC9C,iDAA+B;AAC/B,gDAA8B;AAC9B,gEAA8C;AAC9C,+DAA4C;AAE5C,iDAA+B;AAC/B,0DAAwC;AACxC,0DAAwC;AACxC,2DAAyC;AACzC,gDAA8B;AAC9B,iDAA+B;AAC/B,kDAAgC;AAChC,+CAA6B;AAC7B,0DAAwC;AACxC,yCAAuB;AACvB,+CAA6B;AAC7B,8CAA4B;AAC5B,kEAAgD;AAChD,uDAAqC;AACrC,qDAAmC;AACnC,gDAA8B;AAC9B,4CAA0B;AAC1B,uDAAqC;AAErC,8CAA2B;AAE3B,iDAA+B;AAE/B,kDAAgC","sourcesContent":["export * from \"./Abilitazione\";\nexport * from \"./AdminBootstrapDtos\";\nexport * from \"./AbilitazioneMenu\";\nexport * from \"./AssignPermissionsToUserRequest\";\nexport * from \"./AssignRolesToUserRequest\";\nexport * from \"./AuthenticatedUserPayloadDto\";\nexport * from \"./BaseResponse\";\nexport * from \"./CatalogDtos\";\nexport * from \"./ConfirmResetPasswordRequest\";\nexport * from \"./UpdateEnabledStatusRequest\"\n\nexport * from \"./FiltriUtente\";\nexport * from \"./FederatedIdentityDtos\";\nexport * from \"./GetUserByTokenRequest\";\nexport * from \"./GetUserByTokenResponse\";\nexport * from \"./LoginAsDtos\";\nexport * from \"./LoginRequest\";\nexport * from \"./LoginResponse\";\nexport * from \"./Permission\";\nexport * from \"./PublicRegisterRequest\";\nexport * from \"./Role\";\nexport * from \"./SchemaDtos\";\nexport * from \"./ScopeDtos\";\nexport * from \"./SendResetPasswordEmailRequest\";\nexport * from \"./StatoRegistrazione\";\nexport * from \"./TipoAbilitazione\";\nexport * from \"./TokenResult\";\nexport * from \"./UserDto\";\nexport * from \"./UserGrantsResponse\";\n\nexport * from \"./RuoliMenu\"\n\nexport * from \"./ServiceToken\";\n\nexport * from './TwoFactorDtos';\n"]}
@@ -33,7 +33,7 @@ export declare class AuthService {
33
33
  email?: string;
34
34
  }): TokenResult;
35
35
  /** Builds the standard login response for a user authenticated by a supported method. */
36
- getLoginResultForUser(codiceUtente: number): Promise<LoginResult>;
36
+ getLoginResultForUser(codiceUtente: number, scope?: string): Promise<LoginResult>;
37
37
  /** Users without a row retain the historic password-login enabled default. */
38
38
  private isPasswordLoginEnabled;
39
39
  /**
@@ -151,9 +151,9 @@ let AuthService = AuthService_1 = class AuthService {
151
151
  });
152
152
  }
153
153
  /** Builds the standard login response for a user authenticated by a supported method. */
154
- getLoginResultForUser(codiceUtente) {
154
+ getLoginResultForUser(codiceUtente, scope) {
155
155
  return __awaiter(this, void 0, void 0, function* () {
156
- const users = yield this.userService.getUsers({ codiceUtente }, { includeExtensionFields: true, includeGrants: true });
156
+ const users = yield this.userService.getUsers({ codiceUtente }, Object.assign({ includeExtensionFields: true, includeGrants: true }, (scope ? { scope } : {})));
157
157
  const result = users[0];
158
158
  if (!(result === null || result === void 0 ? void 0 : result.utente)) {
159
159
  throw new Error('Utente Accessi non trovato.');
@@ -250,7 +250,7 @@ let AuthService = AuthService_1 = class AuthService {
250
250
  }
251
251
  const updateLastAccessDateQuery = "UPDATE UTENTI SET DATLASTLOGIN = CURRENT_TIMESTAMP WHERE CODUTE = ?";
252
252
  yield Orm_1.Orm.query(this.accessiOptions.databaseOptions, updateLastAccessDateQuery, [utente.codiceUtente]);
253
- return this.getLoginResultForUser(utente.codiceUtente);
253
+ return this.getLoginResultForUser(utente.codiceUtente, request.scope);
254
254
  });
255
255
  }
256
256
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"AuthService.js","sourceRoot":"","sources":["../../../../src/accessi-module/Services/AuthService/AuthService.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,2CAA2E;AAC3E,2EAAwF;AACxF,kDAAoC;AACpC,sCAAmC;AACnC,kDAAsF;AAItF,sEAAmE;AACnE,4DAAyD;AACzD,kEAA+D;AAC/D,0EAK2C;AAC3C,0EAG2C;AAC3C,kEAAqE;AACrE,4CAAyC;AAGzC,8EAA8E;AACjE,QAAA,uBAAuB,GAAG,yBAAyB,CAAC;AAU1D,IAAM,WAAW,mBAAjB,MAAM,WAAW;IAGtB,YACU,WAAwB,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,CAAC,CACf,CAAC;oBACJ,CAAC;gBACH,CAAC,CAAA,CAAC,CAAC;YACL,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,MAAM,KAAK,CAAC;YACd,CAAC;QACH,CAAC;KAAA;CACF,CAAA;AA/hBY,kCAAW;sBAAX,WAAW;IADvB,IAAA,mBAAU,GAAE;IAOR,WAAA,IAAA,eAAM,EAAC,iBAAiB,CAAC,CAAA;qCAFL,yBAAW;QACT,6BAAa,UAED,mCAAgB;GAP1C,WAAW,CA+hBvB","sourcesContent":["import { Inject, Injectable, UnauthorizedException } from \"@nestjs/common\";\nimport { TwoFactorService, TwoFactorProof } from '../TwoFactorService/TwoFactorService';\nimport * as jwt from \"jsonwebtoken\";\nimport { Orm } from \"../../../Orm\";\nimport { CryptUtilities, PasswordUtilities, RestUtilities } from \"../../../Utilities\";\nimport type { AccessiOptions } from \"../../AccessiModule\";\nimport { LoginRequest } from \"../../Dtos/LoginRequest\";\nimport { LoginResult } from \"../../Dtos/LoginResponse\";\nimport { StatoRegistrazione } from \"../../Dtos/StatoRegistrazione\";\nimport { UserService } from \"../UserService/UserService\";\nimport { FiltriService } from \"../FiltriService/FiltriService\";\nimport {\n buildAuthenticatedTokenPayload,\n isAuthenticatedUserEnabledForJwt,\n isAccessiTokenAllowedForUser,\n resolveCodiceUtenteFromTokenPayload,\n} from \"../../security/authenticatedToken\";\nimport {\n getAccessiJwtSecret,\n verifyPasswordResetToken,\n} from \"../../security/passwordResetToken\";\nimport { assertStrongPassword } from '../../security/passwordPolicy';\nimport { Logger } from \"../../../Logger\";\nimport { TokenResult } from '../../Dtos/TokenResult';\n\n/** Error code deliberately returned when a user is configured as SSO-only. */\nexport const PASSWORD_LOGIN_DISABLED = 'PASSWORD_LOGIN_DISABLED';\n\ninterface AccessiTokenIssueOptions {\n /** Sovrascrive jwtOptions.expiresIn per token a durata ridotta (es. Login as). */\n expiresIn?: string | number;\n /** Claim aggiuntive, per esempio l'attore che ha generato un token di impersonazione. */\n extraClaims?: Record<string, unknown>;\n}\n\n@Injectable()\nexport class AuthService {\n private readonly logger = new Logger(AuthService.name);\n\n constructor(\n private userService: UserService,\n private filtriService: FiltriService,\n @Inject(\"ACCESSI_OPTIONS\") private readonly accessiOptions: AccessiOptions,\n private readonly twoFactorService: TwoFactorService,\n ) {}\n\n private async refreshPasswordExpiration(codiceUtente: number): Promise<void> {\n if (!this.accessiOptions.passwordExpiration) {\n return;\n }\n\n const configuredDays = Number(this.accessiOptions.passwordExpirationDays);\n const expirationDays =\n Number.isFinite(configuredDays) && configuredDays > 0\n ? Math.trunc(configuredDays)\n : 90;\n\n const query = `UPDATE UTENTI SET DATSCAPWD = DATEADD(${expirationDays} DAY TO CURRENT_TIMESTAMP) WHERE CODUTE = ?`;\n await Orm.execute(this.accessiOptions.databaseOptions, query, [codiceUtente]);\n }\n\n private isMockDemoUserEnabled(): boolean {\n if (!this.accessiOptions.mockDemoUser) {\n return false;\n }\n\n // La backdoor mock non e mai attiva in produzione, nemmeno con variabili d'ambiente,\n // perche emette un superutente senza verifica password.\n const nodeEnv = (process.env.NODE_ENV ?? \"production\").toLowerCase();\n return nodeEnv !== \"production\";\n }\n\n /** Creates the normal internal JWT consumed by all existing Accessi guards. */\n public createAccessiToken(\n utente: LoginResult['utente'],\n methods: string[] = [],\n tokenOptions: AccessiTokenIssueOptions = {},\n ): TokenResult {\n if (!utente?.codiceUtente) {\n throw new Error('Impossibile creare un token senza un utente Accessi valido.');\n }\n const loginAs = methods.includes('login_as');\n if ((utente.flagDueFattori === true || Number(utente.flagDueFattori) === 1) && !methods.includes('otp') && !loginAs) {\n throw new UnauthorizedException('Verifica del codice di accesso richiesta.');\n }\n\n const expiresIn = tokenOptions.expiresIn ?? this.accessiOptions.jwtOptions.expiresIn;\n const expiresInIsValid = typeof expiresIn === 'number'\n ? Number.isFinite(expiresIn) && expiresIn > 0\n : typeof expiresIn === 'string' && expiresIn.trim() !== '';\n if (!expiresInIsValid) {\n throw new Error('jwtOptions.expiresIn non configurato: impossibile emettere token senza scadenza.');\n }\n\n const token = jwt.sign(\n { ...(tokenOptions.extraClaims ?? {}), utente, typ: 'access', amr: methods },\n getAccessiJwtSecret(this.accessiOptions),\n { expiresIn: expiresIn as jwt.SignOptions['expiresIn'] },\n );\n\n // Difesa in profondita: un `expiresIn` malformato farebbe emettere un token permanente.\n const decoded = jwt.decode(token);\n const decodedPayload = decoded && typeof decoded === 'object' ? decoded as jwt.JwtPayload : undefined;\n if (typeof decodedPayload?.exp !== 'number') {\n throw new Error('Token emesso senza scadenza: configurazione JWT non valida.');\n }\n\n // Il contratto TokenResult espone sempre la validita in secondi, anche quando\n // jwtOptions.expiresIn usa un formato leggibile come '24h'.\n const issuedAt = typeof decodedPayload.iat === 'number' ? decodedPayload.iat : Math.floor(Date.now() / 1000);\n const expiresInSeconds = Math.max(0, Math.trunc(decodedPayload.exp - issuedAt));\n\n return {\n expiresIn: String(expiresInSeconds),\n value: token,\n type: 'Bearer',\n };\n }\n\n /**\n * Emette l'access token per l'utente target, con l'attore registrato nelle\n * claim `act` e `loginAs`. La durata e' quella standard di jwtOptions.expiresIn.\n */\n public createLoginAsToken(\n utente: LoginResult['utente'],\n actor: { codiceUtente: number; email?: string },\n ): TokenResult {\n return this.createAccessiToken(utente, ['login_as'], {\n extraClaims: {\n loginAs: true,\n act: {\n sub: String(actor.codiceUtente),\n email: actor.email,\n },\n },\n });\n }\n\n /** Builds the standard login response for a user authenticated by a supported method. */\n public async getLoginResultForUser(codiceUtente: number): Promise<LoginResult> {\n const users = await this.userService.getUsers(\n { codiceUtente },\n { includeExtensionFields: true, includeGrants: true },\n );\n const result = users[0];\n if (!result?.utente) {\n throw new Error('Utente Accessi non trovato.');\n }\n const current = await this.userService.getAuthenticatedUserSnapshot(codiceUtente);\n if (!isAuthenticatedUserEnabledForJwt(current)) throw new UnauthorizedException('Utente non abilitato.');\n result.utente = { ...result.utente, ...current };\n\n return {\n utente: result.utente,\n filtri: await this.filtriService.getFiltriUser(codiceUtente),\n userGrants: result.userGrants,\n extensionFields: result.extensionFields,\n };\n }\n\n /** Users without a row retain the historic password-login enabled default. */\n private async isPasswordLoginEnabled(codiceUtente: number): Promise<boolean> {\n if (this.accessiOptions.federatedAuthentication?.enabled !== true) return true;\n\n const rows = await Orm.query(\n this.accessiOptions.databaseOptions,\n 'SELECT COALESCE(FLGPASSWORD, 1) AS password_login_enabled FROM UTENTI_CONFIG WHERE CODUTE = ?',\n [codiceUtente],\n );\n const policy = rows.map(RestUtilities.convertKeysToCamelCase)[0] as { passwordLoginEnabled?: unknown } | undefined;\n return policy?.passwordLoginEnabled !== false && policy?.passwordLoginEnabled !== 0 && policy?.passwordLoginEnabled !== '0';\n }\n\n /**\n * Autentica con credenziali locali e restituisce profilo, filtri e grant effettivi.\n * Non crea il JWT: il controller o il flusso SSO deve chiamare `createAccessiToken` sul risultato.\n * Per utenti SSO-only genera `PASSWORD_LOGIN_DISABLED`, da trattare come istruzione a usare l'SSO.\n */\n async login(request: LoginRequest): Promise<LoginResult> {\n const mockDemoUserEnabled = this.isMockDemoUserEnabled();\n\n if (\n mockDemoUserEnabled &&\n request.email.toLowerCase() === \"demo\"\n ) {\n return this.getDemoUser();\n }\n\n if (\n mockDemoUserEnabled &&\n request.email.toLowerCase() === \"admin\"\n ) {\n return this.getAdminUser();\n }\n\n const utente = await this.userService.getUserByEmail(\n request.email.trim().toLowerCase()\n );\n if (!utente) {\n if (!request.password) return { passwordRequired: true };\n throw new Error(\"Nome utente o password errata!\");\n }\n\n const currentUser = await this.userService.getAuthenticatedUserSnapshot(utente.codiceUtente);\n if (isAuthenticatedUserEnabledForJwt(currentUser) && currentUser.flagDueFattori && currentUser.passwordlessLoginEnabled) {\n return { challenge: await this.twoFactorService.issue({ codiceUtente: utente.codiceUtente, email: (currentUser.email ?? '').trim(), mode: 'passwordless' }) };\n }\n // The email-only step has the same response for unknown and ordinary local accounts.\n if (!request.password) return { passwordRequired: true };\n\n switch (utente.statoRegistrazione) {\n case undefined:\n throw new Error(\n \"Struttura dati compromessa: Stato Registrazione inesistente.\"\n );\n case StatoRegistrazione.BLOCC:\n case StatoRegistrazione.DELETE:\n throw new Error(\"Utente non abilitato\");\n case StatoRegistrazione.INVIO:\n throw new Error(\"Rinnovo password necessario.\");\n }\n\n if (utente.statoRegistrazione !== StatoRegistrazione.CONF) {\n throw new Error(\n `Errore generico. Stato di registrazione non valido: ${utente.statoRegistrazione}.`\n );\n }\n\n if (!isAuthenticatedUserEnabledForJwt(currentUser)) throw new Error('Utente non abilitato');\n if (!(await this.isPasswordLoginEnabled(utente.codiceUtente))) {\n throw new Error(PASSWORD_LOGIN_DISABLED);\n }\n\n if (typeof request.password !== 'string' || request.password.length === 0) {\n throw new Error('Nome utente o password errata!');\n }\n\n const isPasswordValid = await this.verifyPassword(\n utente.codiceUtente,\n request.password\n );\n if (!isPasswordValid) throw new Error(\"Nome utente o password errata!\");\n\n if (\n this.accessiOptions.passwordExpiration &&\n this.accessiOptions.passwordExpiration == true\n ) {\n const today = new Date();\n const targetDate = utente.dataScadenzaPassword\n ? new Date(utente.dataScadenzaPassword)\n : undefined;\n\n // Legacy users may not have an expiration date. Preserve the former non-expiring behaviour for them.\n if (targetDate && !Number.isNaN(targetDate.getTime()) && today >= targetDate) {\n throw new Error(\"PASSWORD_EXPIRED\");\n }\n }\n\n if (currentUser.flagDueFattori) {\n return { challenge: await this.twoFactorService.issue({ codiceUtente: utente.codiceUtente, email: currentUser.email ?? '', mode: 'password' }) };\n }\n\n const updateLastAccessDateQuery =\n \"UPDATE UTENTI SET DATLASTLOGIN = CURRENT_TIMESTAMP WHERE CODUTE = ?\";\n await Orm.query(\n this.accessiOptions.databaseOptions,\n updateLastAccessDateQuery,\n [utente.codiceUtente]\n );\n\n return this.getLoginResultForUser(utente.codiceUtente);\n }\n\n /**\n * Verifica un JWT Accessi e ricostruisce il profilo corrente dal database.\n * Questo evita che privilegi, stato utente o flag amministrativi presenti in un token vecchio restino validi.\n */\n public async getAuthenticatedTokenPayload(token: string): Promise<Record<string, unknown>> {\n if (typeof token !== \"string\" || token.trim() === \"\") {\n throw new Error(\"Token non fornito.\");\n }\n\n const secret = getAccessiJwtSecret(this.accessiOptions);\n const decoded = jwt.verify(token.trim(), secret, { algorithms: ['HS256'] });\n const codiceUtente = resolveCodiceUtenteFromTokenPayload(decoded);\n\n if (!codiceUtente) {\n throw new Error(\"Token non valido.\");\n }\n\n const currentUser = await this.userService.getAuthenticatedUserSnapshot(codiceUtente);\n if (!currentUser || !isAuthenticatedUserEnabledForJwt(currentUser) || !isAccessiTokenAllowedForUser(decoded, currentUser)) {\n throw new Error(\"Token non valido o utente non autorizzato.\");\n }\n\n return buildAuthenticatedTokenPayload(decoded, currentUser);\n }\n\n /** Starts a second-factor challenge after the hosting backend has verified an SSO identity. */\n public async beginFederatedTwoFactor(codiceUtente: number, identityKey: string): Promise<LoginResult> {\n const user = await this.userService.getAuthenticatedUserSnapshot(codiceUtente);\n if (!isAuthenticatedUserEnabledForJwt(user) || !user.flagDueFattori) throw new UnauthorizedException();\n return { challenge: await this.twoFactorService.issue({ codiceUtente, email: user.email ?? '', mode: 'federated', identityKey }) };\n }\n\n private async validateTwoFactorProof(proof: TwoFactorProof): Promise<void> {\n const user = await this.userService.getAuthenticatedUserSnapshot(proof.codiceUtente);\n if (!isAuthenticatedUserEnabledForJwt(user) || !user.flagDueFattori || user.email?.trim().toLowerCase() !== proof.email.trim().toLowerCase()) {\n throw new UnauthorizedException('Profilo modificato o utente non abilitato. Ripeti l accesso.');\n }\n if (proof.mode === 'passwordless' && !user.passwordlessLoginEnabled) throw new UnauthorizedException('Accesso senza password disabilitato.');\n if (proof.mode === 'password' && !(await this.isPasswordLoginEnabled(proof.codiceUtente))) throw new UnauthorizedException('Login locale disabilitato.');\n if (proof.mode === 'federated') {\n if (!this.accessiOptions.federatedAuthentication?.enabled) throw new UnauthorizedException();\n const rows = await Orm.query(this.accessiOptions.databaseOptions,\n 'SELECT I.IDNKEY FROM UTENTI_IDENTITA_EXT I INNER JOIN SSO_PROVIDER P ON P.PROVIDER = I.PROVIDER WHERE I.IDNKEY = ? AND I.CODUTE = ? AND I.FLGATTIVO = 1 AND P.FLGATTIVO = 1',\n [proof.identityKey, proof.codiceUtente], false);\n if (!rows.length) throw new UnauthorizedException('Identita SSO non piu abilitata.');\n }\n }\n\n public async verifyTwoFactor(challengeId: string, code: string): Promise<LoginResult> {\n const proof = await this.twoFactorService.consume(challengeId, code);\n await this.validateTwoFactorProof(proof);\n const result = await this.getLoginResultForUser(proof.codiceUtente);\n result.token = this.createAccessiToken(result.utente, [proof.mode, 'otp']);\n await Orm.execute(this.accessiOptions.databaseOptions, 'UPDATE UTENTI SET DATLASTLOGIN = CURRENT_TIMESTAMP WHERE CODUTE = ?', [proof.codiceUtente]);\n if (proof.mode === 'federated') {\n await Orm.execute(this.accessiOptions.databaseOptions, 'UPDATE UTENTI_IDENTITA_EXT SET DATLASTLOGIN = CURRENT_TIMESTAMP WHERE IDNKEY = ?', [proof.identityKey]);\n }\n return result;\n }\n\n public async resendTwoFactor(challengeId: string): Promise<LoginResult> {\n await this.validateTwoFactorProof(await this.twoFactorService.describe(challengeId));\n return { challenge: await this.twoFactorService.resend(challengeId) };\n }\n\n /**\n * Persiste una password hashata e aggiorna la scadenza, se la policy password e attiva. Non invia email.\n * Con `enforcePolicy` (default true) valida la password secondo la policy moderna; i flussi di\n * migrazione delle password legacy passano `enforcePolicy: false` per non bloccare password storiche.\n */\n public async setPassword(\n codiceUtente: number,\n nuovaPassword: string,\n options?: { enforcePolicy?: boolean },\n ) {\n if (options?.enforcePolicy !== false) {\n assertStrongPassword(nuovaPassword);\n }\n try {\n const query = `UPDATE OR INSERT INTO UTENTI_PWD (CODUTE, PWD) VALUES (?, ?)`;\n const hashedPassword = PasswordUtilities.hashPassword(nuovaPassword);\n\n const result = await Orm.execute(this.accessiOptions.databaseOptions, query, [\n codiceUtente,\n hashedPassword,\n ]);\n await this.refreshPasswordExpiration(codiceUtente);\n return result;\n } catch (error) {\n throw error;\n }\n }\n\n /**\n * Converte le password legacy cifrate nel formato hash compatibile, senza conoscere le password in chiaro.\n * E idempotente: hash moderni e gia migrati vengono ignorati.\n */\n public async migrateLegacyEncryptedPasswords(): Promise<void> {\n const startedAt = performance.now();\n this.logger.info(\"Avvio migrazione password legacy accessi.\");\n const results = await Orm.query(\n this.accessiOptions.databaseOptions,\n \"SELECT CODUTE AS codice_utente, PWD AS password FROM UTENTI_PWD WHERE PWD IS NOT NULL\",\n []\n );\n\n const rows = results.map(RestUtilities.convertKeysToCamelCase) as {\n codiceUtente?: number;\n password?: string;\n }[];\n let migratedCount = 0;\n let skippedCount = 0;\n\n for (const row of rows) {\n const codiceUtente = Number(row.codiceUtente);\n const storedPassword = typeof row.password === \"string\" ? row.password : null;\n\n if (\n !codiceUtente ||\n !storedPassword ||\n PasswordUtilities.isPasswordHash(storedPassword) ||\n PasswordUtilities.isLegacyPasswordHash(storedPassword)\n ) {\n skippedCount += 1;\n continue;\n }\n\n const protectedLegacyPassword =\n PasswordUtilities.hashLegacyEncryptedPassword(storedPassword);\n\n await Orm.execute(\n this.accessiOptions.databaseOptions,\n \"UPDATE UTENTI_PWD SET PWD = ? WHERE CODUTE = ? AND PWD = ?\",\n [protectedLegacyPassword, codiceUtente, storedPassword]\n );\n migratedCount += 1;\n }\n\n this.logger.info(\n `Migrazione password legacy accessi completata. Letti=${rows.length}, migrati=${migratedCount}, ignorati=${skippedCount}, durataMs=${(performance.now() - startedAt).toFixed(2)}`\n );\n }\n\n /** Verifica una password locale e migra automaticamente il formato legacy dopo una verifica positiva. */\n async verifyPassword(\n codiceUtente: number,\n plainPassword: string\n ): Promise<boolean> {\n const query = `SELECT PWD AS password FROM UTENTI_PWD WHERE CODUTE = ?`;\n const result = (await Orm.query(\n this.accessiOptions.databaseOptions,\n query,\n [codiceUtente]\n ).then((results) => results.map(RestUtilities.convertKeysToCamelCase))) as {\n password: string;\n }[];\n\n const stored = result[0];\n if (!stored || typeof stored.password !== \"string\") {\n return false;\n }\n\n const storedPassword = stored.password;\n\n if (PasswordUtilities.isPasswordHash(storedPassword)) {\n return PasswordUtilities.verifyPassword(plainPassword, storedPassword);\n }\n\n const legacyEncryptedPassword = CryptUtilities.encrypt(\n plainPassword,\n this.accessiOptions.encryptionKey\n );\n\n if (PasswordUtilities.isLegacyPasswordHash(storedPassword)) {\n const isMigratedLegacyPasswordValid =\n PasswordUtilities.verifyLegacyEncryptedPassword(\n legacyEncryptedPassword,\n storedPassword\n );\n\n if (isMigratedLegacyPasswordValid) {\n await this.setPassword(codiceUtente, plainPassword, { enforcePolicy: false });\n }\n\n return isMigratedLegacyPasswordValid;\n }\n\n const isLegacyPasswordValid = PasswordUtilities.timingSafeStringEquals(\n storedPassword,\n legacyEncryptedPassword,\n );\n\n if (isLegacyPasswordValid) {\n await this.setPassword(codiceUtente, plainPassword, { enforcePolicy: false });\n }\n\n return isLegacyPasswordValid;\n }\n\n /** Restituisce l'utente fittizio amministratore; usabile solo con `mockDemoUser` esplicitamente abilitato. */\n async getAdminUser(): Promise<LoginResult> {\n return {\n utente: {\n codiceUtente: 6789,\n email: \"admin\",\n statoRegistrazione: StatoRegistrazione.CONF,\n cognome: \"Admin\",\n nome: \"Admin\",\n flagGdpr: true,\n avatar: \"/path/to/avatar.jpg\",\n flagDueFattori: false,\n codiceLingua: \"IT\",\n cellulare: \"+391234567890\",\n flagSuper: true,\n roles: [],\n permissions: [],\n },\n filtri: null,\n userGrants: {\n abilitazioni: [],\n grants: [],\n ruoli: [],\n },\n };\n }\n\n /** Restituisce l'utente demo fittizio; non contiene dati o grant reali. */\n getDemoUser(): LoginResult {\n return {\n utente: {\n codiceUtente: 12345,\n email: \"jdoe\",\n statoRegistrazione: StatoRegistrazione.CONF,\n cognome: \"Doe\",\n nome: \"John\",\n flagGdpr: true,\n avatar: \"/path/to/avatar.jpg\",\n flagDueFattori: false,\n codiceLingua: \"IT\",\n cellulare: \"+391234567890\",\n flagSuper: false,\n roles: [],\n permissions: [],\n },\n filtri: null,\n userGrants: {\n abilitazioni: [],\n grants: [],\n ruoli: [],\n },\n };\n }\n\n /**\n * Consuma un token monouso di reset, riporta l'utente allo stato confermato e salva la nuova password.\n * Il nonce in `UTENTI.KEYREG` viene annullato prima di impostare la password, impedendo il riuso del token.\n */\n public async confirmResetPassword(\n token: string,\n newPassword: string\n ): Promise<void> {\n try {\n if (typeof token !== \"string\" || token.trim() === \"\") {\n throw new Error(\"Token non valido.\");\n }\n\n assertStrongPassword(newPassword);\n\n const secret = getAccessiJwtSecret(this.accessiOptions, 'reset');\n const { codiceUtente, nonce } = verifyPasswordResetToken(token.trim(), secret);\n\n const hashedPassword = PasswordUtilities.hashPassword(newPassword);\n\n await Orm.withTransaction(this.accessiOptions.databaseOptions, async (transaction) => {\n // A conditional write claims the nonce under the database row lock. A second\n // concurrent reset cannot also consume it; failures roll the whole reset back.\n const claimed = await Orm.transactionQuery<unknown>(\n transaction,\n 'UPDATE UTENTI SET KEYREG = NULL, STAREG = ? WHERE CODUTE = ? AND KEYREG = ? AND STAREG IN (?, ?) RETURNING CODUTE',\n [StatoRegistrazione.CONF, codiceUtente, nonce, StatoRegistrazione.CONF, StatoRegistrazione.INVIO],\n );\n const row = (Array.isArray(claimed) ? claimed[0] : claimed) as Record<string, unknown> | undefined;\n if (Number(row?.CODUTE ?? row?.codute) !== codiceUtente) {\n throw new Error('Token non valido, gia usato o utente non autorizzato.');\n }\n\n await Orm.transactionQuery(\n transaction,\n 'UPDATE OR INSERT INTO UTENTI_PWD (CODUTE, PWD) VALUES (?, ?) MATCHING (CODUTE)',\n [codiceUtente, hashedPassword],\n );\n\n if (this.accessiOptions.passwordExpiration) {\n const days = Number(this.accessiOptions.passwordExpirationDays);\n const expirationDays = Number.isFinite(days) && days > 0 ? Math.trunc(days) : 90;\n await Orm.transactionQuery(\n transaction,\n `UPDATE UTENTI SET DATSCAPWD = DATEADD(${expirationDays} DAY TO CURRENT_TIMESTAMP) WHERE CODUTE = ?`,\n [codiceUtente],\n );\n }\n });\n } catch (error) {\n throw error;\n }\n }\n}\n"]}
1
+ {"version":3,"file":"AuthService.js","sourceRoot":"","sources":["../../../../src/accessi-module/Services/AuthService/AuthService.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,2CAA2E;AAC3E,2EAAwF;AACxF,kDAAoC;AACpC,sCAAmC;AACnC,kDAAsF;AAItF,sEAAmE;AACnE,4DAAyD;AACzD,kEAA+D;AAC/D,0EAK2C;AAC3C,0EAG2C;AAC3C,kEAAqE;AACrE,4CAAyC;AAGzC,8EAA8E;AACjE,QAAA,uBAAuB,GAAG,yBAAyB,CAAC;AAU1D,IAAM,WAAW,mBAAjB,MAAM,WAAW;IAGtB,YACU,WAAwB,EACxB,aAA4B,EACT,cAA+C,EACzD,gBAAkC;QAH3C,gBAAW,GAAX,WAAW,CAAa;QACxB,kBAAa,GAAb,aAAa,CAAe;QACQ,mBAAc,GAAd,cAAc,CAAgB;QACzD,qBAAgB,GAAhB,gBAAgB,CAAkB;QANpC,WAAM,GAAG,IAAI,eAAM,CAAC,aAAW,CAAC,IAAI,CAAC,CAAC;IAOpD,CAAC;IAEU,yBAAyB,CAAC,YAAoB;;YAC1D,IAAI,CAAC,IAAI,CAAC,cAAc,CAAC,kBAAkB,EAAE,CAAC;gBAC5C,OAAO;YACT,CAAC;YAED,MAAM,cAAc,GAAG,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;YAC1E,MAAM,cAAc,GAClB,MAAM,CAAC,QAAQ,CAAC,cAAc,CAAC,IAAI,cAAc,GAAG,CAAC;gBACnD,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,cAAc,CAAC;gBAC5B,CAAC,CAAC,EAAE,CAAC;YAET,MAAM,KAAK,GAAG,yCAAyC,cAAc,6CAA6C,CAAC;YACnH,MAAM,SAAG,CAAC,OAAO,CAAC,IAAI,CA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G,CAAE,MAAM,CAAC,KAAK,YAAY,EAAE,CAAC;wBACxD,MAAM,IAAI,KAAK,CAAC,uDAAuD,CAAC,CAAC;oBAC3E,CAAC;oBAED,MAAM,SAAG,CAAC,gBAAgB,CACxB,WAAW,EACX,gFAAgF,EAChF,CAAC,YAAY,EAAE,cAAc,CAAC,CAC/B,CAAC;oBAEF,IAAI,IAAI,CAAC,cAAc,CAAC,kBAAkB,EAAE,CAAC;wBAC3C,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;wBAChE,MAAM,cAAc,GAAG,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;wBACjF,MAAM,SAAG,CAAC,gBAAgB,CACxB,WAAW,EACX,yCAAyC,cAAc,6CAA6C,EACpG,CAAC,YAAY,CAAC,CACf,CAAC;oBACJ,CAAC;gBACH,CAAC,CAAA,CAAC,CAAC;YACL,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,MAAM,KAAK,CAAC;YACd,CAAC;QACH,CAAC;KAAA;CACF,CAAA;AA/hBY,kCAAW;sBAAX,WAAW;IADvB,IAAA,mBAAU,GAAE;IAOR,WAAA,IAAA,eAAM,EAAC,iBAAiB,CAAC,CAAA;qCAFL,yBAAW;QACT,6BAAa,UAED,mCAAgB;GAP1C,WAAW,CA+hBvB","sourcesContent":["import { Inject, Injectable, UnauthorizedException } from \"@nestjs/common\";\nimport { TwoFactorService, TwoFactorProof } from '../TwoFactorService/TwoFactorService';\nimport * as jwt from \"jsonwebtoken\";\nimport { Orm } from \"../../../Orm\";\nimport { CryptUtilities, PasswordUtilities, RestUtilities } from \"../../../Utilities\";\nimport type { AccessiOptions } from \"../../AccessiModule\";\nimport { LoginRequest } from \"../../Dtos/LoginRequest\";\nimport { LoginResult } from \"../../Dtos/LoginResponse\";\nimport { StatoRegistrazione } from \"../../Dtos/StatoRegistrazione\";\nimport { UserService } from \"../UserService/UserService\";\nimport { FiltriService } from \"../FiltriService/FiltriService\";\nimport {\n buildAuthenticatedTokenPayload,\n isAuthenticatedUserEnabledForJwt,\n isAccessiTokenAllowedForUser,\n resolveCodiceUtenteFromTokenPayload,\n} from \"../../security/authenticatedToken\";\nimport {\n getAccessiJwtSecret,\n verifyPasswordResetToken,\n} from \"../../security/passwordResetToken\";\nimport { assertStrongPassword } from '../../security/passwordPolicy';\nimport { Logger } from \"../../../Logger\";\nimport { TokenResult } from '../../Dtos/TokenResult';\n\n/** Error code deliberately returned when a user is configured as SSO-only. */\nexport const PASSWORD_LOGIN_DISABLED = 'PASSWORD_LOGIN_DISABLED';\n\ninterface AccessiTokenIssueOptions {\n /** Sovrascrive jwtOptions.expiresIn per token a durata ridotta (es. Login as). */\n expiresIn?: string | number;\n /** Claim aggiuntive, per esempio l'attore che ha generato un token di impersonazione. */\n extraClaims?: Record<string, unknown>;\n}\n\n@Injectable()\nexport class AuthService {\n private readonly logger = new Logger(AuthService.name);\n\n constructor(\n private userService: UserService,\n private filtriService: FiltriService,\n @Inject(\"ACCESSI_OPTIONS\") private readonly accessiOptions: AccessiOptions,\n private readonly twoFactorService: TwoFactorService,\n ) {}\n\n private async refreshPasswordExpiration(codiceUtente: number): Promise<void> {\n if (!this.accessiOptions.passwordExpiration) {\n return;\n }\n\n const configuredDays = Number(this.accessiOptions.passwordExpirationDays);\n const expirationDays =\n Number.isFinite(configuredDays) && configuredDays > 0\n ? Math.trunc(configuredDays)\n : 90;\n\n const query = `UPDATE UTENTI SET DATSCAPWD = DATEADD(${expirationDays} DAY TO CURRENT_TIMESTAMP) WHERE CODUTE = ?`;\n await Orm.execute(this.accessiOptions.databaseOptions, query, [codiceUtente]);\n }\n\n private isMockDemoUserEnabled(): boolean {\n if (!this.accessiOptions.mockDemoUser) {\n return false;\n }\n\n // La backdoor mock non e mai attiva in produzione, nemmeno con variabili d'ambiente,\n // perche emette un superutente senza verifica password.\n const nodeEnv = (process.env.NODE_ENV ?? \"production\").toLowerCase();\n return nodeEnv !== \"production\";\n }\n\n /** Creates the normal internal JWT consumed by all existing Accessi guards. */\n public createAccessiToken(\n utente: LoginResult['utente'],\n methods: string[] = [],\n tokenOptions: AccessiTokenIssueOptions = {},\n ): TokenResult {\n if (!utente?.codiceUtente) {\n throw new Error('Impossibile creare un token senza un utente Accessi valido.');\n }\n const loginAs = methods.includes('login_as');\n if ((utente.flagDueFattori === true || Number(utente.flagDueFattori) === 1) && !methods.includes('otp') && !loginAs) {\n throw new UnauthorizedException('Verifica del codice di accesso richiesta.');\n }\n\n const expiresIn = tokenOptions.expiresIn ?? this.accessiOptions.jwtOptions.expiresIn;\n const expiresInIsValid = typeof expiresIn === 'number'\n ? Number.isFinite(expiresIn) && expiresIn > 0\n : typeof expiresIn === 'string' && expiresIn.trim() !== '';\n if (!expiresInIsValid) {\n throw new Error('jwtOptions.expiresIn non configurato: impossibile emettere token senza scadenza.');\n }\n\n const token = jwt.sign(\n { ...(tokenOptions.extraClaims ?? {}), utente, typ: 'access', amr: methods },\n getAccessiJwtSecret(this.accessiOptions),\n { expiresIn: expiresIn as jwt.SignOptions['expiresIn'] },\n );\n\n // Difesa in profondita: un `expiresIn` malformato farebbe emettere un token permanente.\n const decoded = jwt.decode(token);\n const decodedPayload = decoded && typeof decoded === 'object' ? decoded as jwt.JwtPayload : undefined;\n if (typeof decodedPayload?.exp !== 'number') {\n throw new Error('Token emesso senza scadenza: configurazione JWT non valida.');\n }\n\n // Il contratto TokenResult espone sempre la validita in secondi, anche quando\n // jwtOptions.expiresIn usa un formato leggibile come '24h'.\n const issuedAt = typeof decodedPayload.iat === 'number' ? decodedPayload.iat : Math.floor(Date.now() / 1000);\n const expiresInSeconds = Math.max(0, Math.trunc(decodedPayload.exp - issuedAt));\n\n return {\n expiresIn: String(expiresInSeconds),\n value: token,\n type: 'Bearer',\n };\n }\n\n /**\n * Emette l'access token per l'utente target, con l'attore registrato nelle\n * claim `act` e `loginAs`. La durata e' quella standard di jwtOptions.expiresIn.\n */\n public createLoginAsToken(\n utente: LoginResult['utente'],\n actor: { codiceUtente: number; email?: string },\n ): TokenResult {\n return this.createAccessiToken(utente, ['login_as'], {\n extraClaims: {\n loginAs: true,\n act: {\n sub: String(actor.codiceUtente),\n email: actor.email,\n },\n },\n });\n }\n\n /** Builds the standard login response for a user authenticated by a supported method. */\n public async getLoginResultForUser(codiceUtente: number, scope?: string): Promise<LoginResult> {\n const users = await this.userService.getUsers(\n { codiceUtente },\n { includeExtensionFields: true, includeGrants: true, ...(scope ? { scope } : {}) },\n );\n const result = users[0];\n if (!result?.utente) {\n throw new Error('Utente Accessi non trovato.');\n }\n const current = await this.userService.getAuthenticatedUserSnapshot(codiceUtente);\n if (!isAuthenticatedUserEnabledForJwt(current)) throw new UnauthorizedException('Utente non abilitato.');\n result.utente = { ...result.utente, ...current };\n\n return {\n utente: result.utente,\n filtri: await this.filtriService.getFiltriUser(codiceUtente),\n userGrants: result.userGrants,\n extensionFields: result.extensionFields,\n };\n }\n\n /** Users without a row retain the historic password-login enabled default. */\n private async isPasswordLoginEnabled(codiceUtente: number): Promise<boolean> {\n if (this.accessiOptions.federatedAuthentication?.enabled !== true) return true;\n\n const rows = await Orm.query(\n this.accessiOptions.databaseOptions,\n 'SELECT COALESCE(FLGPASSWORD, 1) AS password_login_enabled FROM UTENTI_CONFIG WHERE CODUTE = ?',\n [codiceUtente],\n );\n const policy = rows.map(RestUtilities.convertKeysToCamelCase)[0] as { passwordLoginEnabled?: unknown } | undefined;\n return policy?.passwordLoginEnabled !== false && policy?.passwordLoginEnabled !== 0 && policy?.passwordLoginEnabled !== '0';\n }\n\n /**\n * Autentica con credenziali locali e restituisce profilo, filtri e grant effettivi.\n * Non crea il JWT: il controller o il flusso SSO deve chiamare `createAccessiToken` sul risultato.\n * Per utenti SSO-only genera `PASSWORD_LOGIN_DISABLED`, da trattare come istruzione a usare l'SSO.\n */\n async login(request: LoginRequest): Promise<LoginResult> {\n const mockDemoUserEnabled = this.isMockDemoUserEnabled();\n\n if (\n mockDemoUserEnabled &&\n request.email.toLowerCase() === \"demo\"\n ) {\n return this.getDemoUser();\n }\n\n if (\n mockDemoUserEnabled &&\n request.email.toLowerCase() === \"admin\"\n ) {\n return this.getAdminUser();\n }\n\n const utente = await this.userService.getUserByEmail(\n request.email.trim().toLowerCase()\n );\n if (!utente) {\n if (!request.password) return { passwordRequired: true };\n throw new Error(\"Nome utente o password errata!\");\n }\n\n const currentUser = await this.userService.getAuthenticatedUserSnapshot(utente.codiceUtente);\n if (isAuthenticatedUserEnabledForJwt(currentUser) && currentUser.flagDueFattori && currentUser.passwordlessLoginEnabled) {\n return { challenge: await this.twoFactorService.issue({ codiceUtente: utente.codiceUtente, email: (currentUser.email ?? '').trim(), mode: 'passwordless' }) };\n }\n // The email-only step has the same response for unknown and ordinary local accounts.\n if (!request.password) return { passwordRequired: true };\n\n switch (utente.statoRegistrazione) {\n case undefined:\n throw new Error(\n \"Struttura dati compromessa: Stato Registrazione inesistente.\"\n );\n case StatoRegistrazione.BLOCC:\n case StatoRegistrazione.DELETE:\n throw new Error(\"Utente non abilitato\");\n case StatoRegistrazione.INVIO:\n throw new Error(\"Rinnovo password necessario.\");\n }\n\n if (utente.statoRegistrazione !== StatoRegistrazione.CONF) {\n throw new Error(\n `Errore generico. Stato di registrazione non valido: ${utente.statoRegistrazione}.`\n );\n }\n\n if (!isAuthenticatedUserEnabledForJwt(currentUser)) throw new Error('Utente non abilitato');\n if (!(await this.isPasswordLoginEnabled(utente.codiceUtente))) {\n throw new Error(PASSWORD_LOGIN_DISABLED);\n }\n\n if (typeof request.password !== 'string' || request.password.length === 0) {\n throw new Error('Nome utente o password errata!');\n }\n\n const isPasswordValid = await this.verifyPassword(\n utente.codiceUtente,\n request.password\n );\n if (!isPasswordValid) throw new Error(\"Nome utente o password errata!\");\n\n if (\n this.accessiOptions.passwordExpiration &&\n this.accessiOptions.passwordExpiration == true\n ) {\n const today = new Date();\n const targetDate = utente.dataScadenzaPassword\n ? new Date(utente.dataScadenzaPassword)\n : undefined;\n\n // Legacy users may not have an expiration date. Preserve the former non-expiring behaviour for them.\n if (targetDate && !Number.isNaN(targetDate.getTime()) && today >= targetDate) {\n throw new Error(\"PASSWORD_EXPIRED\");\n }\n }\n\n if (currentUser.flagDueFattori) {\n return { challenge: await this.twoFactorService.issue({ codiceUtente: utente.codiceUtente, email: currentUser.email ?? '', mode: 'password' }) };\n }\n\n const updateLastAccessDateQuery =\n \"UPDATE UTENTI SET DATLASTLOGIN = CURRENT_TIMESTAMP WHERE CODUTE = ?\";\n await Orm.query(\n this.accessiOptions.databaseOptions,\n updateLastAccessDateQuery,\n [utente.codiceUtente]\n );\n\n return this.getLoginResultForUser(utente.codiceUtente, request.scope);\n }\n\n /**\n * Verifica un JWT Accessi e ricostruisce il profilo corrente dal database.\n * Questo evita che privilegi, stato utente o flag amministrativi presenti in un token vecchio restino validi.\n */\n public async getAuthenticatedTokenPayload(token: string): Promise<Record<string, unknown>> {\n if (typeof token !== \"string\" || token.trim() === \"\") {\n throw new Error(\"Token non fornito.\");\n }\n\n const secret = getAccessiJwtSecret(this.accessiOptions);\n const decoded = jwt.verify(token.trim(), secret, { algorithms: ['HS256'] });\n const codiceUtente = resolveCodiceUtenteFromTokenPayload(decoded);\n\n if (!codiceUtente) {\n throw new Error(\"Token non valido.\");\n }\n\n const currentUser = await this.userService.getAuthenticatedUserSnapshot(codiceUtente);\n if (!currentUser || !isAuthenticatedUserEnabledForJwt(currentUser) || !isAccessiTokenAllowedForUser(decoded, currentUser)) {\n throw new Error(\"Token non valido o utente non autorizzato.\");\n }\n\n return buildAuthenticatedTokenPayload(decoded, currentUser);\n }\n\n /** Starts a second-factor challenge after the hosting backend has verified an SSO identity. */\n public async beginFederatedTwoFactor(codiceUtente: number, identityKey: string): Promise<LoginResult> {\n const user = await this.userService.getAuthenticatedUserSnapshot(codiceUtente);\n if (!isAuthenticatedUserEnabledForJwt(user) || !user.flagDueFattori) throw new UnauthorizedException();\n return { challenge: await this.twoFactorService.issue({ codiceUtente, email: user.email ?? '', mode: 'federated', identityKey }) };\n }\n\n private async validateTwoFactorProof(proof: TwoFactorProof): Promise<void> {\n const user = await this.userService.getAuthenticatedUserSnapshot(proof.codiceUtente);\n if (!isAuthenticatedUserEnabledForJwt(user) || !user.flagDueFattori || user.email?.trim().toLowerCase() !== proof.email.trim().toLowerCase()) {\n throw new UnauthorizedException('Profilo modificato o utente non abilitato. Ripeti l accesso.');\n }\n if (proof.mode === 'passwordless' && !user.passwordlessLoginEnabled) throw new UnauthorizedException('Accesso senza password disabilitato.');\n if (proof.mode === 'password' && !(await this.isPasswordLoginEnabled(proof.codiceUtente))) throw new UnauthorizedException('Login locale disabilitato.');\n if (proof.mode === 'federated') {\n if (!this.accessiOptions.federatedAuthentication?.enabled) throw new UnauthorizedException();\n const rows = await Orm.query(this.accessiOptions.databaseOptions,\n 'SELECT I.IDNKEY FROM UTENTI_IDENTITA_EXT I INNER JOIN SSO_PROVIDER P ON P.PROVIDER = I.PROVIDER WHERE I.IDNKEY = ? AND I.CODUTE = ? AND I.FLGATTIVO = 1 AND P.FLGATTIVO = 1',\n [proof.identityKey, proof.codiceUtente], false);\n if (!rows.length) throw new UnauthorizedException('Identita SSO non piu abilitata.');\n }\n }\n\n public async verifyTwoFactor(challengeId: string, code: string): Promise<LoginResult> {\n const proof = await this.twoFactorService.consume(challengeId, code);\n await this.validateTwoFactorProof(proof);\n const result = await this.getLoginResultForUser(proof.codiceUtente);\n result.token = this.createAccessiToken(result.utente, [proof.mode, 'otp']);\n await Orm.execute(this.accessiOptions.databaseOptions, 'UPDATE UTENTI SET DATLASTLOGIN = CURRENT_TIMESTAMP WHERE CODUTE = ?', [proof.codiceUtente]);\n if (proof.mode === 'federated') {\n await Orm.execute(this.accessiOptions.databaseOptions, 'UPDATE UTENTI_IDENTITA_EXT SET DATLASTLOGIN = CURRENT_TIMESTAMP WHERE IDNKEY = ?', [proof.identityKey]);\n }\n return result;\n }\n\n public async resendTwoFactor(challengeId: string): Promise<LoginResult> {\n await this.validateTwoFactorProof(await this.twoFactorService.describe(challengeId));\n return { challenge: await this.twoFactorService.resend(challengeId) };\n }\n\n /**\n * Persiste una password hashata e aggiorna la scadenza, se la policy password e attiva. Non invia email.\n * Con `enforcePolicy` (default true) valida la password secondo la policy moderna; i flussi di\n * migrazione delle password legacy passano `enforcePolicy: false` per non bloccare password storiche.\n */\n public async setPassword(\n codiceUtente: number,\n nuovaPassword: string,\n options?: { enforcePolicy?: boolean },\n ) {\n if (options?.enforcePolicy !== false) {\n assertStrongPassword(nuovaPassword);\n }\n try {\n const query = `UPDATE OR INSERT INTO UTENTI_PWD (CODUTE, PWD) VALUES (?, ?)`;\n const hashedPassword = PasswordUtilities.hashPassword(nuovaPassword);\n\n const result = await Orm.execute(this.accessiOptions.databaseOptions, query, [\n codiceUtente,\n hashedPassword,\n ]);\n await this.refreshPasswordExpiration(codiceUtente);\n return result;\n } catch (error) {\n throw error;\n }\n }\n\n /**\n * Converte le password legacy cifrate nel formato hash compatibile, senza conoscere le password in chiaro.\n * E idempotente: hash moderni e gia migrati vengono ignorati.\n */\n public async migrateLegacyEncryptedPasswords(): Promise<void> {\n const startedAt = performance.now();\n this.logger.info(\"Avvio migrazione password legacy accessi.\");\n const results = await Orm.query(\n this.accessiOptions.databaseOptions,\n \"SELECT CODUTE AS codice_utente, PWD AS password FROM UTENTI_PWD WHERE PWD IS NOT NULL\",\n []\n );\n\n const rows = results.map(RestUtilities.convertKeysToCamelCase) as {\n codiceUtente?: number;\n password?: string;\n }[];\n let migratedCount = 0;\n let skippedCount = 0;\n\n for (const row of rows) {\n const codiceUtente = Number(row.codiceUtente);\n const storedPassword = typeof row.password === \"string\" ? row.password : null;\n\n if (\n !codiceUtente ||\n !storedPassword ||\n PasswordUtilities.isPasswordHash(storedPassword) ||\n PasswordUtilities.isLegacyPasswordHash(storedPassword)\n ) {\n skippedCount += 1;\n continue;\n }\n\n const protectedLegacyPassword =\n PasswordUtilities.hashLegacyEncryptedPassword(storedPassword);\n\n await Orm.execute(\n this.accessiOptions.databaseOptions,\n \"UPDATE UTENTI_PWD SET PWD = ? WHERE CODUTE = ? AND PWD = ?\",\n [protectedLegacyPassword, codiceUtente, storedPassword]\n );\n migratedCount += 1;\n }\n\n this.logger.info(\n `Migrazione password legacy accessi completata. Letti=${rows.length}, migrati=${migratedCount}, ignorati=${skippedCount}, durataMs=${(performance.now() - startedAt).toFixed(2)}`\n );\n }\n\n /** Verifica una password locale e migra automaticamente il formato legacy dopo una verifica positiva. */\n async verifyPassword(\n codiceUtente: number,\n plainPassword: string\n ): Promise<boolean> {\n const query = `SELECT PWD AS password FROM UTENTI_PWD WHERE CODUTE = ?`;\n const result = (await Orm.query(\n this.accessiOptions.databaseOptions,\n query,\n [codiceUtente]\n ).then((results) => results.map(RestUtilities.convertKeysToCamelCase))) as {\n password: string;\n }[];\n\n const stored = result[0];\n if (!stored || typeof stored.password !== \"string\") {\n return false;\n }\n\n const storedPassword = stored.password;\n\n if (PasswordUtilities.isPasswordHash(storedPassword)) {\n return PasswordUtilities.verifyPassword(plainPassword, storedPassword);\n }\n\n const legacyEncryptedPassword = CryptUtilities.encrypt(\n plainPassword,\n this.accessiOptions.encryptionKey\n );\n\n if (PasswordUtilities.isLegacyPasswordHash(storedPassword)) {\n const isMigratedLegacyPasswordValid =\n PasswordUtilities.verifyLegacyEncryptedPassword(\n legacyEncryptedPassword,\n storedPassword\n );\n\n if (isMigratedLegacyPasswordValid) {\n await this.setPassword(codiceUtente, plainPassword, { enforcePolicy: false });\n }\n\n return isMigratedLegacyPasswordValid;\n }\n\n const isLegacyPasswordValid = PasswordUtilities.timingSafeStringEquals(\n storedPassword,\n legacyEncryptedPassword,\n );\n\n if (isLegacyPasswordValid) {\n await this.setPassword(codiceUtente, plainPassword, { enforcePolicy: false });\n }\n\n return isLegacyPasswordValid;\n }\n\n /** Restituisce l'utente fittizio amministratore; usabile solo con `mockDemoUser` esplicitamente abilitato. */\n async getAdminUser(): Promise<LoginResult> {\n return {\n utente: {\n codiceUtente: 6789,\n email: \"admin\",\n statoRegistrazione: StatoRegistrazione.CONF,\n cognome: \"Admin\",\n nome: \"Admin\",\n flagGdpr: true,\n avatar: \"/path/to/avatar.jpg\",\n flagDueFattori: false,\n codiceLingua: \"IT\",\n cellulare: \"+391234567890\",\n flagSuper: true,\n roles: [],\n permissions: [],\n },\n filtri: null,\n userGrants: {\n abilitazioni: [],\n grants: [],\n ruoli: [],\n },\n };\n }\n\n /** Restituisce l'utente demo fittizio; non contiene dati o grant reali. */\n getDemoUser(): LoginResult {\n return {\n utente: {\n codiceUtente: 12345,\n email: \"jdoe\",\n statoRegistrazione: StatoRegistrazione.CONF,\n cognome: \"Doe\",\n nome: \"John\",\n flagGdpr: true,\n avatar: \"/path/to/avatar.jpg\",\n flagDueFattori: false,\n codiceLingua: \"IT\",\n cellulare: \"+391234567890\",\n flagSuper: false,\n roles: [],\n permissions: [],\n },\n filtri: null,\n userGrants: {\n abilitazioni: [],\n grants: [],\n ruoli: [],\n },\n };\n }\n\n /**\n * Consuma un token monouso di reset, riporta l'utente allo stato confermato e salva la nuova password.\n * Il nonce in `UTENTI.KEYREG` viene annullato prima di impostare la password, impedendo il riuso del token.\n */\n public async confirmResetPassword(\n token: string,\n newPassword: string\n ): Promise<void> {\n try {\n if (typeof token !== \"string\" || token.trim() === \"\") {\n throw new Error(\"Token non valido.\");\n }\n\n assertStrongPassword(newPassword);\n\n const secret = getAccessiJwtSecret(this.accessiOptions, 'reset');\n const { codiceUtente, nonce } = verifyPasswordResetToken(token.trim(), secret);\n\n const hashedPassword = PasswordUtilities.hashPassword(newPassword);\n\n await Orm.withTransaction(this.accessiOptions.databaseOptions, async (transaction) => {\n // A conditional write claims the nonce under the database row lock. A second\n // concurrent reset cannot also consume it; failures roll the whole reset back.\n const claimed = await Orm.transactionQuery<unknown>(\n transaction,\n 'UPDATE UTENTI SET KEYREG = NULL, STAREG = ? WHERE CODUTE = ? AND KEYREG = ? AND STAREG IN (?, ?) RETURNING CODUTE',\n [StatoRegistrazione.CONF, codiceUtente, nonce, StatoRegistrazione.CONF, StatoRegistrazione.INVIO],\n );\n const row = (Array.isArray(claimed) ? claimed[0] : claimed) as Record<string, unknown> | undefined;\n if (Number(row?.CODUTE ?? row?.codute) !== codiceUtente) {\n throw new Error('Token non valido, gia usato o utente non autorizzato.');\n }\n\n await Orm.transactionQuery(\n transaction,\n 'UPDATE OR INSERT INTO UTENTI_PWD (CODUTE, PWD) VALUES (?, ?) MATCHING (CODUTE)',\n [codiceUtente, hashedPassword],\n );\n\n if (this.accessiOptions.passwordExpiration) {\n const days = Number(this.accessiOptions.passwordExpirationDays);\n const expirationDays = Number.isFinite(days) && days > 0 ? Math.trunc(days) : 90;\n await Orm.transactionQuery(\n transaction,\n `UPDATE UTENTI SET DATSCAPWD = DATEADD(${expirationDays} DAY TO CURRENT_TIMESTAMP) WHERE CODUTE = ?`,\n [codiceUtente],\n );\n }\n });\n } catch (error) {\n throw error;\n }\n }\n}\n"]}
@@ -5,6 +5,7 @@ import { GroupWithMenusEntity } from "../../Dtos/GetGroupsWithMenusResponse";
5
5
  import { MenuEntity } from "../../Dtos/GetMenusResponse";
6
6
  import { Role } from "../../Dtos/Role";
7
7
  import { CreateMenuGroupRequest, CreateMenuRequest, CreateMenuTypeRequest, MenuTypeEntity, UpdateMenuGroupRequest, UpdateMenuRequest, UpdateMenuTypeRequest } from "../../Dtos/CatalogDtos";
8
+ import { CreateScopeRequest, ScopeEntity, UpdateScopeRequest } from "../../Dtos/ScopeDtos";
8
9
  /** Struttura storica menu/gruppi accettata dall'API legacy `addAbilitazioni`. */
9
10
  type LegacyMenuGroup = {
10
11
  menu?: Array<{
@@ -19,6 +20,13 @@ export declare class PermissionService {
19
20
  private getCountFromResult;
20
21
  private extractIntegerColumn;
21
22
  private getAllActiveMenusAsGrants;
23
+ /**
24
+ * Normalizza e valida il filtro `scope` (CSV). Restituisce i codici in
25
+ * maiuscolo; lista vuota significa "nessun filtro" (comportamento storico).
26
+ */
27
+ private resolveScopeCodes;
28
+ /** Clausola SQL EXISTS per filtrare i menu sugli scope richiesti. */
29
+ private scopeFilter;
22
30
  private getUserDirectPermissions;
23
31
  private getUserRoles;
24
32
  /** Costruisce l'albero ruoli/menu a partire dalle righe (riusato da lettura singola e batch). */
@@ -56,12 +64,12 @@ export declare class PermissionService {
56
64
  /** Elimina fisicamente ruolo, associazioni menu e assegnazioni utente. Operazione amministrativa irreversibile. */
57
65
  deleteRole(codiceRuolo: number): Promise<void>;
58
66
  /** Restituisce solo menu abilitati; per il catalogo amministrativo usare `getGroupsWithMenus(true)`. */
59
- getMenus(): Promise<MenuEntity[]>;
67
+ getMenus(scope?: string): Promise<MenuEntity[]>;
60
68
  /**
61
69
  * Restituisce il catalogo ordinato per gruppo e menu. `includeDisabled` e riservato a console e amministrazione:
62
70
  * i flussi applicativi di autorizzazione devono usare il comportamento predefinito, che nasconde voci disabilitate.
63
71
  */
64
- getGroupsWithMenus(includeDisabled?: boolean): Promise<GroupWithMenusEntity[]>;
72
+ getGroupsWithMenus(includeDisabled?: boolean, scope?: string): Promise<GroupWithMenusEntity[]>;
65
73
  private countWhere;
66
74
  private assertMenuGroupExists;
67
75
  private assertMenuTypeExists;
@@ -83,7 +91,7 @@ export declare class PermissionService {
83
91
  * Calcola l'autorizzazione effettiva: grant diretti e grant dei ruoli sono uniti per codice menu
84
92
  * prendendo il livello massimo. I superutenti ricevono tutti i menu attivi.
85
93
  */
86
- getUserRolesAndGrants(codiceUtente: number): Promise<{
94
+ getUserRolesAndGrants(codiceUtente: number, scope?: string): Promise<{
87
95
  abilitazioni: AbilitazioneMenu[];
88
96
  ruoli: Role[];
89
97
  grants: AbilitazioneMenu[];
@@ -94,10 +102,25 @@ export declare class PermissionService {
94
102
  * (invece di N set di query) e restituisce mappa per codice utente. Stessa composizione della
95
103
  * lettura singola.
96
104
  */
97
- getUsersRolesAndGrants(codiciUtente: number[]): Promise<Map<number, {
105
+ getUsersRolesAndGrants(codiciUtente: number[], scope?: string): Promise<Map<number, {
98
106
  abilitazioni: AbilitazioneMenu[];
99
107
  ruoli: Role[];
100
108
  grants: AbilitazioneMenu[];
101
109
  }>>;
110
+ private normalizeScopeCode;
111
+ private assertScopeExists;
112
+ private assertMenuExists;
113
+ /** Catalogo degli scope applicativi (disponibile anche ai client per le etichette). */
114
+ getScopes(): Promise<ScopeEntity[]>;
115
+ createScope(input: CreateScopeRequest): Promise<void>;
116
+ updateScope(codiceScope: string, input: UpdateScopeRequest): Promise<void>;
117
+ /** Elimina lo scope; le associazioni menu/scope spariscono per FK ON DELETE CASCADE. */
118
+ deleteScope(codiceScope: string): Promise<void>;
119
+ /** Scope associati a un menu. */
120
+ getMenuScopes(codiceMenu: string): Promise<string[]>;
121
+ /** Sostituisce in modo atomico gli scope di un menu. */
122
+ setMenuScopes(codiceMenu: string, scopes: string[]): Promise<void>;
123
+ /** Sostituisce in modo atomico i menu di uno scope (assegnazione massiva). */
124
+ setScopeMenus(codiceScope: string, menus: string[]): Promise<void>;
102
125
  }
103
126
  export {};