Source

auth/AdmAuth.js

"use strict"

/**
 *	----------------------------------------------------------------------------------------------
 *	Imports
 * 	----------------------------------------------------------------------------------------------
 */
 import {eventBus} from '../event/AdmEventBus';

/**
 *	----------------------------------------------------------------------------------------------
 *	Class AdmAuth - Authentification Module
 * 	----------------------------------------------------------------------------------------------
 */
 class AdmAuth {

    /**
     * Create an adamantium authentification instance.
     */
	constructor(options = {}){
        this.token = window.localStorage.getItem('authtoken');
        this.data = null;
        this.loggedIn = false;

        this.api = options.api || null;
        this.onLogout = options.onLogout || null;
	}
			
    /**
     * Get API access 
     * @return {object} auth data
     */
    async getAccess(){
        if(!this.api?.access){
            return console.log("Error: No auth api call defined");
        }
        const result = await this.api.access(this.token);
        this.setAuth(result.authtoken, result.user);
    }

    /**
     * Get auth data.
     * @return {object} auth data
     */
    getAuth(){
        return {
            token: this.token, 
            data: this.data, 
            loggedIn: this.loggedIn
        };
    }

    /**
     * Set auth data.
     * @param {string} token authentification token
     * @param {object} data authentification data
     */
    setAuth(token = null, data = null){
        this.token = token;
        this.data = data;
        
        window.localStorage.setItem('authtoken', this.token);
        if(token){
            this.loggedIn = true;
            eventBus.dispatchEvent("authSuccess");
        }else{
            this.loggedIn = false;
            eventBus.dispatchEvent("authFailed");
        }
    }

    /**
     * Funtion for logging out.
     */
    logout(){
        this.setAuth();
        if(this.onLogout){
            this.onLogout();
        }else{
            top.location = "";
        }
    }
}

export { AdmAuth };