api enableStatus

This commit is contained in:
AdisakKanthawilang 2024-06-14 16:23:36 +07:00
parent f05c2f4b63
commit d613637c95
2 changed files with 46 additions and 7 deletions

View file

@ -29,6 +29,7 @@ import {
removeUserRoles,
getRoleMappings,
getUserCount,
enableStatus,
} from "../keycloak";
import { AppDataSource } from "../database/data-source";
import { Profile } from "../entities/Profile";
@ -50,7 +51,6 @@ function stripLeadingSlash(str: string) {
@Tags("Single-Sign On")
@Security("bearerAuth")
export class KeycloakController extends Controller {
private profileRepo = AppDataSource.getRepository(Profile);
private profileEmpRepo = AppDataSource.getRepository(ProfileEmployee);
@ -148,7 +148,7 @@ export class KeycloakController extends Controller {
},
});
if (profile) {
if (profile) {
profile.keycloak = userId;
await this.profileRepo.save(profile);
}
@ -191,9 +191,9 @@ export class KeycloakController extends Controller {
id: userId,
},
});
if (profile) {
const null_:any = null;
const null_: any = null;
profile.keycloak = null_;
await this.profileRepo.save(profile);
}
@ -254,6 +254,7 @@ export class KeycloakController extends Controller {
lastname: x.lastName,
email: x.email,
roles: roles,
enabled: x.enabled,
};
}),
);
@ -314,4 +315,10 @@ export class KeycloakController extends Controller {
}
return result;
}
@Put("user/{userId}/enableStatus/{status}")
async changeEnableStatus(@Path() userId: string, @Path() status: boolean) {
const result = await enableStatus(userId, status);
if (!result) throw new Error("Failed. Cannot change enable status.");
}
}

View file

@ -147,6 +147,7 @@ export async function getUserList(first = "", max = "", search = "") {
firstName: v.firstName,
lastName: v.lastName,
email: v.email,
enabled: v.enabled,
}));
}
@ -233,9 +234,7 @@ export async function updateName(
lastName,
}),
}).catch((e) => console.log("Keycloak Error: ", e));
console.log("firstName: ", firstName);
console.log("lastName: ", lastName);
if (!res) return false;
if (!res.ok) {
// return Boolean(console.error("Keycloak Error Response: ", await res.json()));
@ -247,6 +246,39 @@ export async function updateName(
return id || true;
}
/**
* enable keycloak user by uuid
*
* Client must have permission to manage realm's user
*
* @returns user uuid or true if success, false otherwise.
*/
export async function enableStatus(
userId: string,
status: boolean,
) {
const res = await fetch(`${KC_URL}/admin/realms/${KC_REALM}/users/${userId}`, {
headers: {
authorization: `Bearer ${await getToken()}`,
"content-type": `application/json`,
},
method: "PUT",
body: JSON.stringify({
enabled: status,
}),
}).catch((e) => console.log("Keycloak Error: ", e));
if (!res) return false;
if (!res.ok) {
return await res.json();
}
const path = res.headers.get("Location");
const id = path?.split("/").at(-1);
return id || true;
}
/**
* Delete keycloak user by uuid
*