UNPKG

@mytmpvpn/mytmpvpn-client

Version:

MyTmpVpn Client Library

93 lines (92 loc) 3.46 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.AuthImpl = void 0; // src/auth.ts const auth = require("amazon-cognito-identity-js"); const clientLib = require("./client"); const errors_1 = require("@mytmpvpn/mytmpvpn-common/errors"); const log = require("loglevel"); class AuthImpl { constructor(appConfig, userProfile) { this.session = null; this.userPool = new auth.CognitoUserPool({ UserPoolId: appConfig.userPoolId, ClientId: appConfig.userPoolClientId, }); this.userProfile = userProfile; this.cognitoUser = new auth.CognitoUser({ Username: this.userProfile.username, Pool: this.userPool }); this.client = new clientLib.MyTmpVpnClientImpl(appConfig.apiUrl); } async login() { return new Promise((resolve, reject) => { const authenticationDetails = new auth.AuthenticationDetails({ Username: this.userProfile.username, Password: this.userProfile.password }); this.cognitoUser.authenticateUser(authenticationDetails, { onSuccess: session => resolve(session), onFailure: err => reject(err) }); }); } async authenticate() { log.debug(`Authenticating user ${JSON.stringify(this.userProfile)}`); // Try to get existing session try { this.session = await new Promise((resolve, reject) => { this.cognitoUser.getSession((err, session) => { if (err) reject(err); else resolve(session); }); }); } catch (err) { // No session found, let's login if (!this.userProfile.password) { throw new errors_1.MyTmpVpnError(`Specify a password in profile ${JSON.stringify(this.userProfile)}`); } log.debug(`Session not found for user ${JSON.stringify(this.cognitoUser)}, logging in`); this.session = await this.login(); } log.debug(`Setting user session ${JSON.stringify(this.session)} to client: ${JSON.stringify(this.client)}`); this.client.setUserSession(this.cognitoUser, this.session); // Validate session if (!this.getUser() || !this.getSession()) { throw new errors_1.MyTmpVpnError(`No session found in client: ${JSON.stringify(this.client)}`); } return this.client; } async register() { return new Promise((resolve, reject) => { const userAttributes = []; const validationData = []; this.userPool.signUp(this.userProfile.username, this.userProfile.password ?? '', userAttributes, validationData, (err, result) => { if (err) reject(err); else resolve(result.user); }); }); } async confirmRegistration(code) { return new Promise((resolve, reject) => { this.cognitoUser.confirmRegistration(code, true, (err, result) => { if (err) reject(err); resolve(result); }); }); } getUser() { return this.cognitoUser; } getSession() { return this.session; } } exports.AuthImpl = AuthImpl;