@drax/identity-back 0.0.31 → 0.1.2

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 (156) hide show
  1. package/dist/config/IdentityConfig.js +2 -3
  2. package/dist/factory/RoleServiceFactory.js +8 -7
  3. package/dist/factory/TenantServiceFactory.js +8 -7
  4. package/dist/factory/UserApiKeyServiceFactory.js +24 -0
  5. package/dist/factory/UserServiceFactory.js +8 -7
  6. package/dist/graphql/resolvers/user-api-key.resolvers.js +89 -0
  7. package/dist/graphql/resolvers/user.resolvers.js +7 -2
  8. package/dist/graphql/types/userApiKey.graphql +33 -0
  9. package/dist/index.js +4 -2
  10. package/dist/interfaces/IUserApiKeyRepository.js +1 -0
  11. package/dist/middleware/apiKeyMiddleware.js +30 -0
  12. package/dist/middleware/rbacMiddleware.js +0 -1
  13. package/dist/models/UserApiKeyModel.js +44 -0
  14. package/dist/permissions/IdentityPermissions.js +6 -0
  15. package/dist/rbac/Rbac.js +8 -0
  16. package/dist/repository/mongo/UserApiKeyMongoRepository.js +82 -0
  17. package/dist/repository/mongo/UserMongoRepository.js +3 -3
  18. package/dist/repository/sqlite/RoleSqliteRepository.js +16 -18
  19. package/dist/repository/sqlite/TenantSqliteRepository.js +13 -11
  20. package/dist/repository/sqlite/UserApiKeySqliteRepository.js +147 -0
  21. package/dist/repository/sqlite/UserSqliteRepository.js +29 -26
  22. package/dist/routes/UserApiKeyRoutes.js +119 -0
  23. package/dist/routes/UserRoutes.js +5 -1
  24. package/dist/services/TenantService.js +42 -11
  25. package/dist/services/UserApiKeyService.js +90 -0
  26. package/dist/services/UserService.js +34 -8
  27. package/dist/setup/LoadIdentityConfigFromEnv.js +3 -3
  28. package/dist/utils/AuthUtils.js +10 -0
  29. package/dist/zod/UserApiKeyZod.js +9 -0
  30. package/package.json +7 -6
  31. package/src/config/IdentityConfig.ts +4 -3
  32. package/src/factory/RoleServiceFactory.ts +11 -11
  33. package/src/factory/TenantServiceFactory.ts +11 -11
  34. package/src/factory/UserApiKeyServiceFactory.ts +30 -0
  35. package/src/factory/UserServiceFactory.ts +8 -7
  36. package/src/graphql/resolvers/tenant.resolvers.ts +0 -1
  37. package/src/graphql/resolvers/user-api-key.resolvers.ts +94 -0
  38. package/src/graphql/resolvers/user.resolvers.ts +9 -2
  39. package/src/graphql/types/userApiKey.graphql +33 -0
  40. package/src/index.ts +10 -0
  41. package/src/interfaces/IUserApiKeyRepository.ts +8 -0
  42. package/src/middleware/apiKeyMiddleware.ts +35 -0
  43. package/src/middleware/rbacMiddleware.ts +1 -2
  44. package/src/models/UserApiKeyModel.ts +59 -0
  45. package/src/permissions/IdentityPermissions.ts +7 -0
  46. package/src/rbac/Rbac.ts +13 -2
  47. package/src/repository/mongo/UserApiKeyMongoRepository.ts +114 -0
  48. package/src/repository/mongo/UserMongoRepository.ts +3 -3
  49. package/src/repository/sqlite/RoleSqliteRepository.ts +28 -20
  50. package/src/repository/sqlite/TenantSqliteRepository.ts +25 -11
  51. package/src/repository/sqlite/UserApiKeySqliteRepository.ts +197 -0
  52. package/src/repository/sqlite/UserSqliteRepository.ts +37 -27
  53. package/src/routes/UserApiKeyRoutes.ts +128 -0
  54. package/src/routes/UserRoutes.ts +5 -1
  55. package/src/services/TenantService.ts +49 -17
  56. package/src/services/UserApiKeyService.ts +111 -0
  57. package/src/services/UserService.ts +74 -48
  58. package/src/setup/LoadIdentityConfigFromEnv.ts +5 -3
  59. package/src/utils/AuthUtils.ts +11 -0
  60. package/src/zod/UserApiKeyZod.ts +15 -0
  61. package/test/data-obj/apikey/root-mongo-user-apikey.ts +10 -0
  62. package/test/data-obj/roles/admin-mongo-role.ts +0 -3
  63. package/test/initializers/RoleMongoInitializer.ts +1 -0
  64. package/test/initializers/RoleSqliteInitializer.ts +1 -0
  65. package/test/initializers/UserMongoInitializer.ts +18 -0
  66. package/test/repository/mongo/user-apikey-mongo-repository.test.ts +73 -0
  67. package/tsconfig.tsbuildinfo +1 -1
  68. package/types/config/IdentityConfig.d.ts +2 -3
  69. package/types/config/IdentityConfig.d.ts.map +1 -1
  70. package/types/errors/BadCredentialsError.d.ts +6 -0
  71. package/types/errors/BadCredentialsError.d.ts.map +1 -0
  72. package/types/errors/UnauthorizedError.d.ts +6 -0
  73. package/types/errors/UnauthorizedError.d.ts.map +1 -0
  74. package/types/factory/RoleServiceFactory.d.ts +4 -0
  75. package/types/factory/RoleServiceFactory.d.ts.map +1 -1
  76. package/types/factory/TenantServiceFactory.d.ts +4 -0
  77. package/types/factory/TenantServiceFactory.d.ts.map +1 -1
  78. package/types/factory/UserApiKeyServiceFactory.d.ts +4 -0
  79. package/types/factory/UserApiKeyServiceFactory.d.ts.map +1 -0
  80. package/types/factory/UserServiceFactory.d.ts +4 -0
  81. package/types/factory/UserServiceFactory.d.ts.map +1 -1
  82. package/types/graphql/index.d.ts +6 -0
  83. package/types/graphql/resolvers/tenant.resolvers.d.ts.map +1 -1
  84. package/types/graphql/resolvers/user-api-key.resolvers.d.ts +37 -0
  85. package/types/graphql/resolvers/user-api-key.resolvers.d.ts.map +1 -0
  86. package/types/graphql/resolvers/user.resolvers.d.ts.map +1 -1
  87. package/types/index.d.ts +35 -0
  88. package/types/index.d.ts.map +1 -1
  89. package/types/interfaces/IRoleRepository.d.ts +9 -0
  90. package/types/interfaces/ITenantRepository.d.ts +9 -0
  91. package/types/interfaces/IUserApiKeyRepository.d.ts +7 -0
  92. package/types/interfaces/IUserApiKeyRepository.d.ts.map +1 -0
  93. package/types/interfaces/IUserRepository.d.ts +10 -0
  94. package/types/middleware/apiKeyMiddleware.d.ts +4 -0
  95. package/types/middleware/apiKeyMiddleware.d.ts.map +1 -0
  96. package/types/middleware/jwtMiddleware.d.ts +4 -0
  97. package/types/middleware/rbacMiddleware.d.ts +4 -0
  98. package/types/middleware/rbacMiddleware.d.ts.map +1 -1
  99. package/types/models/RoleModel.d.ts +16 -0
  100. package/types/models/TenantModel.d.ts +16 -0
  101. package/types/models/UserApiKeyModel.d.ts +16 -0
  102. package/types/models/UserApiKeyModel.d.ts.map +1 -0
  103. package/types/models/UserGroupModel.d.ts +16 -0
  104. package/types/models/UserModel.d.ts +16 -0
  105. package/types/permissions/IdentityPermissions.d.ts +27 -0
  106. package/types/permissions/IdentityPermissions.d.ts.map +1 -0
  107. package/types/rbac/Rbac.d.ts +15 -0
  108. package/types/rbac/Rbac.d.ts.map +1 -1
  109. package/types/repository/mongo/RoleMongoRepository.d.ts +14 -0
  110. package/types/repository/mongo/TenantMongoRepository.d.ts +14 -0
  111. package/types/repository/mongo/UserApiKeyMongoRepository.d.ts +14 -0
  112. package/types/repository/mongo/UserApiKeyMongoRepository.d.ts.map +1 -0
  113. package/types/repository/mongo/UserMongoRepository.d.ts +17 -0
  114. package/types/repository/sqlite/RoleSqliteRepository.d.ts +22 -0
  115. package/types/repository/sqlite/RoleSqliteRepository.d.ts.map +1 -1
  116. package/types/repository/sqlite/TenantSqliteRepository.d.ts +19 -0
  117. package/types/repository/sqlite/TenantSqliteRepository.d.ts.map +1 -1
  118. package/types/repository/sqlite/UserApiKeySqliteRepository.d.ts +19 -0
  119. package/types/repository/sqlite/UserApiKeySqliteRepository.d.ts.map +1 -0
  120. package/types/repository/sqlite/UserSqliteRepository.d.ts +25 -0
  121. package/types/repository/sqlite/UserSqliteRepository.d.ts.map +1 -1
  122. package/types/routes/RoleRoutes.d.ts +4 -0
  123. package/types/routes/TenantRoutes.d.ts +4 -0
  124. package/types/routes/UserApiKeyRoutes.d.ts +4 -0
  125. package/types/routes/UserApiKeyRoutes.d.ts.map +1 -0
  126. package/types/routes/UserAvatarRoutes.d.ts +4 -0
  127. package/types/routes/UserRoutes.d.ts +4 -0
  128. package/types/routes/UserRoutes.d.ts.map +1 -1
  129. package/types/services/PermissionService.d.ts +9 -0
  130. package/types/services/PermissionService.d.ts.map +1 -0
  131. package/types/services/RoleService.d.ts +16 -0
  132. package/types/services/TenantService.d.ts +16 -0
  133. package/types/services/TenantService.d.ts.map +1 -1
  134. package/types/services/UserApiKeyService.d.ts +15 -0
  135. package/types/services/UserApiKeyService.d.ts.map +1 -0
  136. package/types/services/UserService.d.ts +21 -0
  137. package/types/services/UserService.d.ts.map +1 -1
  138. package/types/setup/CreateOrUpdateRole.d.ts +5 -0
  139. package/types/setup/CreateUserIfNotExist.d.ts +5 -0
  140. package/types/setup/LoadIdentityConfigFromEnv.d.ts +4 -0
  141. package/types/setup/LoadIdentityConfigFromEnv.d.ts.map +1 -1
  142. package/types/setup/LoadPermissions.d.ts +4 -0
  143. package/types/setup/LoadPermissions.d.ts.map +1 -0
  144. package/types/setup/RecoveryUserPassword.d.ts +4 -0
  145. package/types/utils/AuthUtils.d.ts +18 -0
  146. package/types/utils/AuthUtils.d.ts.map +1 -1
  147. package/types/zod/RoleZod.d.ts +10 -0
  148. package/types/zod/RoleZod.d.ts.map +1 -0
  149. package/types/zod/TenantZod.d.ts +10 -0
  150. package/types/zod/TenantZod.d.ts.map +1 -0
  151. package/types/zod/UserApiKeyZod.d.ts +16 -0
  152. package/types/zod/UserApiKeyZod.d.ts.map +1 -0
  153. package/types/zod/UserZod.d.ts +53 -0
  154. package/types/zod/UserZod.d.ts.map +1 -0
  155. package/src/utils/DbSetupUtils.ts +0 -41
  156. package/types/utils/DbSetupUtils.d.ts.map +0 -1
@@ -0,0 +1,128 @@
1
+ import UserApiKeyServiceFactory from "../factory/UserApiKeyServiceFactory.js";
2
+ import type {IUserApiKey} from "@drax/identity-share";
3
+ import {ValidationError} from "@drax/common-back";
4
+ import {IdentityPermissions} from "../permissions/IdentityPermissions.js";
5
+ import UnauthorizedError from "../errors/UnauthorizedError.js";
6
+ import {IDraxPaginateResult} from "@drax/common-share";
7
+
8
+
9
+ async function UserApiKeyRoutes(fastify, options) {
10
+
11
+ fastify.get('/api/user-api-keys', async (request, reply): Promise<IDraxPaginateResult<IUserApiKey>> => {
12
+
13
+ try {
14
+ request.rbac.assertAuthenticated()
15
+
16
+ request.rbac.assertOrPermissions([
17
+ IdentityPermissions.ViewUserApiKey,
18
+ IdentityPermissions.ViewMyUserApiKey
19
+ ])
20
+
21
+ const filters = []
22
+
23
+ if(!request.rbac.hasPermission(IdentityPermissions.ViewUserApiKey)){
24
+ filters.push({field: "user", operator: "eq", value: request.rbac.authUser.id})
25
+ }
26
+
27
+ const page = request.query.page
28
+ const limit = request.query.limit
29
+ const orderBy = request.query.orderBy
30
+ const orderDesc = request.query.orderDesc
31
+ const search = request.query.search
32
+ const userApiKeyService = UserApiKeyServiceFactory()
33
+
34
+
35
+ let paginateResult = await userApiKeyService.paginate({page, limit, orderBy, orderDesc, search, filters})
36
+ return paginateResult
37
+ } catch (e) {
38
+ console.log("/api/user-api-keys",e)
39
+ if (e instanceof ValidationError) {
40
+ reply.statusCode = e.statusCode
41
+ reply.send({error: e.message, inputErrors: e.errors})
42
+ } else if (e instanceof UnauthorizedError) {
43
+ reply.statusCode = e.statusCode
44
+ reply.send({error: e.message})
45
+ } else {
46
+ reply.statusCode = 500
47
+ reply.send({error: 'error.server'})
48
+ }
49
+ }
50
+ })
51
+
52
+ fastify.post('/api/user-api-keys', async (request, reply): Promise<IUserApiKey> => {
53
+ try {
54
+ request.rbac.assertPermission(IdentityPermissions.CreateUser)
55
+ const payload = request.body
56
+ payload.user = request.rbac.authUser.id
57
+
58
+ const userApiKeyService = UserApiKeyServiceFactory()
59
+
60
+ let userApiKey = await userApiKeyService.create(payload)
61
+ return userApiKey
62
+ } catch (e) {
63
+ if (e instanceof ValidationError) {
64
+ reply.statusCode = e.statusCode
65
+ reply.send({error: e.message, inputErrors: e.errors})
66
+ } else if (e instanceof UnauthorizedError) {
67
+ reply.statusCode = e.statusCode
68
+ reply.send({error: e.message})
69
+ } else {
70
+ reply.statusCode = 500
71
+ reply.send({error: 'error.server'})
72
+ }
73
+ }
74
+
75
+ })
76
+
77
+ fastify.put('/api/user-api-keys/:id', async (request, reply): Promise<IUserApiKey> => {
78
+ try {
79
+ request.rbac.assertPermission(IdentityPermissions.UpdateUser)
80
+ const id = request.params.id
81
+ const payload = request.body
82
+ const userApiKeyService = UserApiKeyServiceFactory()
83
+ let userApiKey = await userApiKeyService.update(id, payload)
84
+ return userApiKey
85
+ } catch (e) {
86
+ if (e instanceof ValidationError) {
87
+ reply.statusCode = e.statusCode
88
+ reply.send({error: e.message, inputErrors: e.errors})
89
+ }
90
+ if (e instanceof UnauthorizedError) {
91
+ reply.statusCode = e.statusCode
92
+ reply.send({error: e.message})
93
+ } else if (e instanceof UnauthorizedError) {
94
+ reply.statusCode = e.statusCode
95
+ reply.send({error: e.message})
96
+ } else {
97
+ reply.statusCode = 500
98
+ reply.send({error: 'error.server'})
99
+ }
100
+ }
101
+ })
102
+
103
+ fastify.delete('/api/user-api-keys/:id', async (request, reply): Promise<any> => {
104
+ try {
105
+ request.rbac.assertPermission(IdentityPermissions.DeleteUser)
106
+ const id = request.params.id
107
+ const userApiKeyService = UserApiKeyServiceFactory()
108
+ let r = await userApiKeyService.delete(id)
109
+ return r
110
+ } catch (e) {
111
+ if (e instanceof ValidationError) {
112
+ reply.statusCode = e.statusCode
113
+ reply.send({error: e.message, inputErrors: e.errors})
114
+ } else if (e instanceof UnauthorizedError) {
115
+ reply.statusCode = e.statusCode
116
+ reply.send({error: e.message})
117
+ } else {
118
+ reply.statusCode = 500
119
+ reply.send({error: 'error.server'})
120
+ }
121
+ }
122
+ })
123
+
124
+
125
+ }
126
+
127
+ export default UserApiKeyRoutes;
128
+ export {UserApiKeyRoutes}
@@ -32,6 +32,7 @@ async function UserRoutes(fastify, options) {
32
32
  if (request.authUser) {
33
33
  const userService = UserServiceFactory()
34
34
  let user = await userService.findById(request.authUser.id)
35
+ user.password = undefined
35
36
  delete user.password
36
37
  return user
37
38
  } else {
@@ -69,9 +70,12 @@ async function UserRoutes(fastify, options) {
69
70
  filters.push({field: 'tenant', operator: '$eq', value: request.rbac.getAuthUser.tenantId})
70
71
  }
71
72
  let paginateResult = await userService.paginate({page, limit, orderBy, orderDesc, search, filters})
73
+ for(let item of paginateResult.items){
74
+ item.password = undefined
75
+ delete item.password
76
+ }
72
77
  return paginateResult
73
78
  } catch (e) {
74
- console.log("/api/users",e)
75
79
  if (e instanceof ValidationError) {
76
80
  reply.statusCode = e.statusCode
77
81
  reply.send({error: e.message, inputErrors: e.errors})
@@ -21,6 +21,7 @@ class TenantService {
21
21
  const tenant = await this._repository.create(tenantData)
22
22
  return tenant
23
23
  } catch (e) {
24
+ console.error("Error creating tenant", e)
24
25
  if (e instanceof ZodError) {
25
26
  throw ZodErrorToValidationError(e, tenantData)
26
27
  }
@@ -35,6 +36,7 @@ class TenantService {
35
36
  const tenant = await this._repository.update(id, tenantData)
36
37
  return tenant
37
38
  } catch (e) {
39
+ console.error("Error updating tenant", e)
38
40
  if (e instanceof ZodError) {
39
41
  throw ZodErrorToValidationError(e, tenantData)
40
42
  }
@@ -43,35 +45,65 @@ class TenantService {
43
45
  }
44
46
 
45
47
  async delete(id: string): Promise<boolean> {
46
- const currentTenant = await this.findById(id)
47
- const deletedTenant = await this._repository.delete(id);
48
- return deletedTenant;
48
+ try {
49
+ const deletedTenant = await this._repository.delete(id);
50
+ return deletedTenant;
51
+ } catch (e) {
52
+ console.error("Error deleting tenant", e)
53
+ throw e;
54
+ }
55
+
49
56
  }
50
57
 
51
58
  async findById(id: string): Promise<ITenant | null> {
52
- const tenant: ITenant = await this._repository.findById(id);
53
- return tenant
59
+ try {
60
+ const tenant: ITenant = await this._repository.findById(id);
61
+ return tenant
62
+ } catch (e) {
63
+ console.error("Error finding tenant by id", e)
64
+ throw e;
65
+ }
66
+
54
67
  }
55
68
 
56
69
  async findByName(name: string): Promise<ITenant | null> {
57
- const tenant: ITenant = await this._repository.findByName(name);
58
- return tenant
70
+ try {
71
+ const tenant: ITenant = await this._repository.findByName(name);
72
+ return tenant
73
+ } catch (e) {
74
+ console.error("Error finding tenant by name", e)
75
+ throw e;
76
+ }
77
+
59
78
  }
60
79
 
61
80
  async fetchAll(): Promise<ITenant[]> {
62
- const tenants: ITenant[] = await this._repository.fetchAll();
63
- return tenants
81
+ try {
82
+ const tenants: ITenant[] = await this._repository.fetchAll();
83
+ return tenants
84
+ } catch (e) {
85
+ console.error("Error fetching all tenants", e)
86
+ throw e;
87
+ }
88
+
64
89
  }
65
90
 
66
91
  async paginate({
67
- page= 1,
68
- limit= 5,
69
- orderBy= '',
70
- orderDesc= false,
71
- search= '',
72
- filters= []} : IDraxPaginateOptions): Promise<IDraxPaginateResult<ITenant>>{
73
- const pagination = await this._repository.paginate({page, limit, orderBy, orderDesc, search, filters});
74
- return pagination;
92
+ page = 1,
93
+ limit = 5,
94
+ orderBy = '',
95
+ orderDesc = false,
96
+ search = '',
97
+ filters = []
98
+ }: IDraxPaginateOptions): Promise<IDraxPaginateResult<ITenant>> {
99
+ try {
100
+ const pagination = await this._repository.paginate({page, limit, orderBy, orderDesc, search, filters});
101
+ return pagination;
102
+ } catch (e) {
103
+ console.error("Error paginating tenants", e)
104
+ throw e;
105
+ }
106
+
75
107
  }
76
108
 
77
109
 
@@ -0,0 +1,111 @@
1
+ import {IUserApiKeyRepository} from "../interfaces/IUserApiKeyRepository";
2
+ import {DraxConfig, ValidationError, ZodErrorToValidationError} from "@drax/common-back"
3
+ import {userApiKeySchema} from "../zod/UserApiKeyZod.js";
4
+ import {ZodError} from "zod";
5
+ import {IUserApiKeyBase, IUserApiKey} from "@drax/identity-share";
6
+ import {IDraxPaginateOptions, IDraxPaginateResult} from "@drax/common-share";
7
+ import crypto from "node:crypto";
8
+ import AuthUtils from "../utils/AuthUtils.js";
9
+ import IdentityConfig from "../config/IdentityConfig.js";
10
+
11
+ class UserApiKeyService {
12
+
13
+ _repository: IUserApiKeyRepository
14
+
15
+ constructor(userApiKeyRepostitory: IUserApiKeyRepository) {
16
+ this._repository = userApiKeyRepostitory
17
+ console.log("UserApiKeyService constructor")
18
+ }
19
+
20
+ async create(userApiKeyData: IUserApiKeyBase): Promise<IUserApiKey> {
21
+ try {
22
+ userApiKeyData.name = userApiKeyData?.name?.trim()
23
+ const secret = crypto.randomUUID()
24
+ const APIKEY_SECRET = DraxConfig.getOrLoad(IdentityConfig.ApiKeySecret)
25
+ userApiKeyData.secret = AuthUtils.generateHMAC(APIKEY_SECRET, secret)
26
+ await userApiKeySchema.parseAsync(userApiKeyData)
27
+ const userApiKey = await this._repository.create(userApiKeyData)
28
+ userApiKey.secret = secret
29
+ return userApiKey
30
+ } catch (e) {
31
+ console.error("Error creating userApiKey", e)
32
+ if (e instanceof ZodError) {
33
+ throw ZodErrorToValidationError(e, userApiKeyData)
34
+ }
35
+ throw e
36
+ }
37
+ }
38
+
39
+ async update(id: string, userApiKeyData: IUserApiKeyBase) {
40
+ try {
41
+ userApiKeyData.name = userApiKeyData?.name?.trim()
42
+ delete userApiKeyData.secret
43
+ await userApiKeySchema.parseAsync(userApiKeyData)
44
+ const userApiKey = await this._repository.update(id, userApiKeyData)
45
+ return userApiKey
46
+ } catch (e) {
47
+ console.error("Error updating userApiKey", e)
48
+ if (e instanceof ZodError) {
49
+ throw ZodErrorToValidationError(e, userApiKeyData)
50
+ }
51
+ throw e
52
+ }
53
+ }
54
+
55
+ async delete(id: string): Promise<boolean> {
56
+ try {
57
+ const deletedUserApiKey = await this._repository.delete(id);
58
+ return deletedUserApiKey;
59
+ } catch (e) {
60
+ console.error("Error deleting userApiKey", e)
61
+ throw e
62
+ }
63
+
64
+ }
65
+
66
+ async findById(id: string): Promise<IUserApiKey | null> {
67
+ try{
68
+ const userApiKey: IUserApiKey = await this._repository.findById(id);
69
+ return userApiKey
70
+ }catch (e){
71
+ console.error("Error finding userApiKey by id", e)
72
+ throw e
73
+ }
74
+
75
+ }
76
+
77
+ async findBySecret(secret: string): Promise<IUserApiKey | null> {
78
+ try{
79
+ const APIKEY_SECRET = DraxConfig.getOrLoad(IdentityConfig.ApiKeySecret)
80
+ const hashedSecret = AuthUtils.generateHMAC(APIKEY_SECRET, secret)
81
+ const userApiKey: IUserApiKey = await this._repository.findBySecret(hashedSecret);
82
+ return userApiKey
83
+ }catch (e){
84
+ console.error("Error finding userApiKey by secret", e)
85
+ throw e
86
+ }
87
+
88
+ }
89
+
90
+
91
+ async paginate({
92
+ page = 1,
93
+ limit = 5,
94
+ orderBy = '',
95
+ orderDesc = false,
96
+ search = '',
97
+ filters = []
98
+ }: IDraxPaginateOptions): Promise<IDraxPaginateResult<IUserApiKey>> {
99
+ try {
100
+ const pagination = await this._repository.paginate({page, limit, orderBy, orderDesc, search, filters});
101
+ return pagination;
102
+ } catch (e) {
103
+ console.error("Error paginating userApiKeys", e)
104
+ throw e
105
+ }
106
+ }
107
+
108
+
109
+ }
110
+
111
+ export default UserApiKeyService
@@ -16,68 +16,68 @@ class UserService {
16
16
  console.log("UserService constructor")
17
17
  }
18
18
 
19
- async auth(username : string, password : string){
19
+ async auth(username: string, password: string) {
20
20
  let user = null
21
- console.log("auth username",username)
21
+ console.log("auth username", username)
22
22
  user = await this.findByUsername(username)
23
23
  if (user && user.active && AuthUtils.checkPassword(password, user.password)) {
24
24
  //TODO: Generar Sesion
25
25
  const session = '123'
26
26
  const accessToken = AuthUtils.generateToken(user.id.toString(), user.username, user.role.id, user.tenant?.id, session)
27
27
  return {accessToken: accessToken}
28
- }else{
28
+ } else {
29
29
  throw new BadCredentialsError()
30
30
  }
31
31
  }
32
32
 
33
- async changeUserPassword(userId : string, newPassword : string){
33
+ async changeUserPassword(userId: string, newPassword: string) {
34
34
  const user = await this.findById(userId)
35
- if(user){
36
- newPassword = AuthUtils.hashPassword(newPassword)
35
+ if (user) {
36
+ newPassword = AuthUtils.hashPassword(newPassword)
37
37
  await this._repository.changePassword(userId, newPassword)
38
38
  return true
39
- }else{
39
+ } else {
40
40
  throw new ValidationError([{field: 'userId', reason: 'validation.notFound'}])
41
41
  }
42
42
  }
43
43
 
44
44
 
45
- async changeOwnPassword(userId : string, currentPassword : string, newPassword : string){
45
+ async changeOwnPassword(userId: string, currentPassword: string, newPassword: string) {
46
46
  const user = await this.findById(userId)
47
47
 
48
48
 
49
- if(user && user.active){
49
+ if (user && user.active) {
50
50
 
51
- if(currentPassword === newPassword){
51
+ if (currentPassword === newPassword) {
52
52
  throw new ValidationError([{field: 'newPassword', reason: 'validation.password.currentDifferent'}])
53
53
  }
54
54
 
55
55
  if (AuthUtils.checkPassword(currentPassword, user.password)) {
56
- newPassword = AuthUtils.hashPassword(newPassword)
56
+ newPassword = AuthUtils.hashPassword(newPassword)
57
57
  await this._repository.changePassword(userId, newPassword)
58
58
  return true
59
- }else{
59
+ } else {
60
60
  throw new ValidationError([{field: 'currentPassword', reason: 'validation.notMatch'}])
61
61
  }
62
62
 
63
- }else{
63
+ } else {
64
64
  throw new BadCredentialsError()
65
65
  }
66
66
  }
67
67
 
68
- async changeAvatar(userId : string, avatar: string){
68
+ async changeAvatar(userId: string, avatar: string) {
69
69
  const user = await this.findById(userId)
70
- if(user && user.active){
71
- await this._repository.changeAvatar(userId, avatar)
72
- return true
73
- }else{
70
+ if (user && user.active) {
71
+ await this._repository.changeAvatar(userId, avatar)
72
+ return true
73
+ } else {
74
74
  throw new BadCredentialsError()
75
75
  }
76
76
  }
77
77
 
78
78
 
79
79
  async create(userData: IUserCreate): Promise<IUser> {
80
- try{
80
+ try {
81
81
  userData.name = userData?.name?.trim()
82
82
  userData.username = userData.username.trim()
83
83
  userData.password = userData.password.trim()
@@ -89,9 +89,10 @@ class UserService {
89
89
 
90
90
  const user: IUser = await this._repository.create(userData)
91
91
  return user
92
- }catch (e){
93
- if(e instanceof ZodError){
94
- throw ZodErrorToValidationError(e,userData)
92
+ } catch (e) {
93
+ console.error("Error creating user", e)
94
+ if (e instanceof ZodError) {
95
+ throw ZodErrorToValidationError(e, userData)
95
96
  }
96
97
  throw e
97
98
  }
@@ -100,50 +101,75 @@ class UserService {
100
101
  }
101
102
 
102
103
  async update(id: string, userData: IUserUpdate) {
103
- try{
104
- userData.name = userData.name.trim()
105
- userData.username = userData.username.trim()
106
- delete userData.password
107
- userData.tenant = userData.tenant === "" ? null : userData.tenant
104
+ try {
105
+ userData.name = userData.name.trim()
106
+ userData.username = userData.username.trim()
107
+ delete userData.password
108
+ userData.tenant = userData.tenant === "" ? null : userData.tenant
108
109
 
109
- await editUserSchema.parseAsync(userData)
110
+ await editUserSchema.parseAsync(userData)
110
111
 
111
112
 
112
- const user: IUser = await this._repository.update(id, userData)
113
- return user
114
- }catch (e){
115
- if(e instanceof ZodError){
116
- throw ZodErrorToValidationError(e,userData)
113
+ const user: IUser = await this._repository.update(id, userData)
114
+ return user
115
+ } catch (e) {
116
+ console.error("Error updating user", e)
117
+ if (e instanceof ZodError) {
118
+ throw ZodErrorToValidationError(e, userData)
117
119
  }
118
120
  throw e
119
121
  }
120
122
  }
121
123
 
122
124
  async delete(id: string): Promise<boolean> {
123
- const deletedRole: boolean = await this._repository.delete(id);
124
- return deletedRole;
125
+ try {
126
+ const deletedRole: boolean = await this._repository.delete(id);
127
+ return deletedRole;
128
+ } catch (e) {
129
+ console.error("Error deleting user", e)
130
+ throw e
131
+ }
132
+
125
133
  }
126
134
 
127
135
  async findById(id: string): Promise<IUser> {
128
- const user: IUser = await this._repository.findById(id);
129
- return user
136
+ try {
137
+ const user: IUser = await this._repository.findById(id);
138
+ return user
139
+ } catch (e) {
140
+ console.error("Error finding user by id", e)
141
+ throw e
142
+ }
143
+
130
144
  }
131
145
 
132
146
  async findByUsername(username: string): Promise<IUser | null> {
133
- const user: IUser = await this._repository.findByUsername(username);
134
- return user
147
+ try {
148
+ const user: IUser = await this._repository.findByUsername(username);
149
+ return user
150
+ } catch (e) {
151
+ console.error("Error finding user by username", e)
152
+ throw e
153
+ }
154
+
135
155
  }
136
156
 
137
157
  async paginate({
138
- page= 1,
139
- limit= 5,
140
- orderBy= '',
141
- orderDesc= false,
142
- search= '',
143
- filters= []} : IDraxPaginateOptions): Promise<IDraxPaginateResult<IUser>>{
144
-
145
- const pagination = await this._repository.paginate( {page, limit, orderBy, orderDesc, search, filters});
146
- return pagination;
158
+ page = 1,
159
+ limit = 5,
160
+ orderBy = '',
161
+ orderDesc = false,
162
+ search = '',
163
+ filters = []
164
+ }: IDraxPaginateOptions): Promise<IDraxPaginateResult<IUser>> {
165
+ try {
166
+ const pagination = await this._repository.paginate({page, limit, orderBy, orderDesc, search, filters});
167
+ return pagination;
168
+ } catch (e) {
169
+ console.error("Error paginating users", e)
170
+ throw e;
171
+ }
172
+
147
173
  }
148
174
  }
149
175
 
@@ -2,12 +2,14 @@ import {DraxConfig} from "@drax/common-back";
2
2
  import IdentityConfig from "../config/IdentityConfig.js";
3
3
 
4
4
  function LoadIdentityConfigFromEnv() {
5
- DraxConfig.set(IdentityConfig.DbEngine, process.env[IdentityConfig.DbEngine])
6
- DraxConfig.set(IdentityConfig.SqliteDbFile, process.env[IdentityConfig.SqliteDbFile])
7
- DraxConfig.set(IdentityConfig.MongoDbUri, process.env[IdentityConfig.MongoDbUri])
5
+
8
6
  DraxConfig.set(IdentityConfig.JwtSecret, process.env[IdentityConfig.JwtSecret])
9
7
  DraxConfig.set(IdentityConfig.JwtExpiration, process.env[IdentityConfig.JwtExpiration])
10
8
  DraxConfig.set(IdentityConfig.JwtIssuer, process.env[IdentityConfig.JwtIssuer])
9
+ DraxConfig.set(IdentityConfig.ApiKeySecret, process.env[IdentityConfig.ApiKeySecret])
10
+
11
+ DraxConfig.set(IdentityConfig.RbacCacheTTL, process.env[IdentityConfig.RbacCacheTTL])
12
+ DraxConfig.set(IdentityConfig.AvatarDir, process.env[IdentityConfig.AvatarDir])
11
13
  }
12
14
 
13
15
  export default LoadIdentityConfigFromEnv
@@ -2,6 +2,7 @@ import bcryptjs from "bcryptjs";
2
2
  import jsonwebtoken, {SignOptions, VerifyOptions} from "jsonwebtoken";
3
3
  import {DraxConfig} from "@drax/common-back";
4
4
  import IdentityConfig from "../config/IdentityConfig.js";
5
+ import crypto from "crypto";
5
6
 
6
7
  class AuthUtils{
7
8
 
@@ -67,6 +68,16 @@ class AuthUtils{
67
68
 
68
69
  return token
69
70
  }
71
+
72
+ static generateHMAC(secret: string, apikey: string) {
73
+ // Crear un objeto HMAC utilizando el algoritmo SHA-256 y el secreto
74
+ const hmac = crypto.createHmac('sha256', secret);
75
+ // Actualizar el HMAC con la apikey
76
+ hmac.update(apikey);
77
+ // Generar el hash en formato hexadecimal
78
+ return hmac.digest('hex');
79
+ }
70
80
  }
71
81
 
72
82
  export default AuthUtils
83
+ export {AuthUtils}
@@ -0,0 +1,15 @@
1
+ import {array, object, string} from "zod"
2
+
3
+ const userApiKeySchema = object({
4
+ name: string({ required_error: "validation.required" })
5
+ .min(1, "validation.required"),
6
+ ipv4: array(string().ip({version: "v4", message: 'validation.invalidIpv4'})),
7
+ ipv6: array(string().ip({version: "v6", message: 'validation.invalidIpv6'})),
8
+
9
+
10
+ })
11
+
12
+
13
+ export default userApiKeySchema
14
+
15
+ export {userApiKeySchema}
@@ -0,0 +1,10 @@
1
+ import user from "../users/root-mongo-user"
2
+
3
+ const userApiKey = {
4
+ _id: "646a661e44c93567c23d8c22",
5
+ name: "root",
6
+ secret: "123",
7
+ user: user._id
8
+ };
9
+
10
+ export default userApiKey
@@ -1,6 +1,3 @@
1
- import {mongoose} from "@drax/common-back"
2
- import {IRole} from "../../../../identity-share/src/interfaces/IRole"
3
-
4
1
 
5
2
  const role = {
6
3
  _id: "646a661e44c93567c23d8d62",
@@ -13,3 +13,4 @@ class RoleMongoInitializer {
13
13
  }
14
14
 
15
15
  export default RoleMongoInitializer
16
+ export {RoleMongoInitializer}
@@ -16,3 +16,4 @@ async function RoleSqliteInitializer(): Promise<IRole> {
16
16
  }
17
17
 
18
18
  export default RoleSqliteInitializer
19
+ export {RoleSqliteInitializer}
@@ -0,0 +1,18 @@
1
+ import UserService from "../../src/services/UserService";
2
+ import {IUser} from "../../../identity-share/src/interfaces/IUser";
3
+ import UserMongoRepository from "../../src/repository/mongo/UserMongoRepository";
4
+
5
+ class UserMongoInitializer {
6
+
7
+ static async initRootUser(): Promise<IUser>{
8
+ const userService = new UserService(new UserMongoRepository())
9
+ let data = (await import("../data-obj/users/root-mongo-user")).default
10
+ let userCreated = await userService.create(data)
11
+ return userCreated
12
+ }
13
+ }
14
+
15
+ export default UserMongoInitializer
16
+ export {
17
+ UserMongoInitializer
18
+ }