add reset password by admin & super_admin
All checks were successful
Build & Deploy on Dev / build (push) Successful in 1m10s

This commit is contained in:
Warunee Tamkoo 2026-04-28 15:14:47 +07:00
parent 3833901bea
commit d82cd842f6

View file

@ -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({