reset-password

This commit is contained in:
Bright 2025-02-21 17:26:11 +07:00
parent 626be7dae6
commit 86be7e9778
2 changed files with 48 additions and 0 deletions

View file

@ -32,6 +32,7 @@ import {
enableStatus,
getUserByUsername,
changeUserPassword,
resetPassword
} from "../keycloak";
import { AppDataSource } from "../database/data-source";
import { Profile } from "../entities/Profile";
@ -828,4 +829,19 @@ export class KeycloakController extends Controller {
}
return result;
}
@Post("user/reset-password")
async forgetPassword(
@Request() request: { user: { sub: string; preferred_username: string } },
@Body()
body: {
username: string;
},
) {
const result = await resetPassword(body.username);
if (!result) {
throw new Error("Failed. Cannot change password.");
}
return result;
}
}

View file

@ -761,3 +761,35 @@ export async function changeUserPassword(userId: string, newPassword: string) {
return false;
}
}
// Function to reset password
export async function resetPassword(username: string) {
try {
const users = await fetch(`${KC_URL}/admin/realms/${KC_REALMS}/users?email=${encodeURIComponent(username)}`, {
headers: {
"authorization": `Bearer ${await getToken()}`,
"content-type": `application/json`,
},
});
if(!users.ok) {
return false;
}
const usersData = await users.json();
const userId = usersData[0].id;
const resetResponse = await fetch(`${KC_URL}/admin/realms/${KC_REALMS}/users/${userId}/execute-actions-email`, {
method: "PUT",
headers: {
"Authorization": `Bearer ${await getToken()}`,
"Content-Type": "application/json"
},
body: JSON.stringify(["UPDATE_PASSWORD"])
});
if (!resetResponse.ok) {
return false;
}
return { message: "Password reset email sent" };
} catch (error) {
console.error("Error triggering password reset:", error);
return false;
}
}