// vue 2 version import Router from 'vue-router' import Vue from 'vue' import { UserManagerSettings, Log, User, UserManager, UserProfile, WebStorageStateStore, UserManagerEvents } from 'oidc-client-ts'
/** * Indicates the sign in behavior. */ export enum SignInType { /** * Uses the main browser window to do sign-in. */ Window, /** * Uses a popup window to do sign-in. */ Popup }
/** * Logging level values used by createOidcAuth(). */ export enum LogLevel { /** * No logs messages. */ None = 0, /** * Only error messages. */ Error = 1, /** * Error and warning messages. */ Warn = 2, /** * Error, warning, and info messages. */ Info = 3, /** * Everything. */ Debug = 4 }
/** * Creates an openid-connect auth instance. * @param authName - short alpha-numeric name that identifies the auth instance for routing purposes. * This is used to generate default redirect urls (slugified) and identifying routes that needs auth. * @param defaultSignInType - the signin behavior when `signIn()` and `signOut()` are called. * @param appUrl - url to the app using this instance for routing purposes. Something like `https://domain/app/`. * @param oidcConfig - config object for oidc-client. * See https://github.com/IdentityModel/oidc-client-js/wiki#configuration for details. * @param logger - logger used by oidc-client. Defaults to console. * @param logLevel - minimum level to log. Defaults to LogLevel.Error. */ export function createOidcAuth( authName: string, defaultSignInType: SignInType, appUrl: string, oidcConfig: UserManagerSettings, ) { // arg check if (!authName) { throw new Error('Auth name is required.') } if ( defaultSignInType !== SignInType.Window && defaultSignInType !== SignInType.Popup ) { throw new Error('Only window or popup are valid default signin types.') } if (!appUrl) { throw new Error('App base url is required.') } if (!oidcConfig) { throw new Error('No config provided to oidc auth.') }
const nameSlug = slugify(authName)
// merge passed oidcConfig with defaults const config = { automaticSilentRenew: true, userStore: new WebStorageStateStore({ store: sessionStorage }), ...oidcConfig // everything can be overridden! }
function signInIfNecessary() { if (auth.myRouter) { const current = auth.myRouter.currentRoute if (current && current.meta.authName === authName) { signInReal(defaultSignInType, { state: { current } }) .then(() => { // auth.myRouter() }) .catch(() => { setTimeout(signInIfNecessary, 5000) }) // window.location.reload(); // auth.myRouter.go(); //replace('/'); } } }
function signInReal(type: SignInType, args?: any) { switch (type) { case SignInType.Popup: return mgr.signinPopup(args) // case SignInType.Silent: // return mgr.signinSilent(args) } return mgr.signinRedirect(args) }
function redirectAfterSignout(router: Router | null) { if (router) { const current = router.currentRoute if (current && current.meta.authName === authName) { router.replace('/') return } } // window.location.reload(true); if (appUrl) window.location.href = appUrl }
/** * Translates user manager events to vue events and perform default actions * if necessary. */ function handleManagerEvents() { mgr.events.addUserLoaded(user => { auth.user = user })
/** * Gets the path portion of a url. * @param url - full url * @returns */ function getUrlPath(url: string) { const a = document.createElement('a') a.href = url let p = a.pathname if (p[0] !== '/') p = '/' + p return p }
/** * Checks if current url's path matches given url's path. * @param {String} testUrl - url to test against. */ function matchesPath(testUrl: string) { return ( window.location.pathname.toLocaleLowerCase() === getUrlPath(testUrl).toLocaleLowerCase() ) }
function slugify(str: string) { str = str.replace(/^\s+|\s+$/g, '') // trim str = str.toLowerCase()
// remove accents, swap ñ for n, etc const from = 'ãàáäâẽèéëêìíïîõòóöôùúüûñç·/_,:;' const to = 'aaaaaeeeeeiiiiooooouuuunc------' for (let i = 0, l = from.length; i < l; i++) { str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i)) }