From 86be7e9778c01344fb0c20f9e0e875d4b0513c9d Mon Sep 17 00:00:00 2001 From: Bright Date: Fri, 21 Feb 2025 17:26:11 +0700 Subject: [PATCH] reset-password --- src/controllers/UserController.ts | 16 ++++++++++++++++ src/keycloak/index.ts | 32 +++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/src/controllers/UserController.ts b/src/controllers/UserController.ts index 2a7068dd..be68be2a 100644 --- a/src/controllers/UserController.ts +++ b/src/controllers/UserController.ts @@ -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; + } } diff --git a/src/keycloak/index.ts b/src/keycloak/index.ts index e55be59a..26701940 100644 --- a/src/keycloak/index.ts +++ b/src/keycloak/index.ts @@ -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; + } +} \ No newline at end of file