feat: update keycloak function

This commit is contained in:
Methapon2001 2024-06-06 09:26:26 +07:00
parent a5d59c6e8b
commit 5053f83470

View file

@ -2,8 +2,8 @@ import { DecodedJwt, createDecoder } from "fast-jwt";
const KC_URL = process.env.KC_URL;
const KC_REALM = process.env.KC_REALM;
const KC_CLIENT_ID = process.env.KC_SERVICE_ACCOUNT_CLIENT_ID;
const KC_SECRET = process.env.KC_SERVICE_ACCOUNT_SECRET;
const KC_ADMIN_USERNAME = process.env.KC_ADMIN_USERNAME;
const KC_ADMIN_PASSWORD = process.env.KC_ADMIN_PASSWORD;
let token: string | null = null;
let decoded: DecodedJwt | null = null;
@ -14,7 +14,7 @@ const jwtDecode = createDecoder({ complete: true });
* Check if token is expired or will expire in 30 seconds
* @returns true if expire or can't get exp, false otherwise
*/
export function isTokenExpired(token: string, beforeExpire: number = 30) {
export function isTokenExpired(token: string, beforeExpire: number = 10) {
decoded = jwtDecode(token);
if (decoded && decoded.payload.exp) {
@ -28,19 +28,20 @@ export function isTokenExpired(token: string, beforeExpire: number = 30) {
* Get token from keycloak if needed
*/
export async function getToken() {
if (!KC_CLIENT_ID || !KC_SECRET) {
throw new Error("KC_CLIENT_ID and KC_SECRET are required to used this feature.");
if (!KC_ADMIN_PASSWORD || !KC_ADMIN_USERNAME) {
throw new Error("KC_ADMIN_USERNAME and KC_ADMIN_PASSWORD are required to used this feature.");
}
if (token && !isTokenExpired(token)) return token;
const body = new URLSearchParams();
body.append("client_id", KC_CLIENT_ID);
body.append("client_secret", KC_SECRET);
body.append("grant_type", "client_credentials");
body.append("client_id", "admin-cli");
body.append("grant_type", "password");
body.append("username", KC_ADMIN_USERNAME);
body.append("password", KC_ADMIN_PASSWORD);
const res = await fetch(`${KC_URL}/realms/${KC_REALM}/protocol/openid-connect/token`, {
const res = await fetch(`${KC_URL}/realms/master/protocol/openid-connect/token`, {
method: "POST",
body: body,
}).catch((e) => console.error(e));