import Keycloak from 'keycloak-js' ; import environment from '../../../environment' ; import AuthScope from '../api/authScope' ; export const dcatdScopes = [ AuthScope . CatR , AuthScope . CatW , ] ; const keycloak = Keycloak ( { url : environment . KEYCLOAK_URL , realm : environment . KEYCLOAK_REALM , clientId : environment . KEYCLOAK_CLIENT , } ) ; const MIN_VALIDITY = 5 ; keycloak . onTokenExpired = async ( ) => { try { await keycloak . updateToken ( MIN_VALIDITY ) ; } catch ( error ) { } } ; export function getAccessToken ( ) { return keycloak . token ?? '' ; } export function login ( ) { keycloak . login ( ) ; } export function logout ( ) { keycloak . logout ( ) ; } export async function initKeycloak ( ) { const authenticated = await keycloak . init ( { checkLoginIframe : false , pkceMethod : 'S256' , onLoad : 'check-sso' , silentCheckSsoRedirectUri : `${ window . location . origin }/silent-check-sso.html` , } ) ; if ( authenticated ) { await keycloak . loadUserInfo ( ) ; } return authenticated ; } export function getReturnPath ( ) { return '' ; } export function getScopes ( ) { const realmRoles = keycloak . realmAccess ?. roles ?? [ ] ; const resourceRoles = Object . values ( keycloak . resourceAccess ?? { } ) . flatMap ( ( resource ) => resource . roles ) ; return [ ... realmRoles , ... resourceRoles ] . map ( ( role ) => role . toUpperCase ( ) . replace ( '_' , '/' ) ) as AuthScope [ ] ; } export function getName ( ) { if ( ! keycloak . userInfo ) { return '' ; } const { preferred_username , given_name } = keycloak . userInfo as any ; if ( typeof preferred_username === 'string' ) { return preferred_username ; } if ( typeof given_name === 'string' ) { return given_name ; } return '' ; } export const getAuthHeaders = ( ) => { if ( ! isAuthenticated ( ) || ! keycloak . token ) { return { } ; } return { Authorization : `Bearer ${ getAccessToken ( ) }` } ; } ; export function isAuthenticated ( ) { try { if ( keycloak . isTokenExpired ( ) ) { return false ; } } catch ( error ) { return false ; } return keycloak . authenticated ?? false ; }