diff --git a/src/controllers/UserController.ts b/src/controllers/UserController.ts index afc686e6..923287e2 100644 --- a/src/controllers/UserController.ts +++ b/src/controllers/UserController.ts @@ -814,6 +814,68 @@ export class KeycloakController extends Controller { if (!result) throw new Error("Failed. Cannot remove group to user."); } + @Post("user/reset-password") + @Security("bearerAuth", ["admin"]) + async resetUserPassword(@Request() req: RequestWithUser, @Body() body: { profileId: string }) { + if (!req.user.role.includes("ADMIN") && !req.user.role.includes("SUPER_ADMIN")) { + throw new HttpError(HttpStatus.FORBIDDEN, "ไม่มีสิทธิ์ดำเนินการ"); + } + + let profile: Profile | ProfileEmployee | null = await this.profileRepo.findOne({ + where: { id: body.profileId }, + select: ["id", "keycloak", "birthDate", "firstName", "lastName", "citizenId"], + }); + + let isEmployee = false; + if (!profile) { + profile = await this.profileEmpRepo.findOne({ + where: { id: body.profileId, employeeClass: "PERM" }, + select: ["id", "keycloak", "birthDate", "firstName", "lastName", "citizenId"], + }); + isEmployee = true; + } + + if (!profile) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลผู้ใช้"); + } + + if (!profile.keycloak) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ผู้ใช้ไม่ได้เชื่อมต่อกับ Keycloak"); + } + + let newPassword: string; + const isProduction = process.env.NODE_ENV === "production"; + + if (isProduction && profile.birthDate) { + const _date = new Date(profile.birthDate.toDateString()) + .getDate() + .toString() + .padStart(2, "0"); + const _month = (new Date(profile.birthDate.toDateString()).getMonth() + 1) + .toString() + .padStart(2, "0"); + const _year = new Date(profile.birthDate.toDateString()).getFullYear() + 543; + newPassword = `${_date}${_month}${_year}`; + } else { + newPassword = "P@ssw0rd"; + } + + const result = await changeUserPassword(profile.keycloak, newPassword); + if (!result) { + throw new HttpError(HttpStatus.INTERNAL_SERVER_ERROR, "ไม่สามารถรีเซ็ตรหัสผ่านได้"); + } + + addLogSequence(req, { + action: "reset-password", + status: "success", + description: `รีเซ็ตรหัสผ่านสำหรับ ${profile.firstName} ${profile.lastName} (${profile.citizenId})`, + }); + + const response = new HttpSuccess(); + response.message = "รีเซ็ตรหัสผ่านสำเร็จ"; + return response; + } + @Get("user/role/{id}") async getRoleUser(@Request() req: RequestWithUser, @Path("id") id: string) { const profile = await this.profileRepo.findOne({