"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const auth0_js_1 = __importDefault(require("auth0-js"));
const config_1 = __importDefault(require("@botsbotsbots/common/config"));
const token_1 = __importDefault(require("@botsbotsbots/common/auth/token"));
const ID_TOKEN_KEY = 'id_token';
const ACCESS_TOKEN_KEY = 'access_token';
const CLIENT_ID = config_1.default.auth.clientId;
const CLIENT_DOMAIN = config_1.default.auth.domain;
const REDIRECT = 'http://localhost:5000/callback';
const SCOPE = 'openid profile read:graphql';
const AUDIENCE = config_1.default.auth.clientId;
var auth = new auth0_js_1.default.WebAuth({
    clientID: CLIENT_ID,
    domain: CLIENT_DOMAIN
});
function login() {
    auth.authorize({
        connection: 'slack',
        responseType: 'token id_token',
        redirectUri: REDIRECT,
        audience: `https://${CLIENT_DOMAIN}/userinfo`,
        scope: SCOPE
    });
}
exports.login = login;
function logout() {
    clearIdToken();
    clearAccessToken();
    clearProfile();
    window.history.pushState('/');
}
exports.logout = logout;
function requireAuth(nextState, replace) {
    if (!isLoggedIn()) {
        replace({ pathname: '/' });
    }
}
exports.requireAuth = requireAuth;
function getIdToken() {
    return localStorage.getItem(ID_TOKEN_KEY);
}
exports.getIdToken = getIdToken;
function getAccessToken() {
    return localStorage.getItem(ACCESS_TOKEN_KEY);
}
exports.getAccessToken = getAccessToken;
function clearIdToken() {
    localStorage.removeItem(ID_TOKEN_KEY);
}
function clearAccessToken() {
    localStorage.removeItem(ACCESS_TOKEN_KEY);
}
function clearProfile() {
    localStorage.removeItem('profile');
}
// Helper function that will allow us to extract the access_token and id_token
function getAndStoreParameters() {
    auth.parseHash(window.location.hash, function (err, authResult) {
        if (err) {
            return console.log(err);
        }
        setIdToken(authResult.idToken);
        setAccessToken(authResult.accessToken);
    });
}
exports.getAndStoreParameters = getAndStoreParameters;
function getEmail() {
    return getProfile().email;
}
exports.getEmail = getEmail;
function getName() {
    return getProfile().nickname;
}
exports.getName = getName;
// Get and store access_token in local storage
function setAccessToken(accessToken) {
    localStorage.setItem(ACCESS_TOKEN_KEY, accessToken);
}
exports.setAccessToken = setAccessToken;
// Get and store id_token in local storage
function setIdToken(idToken) {
    localStorage.setItem(ID_TOKEN_KEY, idToken);
}
function isLoggedIn() {
    const idToken = getIdToken();
    return !!idToken && !isTokenExpired(idToken);
}
exports.isLoggedIn = isLoggedIn;
function getProfile() {
    const tokenString = getIdToken();
    if (!tokenString) {
        return Object.create(null);
    }
    const token = new token_1.default(tokenString);
    return token.safeDecode || Object.create(null);
}
exports.getProfile = getProfile;
function getUser() {
    return new Promise((resolve, reject) => {
        const accessToken = getAccessToken();
        if (!accessToken) {
            return reject(new Error('No access token'));
        }
        auth0_js_1.default.client.userInfo(getAccessToken(), (err, user) => (err ? reject(err) : resolve(user)));
    });
}
exports.getUser = getUser;
function getTokenExpirationDate(encodedToken) {
    const token = new token_1.default(encodedToken).payload;
    if (!token.exp) {
        return 1;
    }
    const date = new Date(0);
    date.setUTCSeconds(token.exp);
    return date;
}
function isTokenExpired(token) {
    const expirationDate = getTokenExpirationDate(token);
    return expirationDate < new Date();
}
// }
// export default class Auth {
// 	auth0: any;
// 	userInfo = null;
// 	constructor({ domain, clientId, callbackUrl }) {
// 		this.login = this.login.bind(this);
// 		this.logout = this.logout.bind(this);
// 		this.handleAuthentication = this.handleAuthentication.bind(this);
// 		this.isAuthenticated = this.isAuthenticated.bind(this);
// 		this.auth0 = new auth0.WebAuth({
// 			domain,
// 			clientID: clientId,
// 			redirectUri: callbackUrl,
// 			audience: `https://${domain}/userinfo`,
// 			responseType: 'token id_token'
// 		});
// 	}
// 	login() {
// 		this.auth0.authorize({ connection: 'slack', scope: 'openid profile read:graphql' });
// 	}
// 	handleAuthentication() {
// 		this.auth0.parseHash((err, authResult) => {
// 			if (authResult && authResult.accessToken && authResult.idToken) {
// 				this.setSession(authResult);
// 			} else if (err) {
// 				console.log(err);
// 				alert(`Error: ${err.error}. Check the console for further details.`);
// 			}
// 		});
// 	}
// 	get access_token() {
// 		return localStorage.getItem('access_token') || null;
// 	}
// 	get id_token() {
// 		return localStorage.getItem('id_token') || null;
// 	}
// 	setSession(authResult) {
// 		console.log(authResult);
// 		// Set the time that the access token will expire at
// 		let expiresAt = JSON.stringify(authResult.expiresIn * 1000 + new Date().getTime());
// 		this.auth0.client.userInfo(authResult.accessToken, function(err, user) {
// 			if (err) {
// 				console.error(err);
// 				return;
// 			}
// 			localStorage.setItem('access_token', authResult.accessToken);
// 			localStorage.setItem('id_token', authResult.idToken);
// 			localStorage.setItem('expires_at', expiresAt);
// 			// Now you have the user's information
// 			localStorage.setItem('user_info', JSON.stringify(user));
// 		});
// 	}
// 	currentUser() {
// 		if (this.isAuthenticated()) {
// 			const user = localStorage.getItem('user_info');
// 			if (!user) {
// 				throw new Error('Missing user info');
// 			}
// 			return JSON.parse(user);
// 		} else {
// 			return null;
// 		}
// 	}
// 	logout() {
// 		// Clear access token and ID token from local storage
// 		localStorage.removeItem('access_token');
// 		localStorage.removeItem('id_token');
// 		localStorage.removeItem('user_info');
// 		localStorage.removeItem('expires_at');
// 		// navigate to the home route
// 	}
// 	isAuthenticated() {
// 		// Check whether the current time is past the
// 		// access token's expiry time
// 		let expiresAt = JSON.parse(localStorage.getItem('expires_at') || '1');
// 		return new Date().getTime() < expiresAt;
// 	}
// }
//# sourceMappingURL=auth.js.map