@toruslabs/customauth
Version:
CustomAuth login with torus to get user private key
102 lines (98 loc) • 3.27 kB
JavaScript
'use strict';
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var httpHelpers = require('@toruslabs/http-helpers');
var deepmerge = require('deepmerge');
var log = require('loglevel');
var helpers = require('../utils/helpers.js');
var AbstractLoginHandler = require('./AbstractLoginHandler.js');
class JwtHandler extends AbstractLoginHandler {
constructor(params) {
super(params);
_defineProperty(this, "SCOPE", "openid profile email");
_defineProperty(this, "RESPONSE_TYPE", "token id_token");
_defineProperty(this, "PROMPT", "login");
this.setFinalUrl();
}
setFinalUrl() {
const {
domain
} = this.params.jwtParams;
const finalUrl = helpers.validateAndConstructUrl(domain);
finalUrl.pathname += finalUrl.pathname.endsWith("/") ? "authorize" : "/authorize";
const clonedParams = JSON.parse(JSON.stringify(this.params.jwtParams));
delete clonedParams.domain;
const finalJwtParams = deepmerge({
state: this.state,
response_type: this.RESPONSE_TYPE,
client_id: this.params.clientId,
prompt: this.PROMPT,
redirect_uri: this.params.redirect_uri,
scope: this.SCOPE,
connection: helpers.loginToConnectionMap[this.params.authConnection],
nonce: this.nonce
}, clonedParams);
Object.keys(finalJwtParams).forEach(key => {
const localKey = key;
if (finalJwtParams[localKey]) finalUrl.searchParams.append(localKey, finalJwtParams[localKey]);
});
this.finalURL = finalUrl;
}
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");
}
}
module.exports = JwtHandler;