diff --git a/src/controllers/UserController.ts b/src/controllers/UserController.ts index c8557eba..cba039c9 100644 --- a/src/controllers/UserController.ts +++ b/src/controllers/UserController.ts @@ -654,6 +654,78 @@ export class KeycloakController extends Controller { } } + @Post("user/emp") + @Security("bearerAuth", ["system", "admin"]) + async createUserEmp( + @Request() request: { user: { sub: string; preferred_username: string } }, + @Body() + body: { + username: string; + password: string; + firstName?: string; + lastName?: string; + email?: string; + roles: string[]; + profileId?: string; + }, + ) { + const checkUser = await getUserByUsername(body.username); + let userId: any = ""; + if (checkUser.length == 0) { + userId = await createUser(body.username, body.password, { + firstName: body.firstName, + lastName: body.lastName, + // email: body.email, + }); + if (typeof userId !== "string") { + throw new Error(userId.errorMessage); + } + } else { + userId = checkUser[0].id; + } + + const list = await getRoles(); + if (!Array.isArray(list)) throw new Error("Failed. Cannot get role(s) data from the server."); + const result = await addUserRoles( + userId, + list.filter((v) => body.roles.includes(v.id)), + ); + + if (!result) { + throw new Error("Failed. Cannot set user's role."); + } + const profile = await this.profileEmpRepo.findOne({ + where: { + id: body.profileId, + }, + }); + + if (profile) { + let _null: any = null; + if (typeof userId === "string") { + profile.keycloak = userId; + } + profile.email = body.email == null ? _null : body.email; + await this.profileEmpRepo.save(profile); + if (body.roles != null && body.roles.length > 0) { + const roleKeycloak = await this.roleKeycloakRepo.find({ + where: { id: In(body.roles) }, + }); + const _profile = await this.profileEmpRepo.findOne({ + where: { keycloak: userId }, + relations: ["roleKeycloaks"], + }); + if (_profile) { + _profile.roleKeycloaks = Array.from( + new Set([..._profile.roleKeycloaks, ...roleKeycloak]), + ); + this.profileEmpRepo.save(_profile); + } + } + } + return userId; + } + @Delete("group/{groupId}") async deleteGroup(@Path() groupId: string) { const result = await deleteGroup(groupId);