@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.
- package/dist/config/IdentityConfig.js +2 -3
- package/dist/factory/RoleServiceFactory.js +8 -7
- package/dist/factory/TenantServiceFactory.js +8 -7
- package/dist/factory/UserApiKeyServiceFactory.js +24 -0
- package/dist/factory/UserServiceFactory.js +8 -7
- package/dist/graphql/resolvers/user-api-key.resolvers.js +89 -0
- package/dist/graphql/resolvers/user.resolvers.js +7 -2
- package/dist/graphql/types/userApiKey.graphql +33 -0
- package/dist/index.js +4 -2
- package/dist/interfaces/IUserApiKeyRepository.js +1 -0
- package/dist/middleware/apiKeyMiddleware.js +30 -0
- package/dist/middleware/rbacMiddleware.js +0 -1
- package/dist/models/UserApiKeyModel.js +44 -0
- package/dist/permissions/IdentityPermissions.js +6 -0
- package/dist/rbac/Rbac.js +8 -0
- package/dist/repository/mongo/UserApiKeyMongoRepository.js +82 -0
- package/dist/repository/mongo/UserMongoRepository.js +3 -3
- package/dist/repository/sqlite/RoleSqliteRepository.js +16 -18
- package/dist/repository/sqlite/TenantSqliteRepository.js +13 -11
- package/dist/repository/sqlite/UserApiKeySqliteRepository.js +147 -0
- package/dist/repository/sqlite/UserSqliteRepository.js +29 -26
- package/dist/routes/UserApiKeyRoutes.js +119 -0
- package/dist/routes/UserRoutes.js +5 -1
- package/dist/services/TenantService.js +42 -11
- package/dist/services/UserApiKeyService.js +90 -0
- package/dist/services/UserService.js +34 -8
- package/dist/setup/LoadIdentityConfigFromEnv.js +3 -3
- package/dist/utils/AuthUtils.js +10 -0
- package/dist/zod/UserApiKeyZod.js +9 -0
- package/package.json +7 -6
- package/src/config/IdentityConfig.ts +4 -3
- package/src/factory/RoleServiceFactory.ts +11 -11
- package/src/factory/TenantServiceFactory.ts +11 -11
- package/src/factory/UserApiKeyServiceFactory.ts +30 -0
- package/src/factory/UserServiceFactory.ts +8 -7
- package/src/graphql/resolvers/tenant.resolvers.ts +0 -1
- package/src/graphql/resolvers/user-api-key.resolvers.ts +94 -0
- package/src/graphql/resolvers/user.resolvers.ts +9 -2
- package/src/graphql/types/userApiKey.graphql +33 -0
- package/src/index.ts +10 -0
- package/src/interfaces/IUserApiKeyRepository.ts +8 -0
- package/src/middleware/apiKeyMiddleware.ts +35 -0
- package/src/middleware/rbacMiddleware.ts +1 -2
- package/src/models/UserApiKeyModel.ts +59 -0
- package/src/permissions/IdentityPermissions.ts +7 -0
- package/src/rbac/Rbac.ts +13 -2
- package/src/repository/mongo/UserApiKeyMongoRepository.ts +114 -0
- package/src/repository/mongo/UserMongoRepository.ts +3 -3
- package/src/repository/sqlite/RoleSqliteRepository.ts +28 -20
- package/src/repository/sqlite/TenantSqliteRepository.ts +25 -11
- package/src/repository/sqlite/UserApiKeySqliteRepository.ts +197 -0
- package/src/repository/sqlite/UserSqliteRepository.ts +37 -27
- package/src/routes/UserApiKeyRoutes.ts +128 -0
- package/src/routes/UserRoutes.ts +5 -1
- package/src/services/TenantService.ts +49 -17
- package/src/services/UserApiKeyService.ts +111 -0
- package/src/services/UserService.ts +74 -48
- package/src/setup/LoadIdentityConfigFromEnv.ts +5 -3
- package/src/utils/AuthUtils.ts +11 -0
- package/src/zod/UserApiKeyZod.ts +15 -0
- package/test/data-obj/apikey/root-mongo-user-apikey.ts +10 -0
- package/test/data-obj/roles/admin-mongo-role.ts +0 -3
- package/test/initializers/RoleMongoInitializer.ts +1 -0
- package/test/initializers/RoleSqliteInitializer.ts +1 -0
- package/test/initializers/UserMongoInitializer.ts +18 -0
- package/test/repository/mongo/user-apikey-mongo-repository.test.ts +73 -0
- package/tsconfig.tsbuildinfo +1 -1
- package/types/config/IdentityConfig.d.ts +2 -3
- package/types/config/IdentityConfig.d.ts.map +1 -1
- package/types/errors/BadCredentialsError.d.ts +6 -0
- package/types/errors/BadCredentialsError.d.ts.map +1 -0
- package/types/errors/UnauthorizedError.d.ts +6 -0
- package/types/errors/UnauthorizedError.d.ts.map +1 -0
- package/types/factory/RoleServiceFactory.d.ts +4 -0
- package/types/factory/RoleServiceFactory.d.ts.map +1 -1
- package/types/factory/TenantServiceFactory.d.ts +4 -0
- package/types/factory/TenantServiceFactory.d.ts.map +1 -1
- package/types/factory/UserApiKeyServiceFactory.d.ts +4 -0
- package/types/factory/UserApiKeyServiceFactory.d.ts.map +1 -0
- package/types/factory/UserServiceFactory.d.ts +4 -0
- package/types/factory/UserServiceFactory.d.ts.map +1 -1
- package/types/graphql/index.d.ts +6 -0
- package/types/graphql/resolvers/tenant.resolvers.d.ts.map +1 -1
- package/types/graphql/resolvers/user-api-key.resolvers.d.ts +37 -0
- package/types/graphql/resolvers/user-api-key.resolvers.d.ts.map +1 -0
- package/types/graphql/resolvers/user.resolvers.d.ts.map +1 -1
- package/types/index.d.ts +35 -0
- package/types/index.d.ts.map +1 -1
- package/types/interfaces/IRoleRepository.d.ts +9 -0
- package/types/interfaces/ITenantRepository.d.ts +9 -0
- package/types/interfaces/IUserApiKeyRepository.d.ts +7 -0
- package/types/interfaces/IUserApiKeyRepository.d.ts.map +1 -0
- package/types/interfaces/IUserRepository.d.ts +10 -0
- package/types/middleware/apiKeyMiddleware.d.ts +4 -0
- package/types/middleware/apiKeyMiddleware.d.ts.map +1 -0
- package/types/middleware/jwtMiddleware.d.ts +4 -0
- package/types/middleware/rbacMiddleware.d.ts +4 -0
- package/types/middleware/rbacMiddleware.d.ts.map +1 -1
- package/types/models/RoleModel.d.ts +16 -0
- package/types/models/TenantModel.d.ts +16 -0
- package/types/models/UserApiKeyModel.d.ts +16 -0
- package/types/models/UserApiKeyModel.d.ts.map +1 -0
- package/types/models/UserGroupModel.d.ts +16 -0
- package/types/models/UserModel.d.ts +16 -0
- package/types/permissions/IdentityPermissions.d.ts +27 -0
- package/types/permissions/IdentityPermissions.d.ts.map +1 -0
- package/types/rbac/Rbac.d.ts +15 -0
- package/types/rbac/Rbac.d.ts.map +1 -1
- package/types/repository/mongo/RoleMongoRepository.d.ts +14 -0
- package/types/repository/mongo/TenantMongoRepository.d.ts +14 -0
- package/types/repository/mongo/UserApiKeyMongoRepository.d.ts +14 -0
- package/types/repository/mongo/UserApiKeyMongoRepository.d.ts.map +1 -0
- package/types/repository/mongo/UserMongoRepository.d.ts +17 -0
- package/types/repository/sqlite/RoleSqliteRepository.d.ts +22 -0
- package/types/repository/sqlite/RoleSqliteRepository.d.ts.map +1 -1
- package/types/repository/sqlite/TenantSqliteRepository.d.ts +19 -0
- package/types/repository/sqlite/TenantSqliteRepository.d.ts.map +1 -1
- package/types/repository/sqlite/UserApiKeySqliteRepository.d.ts +19 -0
- package/types/repository/sqlite/UserApiKeySqliteRepository.d.ts.map +1 -0
- package/types/repository/sqlite/UserSqliteRepository.d.ts +25 -0
- package/types/repository/sqlite/UserSqliteRepository.d.ts.map +1 -1
- package/types/routes/RoleRoutes.d.ts +4 -0
- package/types/routes/TenantRoutes.d.ts +4 -0
- package/types/routes/UserApiKeyRoutes.d.ts +4 -0
- package/types/routes/UserApiKeyRoutes.d.ts.map +1 -0
- package/types/routes/UserAvatarRoutes.d.ts +4 -0
- package/types/routes/UserRoutes.d.ts +4 -0
- package/types/routes/UserRoutes.d.ts.map +1 -1
- package/types/services/PermissionService.d.ts +9 -0
- package/types/services/PermissionService.d.ts.map +1 -0
- package/types/services/RoleService.d.ts +16 -0
- package/types/services/TenantService.d.ts +16 -0
- package/types/services/TenantService.d.ts.map +1 -1
- package/types/services/UserApiKeyService.d.ts +15 -0
- package/types/services/UserApiKeyService.d.ts.map +1 -0
- package/types/services/UserService.d.ts +21 -0
- package/types/services/UserService.d.ts.map +1 -1
- package/types/setup/CreateOrUpdateRole.d.ts +5 -0
- package/types/setup/CreateUserIfNotExist.d.ts +5 -0
- package/types/setup/LoadIdentityConfigFromEnv.d.ts +4 -0
- package/types/setup/LoadIdentityConfigFromEnv.d.ts.map +1 -1
- package/types/setup/LoadPermissions.d.ts +4 -0
- package/types/setup/LoadPermissions.d.ts.map +1 -0
- package/types/setup/RecoveryUserPassword.d.ts +4 -0
- package/types/utils/AuthUtils.d.ts +18 -0
- package/types/utils/AuthUtils.d.ts.map +1 -1
- package/types/zod/RoleZod.d.ts +10 -0
- package/types/zod/RoleZod.d.ts.map +1 -0
- package/types/zod/TenantZod.d.ts +10 -0
- package/types/zod/TenantZod.d.ts.map +1 -0
- package/types/zod/UserApiKeyZod.d.ts +16 -0
- package/types/zod/UserApiKeyZod.d.ts.map +1 -0
- package/types/zod/UserZod.d.ts +53 -0
- package/types/zod/UserZod.d.ts.map +1 -0
- package/src/utils/DbSetupUtils.ts +0 -41
- 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}
|
package/src/routes/UserRoutes.ts
CHANGED
|
@@ -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
|
-
|
|
47
|
-
|
|
48
|
-
|
|
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
|
-
|
|
53
|
-
|
|
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
|
-
|
|
58
|
-
|
|
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
|
-
|
|
63
|
-
|
|
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= []
|
|
73
|
-
|
|
74
|
-
|
|
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
|
|
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
|
|
33
|
+
async changeUserPassword(userId: string, newPassword: string) {
|
|
34
34
|
const user = await this.findById(userId)
|
|
35
|
-
if(user){
|
|
36
|
-
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
|
|
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 =
|
|
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
|
|
68
|
+
async changeAvatar(userId: string, avatar: string) {
|
|
69
69
|
const user = await this.findById(userId)
|
|
70
|
-
if(user && user.active){
|
|
71
|
-
|
|
72
|
-
|
|
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
|
-
|
|
94
|
-
|
|
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
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
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
|
-
|
|
110
|
+
await editUserSchema.parseAsync(userData)
|
|
110
111
|
|
|
111
112
|
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
}catch (e){
|
|
115
|
-
|
|
116
|
-
|
|
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
|
-
|
|
124
|
-
|
|
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
|
-
|
|
129
|
-
|
|
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
|
-
|
|
134
|
-
|
|
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= []
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
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
|
-
|
|
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
|
package/src/utils/AuthUtils.ts
CHANGED
|
@@ -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,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
|
+
}
|