UNPKG

@toruslabs/customauth

Version:

CustomAuth login with torus to get user private key

110 lines (106 loc) 3.18 kB
'use strict'; var httpHelpers = require('@toruslabs/http-helpers'); var deepmerge = require('deepmerge'); var log = require('loglevel'); var enums = require('../utils/enums.js'); var helpers = require('../utils/helpers.js'); var PopupHandler = require('../utils/PopupHandler.js'); var AbstractLoginHandler = require('./AbstractLoginHandler.js'); class MockLoginHandler extends AbstractLoginHandler { constructor(params) { super(params); this.setFinalUrl(); } setFinalUrl() { const clonedParams = JSON.parse(JSON.stringify(this.params.jwtParams)); delete clonedParams.domain; const finalJwtParams = deepmerge({ state: this.state, client_id: this.params.clientId, nonce: this.nonce }, clonedParams); this.finalURL = new URL(helpers.constructURL({ baseURL: this.params.redirect_uri, query: null, hash: finalJwtParams })); } async getUserInfo(params) { const { idToken, accessToken } = params; const { domain, userIdField, isUserIdCaseSensitive, user_info_route = "userinfo" } = this.params.jwtParams; if (idToken) { const decodedToken = helpers.decodeToken(idToken).payload; const { name, email, picture } = decodedToken; return { profileImage: picture, name, email, userId: helpers.getUserId(decodedToken, this.params.authConnection, userIdField, isUserIdCaseSensitive), authConnectionId: this.params.authConnectionId, authConnection: this.params.authConnection, groupedAuthConnectionId: this.params.groupedAuthConnectionId }; } if (accessToken) { try { const domainUrl = new URL(domain); const userInfo = await httpHelpers.get(`${helpers.padUrlString(domainUrl)}${user_info_route}`, { headers: { Authorization: `Bearer ${accessToken}` } }); const { picture, name, email } = userInfo; return { email, name, profileImage: picture, userId: helpers.getUserId(userInfo, this.params.authConnection, userIdField, isUserIdCaseSensitive), authConnectionId: this.params.authConnectionId, authConnection: this.params.authConnection, groupedAuthConnectionId: this.params.groupedAuthConnectionId }; } catch (error) { // ignore log.warn(error, "Unable to get userinfo from endpoint"); } } throw new Error("Access/id token not available"); } handleLoginWindow(params) { const { id_token: idToken, access_token: accessToken } = this.params.jwtParams; const authConnectionWindow = new PopupHandler.PopupHandler({ url: this.finalURL, features: params.popupFeatures }); if (this.params.uxMode === enums.UX_MODE.REDIRECT) { authConnectionWindow.redirect(params.locationReplaceOnRedirect); } else { return Promise.resolve({ state: {}, idToken, accessToken }); } return null; } } module.exports = MockLoginHandler;