From 3de21aee5f76da4ba286c912fb6ea98141d1a6e6 Mon Sep 17 00:00:00 2001 From: kittapath Date: Tue, 4 Mar 2025 22:03:23 +0700 Subject: [PATCH] create user import --- src/controllers/UserController.ts | 63 ++++++++++++++++++++++++++++++- 1 file changed, 62 insertions(+), 1 deletion(-) diff --git a/src/controllers/UserController.ts b/src/controllers/UserController.ts index 4dd90dbf..324f06ab 100644 --- a/src/controllers/UserController.ts +++ b/src/controllers/UserController.ts @@ -32,7 +32,7 @@ import { enableStatus, getUserByUsername, changeUserPassword, - resetPassword + resetPassword, } from "../keycloak"; import { AppDataSource } from "../database/data-source"; import { Profile } from "../entities/Profile"; @@ -830,4 +830,65 @@ export class KeycloakController extends Controller { return result; } + @Post("user/asdasdasd") + @Security("bearerAuth", ["system", "admin"]) + async createUserImport( + @Request() request: { user: { sub: string; preferred_username: string } }, + ) { + const profiles = await this.profileRepo.find({ + // where: { + // citizenId: "3640500632315", + // }, + relations: ["roleKeycloaks"], + }); + + for await (const _item of profiles) { + let password = _item.citizenId; + if (_item.birthDate != null) { + const gregorianYear = _item.birthDate.getFullYear() + 543; + + const formattedDate = + _item.birthDate.toISOString().slice(8, 10) + + _item.birthDate.toISOString().slice(5, 7) + + gregorianYear; + password = formattedDate; + } + const checkUser = await getUserByUsername(_item.citizenId); + let userId: any = ""; + if (checkUser.length == 0) { + userId = await createUser(_item.citizenId, password, { + firstName: _item.firstName, + lastName: _item.lastName, + // email: _item.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) => v.id == "f8619dc2-dc0d-4aab-957f-66bdf905e9d0"), + ); + + if (!result) { + throw new Error("Failed. Cannot set user's role."); + } + if (typeof userId === "string") { + _item.keycloak = userId; + } + const roleKeycloak = await this.roleKeycloakRepo.find({ + where: { id: "f8619dc2-dc0d-4aab-957f-66bdf905e9d0" }, + }); + if (_item) { + _item.roleKeycloaks = Array.from(new Set([..._item.roleKeycloaks, ...roleKeycloak])); + this.profileRepo.save(_item); + } + } + return "555+"; + } }