1 line
46 KiB
Plaintext
1 line
46 KiB
Plaintext
{"version":3,"sources":["User.js"],"names":["async","let","dfd","Deferred","server","http","createServer","req","res","method","url","body","on","data","resolve","qs","parse","writeHead","end","err","socket","connections","conn","key","remoteAddress","remotePort","destroy","cb","close","port","await","freeportAsync","listen","callbackURL","getTokenInfoAsync","promise","_startLoginServerAsync","AUTH0_DOMAIN","AUTHENTICATION_SERVER_TIMEOUT","UserManagerInstance","clientID","loginServer","refreshSessionThreshold","_currentUser","_getSessionLock","static","getGlobalInstance","__globalInstance","initialize","loginAsync","loginType","loginArgs","loginOptions","Error","connection","responseType","sso","username","password","scope","responseMode","device","auth0Options","loginResp","_auth0LoginAsync","_getProfileAsync","currentConnection","accessToken","access_token","refreshToken","refresh_token","idToken","id_token","refreshTokenClientId","destroyServerTimer","setTimeout","listening","tokenInfo","clearTimeout","profile","registerAsync","userData","user","getCurrentUserAsync","kind","userMetadata","onboarded","logoutAsync","shouldUpdateUsernamePassword","currentUser","shouldLinkAccount","registeredUser","createOrUpdateUserAsync","email","givenName","familyName","emailVerified","forceCreate","linkedAccountId","userId","linkedAccountConnection","loginsCount","e","ErrorCode","REGISTRATION_ERROR","message","ensureLoggedInAsync","options","noTrackError","Config","offline","getLegacyUserData","LEGACY_ACCOUNT_ERROR","noTrack","NOT_LOGGED_IN","acquire","_isTokenExpired","UserSettings","getAsync","Logger","global","error","release","legacyUsername","legacy","needsPasswordMigration","api","ApiV2Client","clientForUser","updatedUser","postAsync","_prepareAuth0Profile","_parseAuth0Profile","code","details","Analytics","logEvent","deleteKeyAsync","Intercom","update","forgotPasswordAsync","usernameOrEmail","_auth0ForgotPasswordAsync","dtoken","jwt","decode","complete","aud","payload","currentRefreshTokenClientId","process","env","NODE_ENV","debug","delegationResult","_auth0RefreshToken","_auth0GetProfileAsync","mergeAsync","auth","setUserProperties","intercomUserHash","exp","Date","now","window","Auth0JS","_auth0JSInstanceWithOptions","resp","Auth0Node","_nodeAuth0InstanceWithOptions","oauth","signIn","_formatAuth0NodeError","opn","_buildAuth0SocialLoginUrl","wait","getProfileAsync","tokens","getInfo","clientId","delegationTokenOptions","api_type","target","client_id","getDelegationTokenAsync","getDelegationToken","grant_type","changePasswordAsync","database","changePassword","errData","INVALID_USERNAME_PASSWORD","TOO_MANY_ATTEMPTS","error_description","qsData","response_type","response_mode","redirect_uri","queryString","stringify","Auth0","require","domain","Auth0Instance","Bluebird","promisifyAll","management","_","omit","ManagementClient","AuthenticationClient","rawProfile","Object","keys","reduce","p","camelCase","niceProfile","snakeCase","constructor","Promise","reject"],"mappings":";;;;;;;;;;+BA21BAA,aAIG;AACDC,QAAIC,MAAM,IAAIC,QAAJ,EAAVF;;AAEA,UAAMG,SAA8BC,cAAKC,YAALD,CAAkB,UAACE,GAAD,EAAMC,GAAN,EAAc;AAClE,UAAID,IAAIE,MAAJF,KAAe,MAAfA,IAAyBA,IAAIG,GAAJH,KAAY,WAAzC,EAAsD;AACpDN,YAAIU,OAAO,EAAXV;AACAM,YAAIK,EAAJL,CAAO,MAAPA,EAAe,UAASM,IAAT,EAAe;AAC5BF,kBAAQE,IAARF;AACD,SAFDJ;AAGAA,YAAIK,EAAJL,CAAO,KAAPA,EAAc,YAAW;AACvBL,cAAIY,OAAJZ,CAAYa,qBAAGC,KAAHD,CAASJ,IAATI,CAAZb;AACAM,cAAIS,SAAJT,CAAc,GAAdA,EAAmB,EAAE,gBAAgB,WAAlB,EAAnBA;AACAA,cAAIU,GAAJV,CACG;;;;;;;;;;;SADHA;AAcD,SAjBDD;AAkBF,OAvBA,MAuBO;AACLC,YAAIS,SAAJT,CAAc,GAAdA,EAAmB,EAAE,gBAAgB,WAAlB,EAAnBA;AACAA,YAAIU,GAAJV,CACG;;;;;OADHA;AAQF;AACD,KAnCmCH,CAApC;;AAqCAD,WAAOQ,EAAPR,CAAU,aAAVA,EAAyB,UAACe,GAAD,EAAMC,MAAN,EAAiB;AACxC;AACAA,aAAOF,GAAPE,CAAW,kCAAXA;AACD,KAHDhB;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IhM,GAAJ,KAAY;AAClDgM,MAAER,oCAAES,SAAFT,CAAYxL,GAAZwL,CAAFQ,IAAsBnF,mBAAmB+E,WAAW5L,GAAX4L,CAAnB/E,CAAtBmF;AACA,WAAOA,CAAP;AACD,GAHQH,EAGN,EAHMA,CAAT;AAIF;;AAEA,SAASjF,oBAAT,CAA8BsF,WAA9B,EAAwD;AACtD,MAAI,OAAOA,WAAP,KAAuB,QAA3B,EAAqC;AACnC,WAAOA,WAAP;AACF;;AAEA,SAASL,OAAOC,IAAPD,CAAYK,WAAZL,EAAyBE,MAAzBF,CAAgC,CAACG,CAAD,EAAIhM,GAAJ,KAAY;AACnDgM,MAAER,oCAAEW,SAAFX,CAAYxL,GAAZwL,CAAFQ,IAAsBpF,qBAAqBsF,YAAYlM,GAAZkM,CAArBtF,CAAtBoF;AACA,WAAOA,CAAP;AACD,GAHQH,EAGN,EAHMA,CAAT;AAIF;;AAQA,MAAMjN,QAAN,CAAkB;;AAKhBwN,gBAAc;AACZ,SAAKxL,OAAL,GAAe,IAAIyL,OAAJ,CAAY,CAAC9M,OAAD,EAAU+M,MAAV,KAAqB;AAC9C,WAAKA,MAAL,GAAcA,MAAd;AACA,WAAK/M,OAAL,GAAeA,OAAf;AACD,KAHc,CAAf;AAIF;AAVgB","file":"../User.js","sourcesContent":["/**\n * @flow\n */\n\nimport _ from 'lodash';\nimport Bluebird from 'bluebird';\nimport freeportAsync from 'freeport-async';\nimport http from 'http';\nimport qs from 'querystring';\nimport opn from 'opn';\nimport jwt from 'jsonwebtoken';\n\nimport type Auth0JS from 'auth0-js';\nimport type Auth0Node from 'auth0';\n\nimport ApiV2Client, { ApiV2Error } from './ApiV2';\n\nimport * as Analytics from './Analytics';\nimport Config from './Config';\nimport ErrorCode from './ErrorCode';\nimport XDLError from './XDLError';\nimport Logger from './Logger';\n\nimport * as Intercom from './Intercom';\nimport UserSettings from './UserSettings';\n\nimport { Semaphore } from './Utils';\n\nexport type User = {\n kind: 'user',\n // required\n name: string,\n username: string,\n nickname: string,\n userId: string,\n picture: string,\n // optional\n email?: string,\n emailVerified?: boolean,\n givenName?: string,\n familyName?: string,\n loginsCount?: number,\n intercomUserHash: string,\n userMetadata: {\n onboarded: boolean,\n legacy?: boolean,\n },\n identities: Array<{\n connection: ConnectionType,\n isSocial: boolean,\n provider: string,\n userId: string,\n }>,\n accessToken: string,\n idToken: string,\n refreshToken: string,\n currentConnection: ConnectionType,\n};\n\nexport type LegacyUser = {\n kind: 'legacyUser',\n username: string,\n userMetadata: {\n legacy: boolean,\n needsPasswordMigration: boolean,\n },\n};\n\nexport type UserOrLegacyUser = User | LegacyUser;\n\ntype ConnectionType = 'Username-Password-Authentication' | 'facebook' | 'google-oauth2' | 'github';\n\ntype LoginOptions = {\n connection: ConnectionType,\n device: string,\n responseType: string,\n responseMode: string,\n};\n\nexport type RegistrationData = {\n username: string,\n password: string,\n email?: string,\n givenName?: string,\n familyName?: string,\n};\n\ntype Auth0Options = {\n clientID: string,\n callbackURL?: string,\n};\n\nexport type LoginType = 'user-pass' | 'facebook' | 'google' | 'github';\n\nconst AUTH0_DOMAIN = 'exponent.auth0.com';\nconst AUTHENTICATION_SERVER_TIMEOUT = 1000 * 60 * 5; // 5 minutes\n\nexport class UserManagerInstance {\n clientID = 'o0YygTgKhOTdoWj10Yl9nY2P0SMTw38Y'; // Default Client ID\n loginServer = null;\n refreshSessionThreshold = 60 * 60; // 1 hour\n _currentUser: ?User = null;\n _getSessionLock = new Semaphore();\n\n static getGlobalInstance() {\n if (!__globalInstance) {\n __globalInstance = new UserManagerInstance();\n }\n return __globalInstance;\n }\n\n initialize(clientID: ?string) {\n if (clientID) {\n this.clientID = clientID;\n }\n this.loginServer = null;\n this._currentUser = null;\n this._getSessionLock = new Semaphore();\n }\n\n /**\n * Logs in a user for a given login type.\n *\n * Valid login types are:\n * - \"user-pass\": Username and password authentication\n * - \"facebook\": Facebook authentication\n * - \"google\": Google authentication\n * - \"github\": Github authentication\n *\n * If the login type is \"user-pass\", we directly make the request to Auth0\n * to login a user.\n *\n * If the login type is any of the social providers, we start a web server\n * that can act as the receiver of the OAuth callback from the authentication\n * process. The response we receive on that web server will be token data.\n */\n async loginAsync(\n loginType: LoginType,\n loginArgs?: { username: string, password: string }\n ): Promise<User> {\n let loginOptions;\n\n if (loginType === 'user-pass') {\n if (!loginArgs) {\n throw new Error(`The 'user-pass' login type requires a username and password.`);\n }\n loginOptions = {\n connection: 'Username-Password-Authentication',\n responseType: 'token',\n sso: false,\n username: loginArgs.username,\n password: loginArgs.password,\n };\n } else if (loginType === 'facebook') {\n loginOptions = {\n connection: 'facebook',\n };\n } else if (loginType === 'google') {\n loginOptions = {\n connection: 'google-oauth2',\n };\n } else if (loginType === 'github') {\n loginOptions = {\n connection: 'github',\n };\n } else {\n throw new Error(\n `Invalid login type provided. Must be one of 'user-pass', 'facebook', 'google', or 'github'.`\n );\n }\n\n loginOptions = {\n ...loginOptions,\n scope: 'openid offline_access username nickname',\n // audience: 'https://exp.host',\n responseMode: 'form_post',\n responseType: 'token',\n device: 'xdl',\n };\n\n let auth0Options = {\n clientID: this.clientID,\n };\n\n if (loginType === 'user-pass') {\n try {\n const loginResp = await this._auth0LoginAsync(auth0Options, loginOptions);\n return await this._getProfileAsync({\n currentConnection: loginOptions.connection,\n accessToken: loginResp.access_token,\n refreshToken: loginResp.refresh_token,\n idToken: loginResp.id_token,\n refreshTokenClientId: this.clientID,\n });\n } catch (err) {\n throw err;\n }\n }\n\n // Doing a social login, so start a server\n const { server, callbackURL, getTokenInfoAsync } = await _startLoginServerAsync();\n\n // Kill server after 5 minutes if it hasn't already been closed\n const destroyServerTimer = setTimeout(() => {\n if (server.listening) {\n server.destroy();\n }\n }, AUTHENTICATION_SERVER_TIMEOUT);\n\n auth0Options = {\n clientID: this.clientID,\n callbackURL,\n };\n\n // Don't await -- we'll get response back through server\n // This will open a browser window\n this._auth0LoginAsync(auth0Options, loginOptions);\n\n // Wait for token info to come back from server\n const tokenInfo = await getTokenInfoAsync();\n\n server.destroy();\n clearTimeout(destroyServerTimer);\n\n const profile = await this._getProfileAsync({\n currentConnection: loginOptions.connection,\n accessToken: tokenInfo.access_token,\n refreshToken: tokenInfo.refresh_token,\n idToken: tokenInfo.id_token,\n refreshTokenClientId: this.clientID,\n });\n\n return profile;\n }\n\n async registerAsync(userData: RegistrationData, user: ?UserOrLegacyUser): Promise<User> {\n if (!user) {\n user = await this.getCurrentUserAsync();\n }\n\n if (user && user.kind === 'user' && user.userMetadata && user.userMetadata.onboarded) {\n await this.logoutAsync();\n user = null;\n }\n\n let shouldUpdateUsernamePassword = true;\n if (user && user.kind === 'legacyUser') {\n // we're upgrading from an older client,\n // so login with username/pass\n if (userData.username && userData.password) {\n user = await this.loginAsync('user-pass', {\n username: userData.username,\n password: userData.password,\n });\n }\n shouldUpdateUsernamePassword = false;\n }\n\n const currentUser: ?User = (user: any);\n\n const shouldLinkAccount =\n currentUser && currentUser.currentConnection !== 'Username-Password-Authentication';\n\n try {\n // Create or update the profile\n let registeredUser = await this.createOrUpdateUserAsync({\n connection: 'Username-Password-Authentication', // Always create/update username password\n email: userData.email,\n userMetadata: {\n onboarded: true,\n givenName: userData.givenName,\n familyName: userData.familyName,\n },\n ...(shouldUpdateUsernamePassword ? { username: userData.username } : {}),\n ...(shouldLinkAccount ? { emailVerified: true } : {}),\n ...(shouldUpdateUsernamePassword ? { password: userData.password } : {}),\n ...(currentUser && shouldLinkAccount\n ? {\n forceCreate: true,\n linkedAccountId: currentUser.userId,\n linkedAccountConnection: currentUser.currentConnection,\n }\n : {}),\n });\n\n // if it's a new registration, or if they signed up with a social account,\n // we need to re-log them in with their username/pass. Otherwise, they're\n // already logged in.\n if (\n shouldLinkAccount ||\n (registeredUser &&\n (!registeredUser.loginsCount ||\n (registeredUser.loginsCount && registeredUser.loginsCount < 1)))\n ) {\n // this is a new registration, log them in\n registeredUser = await this.loginAsync('user-pass', {\n username: userData.username,\n password: userData.password,\n });\n }\n\n return registeredUser;\n } catch (e) {\n throw new XDLError(ErrorCode.REGISTRATION_ERROR, 'Error registering user: ' + e.message);\n }\n }\n\n /**\n * Ensure user is logged in and has a valid token.\n *\n * If there are any issues with the login, this method throws.\n */\n async ensureLoggedInAsync(\n options: { noTrackError: boolean } = { noTrackError: false }\n ): Promise<?User> {\n if (Config.offline) {\n return null;\n }\n\n const user = await this.getCurrentUserAsync();\n if (!user) {\n if (await this.getLegacyUserData()) {\n throw new XDLError(\n ErrorCode.LEGACY_ACCOUNT_ERROR,\n `We've updated our account system! Please login again by running \\`exp login\\`. Sorry for the inconvenience!`,\n { noTrack: options.noTrackError }\n );\n }\n throw new XDLError(ErrorCode.NOT_LOGGED_IN, 'Not logged in', {\n noTrack: options.noTrackError,\n });\n }\n return user;\n }\n\n /**\n * Get the current user based on the available token.\n * If there is no current token, returns null.\n */\n async getCurrentUserAsync(): Promise<?User> {\n await this._getSessionLock.acquire();\n\n try {\n // If user is cached and token isn't expired\n // return the user\n if (this._currentUser && !this._isTokenExpired(this._currentUser.idToken)) {\n return this._currentUser;\n }\n\n if (Config.offline) {\n return null;\n }\n\n // Not cached, check for token\n let { currentConnection, idToken, accessToken, refreshToken } = await UserSettings.getAsync(\n 'auth',\n {}\n );\n\n // No tokens, no current user. Need to login\n if (!currentConnection || !idToken || !accessToken || !refreshToken) {\n return null;\n }\n\n try {\n return await this._getProfileAsync({\n currentConnection,\n accessToken,\n idToken,\n refreshToken,\n });\n } catch (e) {\n Logger.global.error(e);\n // This logs us out if theres a fatal error when getting the profile with\n // current access token\n // However, this also logs us out if there is a network error\n await this.logoutAsync();\n return null;\n }\n } finally {\n this._getSessionLock.release();\n }\n }\n\n /**\n * Get legacy user data from UserSettings.\n */\n async getLegacyUserData(): Promise<?LegacyUser> {\n const legacyUsername = await UserSettings.getAsync('username', null);\n if (legacyUsername) {\n return {\n kind: 'legacyUser',\n username: legacyUsername,\n userMetadata: {\n legacy: true,\n needsPasswordMigration: true,\n },\n };\n }\n return null;\n }\n\n /**\n * Create or update a user.\n */\n async createOrUpdateUserAsync(userData: Object): Promise<User> {\n let currentUser = this._currentUser;\n if (!currentUser) {\n // attempt to get the current user\n currentUser = await this.getCurrentUserAsync();\n }\n\n try {\n const api = ApiV2Client.clientForUser(this._currentUser);\n\n const { user: updatedUser } = await api.postAsync('auth/createOrUpdateUser', {\n userData: _prepareAuth0Profile(userData),\n });\n\n this._currentUser = {\n ...(this._currentUser || {}),\n ..._parseAuth0Profile(updatedUser),\n };\n return {\n kind: 'user',\n ...this._currentUser,\n };\n } catch (e) {\n const err: ApiV2Error = (e: any);\n if (err.code === 'AUTHENTICATION_ERROR') {\n throw new Error(err.details.message);\n }\n throw e;\n }\n }\n\n /**\n * Logout\n */\n async logoutAsync(): Promise<void> {\n if (this._currentUser) {\n Analytics.logEvent('Logout', {\n username: this._currentUser.username,\n });\n }\n\n this._currentUser = null;\n\n // Delete saved JWT\n await UserSettings.deleteKeyAsync('auth');\n // Delete legacy auth\n await UserSettings.deleteKeyAsync('username');\n\n // Logout of Intercom\n Intercom.update(null);\n }\n\n /**\n * Forgot Password\n */\n async forgotPasswordAsync(usernameOrEmail: string): Promise<void> {\n return await this._auth0ForgotPasswordAsync(usernameOrEmail);\n }\n\n /**\n * Get profile given token data. Errors if token is not valid or if no\n * user profile is returned.\n *\n * This method is called by all public authentication methods of `UserManager`\n * except `logoutAsync`. Therefore, we use this method as a way to:\n * - update the UserSettings store with the current token and user id\n * - update UserManager._currentUser\n * - Fire login analytics events\n * - Update the currently assigned Intercom user\n *\n * Also updates UserManager._currentUser.\n *\n * @private\n */\n async _getProfileAsync({\n currentConnection,\n accessToken,\n idToken,\n refreshToken,\n refreshTokenClientId,\n }: {\n currentConnection: ConnectionType,\n accessToken: string,\n idToken: string,\n refreshToken: string,\n refreshTokenClientId?: string,\n }): Promise<User> {\n // Attempt to grab profile from Auth0.\n // If token is expired / getting the profile fails, use refresh token to\n let user;\n try {\n const dtoken = jwt.decode(idToken, { complete: true });\n const { aud } = dtoken.payload;\n\n // If it's not a new login, refreshTokenClientId won't be set in the arguments.\n // In this case, try to get the currentRefreshTokenClientId from UserSettings,\n // otherwise, default back to the audience of the current id_token\n if (!refreshTokenClientId) {\n const { refreshTokenClientId: currentRefreshTokenClientId } = await UserSettings.getAsync(\n 'auth',\n {}\n );\n if (!currentRefreshTokenClientId) {\n refreshTokenClientId = aud; // set it to the \"aud\" property of the existing token\n } else {\n refreshTokenClientId = currentRefreshTokenClientId;\n }\n }\n\n // TODO(@skevy): remove\n if (process.env.NODE_ENV !== 'production') {\n Logger.global.debug('REFRESH_TOKEN_CLIENT_ID', refreshTokenClientId);\n }\n // TODO(@skevy): remove\n if (process.env.NODE_ENV !== 'production') {\n Logger.global.debug('DECODED TOKEN', dtoken);\n }\n\n if (this._isTokenExpired(idToken)) {\n // if there's less than the refresh session threshold left on the token, refresh it\n // TODO(@skevy): remove\n if (process.env.NODE_ENV !== 'production') {\n Logger.global.debug('REFRESHING ID TOKEN');\n }\n // TODO(@skevy): remove\n if (process.env.NODE_ENV !== 'production') {\n Logger.global.debug('REFRESH TOKEN', refreshToken);\n }\n const delegationResult = await this._auth0RefreshToken(\n refreshTokenClientId, // client id that's associated with the refresh token\n refreshToken // refresh token to use\n );\n // TODO(@skevy): remove\n if (process.env.NODE_ENV !== 'production') {\n Logger.global.debug('SUCCESSFULLY GOT NEW ID TOKEN');\n }\n idToken = delegationResult.id_token;\n // TODO(@skevy): remove\n if (process.env.NODE_ENV !== 'production') {\n Logger.global.debug('NEW ID TOKEN', idToken);\n }\n }\n // TODO(@skevy): remove\n if (process.env.NODE_ENV !== 'production') {\n Logger.global.debug('ID TOKEN FOR PROFILE', idToken);\n }\n user = await this._auth0GetProfileAsync(idToken);\n // TODO(@skevy): remove\n if (process.env.NODE_ENV !== 'production') {\n Logger.global.debug('USER DATA', user);\n }\n if (!user) {\n throw new Error('No user profile associated with this token');\n }\n } catch (e) {\n throw e;\n }\n\n if (!user) {\n throw new Error('Unable to fetch user.');\n }\n\n user = {\n ..._parseAuth0Profile(user),\n kind: 'user',\n currentConnection,\n accessToken,\n idToken,\n refreshToken,\n };\n\n await UserSettings.mergeAsync({\n auth: {\n userId: user.userId,\n username: user.username,\n currentConnection,\n accessToken,\n idToken,\n refreshToken,\n ...(refreshTokenClientId ? { refreshTokenClientId } : {}),\n },\n });\n\n await UserSettings.deleteKeyAsync('username');\n\n // If no currentUser, or currentUser.id differs from profiles\n // user id, that means we have a new login\n if (\n (!this._currentUser || this._currentUser.userId !== user.userId) &&\n user.username &&\n user.username !== ''\n ) {\n Analytics.logEvent('Login', {\n userId: user.userId,\n currentConnection: user.currentConnection,\n username: user.username,\n });\n\n Analytics.setUserProperties(user.username, {\n userId: user.userId,\n currentConnection: user.currentConnection,\n username: user.username,\n });\n\n if (user.intercomUserHash) {\n Intercom.update(user);\n }\n } else {\n Intercom.update(null);\n }\n\n this._currentUser = user;\n\n return user;\n }\n\n _isTokenExpired(idToken: string): boolean {\n const dtoken = jwt.decode(idToken, { complete: true });\n const { exp } = dtoken.payload;\n // TODO(@skevy): remove\n if (process.env.NODE_ENV !== 'production') {\n Logger.global.debug('TOKEN EXPIRATION', exp);\n }\n // TODO(@skevy): remove\n if (process.env.NODE_ENV !== 'production') {\n Logger.global.debug('TOKEN TIME LEFT', exp - Date.now() / 1000);\n }\n\n return exp - Date.now() / 1000 <= this.refreshSessionThreshold;\n }\n\n async _auth0LoginAsync(auth0Options: Auth0Options, loginOptions: LoginOptions): Promise<*> {\n if (typeof window !== 'undefined' && window) {\n const Auth0JS = _auth0JSInstanceWithOptions(auth0Options);\n const resp = await Auth0JS.loginAsync(loginOptions);\n return {\n access_token: resp.accessToken,\n id_token: resp.idToken,\n refresh_token: resp.refreshToken,\n };\n }\n\n const Auth0Node = _nodeAuth0InstanceWithOptions(auth0Options);\n\n if (loginOptions.connection === 'Username-Password-Authentication') {\n try {\n return await Auth0Node.oauth.signIn(loginOptions);\n } catch (e) {\n throw _formatAuth0NodeError(e);\n }\n } else {\n // social\n opn(_buildAuth0SocialLoginUrl(auth0Options, loginOptions), {\n wait: false,\n });\n return {};\n }\n }\n\n async _auth0GetProfileAsync(idToken: string): Promise<*> {\n if (typeof window !== 'undefined' && window) {\n const Auth0JS = _auth0JSInstanceWithOptions({ clientID: this.clientID });\n return await Auth0JS.getProfileAsync(idToken);\n }\n\n const Auth0Node = _nodeAuth0InstanceWithOptions({\n clientID: this.clientID,\n });\n\n const profile = await Auth0Node.tokens.getInfo(idToken);\n return profile;\n }\n\n async _auth0RefreshToken(clientId: string, refreshToken: string): Promise<*> {\n const delegationTokenOptions = {\n refresh_token: refreshToken,\n api_type: 'app',\n scope: 'openid offline_access nickname username',\n target: this.clientID,\n client_id: clientId,\n };\n\n if (typeof window !== 'undefined' && window) {\n const Auth0JS = _auth0JSInstanceWithOptions({\n clientID: clientId,\n });\n\n return await Auth0JS.getDelegationTokenAsync({\n ...delegationTokenOptions,\n });\n }\n\n const Auth0Node = _nodeAuth0InstanceWithOptions({\n clientID: this.clientID,\n });\n\n const delegationResult = await Auth0Node.tokens.getDelegationToken({\n grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',\n ...delegationTokenOptions,\n });\n\n return delegationResult;\n }\n\n async _auth0ForgotPasswordAsync(usernameOrEmail: string): Promise<void> {\n if (typeof window !== 'undefined' && window) {\n const Auth0JS = _auth0JSInstanceWithOptions({ clientID: this.clientID });\n return await Auth0JS.changePasswordAsync({\n connection: 'Username-Password-Authentication',\n email: usernameOrEmail,\n });\n }\n\n const Auth0Node = _nodeAuth0InstanceWithOptions({\n clientID: this.clientID,\n });\n\n return await Auth0Node.database.changePassword({\n connection: 'Username-Password-Authentication',\n email: usernameOrEmail,\n });\n }\n}\n\nlet __globalInstance;\nexport default UserManagerInstance.getGlobalInstance();\n\n/** Private Methods **/\n\ntype APIError = Error & {\n name: string,\n statusCode: string,\n};\n\ntype ErrorWithDescription = Error & {\n description?: string,\n};\n\nfunction _formatAuth0NodeError(e: APIError) {\n // TODO: Fix the Auth0 js library to throw better error messages when the network fails.\n // Auth0 returns an error object whenver Auth0 fails to make an API request.\n // These error messages are usually well-formed when you have an invalid login or too many attempts,\n // but when the network is down it does not give any meaningful messages.\n // Network failures log the user out in _getCurrentUserAsync() when it uses Auth0.\n const errData = e.message;\n switch (errData.error) {\n case 'invalid_user_password':\n return new XDLError(ErrorCode.INVALID_USERNAME_PASSWORD, 'Invalid username or password');\n case 'too_many_attempts':\n return new XDLError(ErrorCode.TOO_MANY_ATTEMPTS, errData.error_description);\n default:\n return new Error(errData.error_description);\n }\n return e;\n}\n\nfunction _buildAuth0SocialLoginUrl(auth0Options: Auth0Options, loginOptions: LoginOptions) {\n const qsData = {\n scope: 'openid offline_access username nickname',\n response_type: loginOptions.responseType,\n response_mode: loginOptions.responseMode,\n connection: loginOptions.connection,\n device: 'xdl',\n client_id: auth0Options.clientID,\n redirect_uri: auth0Options.callbackURL,\n };\n\n const queryString = qs.stringify(qsData);\n\n return `https://${AUTH0_DOMAIN}/authorize?${queryString}`;\n}\n\nfunction _auth0JSInstanceWithOptions(options: Object = {}): any {\n const Auth0 = require('auth0-js');\n\n let auth0Options = {\n domain: AUTH0_DOMAIN,\n responseType: 'token',\n ...options,\n };\n\n const Auth0Instance = Bluebird.promisifyAll(new Auth0(auth0Options));\n\n return Auth0Instance;\n}\n\nfunction _nodeAuth0InstanceWithOptions(options: Object = {}): any {\n let auth0Options = {\n domain: AUTH0_DOMAIN,\n clientId: options.clientID || options.clientId,\n ...options,\n };\n\n let Auth0Instance;\n if (auth0Options.management === true) {\n auth0Options = _.omit(auth0Options, 'management');\n const ManagementClient = require('auth0').ManagementClient;\n Auth0Instance = new ManagementClient(auth0Options);\n } else {\n const AuthenticationClient = require('auth0').AuthenticationClient;\n Auth0Instance = new AuthenticationClient(auth0Options);\n }\n\n return Auth0Instance;\n}\n\nfunction _parseAuth0Profile(rawProfile: any): User {\n if (!rawProfile || typeof rawProfile !== 'object') {\n return rawProfile;\n }\n return ((Object.keys(rawProfile).reduce((p, key) => {\n p[_.camelCase(key)] = _parseAuth0Profile(rawProfile[key]);\n return p;\n }, {}): any): User);\n}\n\nfunction _prepareAuth0Profile(niceProfile: any): Object {\n if (typeof niceProfile !== 'object') {\n return niceProfile;\n }\n\n return ((Object.keys(niceProfile).reduce((p, key) => {\n p[_.snakeCase(key)] = _prepareAuth0Profile(niceProfile[key]);\n return p;\n }, {}): any): User);\n}\n\ntype TokenInfo = {\n access_token: string,\n id_token: string,\n refresh_token: string,\n};\n\nclass Deferred<X> {\n promise: Promise<X>;\n resolve: (...args: Array<*>) => void;\n reject: (...args: Array<*>) => void;\n\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this.reject = reject;\n this.resolve = resolve;\n });\n }\n}\n\ntype ServerWithDestroy = {\n destroy: Function,\n listening: boolean,\n on: Function,\n close: Function,\n listen: Function,\n};\n\nasync function _startLoginServerAsync(): Promise<{\n server: ServerWithDestroy,\n callbackURL: string,\n getTokenInfoAsync: () => Promise<TokenInfo>,\n}> {\n let dfd = new Deferred();\n\n const server: ServerWithDestroy = ((http.createServer((req, res) => {\n if (req.method === 'POST' && req.url === '/callback') {\n let body = '';\n req.on('data', function(data) {\n body += data;\n });\n req.on('end', function() {\n dfd.resolve(qs.parse(body));\n res.writeHead(200, { 'Content-Type': 'text/html' });\n res.end(\n `\n <html>\n <head>\n <script>\n window.close();\n </script>\n </head>\n <body>\n Authenticated successfully! You can close this window.\n </body>\n </html>\n `\n );\n });\n } else {\n res.writeHead(200, { 'Content-Type': 'text/html' });\n res.end(\n `\n <html>\n <head></head>\n <body></body>\n </html>\n `\n );\n }\n }): any): ServerWithDestroy);\n\n server.on('clientError', (err, socket) => {\n //eslint-disable-line\n socket.end('HTTP/1.1 400 Bad Request\\r\\n\\r\\n');\n });\n\n let connections = {};\n\n server.on('connection', function(conn) {\n let key = conn.remoteAddress + ':' + conn.remotePort;\n connections[key] = conn;\n conn.on('close', function() {\n delete connections[key];\n });\n });\n\n server.destroy = function(cb) {\n server.close(cb);\n for (let key in connections) {\n connections[key].destroy();\n }\n };\n\n const port = await freeportAsync(11000);\n try {\n server.listen(port, '127.0.0.1');\n\n return {\n server,\n callbackURL: `http://127.0.0.1:${port}/callback`,\n getTokenInfoAsync: (): Promise<TokenInfo> => dfd.promise,\n };\n } catch (err) {\n throw err;\n }\n}\n"],"sourceRoot":"/xdl/src"} |