100 lines
2.4 KiB
TypeScript
100 lines
2.4 KiB
TypeScript
import Keycloak from 'keycloak-js';
|
|
|
|
const options = {
|
|
url: import.meta.env.VITE_KEYCLOAK_URL,
|
|
clientId: import.meta.env.VITE_KEYCLOAK_CLIENT_ID,
|
|
realm: import.meta.env.VITE_KEYCLOAK_REALM
|
|
}
|
|
|
|
|
|
const keycloak = new Keycloak(options);
|
|
let authenticated: boolean | undefined;
|
|
let store = null;
|
|
|
|
async function login(){
|
|
try {
|
|
await keycloak.login() // https://www.keycloak.org/securing-apps/javascript-adapter#:~:text=when%20initialization%20completes.-,login(options),-Redirects%20to%20login
|
|
return keycloak;
|
|
} catch (error) {
|
|
console.log(error)
|
|
}
|
|
}
|
|
|
|
async function signup(){
|
|
try {
|
|
await keycloak.login(
|
|
{action: "register"}
|
|
) // https://www.keycloak.org/securing-apps/javascript-adapter#:~:text=when%20initialization%20completes.-,login(options),-Redirects%20to%20login
|
|
return keycloak;
|
|
} catch (error) {
|
|
console.log(error)
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Initializes Keycloak, then run callback. This will prompt you to login.
|
|
*
|
|
* @param onInitCallback
|
|
*/
|
|
async function init(onInitCallback: () => void) {
|
|
try {
|
|
authenticated = await keycloak.init({
|
|
onLoad: "check-sso",
|
|
silentCheckSsoRedirectUri: `${location.origin}/silent-check-sso.htm`,
|
|
responseMode: "query",
|
|
})
|
|
onInitCallback()
|
|
} catch (error) {
|
|
console.error("Keycloak init failed")
|
|
console.error(error)
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Initializes store with Keycloak user data
|
|
*
|
|
*/
|
|
async function initStore(storeInstance: any) {
|
|
try {
|
|
store = storeInstance
|
|
console.log(keycloak)
|
|
await store.initOauth(keycloak)
|
|
|
|
// Show alert if user is not authenticated
|
|
if (!authenticated) { console.warn("not authenticated") }
|
|
} catch (error) {
|
|
console.error("Keycloak init failed")
|
|
console.error(error)
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Logout user
|
|
*/
|
|
function logout(url: string) {
|
|
keycloak.logout({ redirectUri: url });
|
|
}
|
|
|
|
/**
|
|
* Refreshes token
|
|
*/
|
|
async function refreshToken() {
|
|
try {
|
|
await keycloak.updateToken(480);
|
|
return keycloak;
|
|
} catch (error) {
|
|
console.error('Failed to refresh token');
|
|
console.error(error);
|
|
}
|
|
}
|
|
|
|
const KeycloakService = {
|
|
CallInit: init,
|
|
CallInitStore: initStore,
|
|
CallLogout: logout,
|
|
CallTokenRefresh: refreshToken,
|
|
callLogin: login,
|
|
callSignup: signup,
|
|
};
|
|
|
|
export default KeycloakService; |