@ndustrial/contxt-sdk 4.1.1 → 4.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/.envrc +0 -0
  2. package/.nvmrc +1 -1
  3. package/CHANGELOG.md +19 -1
  4. package/README.md +2 -12
  5. package/docs/Typedefs.md +1 -0
  6. package/esm/config/audiences.js +4 -4
  7. package/esm/config/audiences.js.map +1 -1
  8. package/esm/config/defaults.js +1 -0
  9. package/esm/config/defaults.js.map +1 -1
  10. package/esm/config/index.js +2 -0
  11. package/esm/config/index.js.map +1 -1
  12. package/esm/coordinator/roles.js +6 -6
  13. package/esm/coordinator/roles.js.map +1 -1
  14. package/esm/coordinator/users.js +6 -6
  15. package/esm/coordinator/users.js.map +1 -1
  16. package/esm/sessionTypes/auth0WebAuth.js +1 -1
  17. package/esm/sessionTypes/auth0WebAuth.js.map +1 -1
  18. package/esm/sessionTypes/passwordGrantAuth.js +1 -1
  19. package/esm/sessionTypes/passwordGrantAuth.js.map +1 -1
  20. package/lib/config/audiences.js +4 -4
  21. package/lib/config/audiences.js.map +1 -1
  22. package/lib/config/defaults.js +1 -0
  23. package/lib/config/defaults.js.map +1 -1
  24. package/lib/config/index.js +2 -0
  25. package/lib/config/index.js.map +1 -1
  26. package/lib/coordinator/roles.js +6 -6
  27. package/lib/coordinator/roles.js.map +1 -1
  28. package/lib/coordinator/users.js +6 -6
  29. package/lib/coordinator/users.js.map +1 -1
  30. package/lib/sessionTypes/auth0WebAuth.js +1 -1
  31. package/lib/sessionTypes/auth0WebAuth.js.map +1 -1
  32. package/lib/sessionTypes/passwordGrantAuth.js +1 -1
  33. package/lib/sessionTypes/passwordGrantAuth.js.map +1 -1
  34. package/package.json +5 -2
  35. package/src/config/audiences.js +4 -4
  36. package/src/config/defaults.js +1 -0
  37. package/src/config/index.js +2 -0
  38. package/src/coordinator/roles.js +6 -6
  39. package/src/coordinator/roles.spec.js +8 -8
  40. package/src/coordinator/users.js +6 -6
  41. package/src/coordinator/users.spec.js +8 -8
  42. package/src/sessionTypes/auth0WebAuth.js +1 -1
  43. package/src/sessionTypes/auth0WebAuth.spec.js +17 -1
  44. package/src/sessionTypes/passwordGrantAuth.js +1 -1
  45. package/src/sessionTypes/passwordGrantAuth.spec.js +2 -1
  46. package/tmp/package.json +11 -0
  47. package/.idea/codeStyles/Project.xml +0 -49
  48. package/.idea/codeStyles/codeStyleConfig.xml +0 -5
  49. package/.idea/contxt-sdk-js.iml +0 -15
  50. package/.idea/inspectionProfiles/Project_Default.xml +0 -7
  51. package/.idea/inspectionProfiles/profiles_settings.xml +0 -6
  52. package/.idea/misc.xml +0 -4
  53. package/.idea/modules.xml +0 -9
  54. package/.idea/vcs.xml +0 -6
@@ -1 +1 @@
1
- {"version":3,"sources":["sessionTypes/auth0WebAuth.js"],"names":["auth0","axios","URL","Auth0WebAuth","sdk","_sdk","config","auth","clientId","Error","_onAuthenticate","onAuthenticate","_defaultOnAuthenticate","_onRedirect","onRedirect","_defaultOnRedirect","_sessionInfo","_getStoredSession","_sessionRenewalTimeout","_tokenPromises","currentUrl","window","location","set","authorizationPath","_auth0","WebAuth","audience","audiences","contxtAuth","clientID","domain","redirectUri","origin","pathname","responseType","scope","isAuthenticated","_scheduleSessionRefresh","audienceName","promise","Promise","resolve","then","reject","_generateUnauthorizedError","accessToken","post","host","nonce","headers","Authorization","data","access_token","client","userInfo","err","profile","formattedProfile","updatedAt","updated_at","_parseHash","authResult","_storeSession","redirectPathname","_getRedirectPathname","catch","console","log","expiresAt","Date","now","options","authOptions","forceLogin","prompt","authorize","localStorage","removeItem","clearTimeout","logout","returnTo","checkSession","response","getItem","JSON","parse","_checkSession","sessionInfo","errorToThrow","error","indexOf","logOut","status","fromSdk","originalError","code","parseHash","tokenExpiresAtBufferMs","bufferedExpiresAt","delay","setTimeout","_getUpdatedSession","expiresIn","setItem","stringify","TYPE"],"mappings":";;;;;;AAAA,OAAOA,KAAP,MAAkB,U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th0WebAuth.js","sourcesContent":["import auth0 from 'auth0-js';\nimport axios from 'axios';\nimport URL from 'url-parse';\n\n/**\n * @typedef {Object} UserProfile\n * @property {string} email\n * @property {boolean} email_verified\n * @property {string} name\n * @property {string} nickname\n * @property {string} picture URL to an avatar\n * @property {string} sub The Subject Claim of the user's JWT\n * @property {string} updatedAt ISO 8601 Extended Format date/time string\n */\n\n/**\n * @typedef {Object} Auth0WebAuthSessionInfo\n * @property {string} accessToken\n * @property {number} expiresAt\n */\n\n/**\n * A SessionType that allows the user to initially authenticate with Auth0 and then gain a valid JWT\n * from the Contxt Auth service. This would only be used in web applications. You will need to\n * integrate this module's `logIn`, `logOut`, and `handleAuthentication` methods with your UI\n * elements. `logIn` would be tied to a UI element to log the user in. `logOut` would be tied to a\n * UI element to log the user out. `handleAuthentication` would be tied with your application's\n * router and would be called when visting the route defined by `config.authorizationPath` (the\n * default is `/callback`).\n *\n * This SessionType is set up to refresh auth tokens automatically. To ensure this works, make sure\n * your single page application has {@link https://auth0.com/docs/cross-origin-authentication#configure-your-application-for-cross-origin-authentication Cross-Origin Authentication}\n * enabled in Auth0.\n *\n * *NOTE*: The web origin added in auth0 should be something like\n * \"http://localhost:5000\", not \"http://localhost:5000/callback\"\n *\n * @type SessionType\n *\n * @typicalname contxtSdk.auth\n *\n * @example\n * import ContxtSdk from '@ndustrial/contxt-sdk';\n * import history from '../services/history';\n *\n * const contxtSdk = new ContxtSdk({\n * config: {\n * auth: {\n * clientId: '<client id>',\n * onAuthenticate: (auth0WebAuthSessionInfo) => handleSuccessfulAuth(auth0WebAuthSessionInfo),\n * onRedirect: (pathname) => history.push(pathname)\n * }\n * },\n * sessionType: 'auth0WebAuth'\n * });\n */\nclass Auth0WebAuth {\n /**\n * @param {Object} sdk An instance of the SDK so the module can communicate with other modules\n * @param {Object} sdk.audiences\n * @param {Object} sdk.audiences.contxtAuth\n * @param {string} sdk.audiences.contxtAuth.clientId The Auth0 client id of the\n * Contxt Auth environment\n * @param {Object} sdk.config\n * @param {Object} sdk.config.auth\n * @param {string} sdk.config.auth.authorizationPath Path that is called by Auth0 after\n * successfully authenticating\n * @param {string} sdk.config.auth.clientId The Auth0 client id of this application\n * @param {function} [sdk.config.auth.onRedirect] Redirect method used when navigating between\n * Auth0 callbacks\n */\n constructor(sdk) {\n this._sdk = sdk;\n\n if (!this._sdk.config.auth.clientId) {\n throw new Error('clientId is required for the WebAuth config');\n }\n\n this._onAuthenticate =\n this._sdk.config.auth.onAuthenticate || this._defaultOnAuthenticate;\n this._onRedirect =\n this._sdk.config.auth.onRedirect || this._defaultOnRedirect;\n this._sessionInfo = this._getStoredSession();\n this._sessionRenewalTimeout = null;\n this._tokenPromises = {};\n\n const currentUrl = new URL(window.location);\n currentUrl.set('pathname', this._sdk.config.auth.authorizationPath);\n\n this._auth0 = new auth0.WebAuth({\n audience: this._sdk.config.audiences.contxtAuth.clientId,\n clientID: this._sdk.config.auth.clientId,\n domain: 'ndustrial.auth0.com',\n redirectUri: `${currentUrl.origin}${currentUrl.pathname}`,\n responseType: 'token',\n scope: 'email profile openid'\n });\n\n if (this.isAuthenticated()) {\n this._scheduleSessionRefresh();\n }\n }\n\n /**\n * Removes an audience's API token from the in-memory token storage\n *\n * @param audienceName\n *\n * @returns {Promise}\n */\n clearCurrentApiToken(audienceName) {\n const promise = this._tokenPromises[audienceName] || Promise.resolve();\n\n return promise.then(() => {\n delete this._tokenPromises[audienceName];\n });\n }\n\n /**\n * Gets the current auth0 access token\n *\n * @returns {Promise}\n * @fulfills {string} accessToken\n */\n getCurrentAccessToken() {\n if (!this.isAuthenticated()) {\n return Promise.reject(this._generateUnauthorizedError());\n }\n\n return Promise.resolve(this._sessionInfo.accessToken);\n }\n\n /**\n * Requests an api token from Contxt Auth for the correct audience\n *\n * @param audienceName\n *\n * @returns {Promise}\n * @fulfills {string} apiToken\n */\n getCurrentApiToken(audienceName) {\n if (!this.isAuthenticated()) {\n return Promise.reject(this._generateUnauthorizedError());\n }\n\n const audience = this._sdk.config.audiences[audienceName];\n\n if (!(audience && audience.clientId)) {\n return Promise.reject(new Error('No valid audience found'));\n }\n\n if (!this._tokenPromises[audienceName]) {\n this._tokenPromises[audienceName] = axios\n .post(\n `${this._sdk.config.audiences.contxtAuth.host}/v1/token`,\n {\n audiences: [audience.clientId],\n nonce: 'nonce'\n },\n {\n headers: {\n Authorization: `Bearer ${this._sessionInfo.accessToken}`\n }\n }\n )\n .then(({ data }) => data.access_token);\n }\n\n return this._tokenPromises[audienceName];\n }\n\n /**\n * Gets the current user's profile from Auth0\n *\n * @returns {Promise}\n * @fulfill {UserProfile}\n * @rejects {Error}\n */\n getProfile() {\n return new Promise((resolve, reject) => {\n this._auth0.client.userInfo(\n this._sessionInfo.accessToken,\n (err, profile) => {\n if (err) {\n return reject(err);\n }\n\n const formattedProfile = {\n ...profile,\n updatedAt: profile.updated_at\n };\n delete formattedProfile.updated_at;\n\n resolve(formattedProfile);\n }\n );\n });\n }\n\n /**\n * Routine that takes unparsed information from Auth0, stores it in a way that\n * can be used for getting access tokens, schedules its future renewal, and\n * redirects to the correct page in the application.\n *\n * @returns {Promise}\n * @fulfill {Auth0WebAuthSessionInfo}\n * @rejects {Error}\n */\n handleAuthentication() {\n return this._parseHash()\n .then(this._onAuthenticate)\n .then((authResult) => {\n this._storeSession(authResult);\n this._scheduleSessionRefresh();\n\n const redirectPathname = this._getRedirectPathname();\n this._onRedirect(redirectPathname);\n })\n .catch((err) => {\n console.log(`Error while handling authentication: ${err}`);\n\n this._onRedirect('/');\n\n throw err;\n });\n }\n\n /**\n * Tells caller if the current user is authenticated.\n *\n * @returns {boolean}\n */\n isAuthenticated() {\n return !!(\n this._sessionInfo &&\n this._sessionInfo.accessToken &&\n this._sessionInfo.expiresAt > Date.now()\n );\n }\n\n /**\n * Starts the Auth0 log in process\n *\n * @param {Object} options\n * @param {Boolean} [options.forceLogin = false] When true will bypass any sso settings in the authorization provider\n */\n logIn(options = {}) {\n let authOptions = {};\n\n if (options.forceLogin) {\n authOptions.prompt = 'login';\n }\n this._auth0.authorize(authOptions);\n }\n\n /**\n * Logs the user out by removing any stored session info, clearing any token\n * renewal, and redirecting to the root\n *\n * @param {Object} options\n * @param {Boolean} [options.federated = false] Indicator for if Auth0 should\n * attempt to log out the user from an external IdP\n * @param {String} [options.returnTo = window.location.origin] URL that the\n * user will be redirected to after a successful log out\n */\n logOut(options) {\n this._sessionInfo = {};\n this._tokenPromises = {};\n\n localStorage.removeItem('access_token');\n localStorage.removeItem('expires_at');\n\n clearTimeout(this._sessionRenewalTimeout);\n\n this._auth0.logout({\n returnTo: new URL(window.location).origin,\n ...options\n });\n }\n\n /**\n * Wraps Auth0's `checkSession` method. Will check if the current Auth0\n * session is valid and get updated information if needed\n *\n * @fulfill {Object} sessionResponse Information returned from Auth0\n * @rejects {Error}\n *\n * @private\n */\n _checkSession(options = {}) {\n return new Promise((resolve, reject) => {\n this._auth0.checkSession(options, (err, response) => {\n if (err || !response) {\n return reject(\n err || new Error('No valid tokens returned from auth0')\n );\n }\n\n return resolve(response);\n });\n });\n }\n\n /**\n * Default method used for redirecting around the web application. Overridden\n * by `onRedirect` in the auth config\n *\n * @private\n */\n _defaultOnRedirect(pathname) {\n window.location = pathname;\n }\n\n /**\n * Default method used for intercepting a successful authentication result. Overridden\n * by `onAuthenticate` in the auth config\n *\n * @private\n */\n _defaultOnAuthenticate(authResult) {\n return authResult;\n }\n\n /**\n * Grabs a stored redirect pathname that may have been stored in another part\n * of the web application\n *\n * @private\n */\n _getRedirectPathname() {\n const redirectPathname = localStorage.getItem('redirect_pathname');\n localStorage.removeItem('redirect_pathname');\n\n return redirectPathname || '/';\n }\n\n /**\n * Loads a saved session from local storage\n *\n * @returns {Object} session\n * @returns {string} session.accessToken\n * @returns {number} session.expiresAt\n *\n * @private\n */\n _getStoredSession() {\n return {\n accessToken: localStorage.getItem('access_token'),\n expiresAt: JSON.parse(localStorage.getItem('expires_at'))\n };\n }\n\n /**\n * Gets up to date session info. Will get an updated session/tokens if the\n * previous session has already expired. Will log the user out if an error\n * from Auth0 indicates the session cannot continue without re-authentication.\n *\n * @returns {Promise}\n * @rejects {Error}\n *\n * @private\n */\n _getUpdatedSession() {\n return this._checkSession()\n .then((sessionInfo) => {\n this._storeSession(sessionInfo);\n\n this._tokenPromises = {};\n\n this._scheduleSessionRefresh();\n })\n .catch((err) => {\n let errorToThrow = err;\n\n if (\n err.error &&\n [\n 'consent_required',\n 'interaction_required',\n 'login_required'\n ].indexOf(err.error) > -1\n ) {\n errorToThrow = this._generateUnauthorizedError(err);\n\n this.logOut();\n } else if (!(err.response && err.response.status)) {\n errorToThrow = new Error(\n 'There was a problem getting new session info. Please check your configuration settings.'\n );\n errorToThrow.fromSdk = true;\n errorToThrow.originalError = err;\n }\n\n throw errorToThrow;\n });\n }\n\n _generateUnauthorizedError(err) {\n const error = new Error('Unauthorized');\n\n if (!err) {\n error.fromSdk = true;\n }\n\n error.response = {\n data: {\n ...err,\n code: 401\n },\n status: 401\n };\n\n return error;\n }\n\n /**\n * Wraps Auth0's method for parsing hash information after a successful\n * authentication.\n *\n * @returns {Promise}\n * @fulfill {Object} hashResponse Information returned from Auth0\n * @rejects {Error}\n *\n * @private\n */\n _parseHash() {\n return new Promise((resolve, reject) => {\n this._auth0.parseHash((err, authResult) => {\n if (err || !authResult) {\n return reject(\n err || new Error('No valid tokens returned from auth0')\n );\n }\n\n return resolve(authResult);\n });\n });\n }\n\n /**\n * Schedules the Access token to renew before they expire\n *\n * @private\n */\n _scheduleSessionRefresh() {\n const tokenExpiresAtBufferMs =\n this._sdk.config.auth.tokenExpiresAtBufferMs || 0;\n const bufferedExpiresAt =\n this._sessionInfo.expiresAt - tokenExpiresAtBufferMs;\n const delay = bufferedExpiresAt - Date.now();\n\n if (this._sessionRenewalTimeout) {\n clearTimeout(this._sessionRenewalTimeout);\n }\n\n this._sessionRenewalTimeout = setTimeout(() => {\n this._getUpdatedSession();\n }, delay);\n }\n\n /**\n * Saves a session in local storage for future use\n *\n * @param {Object} sessionInfo\n * @param {string} sessionInfo.accessToken\n * @param {number} sessionInfo.expiresAt\n *\n * @private\n */\n _storeSession({ accessToken, expiresIn }) {\n const expiresAt = expiresIn * 1000 + Date.now();\n\n localStorage.setItem('access_token', accessToken);\n localStorage.setItem('expires_at', JSON.stringify(expiresAt));\n\n this._sessionInfo.accessToken = accessToken;\n this._sessionInfo.expiresAt = expiresAt;\n }\n}\n\nexport const TYPE = 'auth0WebAuth';\nexport default Auth0WebAuth;\n"]}
1
+ {"version":3,"sources":["sessionTypes/auth0WebAuth.js"],"names":["auth0","axios","URL","Auth0WebAuth","sdk","_sdk","config","auth","clientId","Error","_onAuthenticate","onAuthenticate","_defaultOnAuthenticate","_onRedirect","onRedirect","_defaultOnRedirect","_sessionInfo","_getStoredSession","_sessionRenewalTimeout","_tokenPromises","currentUrl","window","location","set","authorizationPath","_auth0","WebAuth","audience","audiences","contxtAuth","clientID","domain","redirectUri","origin","pathname","responseType","scope","isAuthenticated","_scheduleSessionRefresh","audienceName","promise","Promise","resolve","then","reject","_generateUnauthorizedError","accessToken","post","host","nonce","headers","Authorization","data","access_token","client","userInfo","err","profile","formattedProfile","updatedAt","updated_at","_parseHash","authResult","_storeSession","redirectPathname","_getRedirectPathname","catch","console","log","expiresAt","Date","now","options","authOptions","forceLogin","prompt","authorize","localStorage","removeItem","clearTimeout","logout","returnTo","checkSession","response","getItem","JSON","parse","_checkSession","sessionInfo","errorToThrow","error","indexOf","logOut","status","fromSdk","originalError","code","parseHash","tokenExpiresAtBufferMs","bufferedExpiresAt","delay","setTimeout","_getUpdatedSession","expiresIn","setItem","stringify","TYPE"],"mappings":";;;;;;AAAA,OAAOA,KAAP,MAAkB,UAAlB;AACA,OAAOC,KAAP,MAAkB,OAAlB;AACA,OAAOC,GAAP,MAAgB,WAAhB;;AAEA;;;;;;;;;;;AAWA;;;;;;AAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAmCMC,Y;AACJ;;;;;;;;;;;;;;AAc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MM,UAAN,EAAqB;AACzC,cAAIN,OAAO,CAACM,UAAZ,EAAwB;AACtB,mBAAOlB,OACLY,OAAO,IAAI/C,KAAJ,CAAU,qCAAV,CADF,CAAP;AAGD;;AAED,iBAAOiC,QAAQoB,UAAR,CAAP;AACD,SARD;AASD,OAVM,CAAP;AAWD;;AAED;;;;;;;;8CAK0B;AAAA;;AACxB,UAAMoC,yBACJ,KAAK7F,IAAL,CAAUC,MAAV,CAAiBC,IAAjB,CAAsB2F,sBAAtB,IAAgD,CADlD;AAEA,UAAMC,oBACJ,KAAKnF,YAAL,CAAkBqD,SAAlB,GAA8B6B,sBADhC;AAEA,UAAME,QAAQD,oBAAoB7B,KAAKC,GAAL,EAAlC;;AAEA,UAAI,KAAKrD,sBAAT,EAAiC;AAC/B6D,qBAAa,KAAK7D,sBAAlB;AACD;;AAED,WAAKA,sBAAL,GAA8BmF,WAAW,YAAM;AAC7C,eAAKC,kBAAL;AACD,OAF6B,EAE3BF,KAF2B,CAA9B;AAGD;;AAED;;;;;;;;;;;;yCAS0C;AAAA,UAA1BtD,WAA0B,SAA1BA,WAA0B;AAAA,UAAbyD,SAAa,SAAbA,SAAa;;AACxC,UAAMlC,YAAYkC,YAAY,IAAZ,GAAmBjC,KAAKC,GAAL,EAArC;;AAEAM,mBAAa2B,OAAb,CAAqB,cAArB,EAAqC1D,WAArC;AACA+B,mBAAa2B,OAAb,CAAqB,YAArB,EAAmCnB,KAAKoB,SAAL,CAAepC,SAAf,CAAnC;;AAEA,WAAKrD,YAAL,CAAkB8B,WAAlB,GAAgCA,WAAhC;AACA,WAAK9B,YAAL,CAAkBqD,SAAlB,GAA8BA,SAA9B;AACD;;;;;;AAGH,OAAO,IAAMqC,OAAO,cAAb;AACP,eAAevG,YAAf","file":"auth0WebAuth.js","sourcesContent":["import auth0 from 'auth0-js';\nimport axios from 'axios';\nimport URL from 'url-parse';\n\n/**\n * @typedef {Object} UserProfile\n * @property {string} email\n * @property {boolean} email_verified\n * @property {string} name\n * @property {string} nickname\n * @property {string} picture URL to an avatar\n * @property {string} sub The Subject Claim of the user's JWT\n * @property {string} updatedAt ISO 8601 Extended Format date/time string\n */\n\n/**\n * @typedef {Object} Auth0WebAuthSessionInfo\n * @property {string} accessToken\n * @property {number} expiresAt\n */\n\n/**\n * A SessionType that allows the user to initially authenticate with Auth0 and then gain a valid JWT\n * from the Contxt Auth service. This would only be used in web applications. You will need to\n * integrate this module's `logIn`, `logOut`, and `handleAuthentication` methods with your UI\n * elements. `logIn` would be tied to a UI element to log the user in. `logOut` would be tied to a\n * UI element to log the user out. `handleAuthentication` would be tied with your application's\n * router and would be called when visting the route defined by `config.authorizationPath` (the\n * default is `/callback`).\n *\n * This SessionType is set up to refresh auth tokens automatically. To ensure this works, make sure\n * your single page application has {@link https://auth0.com/docs/cross-origin-authentication#configure-your-application-for-cross-origin-authentication Cross-Origin Authentication}\n * enabled in Auth0.\n *\n * *NOTE*: The web origin added in auth0 should be something like\n * \"http://localhost:5000\", not \"http://localhost:5000/callback\"\n *\n * @type SessionType\n *\n * @typicalname contxtSdk.auth\n *\n * @example\n * import ContxtSdk from '@ndustrial/contxt-sdk';\n * import history from '../services/history';\n *\n * const contxtSdk = new ContxtSdk({\n * config: {\n * auth: {\n * clientId: '<client id>',\n * onAuthenticate: (auth0WebAuthSessionInfo) => handleSuccessfulAuth(auth0WebAuthSessionInfo),\n * onRedirect: (pathname) => history.push(pathname)\n * }\n * },\n * sessionType: 'auth0WebAuth'\n * });\n */\nclass Auth0WebAuth {\n /**\n * @param {Object} sdk An instance of the SDK so the module can communicate with other modules\n * @param {Object} sdk.audiences\n * @param {Object} sdk.audiences.contxtAuth\n * @param {string} sdk.audiences.contxtAuth.clientId The Auth0 client id of the\n * Contxt Auth environment\n * @param {Object} sdk.config\n * @param {Object} sdk.config.auth\n * @param {string} sdk.config.auth.authorizationPath Path that is called by Auth0 after\n * successfully authenticating\n * @param {string} sdk.config.auth.clientId The Auth0 client id of this application\n * @param {function} [sdk.config.auth.onRedirect] Redirect method used when navigating between\n * Auth0 callbacks\n */\n constructor(sdk) {\n this._sdk = sdk;\n\n if (!this._sdk.config.auth.clientId) {\n throw new Error('clientId is required for the WebAuth config');\n }\n\n this._onAuthenticate =\n this._sdk.config.auth.onAuthenticate || this._defaultOnAuthenticate;\n this._onRedirect =\n this._sdk.config.auth.onRedirect || this._defaultOnRedirect;\n this._sessionInfo = this._getStoredSession();\n this._sessionRenewalTimeout = null;\n this._tokenPromises = {};\n\n const currentUrl = new URL(window.location);\n currentUrl.set('pathname', this._sdk.config.auth.authorizationPath);\n\n this._auth0 = new auth0.WebAuth({\n audience: this._sdk.config.audiences.contxtAuth.clientId,\n clientID: this._sdk.config.auth.clientId,\n domain: this._sdk.config.auth.domain,\n redirectUri: `${currentUrl.origin}${currentUrl.pathname}`,\n responseType: 'token',\n scope: 'email profile openid'\n });\n\n if (this.isAuthenticated()) {\n this._scheduleSessionRefresh();\n }\n }\n\n /**\n * Removes an audience's API token from the in-memory token storage\n *\n * @param audienceName\n *\n * @returns {Promise}\n */\n clearCurrentApiToken(audienceName) {\n const promise = this._tokenPromises[audienceName] || Promise.resolve();\n\n return promise.then(() => {\n delete this._tokenPromises[audienceName];\n });\n }\n\n /**\n * Gets the current auth0 access token\n *\n * @returns {Promise}\n * @fulfills {string} accessToken\n */\n getCurrentAccessToken() {\n if (!this.isAuthenticated()) {\n return Promise.reject(this._generateUnauthorizedError());\n }\n\n return Promise.resolve(this._sessionInfo.accessToken);\n }\n\n /**\n * Requests an api token from Contxt Auth for the correct audience\n *\n * @param audienceName\n *\n * @returns {Promise}\n * @fulfills {string} apiToken\n */\n getCurrentApiToken(audienceName) {\n if (!this.isAuthenticated()) {\n return Promise.reject(this._generateUnauthorizedError());\n }\n\n const audience = this._sdk.config.audiences[audienceName];\n\n if (!(audience && audience.clientId)) {\n return Promise.reject(new Error('No valid audience found'));\n }\n\n if (!this._tokenPromises[audienceName]) {\n this._tokenPromises[audienceName] = axios\n .post(\n `${this._sdk.config.audiences.contxtAuth.host}/v1/token`,\n {\n audiences: [audience.clientId],\n nonce: 'nonce'\n },\n {\n headers: {\n Authorization: `Bearer ${this._sessionInfo.accessToken}`\n }\n }\n )\n .then(({ data }) => data.access_token);\n }\n\n return this._tokenPromises[audienceName];\n }\n\n /**\n * Gets the current user's profile from Auth0\n *\n * @returns {Promise}\n * @fulfill {UserProfile}\n * @rejects {Error}\n */\n getProfile() {\n return new Promise((resolve, reject) => {\n this._auth0.client.userInfo(\n this._sessionInfo.accessToken,\n (err, profile) => {\n if (err) {\n return reject(err);\n }\n\n const formattedProfile = {\n ...profile,\n updatedAt: profile.updated_at\n };\n delete formattedProfile.updated_at;\n\n resolve(formattedProfile);\n }\n );\n });\n }\n\n /**\n * Routine that takes unparsed information from Auth0, stores it in a way that\n * can be used for getting access tokens, schedules its future renewal, and\n * redirects to the correct page in the application.\n *\n * @returns {Promise}\n * @fulfill {Auth0WebAuthSessionInfo}\n * @rejects {Error}\n */\n handleAuthentication() {\n return this._parseHash()\n .then(this._onAuthenticate)\n .then((authResult) => {\n this._storeSession(authResult);\n this._scheduleSessionRefresh();\n\n const redirectPathname = this._getRedirectPathname();\n this._onRedirect(redirectPathname);\n })\n .catch((err) => {\n console.log(`Error while handling authentication: ${err}`);\n\n this._onRedirect('/');\n\n throw err;\n });\n }\n\n /**\n * Tells caller if the current user is authenticated.\n *\n * @returns {boolean}\n */\n isAuthenticated() {\n return !!(\n this._sessionInfo &&\n this._sessionInfo.accessToken &&\n this._sessionInfo.expiresAt > Date.now()\n );\n }\n\n /**\n * Starts the Auth0 log in process\n *\n * @param {Object} options\n * @param {Boolean} [options.forceLogin = false] When true will bypass any sso settings in the authorization provider\n */\n logIn(options = {}) {\n let authOptions = {};\n\n if (options.forceLogin) {\n authOptions.prompt = 'login';\n }\n this._auth0.authorize(authOptions);\n }\n\n /**\n * Logs the user out by removing any stored session info, clearing any token\n * renewal, and redirecting to the root\n *\n * @param {Object} options\n * @param {Boolean} [options.federated = false] Indicator for if Auth0 should\n * attempt to log out the user from an external IdP\n * @param {String} [options.returnTo = window.location.origin] URL that the\n * user will be redirected to after a successful log out\n */\n logOut(options) {\n this._sessionInfo = {};\n this._tokenPromises = {};\n\n localStorage.removeItem('access_token');\n localStorage.removeItem('expires_at');\n\n clearTimeout(this._sessionRenewalTimeout);\n\n this._auth0.logout({\n returnTo: new URL(window.location).origin,\n ...options\n });\n }\n\n /**\n * Wraps Auth0's `checkSession` method. Will check if the current Auth0\n * session is valid and get updated information if needed\n *\n * @fulfill {Object} sessionResponse Information returned from Auth0\n * @rejects {Error}\n *\n * @private\n */\n _checkSession(options = {}) {\n return new Promise((resolve, reject) => {\n this._auth0.checkSession(options, (err, response) => {\n if (err || !response) {\n return reject(\n err || new Error('No valid tokens returned from auth0')\n );\n }\n\n return resolve(response);\n });\n });\n }\n\n /**\n * Default method used for redirecting around the web application. Overridden\n * by `onRedirect` in the auth config\n *\n * @private\n */\n _defaultOnRedirect(pathname) {\n window.location = pathname;\n }\n\n /**\n * Default method used for intercepting a successful authentication result. Overridden\n * by `onAuthenticate` in the auth config\n *\n * @private\n */\n _defaultOnAuthenticate(authResult) {\n return authResult;\n }\n\n /**\n * Grabs a stored redirect pathname that may have been stored in another part\n * of the web application\n *\n * @private\n */\n _getRedirectPathname() {\n const redirectPathname = localStorage.getItem('redirect_pathname');\n localStorage.removeItem('redirect_pathname');\n\n return redirectPathname || '/';\n }\n\n /**\n * Loads a saved session from local storage\n *\n * @returns {Object} session\n * @returns {string} session.accessToken\n * @returns {number} session.expiresAt\n *\n * @private\n */\n _getStoredSession() {\n return {\n accessToken: localStorage.getItem('access_token'),\n expiresAt: JSON.parse(localStorage.getItem('expires_at'))\n };\n }\n\n /**\n * Gets up to date session info. Will get an updated session/tokens if the\n * previous session has already expired. Will log the user out if an error\n * from Auth0 indicates the session cannot continue without re-authentication.\n *\n * @returns {Promise}\n * @rejects {Error}\n *\n * @private\n */\n _getUpdatedSession() {\n return this._checkSession()\n .then((sessionInfo) => {\n this._storeSession(sessionInfo);\n\n this._tokenPromises = {};\n\n this._scheduleSessionRefresh();\n })\n .catch((err) => {\n let errorToThrow = err;\n\n if (\n err.error &&\n [\n 'consent_required',\n 'interaction_required',\n 'login_required'\n ].indexOf(err.error) > -1\n ) {\n errorToThrow = this._generateUnauthorizedError(err);\n\n this.logOut();\n } else if (!(err.response && err.response.status)) {\n errorToThrow = new Error(\n 'There was a problem getting new session info. Please check your configuration settings.'\n );\n errorToThrow.fromSdk = true;\n errorToThrow.originalError = err;\n }\n\n throw errorToThrow;\n });\n }\n\n _generateUnauthorizedError(err) {\n const error = new Error('Unauthorized');\n\n if (!err) {\n error.fromSdk = true;\n }\n\n error.response = {\n data: {\n ...err,\n code: 401\n },\n status: 401\n };\n\n return error;\n }\n\n /**\n * Wraps Auth0's method for parsing hash information after a successful\n * authentication.\n *\n * @returns {Promise}\n * @fulfill {Object} hashResponse Information returned from Auth0\n * @rejects {Error}\n *\n * @private\n */\n _parseHash() {\n return new Promise((resolve, reject) => {\n this._auth0.parseHash((err, authResult) => {\n if (err || !authResult) {\n return reject(\n err || new Error('No valid tokens returned from auth0')\n );\n }\n\n return resolve(authResult);\n });\n });\n }\n\n /**\n * Schedules the Access token to renew before they expire\n *\n * @private\n */\n _scheduleSessionRefresh() {\n const tokenExpiresAtBufferMs =\n this._sdk.config.auth.tokenExpiresAtBufferMs || 0;\n const bufferedExpiresAt =\n this._sessionInfo.expiresAt - tokenExpiresAtBufferMs;\n const delay = bufferedExpiresAt - Date.now();\n\n if (this._sessionRenewalTimeout) {\n clearTimeout(this._sessionRenewalTimeout);\n }\n\n this._sessionRenewalTimeout = setTimeout(() => {\n this._getUpdatedSession();\n }, delay);\n }\n\n /**\n * Saves a session in local storage for future use\n *\n * @param {Object} sessionInfo\n * @param {string} sessionInfo.accessToken\n * @param {number} sessionInfo.expiresAt\n *\n * @private\n */\n _storeSession({ accessToken, expiresIn }) {\n const expiresAt = expiresIn * 1000 + Date.now();\n\n localStorage.setItem('access_token', accessToken);\n localStorage.setItem('expires_at', JSON.stringify(expiresAt));\n\n this._sessionInfo.accessToken = accessToken;\n this._sessionInfo.expiresAt = expiresAt;\n }\n}\n\nexport const TYPE = 'auth0WebAuth';\nexport default Auth0WebAuth;\n"]}
@@ -48,7 +48,7 @@ var PasswordGrantAuth = function () {
48
48
  this._sessionInfo = {};
49
49
 
50
50
  this._auth0 = new auth0.Authentication({
51
- domain: 'ndustrial.auth0.com',
51
+ domain: this._sdk.config.auth.domain,
52
52
  clientID: this._sdk.config.auth.clientId
53
53
  });
54
54
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["sessionTypes/passwordGrantAuth.js"],"names":["auth0","axios","PasswordGrantAuth","sdk","_sdk","_sessionInfo","_auth0","Authentication","domain","clientID","config","auth","clientId","Promise","resolve","reject","accessToken","Error","hasToken","username","password","audience","audiences","contxtAuth","loginWithDefaultDirectory","err","response","errorMessage","description","then","_getApiToken","post","host","Object","keys","map","audienceName","filter","nonce","headers","Authorization","data","_saveSession","access_token","sessionInfo","TYPE"],"mappings":";;;;AAAA,OAAOA,KAAP,MAAkB,UAAlB;AACA,OAAOC,KAAP,MAAkB,OAAlB;;AAEA;;;;;;;;;;;;;;;;;;;;;;;;IAwBMC,iB;AACJ;;;;;;;;;;;AAWA,6BAAYC,GAAZ,EAAiB;AAAA;;AACf,SAAKC,IAAL,GAAYD,GAAZ;AACA,SAAKE,YAAL,GAAoB,EAApB;;AAEA,SAAKC,MAAL,GAAc,IAAIN,MAAMO,cAAV,CAAyB;AACrCC,cAAQ,qBAD6B;AAErCC,gBAAU,KAAKL,IAAL,CAAUM,MAAV,CAAiBC,IAAjB,CAAsBC;AAFK,KAAzB,CAAd;AAID;;AAED;;;;;;;;;;;yCAOqB;AAAA;;AACnB,aAAO,IAAIC,OAAJ,CAAY,UAACC,OAAD,EAAUC,MAAV,EAAqB;AACtC,YAAI,CAAC,MAAKV,YAAL,CAAkBW,WAAvB,EAAoC;AAClC,iBAAOD,OAAO,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UAA3B,CAAsCS,IAFtC,gBAGH;AACEV,mBAAWW,OAAOC,IAAP,CAAY,KAAK9B,IAAL,CAAUM,MAAV,CAAiBY,SAA7B,EACRa,GADQ,CACJ,UAACC,YAAD,EAAkB;AACrB,iBAAO,OAAKhC,IAAL,CAAUM,MAAV,CAAiBY,SAAjB,CAA2Bc,YAA3B,EAAyCxB,QAAhD;AACD,SAHQ,EAIRyB,MAJQ,CAID,UAACzB,QAAD,EAAc;AACpB,iBACEA,YACAA,aAAa,OAAKR,IAAL,CAAUM,MAAV,CAAiBY,SAAjB,CAA2BC,UAA3B,CAAsCX,QAFrD;AAID,SATQ,CADb;AAWE0B,eAAO;AAXT,OAHG,EAgBH;AACEC,iBAAS,EAAEC,2BAAyBxB,WAA3B;AADX,OAhBG,EAoBJa,IApBI,CAoBC,UAACH,QAAD,EAAc;AAAA,YACVe,IADU,GACDf,QADC,CACVe,IADU;;;AAGlB,eAAKC,YAAL,CAAkB;AAChB1B,uBAAayB,KAAKE;AADF,SAAlB;;AAIA,eAAOF,KAAKE,YAAZ;AACD,OA5BI,CAAP;AA6BD;;AAED;;;;;;;;;;;iCAQaC,W,EAAa;AACxB,WAAKvC,YAAL,GAAoBuC,WAApB;AACD;;;;;;AAGH,OAAO,IAAMC,OAAO,mBAAb;AACP,eAAe3C,iBAAf","file":"passwordGrantAuth.js","sourcesContent":["import auth0 from 'auth0-js';\nimport axios from 'axios';\n\n/**\n * A SessionType that allows the user to authenticate with Auth0 and\n * then gain a valid JWT from the Contxt Auth service. This method\n * utitlizes the password grant type authorization with Auth0. This\n * SessionType will expect a username and a password to be passed into\n * the `logIn` function from the user to authenticate.\n *\n * @type SessionType\n *\n * @typicalname contxtSdk.auth\n *\n * @example\n * const ContxtSdk = require('@ndustrial/contxt-sdk');\n *\n * const contxtService = new ContxtSdk({\n * config: {\n * auth: {\n * clientId: '<client id>'\n * }\n * },\n * sessionType: 'passwordGrantAuth'\n * });\n */\n\nclass PasswordGrantAuth {\n /**\n * @param {Object} sdk An instance of the SDK so the module can communicate with other modules\n * @param {Object} sdk.audiences\n * @param {Object} sdk.audiences.contxtAuth\n * @param {string} sdk.audiences.contxtAuth.clientId The Auth0 client id of the\n * Contxt Auth environment\n * @param {string} sdk.audiences.contxtAuth.host\n * @param {Object} sdk.config\n * @param {Object} sdk.config.auth\n * @param {string} sdk.config.auth.clientId The Auth0 client id of the application\n */\n constructor(sdk) {\n this._sdk = sdk;\n this._sessionInfo = {};\n\n this._auth0 = new auth0.Authentication({\n domain: 'ndustrial.auth0.com',\n clientID: this._sdk.config.auth.clientId\n });\n }\n\n /**\n * Gets the current API token (used to communicate with other Contxt APIs)\n *\n * @returns {Promise}\n * @fulfills {string} apiToken\n * @rejects {Error}\n */\n getCurrentApiToken() {\n return new Promise((resolve, reject) => {\n if (!this._sessionInfo.accessToken) {\n return reject(new Error('No api token found.'));\n }\n\n return resolve(this._sessionInfo.accessToken);\n });\n }\n\n /**\n * Tells caller if the current user is authenticated\n *\n * @returns {boolean}\n */\n isAuthenticated() {\n const hasToken = !!(this._sessionInfo && this._sessionInfo.accessToken);\n\n return hasToken;\n }\n\n /**\n * Logs the user in using Auth0 using a username a password\n *\n * @param {string} username The username of the user to authenticate\n * @param {string} password The password of the user to authenticate\n *\n * @returns {Promise}\n * @fulfills {string}\n * @rejects {Error}\n */\n logIn(username, password) {\n return new Promise((resolve, reject) => {\n const audience = this._sdk.config.audiences.contxtAuth.clientId;\n\n this._auth0.loginWithDefaultDirectory(\n { password, username, audience },\n (err, response) => {\n if (err) {\n const errorMessage =\n (err && err.description) || 'Authentication failed.';\n\n return reject(new Error(errorMessage));\n }\n\n return resolve(response.accessToken);\n }\n );\n }).then((accessToken) => {\n return this._getApiToken(accessToken);\n });\n }\n\n /**\n * Logs the user out by removing any stored session info.\n *\n * @returns {Promise}\n * @fulfills {string}\n */\n logOut() {\n return new Promise((resolve) => {\n this._sessionInfo = {};\n\n return resolve('Logout successful - session info cleared.');\n });\n }\n\n /**\n * Requests an access token from Contxt Auth with the correct audiences.\n *\n * @param {string} accessToken\n *\n * @returns {Promise}\n * @fulfill {string} accessToken\n * @rejects {Error}\n *\n * @private\n */\n _getApiToken(accessToken) {\n return axios\n .post(\n `${this._sdk.config.audiences.contxtAuth.host}/v1/token`,\n {\n audiences: Object.keys(this._sdk.config.audiences)\n .map((audienceName) => {\n return this._sdk.config.audiences[audienceName].clientId;\n })\n .filter((clientId) => {\n return (\n clientId &&\n clientId !== this._sdk.config.audiences.contxtAuth.clientId\n );\n }),\n nonce: 'nonce'\n },\n {\n headers: { Authorization: `Bearer ${accessToken}` }\n }\n )\n .then((response) => {\n const { data } = response;\n\n this._saveSession({\n accessToken: data.access_token\n });\n\n return data.access_token;\n });\n }\n\n /**\n * Saves the session info (i.e. the Contxt access token) for future use\n *\n * @param {Object} sessionInfo\n * @param {string} sessionInfo.accessToken\n *\n * @private\n */\n _saveSession(sessionInfo) {\n this._sessionInfo = sessionInfo;\n }\n}\n\nexport const TYPE = 'passwordGrantAuth';\nexport default PasswordGrantAuth;\n"]}
1
+ {"version":3,"sources":["sessionTypes/passwordGrantAuth.js"],"names":["auth0","axios","PasswordGrantAuth","sdk","_sdk","_sessionInfo","_auth0","Authentication","domain","config","auth","clientID","clientId","Promise","resolve","reject","accessToken","Error","hasToken","username","password","audience","audiences","contxtAuth","loginWithDefaultDirectory","err","response","errorMessage","description","then","_getApiToken","post","host","Object","keys","map","audienceName","filter","nonce","headers","Authorization","data","_saveSession","access_token","sessionInfo","TYPE"],"mappings":";;;;AAAA,OAAOA,KAAP,MAAkB,UAAlB;AACA,OAAOC,KAAP,MAAkB,OAAlB;;AAEA;;;;;;;;;;;;;;;;;;;;;;;;IAwBMC,iB;AACJ;;;;;;;;;;;AAWA,6BAAYC,GAAZ,EAAiB;AAAA;;AACf,SAAKC,IAAL,GAAYD,GAAZ;AACA,SAAKE,YAAL,GAAoB,EAApB;;AAEA,SAAKC,MAAL,GAAc,IAAIN,MAAMO,cAAV,CAAyB;AACrCC,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AACD,OAlBM,CAAP;AAmBD;;AAED;;;;;;;;;6BAMS;AAAA;;AACP,aAAO,IAAIH,OAAJ,CAAY,UAACC,OAAD,EAAa;AAC9B,eAAKT,YAAL,GAAoB,EAApB;;AAEA,eAAOS,QAAQ,2CAAR,CAAP;AACD,OAJM,CAAP;AAKD;;AAED;;;;;;;;;;;;;;iCAWaE,W,EAAa;AAAA;;AACxB,aAAOf,MACJ8B,IADI,CAEA,KAAK3B,IAAL,CAAUK,MAAV,CAAiBa,SAAjB,CAA2BC,UAA3B,CAAsCS,IAFtC,gBAGH;AACEV,mBAAWW,OAAOC,IAAP,CAAY,KAAK9B,IAAL,CAAUK,MAAV,CAAiBa,SAA7B,EACRa,GADQ,CACJ,UAACC,YAAD,EAAkB;AACrB,iBAAO,OAAKhC,IAAL,CAAUK,MAAV,CAAiBa,SAAjB,CAA2Bc,YAA3B,EAAyCxB,QAAhD;AACD,SAHQ,EAIRyB,MAJQ,CAID,UAACzB,QAAD,EAAc;AACpB,iBACEA,YACAA,aAAa,OAAKR,IAAL,CAAUK,MAAV,CAAiBa,SAAjB,CAA2BC,UAA3B,CAAsCX,QAFrD;AAID,SATQ,CADb;AAWE0B,eAAO;AAXT,OAHG,EAgBH;AACEC,iBAAS,EAAEC,2BAAyBxB,WAA3B;AADX,OAhBG,EAoBJa,IApBI,CAoBC,UAACH,QAAD,EAAc;AAAA,YACVe,IADU,GACDf,QADC,CACVe,IADU;;;AAGlB,eAAKC,YAAL,CAAkB;AAChB1B,uBAAayB,KAAKE;AADF,SAAlB;;AAIA,eAAOF,KAAKE,YAAZ;AACD,OA5BI,CAAP;AA6BD;;AAED;;;;;;;;;;;iCAQaC,W,EAAa;AACxB,WAAKvC,YAAL,GAAoBuC,WAApB;AACD;;;;;;AAGH,OAAO,IAAMC,OAAO,mBAAb;AACP,eAAe3C,iBAAf","file":"passwordGrantAuth.js","sourcesContent":["import auth0 from 'auth0-js';\nimport axios from 'axios';\n\n/**\n * A SessionType that allows the user to authenticate with Auth0 and\n * then gain a valid JWT from the Contxt Auth service. This method\n * utitlizes the password grant type authorization with Auth0. This\n * SessionType will expect a username and a password to be passed into\n * the `logIn` function from the user to authenticate.\n *\n * @type SessionType\n *\n * @typicalname contxtSdk.auth\n *\n * @example\n * const ContxtSdk = require('@ndustrial/contxt-sdk');\n *\n * const contxtService = new ContxtSdk({\n * config: {\n * auth: {\n * clientId: '<client id>'\n * }\n * },\n * sessionType: 'passwordGrantAuth'\n * });\n */\n\nclass PasswordGrantAuth {\n /**\n * @param {Object} sdk An instance of the SDK so the module can communicate with other modules\n * @param {Object} sdk.audiences\n * @param {Object} sdk.audiences.contxtAuth\n * @param {string} sdk.audiences.contxtAuth.clientId The Auth0 client id of the\n * Contxt Auth environment\n * @param {string} sdk.audiences.contxtAuth.host\n * @param {Object} sdk.config\n * @param {Object} sdk.config.auth\n * @param {string} sdk.config.auth.clientId The Auth0 client id of the application\n */\n constructor(sdk) {\n this._sdk = sdk;\n this._sessionInfo = {};\n\n this._auth0 = new auth0.Authentication({\n domain: this._sdk.config.auth.domain,\n clientID: this._sdk.config.auth.clientId\n });\n }\n\n /**\n * Gets the current API token (used to communicate with other Contxt APIs)\n *\n * @returns {Promise}\n * @fulfills {string} apiToken\n * @rejects {Error}\n */\n getCurrentApiToken() {\n return new Promise((resolve, reject) => {\n if (!this._sessionInfo.accessToken) {\n return reject(new Error('No api token found.'));\n }\n\n return resolve(this._sessionInfo.accessToken);\n });\n }\n\n /**\n * Tells caller if the current user is authenticated\n *\n * @returns {boolean}\n */\n isAuthenticated() {\n const hasToken = !!(this._sessionInfo && this._sessionInfo.accessToken);\n\n return hasToken;\n }\n\n /**\n * Logs the user in using Auth0 using a username a password\n *\n * @param {string} username The username of the user to authenticate\n * @param {string} password The password of the user to authenticate\n *\n * @returns {Promise}\n * @fulfills {string}\n * @rejects {Error}\n */\n logIn(username, password) {\n return new Promise((resolve, reject) => {\n const audience = this._sdk.config.audiences.contxtAuth.clientId;\n\n this._auth0.loginWithDefaultDirectory(\n { password, username, audience },\n (err, response) => {\n if (err) {\n const errorMessage =\n (err && err.description) || 'Authentication failed.';\n\n return reject(new Error(errorMessage));\n }\n\n return resolve(response.accessToken);\n }\n );\n }).then((accessToken) => {\n return this._getApiToken(accessToken);\n });\n }\n\n /**\n * Logs the user out by removing any stored session info.\n *\n * @returns {Promise}\n * @fulfills {string}\n */\n logOut() {\n return new Promise((resolve) => {\n this._sessionInfo = {};\n\n return resolve('Logout successful - session info cleared.');\n });\n }\n\n /**\n * Requests an access token from Contxt Auth with the correct audiences.\n *\n * @param {string} accessToken\n *\n * @returns {Promise}\n * @fulfill {string} accessToken\n * @rejects {Error}\n *\n * @private\n */\n _getApiToken(accessToken) {\n return axios\n .post(\n `${this._sdk.config.audiences.contxtAuth.host}/v1/token`,\n {\n audiences: Object.keys(this._sdk.config.audiences)\n .map((audienceName) => {\n return this._sdk.config.audiences[audienceName].clientId;\n })\n .filter((clientId) => {\n return (\n clientId &&\n clientId !== this._sdk.config.audiences.contxtAuth.clientId\n );\n }),\n nonce: 'nonce'\n },\n {\n headers: { Authorization: `Bearer ${accessToken}` }\n }\n )\n .then((response) => {\n const { data } = response;\n\n this._saveSession({\n accessToken: data.access_token\n });\n\n return data.access_token;\n });\n }\n\n /**\n * Saves the session info (i.e. the Contxt access token) for future use\n *\n * @param {Object} sessionInfo\n * @param {string} sessionInfo.accessToken\n *\n * @private\n */\n _saveSession(sessionInfo) {\n this._sessionInfo = sessionInfo;\n }\n}\n\nexport const TYPE = 'passwordGrantAuth';\nexport default PasswordGrantAuth;\n"]}
@@ -32,14 +32,14 @@ exports.default = {
32
32
  host: 'https://contxt.api.ndustrial.io'
33
33
  },
34
34
  staging: {
35
- clientId: '8qY2xJob1JAxhmVhIDLCNnGriTM9bct8',
36
- host: 'https://contxt-staging.api.ndustrial.io'
35
+ clientId: 'qGzdTXcmB57zlTp86rYsivG9qEss1lbF',
36
+ host: 'https://contxt-api.staging.ndustrial.io'
37
37
  }
38
38
  },
39
39
  events: {
40
40
  staging: {
41
41
  clientId: 'dn4MaocJFdKtsBy9sFFaTeuJWL1nt5xu',
42
- host: 'https://events-staging.api.ndustrial.io'
42
+ host: 'https://events.api.staging.ndustrial.io'
43
43
  },
44
44
  production: {
45
45
  clientId: '7jzwfE20O2XZ4aq3cO1wmk63G9GzNc8j',
@@ -63,7 +63,7 @@ exports.default = {
63
63
  },
64
64
  staging: {
65
65
  clientId: 'SLE310LY4nDT5p06sUGPVOLlGXk5osbQ',
66
- host: 'https://files-staging.api.ndustrial.io'
66
+ host: 'https://files.api.staging.ndustrial.io'
67
67
  }
68
68
  },
69
69
  health: {
@@ -1 +1 @@
1
- {"version":3,"sources":["config/audiences.js"],"names":["bus","production","clientId","host","webSocket","staging","contxtAuth","coordinator","events","facilities","files","health","iot"],"mappings":";;;;;kBAAe;AACbA,OAAK;AACHC,gBAAY;AACVC,gBAAU,kCADA;AAEVC,YAAM,0BAFI;AAGVC,iBAAW;AAHD,KADT;AAMHC,aAAS;AACPH,gBAAU,kCADH;AAEPC,YAAM,kCAFC;AAGPC,iBAAW;AAHJ;AANN,GADQ;AAabE,cAAY;AACVL,gBAAY;AACVC,gBAAU,kCADA;AAEVC,YAAM;AAFI,KADF;AAKVE,aAAS;AACPH,gBAAU,kCADH;AAEPC,YAAM;AAFC;AALC,GAbC;AAuBbI,eAAa;AACXN,gBAAY;AACVC,gBAAU,kCADA;AAEVC,YAAM;AAFI,KADD;AAKXE,aAAS;AACPH,gBAAU,kCADH;AAEPC,YAAM;AAFC;AALE,GAvBA;AAiCbK,UAAQ;AACNH,aAAS;AACPH,gBAAU,kCADH;AAEPC,YAAM;AAFC,KADH;AAKNF,gBAAY;AACVC,gBAAU,kCADA;AAEVC,YAAM;AAFI;AALN,GAjCK;AA2CbM,cAAY;AACVR,gBAAY;AACVC,gBAAU,kCADA;AAEVC,YAAM;AAFI,KADF;AAKVE,aAAS;AACPH,gBAAU,kCADH;AAEPC,YAAM;AAFC;AALC,GA3CC;AAqDbO,SAAO;AACLT,gBAAY;AACVC,gBAAU,kCADA;AAEVC,YAAM;AAFI,KADP;AAKLE,aAAS;AACPH,gBAAU,kCADH;AAEPC,YAAM;AAFC;AALJ,GArDM;AA+DbQ,UAAQ;AACNN,aAAS;AACPH,gBAAU,kCADH;AAEPC,YAAM;AAFC,KADH;AAKNF,gBAAY;AACVC,gBAAU,kCADA;AAEVC,YAAM;AAFI;AALN,GA/DK;AAyEbS,OAAK;AACHP,aAAS;AACPH,gBAAU,kCADH;AAEPC,YAAM;AAFC,KADN;AAKHF,gBAAY;AACVC,gBAAU,kCADA;AAEVC,YAAM;AAFI;AALT;AAzEQ,C","file":"audiences.js","sourcesContent":["export default {\n bus: {\n production: {\n clientId: 'bmoJ2jhfyIP5s4IZx5Ss6xQ9lmkoDixO',\n host: 'https://bus.ndustrial.io',\n webSocket: 'wss://bus.ndustrial.io'\n },\n staging: {\n clientId: '1HD1NG1VTBtkqRt2HRRj3E3hdmqmwzoz',\n host: 'https://bus-staging.ndustrial.io',\n webSocket: 'wss://bus-staging.ndustrial.io'\n }\n },\n contxtAuth: {\n production: {\n clientId: '75wT048QcpE7ujwBJPPjr263eTHl4gEX',\n host: 'https://contxtauth.com'\n },\n staging: {\n clientId: 'XzgumXUg5U57015haylz4zaJsiQqZy4l',\n host: 'https://contxt-auth-staging.api.ndustrial.io'\n }\n },\n coordinator: {\n production: {\n clientId: '8qY2xJob1JAxhmVhIDLCNnGriTM9bct8',\n host: 'https://contxt.api.ndustrial.io'\n },\n staging: {\n clientId: '8qY2xJob1JAxhmVhIDLCNnGriTM9bct8',\n host: 'https://contxt-staging.api.ndustrial.io'\n }\n },\n events: {\n staging: {\n clientId: 'dn4MaocJFdKtsBy9sFFaTeuJWL1nt5xu',\n host: 'https://events-staging.api.ndustrial.io'\n },\n production: {\n clientId: '7jzwfE20O2XZ4aq3cO1wmk63G9GzNc8j',\n host: 'https://events.api.ndustrial.io'\n }\n },\n facilities: {\n production: {\n clientId: 'SgbCopArnGMa9PsRlCVUCVRwxocntlg0',\n host: 'https://facilities.api.ndustrial.io'\n },\n staging: {\n clientId: 'xG775XHIOZVUn84seNeHXi0Qe55YuR5w',\n host: 'https://facilities-staging.api.ndustrial.io'\n }\n },\n files: {\n production: {\n clientId: 'VZJ2MRd71dM9oX2hB1EVAEjUe6loL7pl',\n host: 'https://files.api.ndustrial.io'\n },\n staging: {\n clientId: 'SLE310LY4nDT5p06sUGPVOLlGXk5osbQ',\n host: 'https://files-staging.api.ndustrial.io'\n }\n },\n health: {\n staging: {\n clientId: '1zQ2YXbHXotrf2dDKgySqEjlJBz465qq',\n host: 'https://health-staging.api.ndustrial.io'\n },\n production: {\n clientId: '6uaQIV1KnnWhXiTm09iGDvy2aQaz2xVI',\n host: 'https://health.api.ndustrial.io'\n }\n },\n iot: {\n staging: {\n clientId: 'm35AEcxD8hf65sq04ZU7yFxqpqVkKzES',\n host: 'https://feeds-staging.api.ndustrial.io'\n },\n production: {\n clientId: 'iznTb30Sfp2Jpaf398I5DN6MyPuDCftA',\n host: 'https://feeds.api.ndustrial.io'\n }\n }\n};\n"]}
1
+ {"version":3,"sources":["config/audiences.js"],"names":["bus","production","clientId","host","webSocket","staging","contxtAuth","coordinator","events","facilities","files","health","iot"],"mappings":";;;;;kBAAe;AACbA,OAAK;AACHC,gBAAY;AACVC,gBAAU,kCADA;AAEVC,YAAM,0BAFI;AAGVC,iBAAW;AAHD,KADT;AAMHC,aAAS;AACPH,gBAAU,kCADH;AAEPC,YAAM,kCAFC;AAGPC,iBAAW;AAHJ;AANN,GADQ;AAabE,cAAY;AACVL,gBAAY;AACVC,gBAAU,kCADA;AAEVC,YAAM;AAFI,KADF;AAKVE,aAAS;AACPH,gBAAU,kCADH;AAEPC,YAAM;AAFC;AALC,GAbC;AAuBbI,eAAa;AACXN,gBAAY;AACVC,gBAAU,kCADA;AAEVC,YAAM;AAFI,KADD;AAKXE,aAAS;AACPH,gBAAU,kCADH;AAEPC,YAAM;AAFC;AALE,GAvBA;AAiCbK,UAAQ;AACNH,aAAS;AACPH,gBAAU,kCADH;AAEPC,YAAM;AAFC,KADH;AAKNF,gBAAY;AACVC,gBAAU,kCADA;AAEVC,YAAM;AAFI;AALN,GAjCK;AA2CbM,cAAY;AACVR,gBAAY;AACVC,gBAAU,kCADA;AAEVC,YAAM;AAFI,KADF;AAKVE,aAAS;AACPH,gBAAU,kCADH;AAEPC,YAAM;AAFC;AALC,GA3CC;AAqDbO,SAAO;AACLT,gBAAY;AACVC,gBAAU,kCADA;AAEVC,YAAM;AAFI,KADP;AAKLE,aAAS;AACPH,gBAAU,kCADH;AAEPC,YAAM;AAFC;AALJ,GArDM;AA+DbQ,UAAQ;AACNN,aAAS;AACPH,gBAAU,kCADH;AAEPC,YAAM;AAFC,KADH;AAKNF,gBAAY;AACVC,gBAAU,kCADA;AAEVC,YAAM;AAFI;AALN,GA/DK;AAyEbS,OAAK;AACHP,aAAS;AACPH,gBAAU,kCADH;AAEPC,YAAM;AAFC,KADN;AAKHF,gBAAY;AACVC,gBAAU,kCADA;AAEVC,YAAM;AAFI;AALT;AAzEQ,C","file":"audiences.js","sourcesContent":["export default {\n bus: {\n production: {\n clientId: 'bmoJ2jhfyIP5s4IZx5Ss6xQ9lmkoDixO',\n host: 'https://bus.ndustrial.io',\n webSocket: 'wss://bus.ndustrial.io'\n },\n staging: {\n clientId: '1HD1NG1VTBtkqRt2HRRj3E3hdmqmwzoz',\n host: 'https://bus-staging.ndustrial.io',\n webSocket: 'wss://bus-staging.ndustrial.io'\n }\n },\n contxtAuth: {\n production: {\n clientId: '75wT048QcpE7ujwBJPPjr263eTHl4gEX',\n host: 'https://contxtauth.com'\n },\n staging: {\n clientId: 'XzgumXUg5U57015haylz4zaJsiQqZy4l',\n host: 'https://contxt-auth-staging.api.ndustrial.io'\n }\n },\n coordinator: {\n production: {\n clientId: '8qY2xJob1JAxhmVhIDLCNnGriTM9bct8',\n host: 'https://contxt.api.ndustrial.io'\n },\n staging: {\n clientId: 'qGzdTXcmB57zlTp86rYsivG9qEss1lbF',\n host: 'https://contxt-api.staging.ndustrial.io'\n }\n },\n events: {\n staging: {\n clientId: 'dn4MaocJFdKtsBy9sFFaTeuJWL1nt5xu',\n host: 'https://events.api.staging.ndustrial.io'\n },\n production: {\n clientId: '7jzwfE20O2XZ4aq3cO1wmk63G9GzNc8j',\n host: 'https://events.api.ndustrial.io'\n }\n },\n facilities: {\n production: {\n clientId: 'SgbCopArnGMa9PsRlCVUCVRwxocntlg0',\n host: 'https://facilities.api.ndustrial.io'\n },\n staging: {\n clientId: 'xG775XHIOZVUn84seNeHXi0Qe55YuR5w',\n host: 'https://facilities-staging.api.ndustrial.io'\n }\n },\n files: {\n production: {\n clientId: 'VZJ2MRd71dM9oX2hB1EVAEjUe6loL7pl',\n host: 'https://files.api.ndustrial.io'\n },\n staging: {\n clientId: 'SLE310LY4nDT5p06sUGPVOLlGXk5osbQ',\n host: 'https://files.api.staging.ndustrial.io'\n }\n },\n health: {\n staging: {\n clientId: '1zQ2YXbHXotrf2dDKgySqEjlJBz465qq',\n host: 'https://health-staging.api.ndustrial.io'\n },\n production: {\n clientId: '6uaQIV1KnnWhXiTm09iGDvy2aQaz2xVI',\n host: 'https://health.api.ndustrial.io'\n }\n },\n iot: {\n staging: {\n clientId: 'm35AEcxD8hf65sq04ZU7yFxqpqVkKzES',\n host: 'https://feeds-staging.api.ndustrial.io'\n },\n production: {\n clientId: 'iznTb30Sfp2Jpaf398I5DN6MyPuDCftA',\n host: 'https://feeds.api.ndustrial.io'\n }\n }\n};\n"]}
@@ -5,6 +5,7 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.default = {
7
7
  auth: {
8
+ domain: 'ndustrial.auth0.com',
8
9
  authorizationPath: '/callback',
9
10
  tokenExpiresAtBufferMs: 5 * 60 * 1000 // 5 minutes
10
11
  },
@@ -1 +1 @@
1
- {"version":3,"sources":["config/defaults.js"],"names":["auth","authorizationPath","tokenExpiresAtBufferMs","interceptors","request","response"],"mappings":";;;;;kBAAe;AACbA,QAAM;AACJC,uBAAmB,WADf;AAEJC,4BAAwB,IAAI,EAAJ,GAAS,IAF7B,CAEkC;AAFlC,GADO;AAKbC,gBAAc;AACZC,aAAS,EADG;AAEZC,cAAU;AAFE;AALD,C","file":"defaults.js","sourcesContent":["export default {\n auth: {\n authorizationPath: '/callback',\n tokenExpiresAtBufferMs: 5 * 60 * 1000 // 5 minutes\n },\n interceptors: {\n request: [],\n response: []\n }\n};\n"]}
1
+ {"version":3,"sources":["config/defaults.js"],"names":["auth","domain","authorizationPath","tokenExpiresAtBufferMs","interceptors","request","response"],"mappings":";;;;;kBAAe;AACbA,QAAM;AACJC,YAAQ,qBADJ;AAEJC,uBAAmB,WAFf;AAGJC,4BAAwB,IAAI,EAAJ,GAAS,IAH7B,CAGkC;AAHlC,GADO;AAMbC,gBAAc;AACZC,aAAS,EADG;AAEZC,cAAU;AAFE;AAND,C","file":"defaults.js","sourcesContent":["export default {\n auth: {\n domain: 'ndustrial.auth0.com',\n authorizationPath: '/callback',\n tokenExpiresAtBufferMs: 5 * 60 * 1000 // 5 minutes\n },\n interceptors: {\n request: [],\n response: []\n }\n};\n"]}
@@ -86,6 +86,8 @@ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Cons
86
86
  * @property {string} auth.clientId Client Id provided by Auth0 for this application
87
87
  * @property {string} [auth.clientSecret] Client secret provided by Auth0 for this application. This
88
88
  * is optional for the auth0WebAuth SessionType, but required for the machineAuth SessionType
89
+ * @property {string} [auth.domain] Auth0 domain for this application. This is an optional configuration
90
+ * that defaults to the production Auth0 tenant
89
91
  * @property {Object.<string, CustomAudience>} [auth.customModuleConfigs] Custom environment setups
90
92
  * for individual modules. Requires clientId/host or env
91
93
  * @property {string} [auth.env = 'production'] The environment that every module should use for
@@ -1 +1 @@
1
- {"version":3,"sources":["config/index.js"],"names":["Config","userConfig","externalModules","Object","assign","_dynamicAudienceNames","_replacedAudiences","audiences","_getAudiences","customModuleConfigs","auth","env","defaultConfigs","interceptors","audienceName","clientId","host","Error","indexOf","filter","name","config","audience","webSocket","options","_getInternalAudiences","defaultAudiences","_getExternalAudiences","keys","reduce","memo","key","hasClientId","hasHost","customModuleConfig","moduleAudiences","_getAudienceFromCustomConfig"],"mappings":";;;;;;;;;;AAAA;;;;AACA;;;;;;;;;;AAEA;;;;;;;;;;AAUA;;;;;;;;;;;;;AAaA;;;;;;;AAOA;;;;;;;;;;;;;;AAcA;;;;;;;;;;AAUA;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA;;;;;IAKMA,M;AACJ;;;;;AAKA,kBAAYC,UAAZ,EAAwBC,eAAxB,EAAyC;AAAA;;AACvCC,WAAOC,MAAP,CAAc,IAAd,EAAoBH,UAApB;;AAEA,SAAKI,qBAAL,GAA6B,EAA7B;AACA,SAAKC,kBAAL,GAA0B,EAA1B;;AAEA,SAAKC,SAAL,GAAiB,KAAKC,aAAL,CAAmB;AAClCN,sCADkC;AAElCO,2BAAqBR,WAAWS,IAAX,CAAgBD,mBAFH;AAGlCE,WAAKV,WAAWS,IAAX,CAAgBC;AAHa,KAAnB,CAAjB;;AAMA,SAAKD,IAAL,gBACKE,mBAAeF,IADpB,EAEKT,WAAWS,IAFhB;;AAKA,SAAKG,YAAL,gBACKD,mBAAeC,YADpB,EAEKZ,WAAWY,YAFhB;AAID;;;;uCAEkBC,Y,QAAkC;AAAA,UAAlBC,QAAkB,QAAlBA,QAAkB;AAAA,UAARC,IAAQ,QAARA,IAAQ;;AACnD,UAAI,CAACD,QAAD,IAAa,CAACC,IAAlB,EAAwB;AACtB,cAAM,IAAIC,KAAJ,CACJ,kEADI,CAAN;AAGD;;AAED,UAAI,KAAKZ,qBAAL,CAA2Ba,OAA3B,CAAmCJ,YAAnC,IAAmD,CAAC,CAAxD,EAA2D;AACzD,cAAM,IAAIG,KAAJ,sCACgCH,YADhC,iGAAN;AAGD;;AAED,WAAKT,qBAAL,gCAAiC,KAAKA,qBAAtC,IAA6DS,YAA7D;;AAE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A3B;AACA,YAAMI,kBAAkB5B,UAAUwB,GAAV,CAAxB;;AAEA,YAAIG,kBAAJ,EAAwB;AACtBJ,eAAKC,GAAL,IAAY,MAAKK,4BAAL,CACVF,kBADU,EAEVC,eAFU,CAAZ;AAID,SALD,MAKO;AACLL,eAAKC,GAAL,IAAYI,gBAAgBxB,GAAhB,CAAZ;AACD;;AAED,eAAOmB,IAAP;AACD,OAdM,EAcJ,EAdI,CAAP;AAeD;;;;;;kBAGY9B,M","file":"index.js","sourcesContent":["import defaultAudiences from './audiences';\nimport defaultConfigs from './defaults';\n\n/**\n * A single audience used for authenticating and communicating with an individual API.\n *\n * @typedef {Object} Audience\n * @param {string} config.clientId Client Id provided by Auth0 for the environment you are\n * trying to communicate with\n * @param {string} config.host Hostname for the API that corresponds with the clientId provided\n * @param {string} [config.webSocket] WebSocket URL for the API that corresponds with the clientId provided\n */\n\n/**\n * A custom audience that will override the configuration of an individual module. Consists of\n * either a reference to an environment that already exists or a clientId and host for a\n * custom environment.\n *\n * @typedef {Object} CustomAudience\n * @param {string} [config.clientId] Client Id provided by Auth0 for the environment you are\n * trying to communicate with\n * @param {string} [config.env] The SDK provided environment name you are trying to reach\n * @param {string} [config.host] Hostname for the API that corresponds with the clientId provided\n * @param {string} [config.webSocket] WebSocket URL for the API that corresponds with the clientId provided\n */\n\n/**\n * An object of audiences that corresponds to all the different environments available for a\n * single module.\n *\n * @typedef {Object.<string, Audience>} Environments\n */\n\n/**\n * An external module to be integrated into the SDK as a first class citizen. Includes information\n * for authenticating and communicating with an individual API and the external module itself.\n *\n * @typedef {Object} ExternalModule\n * @param {string} config.clientId Client Id provided by Auth0 for the environment you are\n * trying to communicate with. Can be a `null` value if the value is not needed. Some SessionType\n * adapters (currently, just the MachineAuth adapter) require a value other than `null` if the\n * built-in `request` module is used since they acquire contxt tokens based on a single clientId.\n * @param {string} config.host Hostname for the API that corresponds with the clientId provided.\n * Can be a `null` value if the value is not needed.\n * @param {function} config.module The module that will be decorated into the SDK\n */\n\n/**\n * An object of interceptors that get called on every request or response.\n * More information at {@link https://github.com/axios/axios#interceptors axios Interceptors}\n *\n * @typedef {Object} AxiosInterceptor\n * @param {function} interceptor.fulfilled A function that is run on every successful request or\n * response\n * @param {function} interceptor.rejected A function that is run on every failed request or response\n */\n\n/**\n * User provided configuration options\n *\n * @typedef {Object} UserConfig\n * @property {Object} auth User assigned configurations specific for their authentication methods\n * @property {string} [auth.authorizationPath] Path Auth0WebAuth process should redirect to after a\n * successful sign in attempt\n * @property {string} auth.clientId Client Id provided by Auth0 for this application\n * @property {string} [auth.clientSecret] Client secret provided by Auth0 for this application. This\n * is optional for the auth0WebAuth SessionType, but required for the machineAuth SessionType\n * @property {Object.<string, CustomAudience>} [auth.customModuleConfigs] Custom environment setups\n * for individual modules. Requires clientId/host or env\n * @property {string} [auth.env = 'production'] The environment that every module should use for\n * their clientId and host\n * @property {function} [auth.onAuthenticate = (auth0WebAuthSessionInfo) => handleSuccessfulAuth(auth0WebAuthSessionInfo); ] An optional\n * hook for handling a successful authentication request or overriding returned values.\n * @property {function} [auth.onRedirect = (pathname) => { window.location = pathname; }] A redirect\n * method used for navigating through Auth0 callbacks in Web applications\n * @property {number} [auth.tokenExpiresAtBufferMs = 300000] The time (in milliseconds) before a\n * token truly expires that we consider it expired (i.e. the token's expiresAt - this = calculated\n * expiresAt). Defaults to 5 minutes.\n * @property {Object} [interceptors] Axios interceptors that can transform requests and responses.\n * More information at {@link https://github.com/axios/axios#interceptors axios Interceptors}\n * @property {AxiosInterceptor[]} [interceptors.request] Interceptors that act on every request\n * @property {AxiosInterceptor[]} [intercepotrs.response] Intereptors that act on every response\n */\n\n/**\n * Module that merges user assigned configurations with default configurations.\n *\n * @typicalname contxtSdk.config\n */\nclass Config {\n /**\n * @param {UserConfig} userConfig The user provided configuration options\n * @param {Object.<string, ExternalModule>} [externalModules] User provided external modules that should be treated as\n * first class citizens\n */\n constructor(userConfig, externalModules) {\n Object.assign(this, userConfig);\n\n this._dynamicAudienceNames = [];\n this._replacedAudiences = {};\n\n this.audiences = this._getAudiences({\n externalModules,\n customModuleConfigs: userConfig.auth.customModuleConfigs,\n env: userConfig.auth.env\n });\n\n this.auth = {\n ...defaultConfigs.auth,\n ...userConfig.auth\n };\n\n this.interceptors = {\n ...defaultConfigs.interceptors,\n ...userConfig.interceptors\n };\n }\n\n addDynamicAudience(audienceName, { clientId, host }) {\n if (!clientId || !host) {\n throw new Error(\n 'A dynamic audience must contain `clientId` and `host` properties'\n );\n }\n\n if (this._dynamicAudienceNames.indexOf(audienceName) > -1) {\n throw new Error(\n `A dynamic audience of the name \\`${audienceName}\\` already exists. This problem can be rectified by using a different name for the audience.`\n );\n }\n\n this._dynamicAudienceNames = [...this._dynamicAudienceNames, audienceName];\n\n if (this.audiences[audienceName]) {\n this._replacedAudiences[audienceName] = this.audiences[audienceName];\n }\n\n this.audiences[audienceName] = {\n clientId,\n host\n };\n }\n\n removeDynamicAudience(audienceName) {\n if (this._dynamicAudienceNames.indexOf(audienceName) === -1) {\n throw new Error('There is no dynamic audience to remove.');\n }\n\n this.audiences[audienceName] = this._replacedAudiences[audienceName];\n\n delete this._replacedAudiences[audienceName];\n this._dynamicAudienceNames = this._dynamicAudienceNames.filter(\n (name) => name !== audienceName\n );\n }\n\n /**\n * Parses a custom module configuration for a valid environment/audience. Requires either a\n * clientId and host, or an environment that matches a default audience/environment.\n *\n * @param {CustomAudience} config A custom audience configuration to parse\n * @param {Object.<string, Audience>} audiences An object with keys for environment names and values of Audience information\n *\n * @returns {Audience}\n * @throws {Error}\n *\n * @private\n */\n _getAudienceFromCustomConfig(config, audiences) {\n if (config.clientId && config.host) {\n const audience = {\n clientId: config.clientId,\n host: config.host\n };\n\n if (config.webSocket) {\n audience.webSocket = config.webSocket;\n }\n\n return audience;\n } else if (config.env) {\n return audiences[config.env];\n } else {\n throw new Error(\n 'Custom module configurations must either contain a `host` and `clientId` or specify a specific target environment via the `env` property'\n );\n }\n }\n\n /**\n * Reconciles the main environment with custom environments and external modules.\n *\n * @param {Object} options\n * @param {Object.<string, CustomAudience>} [options.customModuleConfigs = {}] Any custom\n * configurations for internal modules\n * @param {string} [options.env = 'production'] The base environment for any\n * non-overridden modules\n * @param {Object.<string, ExternalModule>} [options.externalModules = {}] An object of external\n * modules from which to build a set of audiences\n *\n * @returns {Object.<string, Audience>}\n *\n * @private\n */\n _getAudiences(options = {}) {\n const {\n customModuleConfigs = {},\n env = 'production',\n externalModules = {}\n } = options;\n\n return {\n ...this._getInternalAudiences({\n customModuleConfigs,\n env,\n audiences: defaultAudiences\n }),\n ...this._getExternalAudiences({ externalModules })\n };\n }\n\n /**\n * Builds up the audiences for external modules.\n *\n * @param {Object}\n * @param {Object.<string, ExternalModule>} externalModules An object of external modules from\n * which to build a set of audiences\n *\n * @returns {Object.<string, Audience>}\n * @throws {Error}\n *\n * @private\n */\n _getExternalAudiences({ externalModules }) {\n return Object.keys(externalModules).reduce((memo, key) => {\n const clientId = externalModules[key].clientId;\n const host = externalModules[key].host;\n const hasClientId = !!clientId || clientId === null;\n const hasHost = !!host || host === null;\n\n if (!(hasClientId && hasHost)) {\n throw new Error(\n 'External modules must contain `clientId` and `host` properties'\n );\n }\n\n memo[key] = {\n clientId,\n host\n };\n\n return memo;\n }, {});\n }\n\n /**\n * Reconciles the main environment with custom environments to build up audiences for\n * internal modules.\n *\n * @param {Object.<string, Environments>} audiences All possible audiences/environments for\n * internal modules\n * @param {Object.<string, CustomAudience>} customModuleConfigs Any custom configurations for\n * internal modules\n * @param {string} env The base environment for any non-overridden modules\n *\n * @returns {Object.<string, Audience>}\n *\n * @private\n */\n _getInternalAudiences({ audiences, customModuleConfigs, env }) {\n return Object.keys(audiences).reduce((memo, key) => {\n const customModuleConfig = customModuleConfigs[key];\n const moduleAudiences = audiences[key];\n\n if (customModuleConfig) {\n memo[key] = this._getAudienceFromCustomConfig(\n customModuleConfig,\n moduleAudiences\n );\n } else {\n memo[key] = moduleAudiences[env];\n }\n\n return memo;\n }, {});\n }\n}\n\nexport default Config;\n"]}
1
+ {"version":3,"sources":["config/index.js"],"names":["Config","userConfig","externalModules","Object","assign","_dynamicAudienceNames","_replacedAudiences","audiences","_getAudiences","customModuleConfigs","auth","env","defaultConfigs","interceptors","audienceName","clientId","host","Error","indexOf","filter","name","config","audience","webSocket","options","_getInternalAudiences","defaultAudiences","_getExternalAudiences","keys","reduce","memo","key","hasClientId","hasHost","customModuleConfig","moduleAudiences","_getAudienceFromCustomConfig"],"mappings":";;;;;;;;;;AAAA;;;;AACA;;;;;;;;;;AAEA;;;;;;;;;;AAUA;;;;;;;;;;;;;AAaA;;;;;;;AAOA;;;;;;;;;;;;;;AAcA;;;;;;;;;;AAUA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA;;;;;IAKMA,M;AACJ;;;;;AAKA,kBAAYC,UAAZ,EAAwBC,eAAxB,EAAyC;AAAA;;AACvCC,WAAOC,MAAP,CAAc,IAAd,EAAoBH,UAApB;;AAEA,SAAKI,qBAAL,GAA6B,EAA7B;AACA,SAAKC,kBAAL,GAA0B,EAA1B;;AAEA,SAAKC,SAAL,GAAiB,KAAKC,aAAL,CAAmB;AAClCN,sCADkC;AAElCO,2BAAqBR,WAAWS,IAAX,CAAgBD,mBAFH;AAGlCE,WAAKV,WAAWS,IAAX,CAAgBC;AAHa,KAAnB,CAAjB;;AAMA,SAAKD,IAAL,gBACKE,mBAAeF,IADpB,EAEKT,WAAWS,IAFhB;;AAKA,SAAKG,YAAL,gBACKD,mBAAeC,YADpB,EAEKZ,WAAWY,YAFhB;AAID;;;;uCAEkBC,Y,QAAkC;AAAA,UAAlBC,QAAkB,QAAlBA,QAAkB;AAAA,UAARC,IAAQ,QAARA,IAAQ;;AACnD,UAAI,CAACD,QAAD,IAAa,CAACC,IAAlB,EAAwB;AACtB,cAAM,IAAIC,KAAJ,CACJ,kEADI,CAAN;AAGD;;AAED,UAAI,KAAKZ,qBAAL,CAA2Ba,OAA3B,CAAmCJ,YAAnC,IAAmD,CA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,aAAOR,OAAOyB,IAAP,CAAYrB,SAAZ,EAAuBsB,MAAvB,CAA8B,UAACC,IAAD,EAAOC,GAAP,EAAe;AAClD,YAAMG,qBAAqBzB,oBAAoBsB,GAApB,CAA3B;AACA,YAAMI,kBAAkB5B,UAAUwB,GAAV,CAAxB;;AAEA,YAAIG,kBAAJ,EAAwB;AACtBJ,eAAKC,GAAL,IAAY,MAAKK,4BAAL,CACVF,kBADU,EAEVC,eAFU,CAAZ;AAID,SALD,MAKO;AACLL,eAAKC,GAAL,IAAYI,gBAAgBxB,GAAhB,CAAZ;AACD;;AAED,eAAOmB,IAAP;AACD,OAdM,EAcJ,EAdI,CAAP;AAeD;;;;;;kBAGY9B,M","file":"index.js","sourcesContent":["import defaultAudiences from './audiences';\nimport defaultConfigs from './defaults';\n\n/**\n * A single audience used for authenticating and communicating with an individual API.\n *\n * @typedef {Object} Audience\n * @param {string} config.clientId Client Id provided by Auth0 for the environment you are\n * trying to communicate with\n * @param {string} config.host Hostname for the API that corresponds with the clientId provided\n * @param {string} [config.webSocket] WebSocket URL for the API that corresponds with the clientId provided\n */\n\n/**\n * A custom audience that will override the configuration of an individual module. Consists of\n * either a reference to an environment that already exists or a clientId and host for a\n * custom environment.\n *\n * @typedef {Object} CustomAudience\n * @param {string} [config.clientId] Client Id provided by Auth0 for the environment you are\n * trying to communicate with\n * @param {string} [config.env] The SDK provided environment name you are trying to reach\n * @param {string} [config.host] Hostname for the API that corresponds with the clientId provided\n * @param {string} [config.webSocket] WebSocket URL for the API that corresponds with the clientId provided\n */\n\n/**\n * An object of audiences that corresponds to all the different environments available for a\n * single module.\n *\n * @typedef {Object.<string, Audience>} Environments\n */\n\n/**\n * An external module to be integrated into the SDK as a first class citizen. Includes information\n * for authenticating and communicating with an individual API and the external module itself.\n *\n * @typedef {Object} ExternalModule\n * @param {string} config.clientId Client Id provided by Auth0 for the environment you are\n * trying to communicate with. Can be a `null` value if the value is not needed. Some SessionType\n * adapters (currently, just the MachineAuth adapter) require a value other than `null` if the\n * built-in `request` module is used since they acquire contxt tokens based on a single clientId.\n * @param {string} config.host Hostname for the API that corresponds with the clientId provided.\n * Can be a `null` value if the value is not needed.\n * @param {function} config.module The module that will be decorated into the SDK\n */\n\n/**\n * An object of interceptors that get called on every request or response.\n * More information at {@link https://github.com/axios/axios#interceptors axios Interceptors}\n *\n * @typedef {Object} AxiosInterceptor\n * @param {function} interceptor.fulfilled A function that is run on every successful request or\n * response\n * @param {function} interceptor.rejected A function that is run on every failed request or response\n */\n\n/**\n * User provided configuration options\n *\n * @typedef {Object} UserConfig\n * @property {Object} auth User assigned configurations specific for their authentication methods\n * @property {string} [auth.authorizationPath] Path Auth0WebAuth process should redirect to after a\n * successful sign in attempt\n * @property {string} auth.clientId Client Id provided by Auth0 for this application\n * @property {string} [auth.clientSecret] Client secret provided by Auth0 for this application. This\n * is optional for the auth0WebAuth SessionType, but required for the machineAuth SessionType\n * @property {string} [auth.domain] Auth0 domain for this application. This is an optional configuration\n * that defaults to the production Auth0 tenant\n * @property {Object.<string, CustomAudience>} [auth.customModuleConfigs] Custom environment setups\n * for individual modules. Requires clientId/host or env\n * @property {string} [auth.env = 'production'] The environment that every module should use for\n * their clientId and host\n * @property {function} [auth.onAuthenticate = (auth0WebAuthSessionInfo) => handleSuccessfulAuth(auth0WebAuthSessionInfo); ] An optional\n * hook for handling a successful authentication request or overriding returned values.\n * @property {function} [auth.onRedirect = (pathname) => { window.location = pathname; }] A redirect\n * method used for navigating through Auth0 callbacks in Web applications\n * @property {number} [auth.tokenExpiresAtBufferMs = 300000] The time (in milliseconds) before a\n * token truly expires that we consider it expired (i.e. the token's expiresAt - this = calculated\n * expiresAt). Defaults to 5 minutes.\n * @property {Object} [interceptors] Axios interceptors that can transform requests and responses.\n * More information at {@link https://github.com/axios/axios#interceptors axios Interceptors}\n * @property {AxiosInterceptor[]} [interceptors.request] Interceptors that act on every request\n * @property {AxiosInterceptor[]} [intercepotrs.response] Intereptors that act on every response\n */\n\n/**\n * Module that merges user assigned configurations with default configurations.\n *\n * @typicalname contxtSdk.config\n */\nclass Config {\n /**\n * @param {UserConfig} userConfig The user provided configuration options\n * @param {Object.<string, ExternalModule>} [externalModules] User provided external modules that should be treated as\n * first class citizens\n */\n constructor(userConfig, externalModules) {\n Object.assign(this, userConfig);\n\n this._dynamicAudienceNames = [];\n this._replacedAudiences = {};\n\n this.audiences = this._getAudiences({\n externalModules,\n customModuleConfigs: userConfig.auth.customModuleConfigs,\n env: userConfig.auth.env\n });\n\n this.auth = {\n ...defaultConfigs.auth,\n ...userConfig.auth\n };\n\n this.interceptors = {\n ...defaultConfigs.interceptors,\n ...userConfig.interceptors\n };\n }\n\n addDynamicAudience(audienceName, { clientId, host }) {\n if (!clientId || !host) {\n throw new Error(\n 'A dynamic audience must contain `clientId` and `host` properties'\n );\n }\n\n if (this._dynamicAudienceNames.indexOf(audienceName) > -1) {\n throw new Error(\n `A dynamic audience of the name \\`${audienceName}\\` already exists. This problem can be rectified by using a different name for the audience.`\n );\n }\n\n this._dynamicAudienceNames = [...this._dynamicAudienceNames, audienceName];\n\n if (this.audiences[audienceName]) {\n this._replacedAudiences[audienceName] = this.audiences[audienceName];\n }\n\n this.audiences[audienceName] = {\n clientId,\n host\n };\n }\n\n removeDynamicAudience(audienceName) {\n if (this._dynamicAudienceNames.indexOf(audienceName) === -1) {\n throw new Error('There is no dynamic audience to remove.');\n }\n\n this.audiences[audienceName] = this._replacedAudiences[audienceName];\n\n delete this._replacedAudiences[audienceName];\n this._dynamicAudienceNames = this._dynamicAudienceNames.filter(\n (name) => name !== audienceName\n );\n }\n\n /**\n * Parses a custom module configuration for a valid environment/audience. Requires either a\n * clientId and host, or an environment that matches a default audience/environment.\n *\n * @param {CustomAudience} config A custom audience configuration to parse\n * @param {Object.<string, Audience>} audiences An object with keys for environment names and values of Audience information\n *\n * @returns {Audience}\n * @throws {Error}\n *\n * @private\n */\n _getAudienceFromCustomConfig(config, audiences) {\n if (config.clientId && config.host) {\n const audience = {\n clientId: config.clientId,\n host: config.host\n };\n\n if (config.webSocket) {\n audience.webSocket = config.webSocket;\n }\n\n return audience;\n } else if (config.env) {\n return audiences[config.env];\n } else {\n throw new Error(\n 'Custom module configurations must either contain a `host` and `clientId` or specify a specific target environment via the `env` property'\n );\n }\n }\n\n /**\n * Reconciles the main environment with custom environments and external modules.\n *\n * @param {Object} options\n * @param {Object.<string, CustomAudience>} [options.customModuleConfigs = {}] Any custom\n * configurations for internal modules\n * @param {string} [options.env = 'production'] The base environment for any\n * non-overridden modules\n * @param {Object.<string, ExternalModule>} [options.externalModules = {}] An object of external\n * modules from which to build a set of audiences\n *\n * @returns {Object.<string, Audience>}\n *\n * @private\n */\n _getAudiences(options = {}) {\n const {\n customModuleConfigs = {},\n env = 'production',\n externalModules = {}\n } = options;\n\n return {\n ...this._getInternalAudiences({\n customModuleConfigs,\n env,\n audiences: defaultAudiences\n }),\n ...this._getExternalAudiences({ externalModules })\n };\n }\n\n /**\n * Builds up the audiences for external modules.\n *\n * @param {Object}\n * @param {Object.<string, ExternalModule>} externalModules An object of external modules from\n * which to build a set of audiences\n *\n * @returns {Object.<string, Audience>}\n * @throws {Error}\n *\n * @private\n */\n _getExternalAudiences({ externalModules }) {\n return Object.keys(externalModules).reduce((memo, key) => {\n const clientId = externalModules[key].clientId;\n const host = externalModules[key].host;\n const hasClientId = !!clientId || clientId === null;\n const hasHost = !!host || host === null;\n\n if (!(hasClientId && hasHost)) {\n throw new Error(\n 'External modules must contain `clientId` and `host` properties'\n );\n }\n\n memo[key] = {\n clientId,\n host\n };\n\n return memo;\n }, {});\n }\n\n /**\n * Reconciles the main environment with custom environments to build up audiences for\n * internal modules.\n *\n * @param {Object.<string, Environments>} audiences All possible audiences/environments for\n * internal modules\n * @param {Object.<string, CustomAudience>} customModuleConfigs Any custom configurations for\n * internal modules\n * @param {string} env The base environment for any non-overridden modules\n *\n * @returns {Object.<string, Audience>}\n *\n * @private\n */\n _getInternalAudiences({ audiences, customModuleConfigs, env }) {\n return Object.keys(audiences).reduce((memo, key) => {\n const customModuleConfig = customModuleConfigs[key];\n const moduleAudiences = audiences[key];\n\n if (customModuleConfig) {\n memo[key] = this._getAudienceFromCustomConfig(\n customModuleConfig,\n moduleAudiences\n );\n } else {\n memo[key] = moduleAudiences[env];\n }\n\n return memo;\n }, {});\n }\n}\n\nexport default Config;\n"]}
@@ -136,12 +136,12 @@ var Roles = function () {
136
136
 
137
137
  }, {
138
138
  key: 'addProjectEnvironment',
139
- value: function addProjectEnvironment(roleId, projectEnvironmentSlug, accessType) {
139
+ value: function addProjectEnvironment(roleId, projectEnvironmentId, accessType) {
140
140
  if (!roleId) {
141
141
  return Promise.reject(new Error('A roleId is required for adding a project environment to a role.'));
142
142
  }
143
143
 
144
- if (!projectEnvironmentSlug) {
144
+ if (!projectEnvironmentId) {
145
145
  return Promise.reject(new Error('A project environment slug is required for adding a project environment to a role.'));
146
146
  }
147
147
 
@@ -149,7 +149,7 @@ var Roles = function () {
149
149
  return Promise.reject(new Error('An accessType of "reader" or "admin" is required for adding a project environment to a role.'));
150
150
  }
151
151
 
152
- return this._request.post(this._baseUrl + '/roles/' + roleId + '/project_environments/' + projectEnvironmentSlug, {
152
+ return this._request.post(this._baseUrl + '/roles/' + roleId + '/project_environments/' + projectEnvironmentId, {
153
153
  access_type: accessType
154
154
  }).then(function (response) {
155
155
  return (0, _objects.toCamelCase)(response);
@@ -346,16 +346,16 @@ var Roles = function () {
346
346
 
347
347
  }, {
348
348
  key: 'removeProjectEnvironment',
349
- value: function removeProjectEnvironment(roleId, projectEnvironmentSlug) {
349
+ value: function removeProjectEnvironment(roleId, projectEnvironmentId) {
350
350
  if (!roleId) {
351
351
  return Promise.reject(new Error('A roleId is required for removing a project environment from a role.'));
352
352
  }
353
353
 
354
- if (!projectEnvironmentSlug) {
354
+ if (!projectEnvironmentId) {
355
355
  return Promise.reject(new Error('A project environment slug is required for removing a project environment from a role.'));
356
356
  }
357
357
 
358
- return this._request.delete(this._baseUrl + '/roles/' + roleId + '/project_environments/' + projectEnvironmentSlug);
358
+ return this._request.delete(this._baseUrl + '/roles/' + roleId + '/project_environments/' + projectEnvironmentId);
359
359
  }
360
360
  }]);
361
361
 
@@ -1 +1 @@
1
- {"version":3,"sources":["coordinator/roles.js"],"names":["Roles","sdk","request","baseUrl","organizationId","_baseUrl","_request","_sdk","_organizationId","roleId","applicationId","Promise","reject","Error","post","then","response","projectEnvironmentSlug","accessType","indexOf","access_type","role","name","description","delete","get","roles"],"mappings":";;;;;;;;AAAA;;;;AAEA;;;;;;;;;;;AAWA;;;;;;;;;AASA;;;;;;;;;AASA;;;;;;;;;;;;;;AAcA;;;;;IAKMA,K;AACJ;;;;;;AAMA,iBAAYC,GAAZ,EAAiBC,OAAjB,EAA0BC,OAA1B,EAA0D;AAAA,QAAvBC,cAAuB,uEAAN,IAAM;;AAAA;;AACxD,SAAKC,QAAL,GAAgBF,OAAhB;AACA,SAAKG,QAAL,GAAgBJ,OAAhB;AACA,SAAKK,IAAL,GAAYN,GAAZ;AACA,SAAKO,eAAL,GAAuBJ,cAAvB;AACD;;AAED;;;;;;;;;;;;;;;;;;;;;;;mCAmBeK,M,EAAQC,a,EAAe;AACpC,UAAI,CAACD,MAAL,EAAa;AACX,eAAOE,QAAQC,MAAR,CACL,IAAIC,KAAJ,CAAU,2DAAV,CADK,CAAP;AAGD;;AAED,UAAI,CAACH,aAAL,EAAoB;AAClB,eAAOC,QAAQC,MAAR,CACL,IAAIC,KAAJ,CACE,mEADF,CADK,CAAP;AAKD;;AAED,aAAO,KAAKP,QAAL,CACJQ,IADI,CACI,KAAKT,QADT,eAC2BI,MAD3B,sBACkDC,aADlD,EAEJK,IAFI,CAEC,UAACC,QAAD;AAAA,eAAc,0BAAYA,QAAZ,CAAd;AAAA,OAFD,CAAP;AAGD;;AAED;;;;;;;;;;;;;;;;;;;;;;;0CAoBsBP,M,EAAQQ,sB,EAAwBC,U,EAAY;AAChE,UAAI,CAACT,MAAL,EAAa;AACX,eAAOE,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CADK,CAAP;AAKD;;AAED,aAAO,KAAKP,QAAL,CACJmB,GADI,CACG,KAAKpB,QADR,uBACkCD,cADlC,aAEJW,IAFI,CAEC,UAACW,KAAD;AAAA,eAAW,0BAAYA,KAAZ,CAAX;AAAA,OAFD,CAAP;AAGD;;AAED;;;;;;;;;;;;;;;;;;;;;sCAkBkBjB,M,EAAQC,a,EAAe;AACvC,UAAI,CAACD,MAAL,EAAa;AACX,eAAOE,QAAQC,MAAR,CACL,IAAIC,KAAJ,CACE,+DADF,CADK,CAAP;AAKD;;AAED,UAAI,CAACH,aAAL,EAAoB;AAClB,eAAOC,QAAQC,MAAR,CACL,IAAIC,KAAJ,CACE,uEADF,CADK,CAAP;AAKD;;AAED,aAAO,KAAKP,QAAL,CAAckB,MAAd,CACF,KAAKnB,QADH,eACqBI,MADrB,sBAC4CC,aAD5C,CAAP;AAGD;;AAED;;;;;;;;;;;;;;;;;;;;;6CAkByBD,M,EAAQQ,sB,EAAwB;AACvD,UAAI,CAACR,MAAL,EAAa;AACX,eAAOE,QAAQC,MAAR,CACL,IAAIC,KAAJ,CACE,sEADF,CADK,CAAP;AAKD;;AAED,UAAI,CAACI,sBAAL,EAA6B;AAC3B,eAAON,QAAQC,MAAR,CACL,IAAIC,KAAJ,CACE,wFADF,CADK,CAAP;AAKD;;AAED,aAAO,KAAKP,QAAL,CAAckB,MAAd,CAEH,KAAKnB,QAFF,eAGKI,MAHL,8BAGoCQ,sBAHpC,CAAP;AAKD;;;;;;kBAGYjB,K","file":"roles.js","sourcesContent":["import { toSnakeCase, toCamelCase } from '../utils/objects';\n\n/**\n * @typedef {Object} ContxtRole\n * @property {ContxtApplication[]} applications\n * @property {string} createdAt ISO 8601 Extended Format date/time string\n * @property {string} description\n * @property {string} id\n * @property {string} name\n * @property {string} organizationId\n * @property {ContxtProjectEnvironment[]} projectEnvironments\n * @property {string} updatedAt ISO 8601 Extended Format date/time string\n */\n/**\n * @typedef {Object} ContxtRoleApplication\n * @property {number} applicationId\n * @property {string} createdAt ISO 8601 Extended Format date/time string\n * @property {number} id\n * @property {string} roleId\n * @property {string} updatedAt ISO 8601 Extended Format date/time string\n */\n\n/**\n * @typedef {Object} ContxtRoleProjectEnvironment\n * @property {string} accessType Access Type of the user for this project with options \"reader\", \"admin\"\n * @property {string} createdAt ISO 8601 Extended Format date/time string\n * @property {string} userId\n * @property {string} environmentId\n * @property {string} updatedAt ISO 8601 Extended Format date/time string\n */\n\n/**\n * @typedef {Object} ContxtProjectEnvironment\n * @property {string} createdAt ISO 8601 Extended Format date/time string\n * @property {string} updatedAt ISO 8601 Extended Format date/time string\n * @property {string} id\n * @property {string} organizationId\n * @property {number} projectId\n * @property {string} clusterId\n * @property {string} slug\n * @property {string} name\n * @property {string} type\n * @property {string} description\n */\n\n/**\n * Module that provides access to contxt roles\n *\n * @typicalname contxtSdk.coordinator.roles\n */\nclass Roles {\n /**\n * @param {Object} sdk An instance of the SDK so the module can communicate with other modules\n * @param {Object} request An instance of the request module tied to this module's audience.\n * @param {string} baseUrl The base URL provided by the parent module\n * @param {string} [organizationId] The organization ID to be used in tenant url requests\n */\n constructor(sdk, request, baseUrl, organizationId = null) {\n this._baseUrl = baseUrl;\n this._request = request;\n this._sdk = sdk;\n this._organizationId = organizationId;\n }\n\n /**\n * Add an application to a role\n *\n * API Endpoint: '/roles/:roleId/applications/:applicationId'\n * Method: POST\n *\n * @param {string} roleId The UUID formatted ID of the role\n * @param {number} applicationId The ID of the application\n *\n * @returns {Promise}\n * @fulfill {ContxtRoleApplication}\n * @reject {Error}\n *\n * @example\n * contxtSdk.roles\n * .addApplication('36b8421a-cc4a-4204-b839-1397374fb16b', 42)\n * .then((roleApplication) => console.log(roleApplication))\n * .catch((err) => console.log(err));\n */\n addApplication(roleId, applicationId) {\n if (!roleId) {\n return Promise.reject(\n new Error('A roleId is required for adding an application to a role.')\n );\n }\n\n if (!applicationId) {\n return Promise.reject(\n new Error(\n 'An applicationId is required for adding an application to a role.'\n )\n );\n }\n\n return this._request\n .post(`${this._baseUrl}/roles/${roleId}/applications/${applicationId}`)\n .then((response) => toCamelCase(response));\n }\n\n /**\n * Add a project environment to a role\n *\n * API Endpoint: 'roles/:roleId/project_environments/:projectEnvironmentSlug'\n * Method: POST\n *\n * @param {string} roleId The UUID formatted ID of the role\n * @param {string} projectEnvironmentSlug The slug of the project environment\n * @param {'reader' | 'admin'} accessType The level of access for the role\n *\n * @returns {Promise}\n * @fulfill {ContxtRoleProjectEnvironment}\n * @reject {Error}\n *\n * @example\n * contxtSdk.roles\n * .addProjectEnvironment('36b8421a-cc4a-4204-b839-1397374fb16b', 'project-environment-slug', 'admin')\n * .then((roleProject) => console.log(roleProject))\n * .catch((err) => console.log(err));\n */\n addProjectEnvironment(roleId, projectEnvironmentSlug, accessType) {\n if (!roleId) {\n return Promise.reject(\n new Error(\n 'A roleId is required for adding a project environment to a role.'\n )\n );\n }\n\n if (!projectEnvironmentSlug) {\n return Promise.reject(\n new Error(\n 'A project environment slug is required for adding a project environment to a role.'\n )\n );\n }\n\n if (['reader', 'admin'].indexOf(accessType) === -1) {\n return Promise.reject(\n new Error(\n 'An accessType of \"reader\" or \"admin\" is required for adding a project environment to a role.'\n )\n );\n }\n\n return this._request\n .post(\n `${\n this._baseUrl\n }/roles/${roleId}/project_environments/${projectEnvironmentSlug}`,\n {\n access_type: accessType\n }\n )\n .then((response) => toCamelCase(response));\n }\n\n /**\n * Create a new role for an organization\n *\n * @param {string} organizationId The ID of the organization, optional when using the tenant API and an organization ID has been set\n * @param {Object} role\n * @param {string} role.name The name of the new role\n * @param {string} role.description Some text describing the purpose of the role\n *\n * @returns {Promise}\n * @fulfill {ContxtRole} The newly created role\n * @reject {Error}\n *\n * @example\n * contxtSdk.coordinator.roles\n * .create('36b8421a-cc4a-4204-b839-1397374fb16b', {\n * name: 'view-myapp',\n * description: 'Give this role for viewing myapp'\n * })\n * .then((role) => console.log(role))\n * .catch((err) => console.log(err));\n */\n create(organizationId, role = {}) {\n if (this._organizationId) {\n if (!role.name) {\n return Promise.reject(\n new Error(`A name is required to create a new role.`)\n );\n }\n\n if (!role.description) {\n return Promise.reject(\n new Error(`A description is required to create a new role.`)\n );\n }\n\n return this._request\n .post(`${this._baseUrl}/roles`, toSnakeCase(role))\n .then((response) => toCamelCase(response));\n }\n\n if (!organizationId) {\n return Promise.reject(\n new Error(\n 'An organizationId is required for creating roles for an organization.'\n )\n );\n }\n\n if (!role.name) {\n return Promise.reject(\n new Error(`A name is required to create a new role.`)\n );\n }\n\n if (!role.description) {\n return Promise.reject(\n new Error(`A description is required to create a new role.`)\n );\n }\n\n return this._request\n .post(\n `${this._baseUrl}/organizations/${organizationId}/roles`,\n toSnakeCase(role)\n )\n .then((response) => toCamelCase(response));\n }\n\n /**\n * Deletes a role from an organization\n *\n * Legacy API Endpoint: '/organizations/:organizationId/roles/:roleId'\n * API Endpiont: '/roles/:roleId'\n * Method: DELETE\n *\n * @param {string} organizationId The ID of the organization, optional when using the tenant API and an organization ID has been set\n * @param {string} roleId The UUID formatted ID of the role\n *\n * @returns {Promise}\n * @fulfill {undefined}\n * @reject {Error}\n *\n * @example\n * contxtSdk.roles.delete('4f0e51c6-728b-4892-9863-6d002e61204d', '8b64fb12-e649-46be-b330-e672d28eed99s');\n */\n delete(organizationId, roleId) {\n if (this._organizationId) {\n if (!roleId) {\n return Promise.reject(\n new Error('A roleId is required for deleting a role.')\n );\n }\n\n return this._request.delete(`${this._baseUrl}/roles/${roleId}`);\n }\n\n if (!organizationId) {\n return Promise.reject(\n new Error('An organizationId is required for deleting a role.')\n );\n }\n\n if (!roleId) {\n return Promise.reject(\n new Error('A roleId is required for deleting a role.')\n );\n }\n\n return this._request.delete(\n `${this._baseUrl}/organizations/${organizationId}/roles/${roleId}`\n );\n }\n\n /**\n * Gets an organization's list of roles\n *\n * Legacy API Endpoint: '/organizations/:organizationId/roles'\n * API Endpoint: '/roles'\n * Method: GET\n *\n * @param {string} organizationId The ID of the organization, optional when using the tenant API and an organization ID has been set\n *\n * @returns {Promise}\n * @fulfill {ContxtRole[]} A list of roles\n * @reject {Error}\n *\n * @example\n * contxtSdk.coordinator.roles\n * .getByOrganizationId('36b8421a-cc4a-4204-b839-1397374fb16b')\n * .then((roles) => console.log(roles))\n * .catch((err) => console.log(err));\n */\n getByOrganizationId(organizationId) {\n if (this._organizationId) {\n return this._request\n .get(`${this._baseUrl}/roles`)\n .then((roles) => toCamelCase(roles));\n }\n\n if (!organizationId) {\n return Promise.reject(\n new Error(\n 'An organizationId is required for getting roles for an organization.'\n )\n );\n }\n\n return this._request\n .get(`${this._baseUrl}/organizations/${organizationId}/roles`)\n .then((roles) => toCamelCase(roles));\n }\n\n /**\n * Remove an application from a role\n *\n * API Endpoint: '/roles/:roleId/applications/:applicationId'\n * Method: DELETE\n *\n * @param {string} roleId The UUID formatted ID of the role\n * @param {number} applicationId The ID of the application\n *\n * @returns {Promise}\n * @fulfill {undefined}\n * @reject {Error}\n *\n * @example\n * contxtSdk.roles\n * .removeApplication('36b8421a-cc4a-4204-b839-1397374fb16b', 42)\n * .catch((err) => console.log(err));\n */\n removeApplication(roleId, applicationId) {\n if (!roleId) {\n return Promise.reject(\n new Error(\n 'A roleId is required for removing an application from a role.'\n )\n );\n }\n\n if (!applicationId) {\n return Promise.reject(\n new Error(\n 'An applicationId is required for removing an application from a role.'\n )\n );\n }\n\n return this._request.delete(\n `${this._baseUrl}/roles/${roleId}/applications/${applicationId}`\n );\n }\n\n /**\n * Remove a project environment from a role\n *\n * API Endpoint: 'roles/:roleId/project_environments/:projectEnvironmentSlug'\n * Method: DELETE\n *\n * @param {string} roleId The UUID formatted ID of the role\n * @param {string} projectEnvironmentSlug The slug of the project environment\n *\n * @returns {Promise}\n * @fulfill {undefined}\n * @reject {Error}\n *\n * @example\n * contxtSdk.roles\n * .removeProjectEnvironment('36b8421a-cc4a-4204-b839-1397374fb16b', 'project-environment-slug')\n * .catch((err) => console.log(err));\n */\n removeProjectEnvironment(roleId, projectEnvironmentSlug) {\n if (!roleId) {\n return Promise.reject(\n new Error(\n 'A roleId is required for removing a project environment from a role.'\n )\n );\n }\n\n if (!projectEnvironmentSlug) {\n return Promise.reject(\n new Error(\n 'A project environment slug is required for removing a project environment from a role.'\n )\n );\n }\n\n return this._request.delete(\n `${\n this._baseUrl\n }/roles/${roleId}/project_environments/${projectEnvironmentSlug}`\n );\n }\n}\n\nexport default Roles;\n"]}
1
+ {"version":3,"sources":["coordinator/roles.js"],"names":["Roles","sdk","request","baseUrl","organizationId","_baseUrl","_request","_sdk","_organizationId","roleId","applicationId","Promise","reject","Error","post","then","response","projectEnvironmentId","accessType","indexOf","access_type","role","name","description","delete","get","roles"],"mappings":";;;;;;;;AAAA;;;;AAEA;;;;;;;;;;;AAWA;;;;;;;;;AASA;;;;;;;;;AASA;;;;;;;;;;;;;;AAcA;;;;;IAKMA,K;AACJ;;;;;;AAMA,iBAAYC,GAAZ,EAAiBC,OAAjB,EAA0BC,OAA1B,EAA0D;AAAA,QAAvBC,cAAuB,uEAAN,IAAM;;AAAA;;AACxD,SAAKC,QAAL,GAAgBF,OAAhB;AACA,SAAKG,QAAL,GAAgBJ,OAAhB;AACA,SAAKK,IAAL,GAAYN,GAAZ;AACA,SAAKO,eAAL,GAAuBJ,cAAvB;AACD;;AAED;;;;;;;;;;;;;;;;;;;;;;;mCAmBeK,M,EAAQC,a,EAAe;AACpC,UAAI,CAACD,MAAL,EAAa;AACX,eAAOE,QAAQC,MAAR,CACL,IAAIC,KAAJ,CAAU,2DAAV,CADK,CAAP;AAGD;;AAED,UAAI,CAACH,aAAL,EAAoB;AAClB,eAAOC,QAAQC,MAAR,CACL,IAAIC,KAAJ,CACE,mEADF,CADK,CAAP;AAKD;;AAED,aAAO,KAAKP,QAAL,CACJQ,IADI,CACI,KAAKT,QADT,eAC2BI,MAD3B,sBACkDC,aADlD,EAEJK,IAFI,CAEC,UAACC,QAAD;AAAA,eAAc,0BAAYA,QAAZ,CAAd;AAAA,OAFD,CAAP;AAGD;;AAED;;;;;;;;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,CAAP;AAGD;;AAED,UAAI,CAACtB,cAAL,EAAqB;AACnB,eAAOO,QAAQC,MAAR,CACL,IAAIC,KAAJ,CACE,sEADF,CADK,CAAP;AAKD;;AAED,aAAO,KAAKP,QAAL,CACJmB,GADI,CACG,KAAKpB,QADR,uBACkCD,cADlC,aAEJW,IAFI,CAEC,UAACW,KAAD;AAAA,eAAW,0BAAYA,KAAZ,CAAX;AAAA,OAFD,CAAP;AAGD;;AAED;;;;;;;;;;;;;;;;;;;;;sCAkBkBjB,M,EAAQC,a,EAAe;AACvC,UAAI,CAACD,MAAL,EAAa;AACX,eAAOE,QAAQC,MAAR,CACL,IAAIC,KAAJ,CACE,+DADF,CADK,CAAP;AAKD;;AAED,UAAI,CAACH,aAAL,EAAoB;AAClB,eAAOC,QAAQC,MAAR,CACL,IAAIC,KAAJ,CACE,uEADF,CADK,CAAP;AAKD;;AAED,aAAO,KAAKP,QAAL,CAAckB,MAAd,CACF,KAAKnB,QADH,eACqBI,MADrB,sBAC4CC,aAD5C,CAAP;AAGD;;AAED;;;;;;;;;;;;;;;;;;;;;6CAkByBD,M,EAAQQ,oB,EAAsB;AACrD,UAAI,CAACR,MAAL,EAAa;AACX,eAAOE,QAAQC,MAAR,CACL,IAAIC,KAAJ,CACE,sEADF,CADK,CAAP;AAKD;;AAED,UAAI,CAACI,oBAAL,EAA2B;AACzB,eAAON,QAAQC,MAAR,CACL,IAAIC,KAAJ,CACE,wFADF,CADK,CAAP;AAKD;;AAED,aAAO,KAAKP,QAAL,CAAckB,MAAd,CAEH,KAAKnB,QAFF,eAGKI,MAHL,8BAGoCQ,oBAHpC,CAAP;AAKD;;;;;;kBAGYjB,K","file":"roles.js","sourcesContent":["import { toSnakeCase, toCamelCase } from '../utils/objects';\n\n/**\n * @typedef {Object} ContxtRole\n * @property {ContxtApplication[]} applications\n * @property {string} createdAt ISO 8601 Extended Format date/time string\n * @property {string} description\n * @property {string} id\n * @property {string} name\n * @property {string} organizationId\n * @property {ContxtProjectEnvironment[]} projectEnvironments\n * @property {string} updatedAt ISO 8601 Extended Format date/time string\n */\n/**\n * @typedef {Object} ContxtRoleApplication\n * @property {number} applicationId\n * @property {string} createdAt ISO 8601 Extended Format date/time string\n * @property {number} id\n * @property {string} roleId\n * @property {string} updatedAt ISO 8601 Extended Format date/time string\n */\n\n/**\n * @typedef {Object} ContxtRoleProjectEnvironment\n * @property {string} accessType Access Type of the user for this project with options \"reader\", \"admin\"\n * @property {string} createdAt ISO 8601 Extended Format date/time string\n * @property {string} userId\n * @property {string} environmentId\n * @property {string} updatedAt ISO 8601 Extended Format date/time string\n */\n\n/**\n * @typedef {Object} ContxtProjectEnvironment\n * @property {string} createdAt ISO 8601 Extended Format date/time string\n * @property {string} updatedAt ISO 8601 Extended Format date/time string\n * @property {string} id\n * @property {string} organizationId\n * @property {number} projectId\n * @property {string} clusterId\n * @property {string} slug\n * @property {string} name\n * @property {string} type\n * @property {string} description\n */\n\n/**\n * Module that provides access to contxt roles\n *\n * @typicalname contxtSdk.coordinator.roles\n */\nclass Roles {\n /**\n * @param {Object} sdk An instance of the SDK so the module can communicate with other modules\n * @param {Object} request An instance of the request module tied to this module's audience.\n * @param {string} baseUrl The base URL provided by the parent module\n * @param {string} [organizationId] The organization ID to be used in tenant url requests\n */\n constructor(sdk, request, baseUrl, organizationId = null) {\n this._baseUrl = baseUrl;\n this._request = request;\n this._sdk = sdk;\n this._organizationId = organizationId;\n }\n\n /**\n * Add an application to a role\n *\n * API Endpoint: '/roles/:roleId/applications/:applicationId'\n * Method: POST\n *\n * @param {string} roleId The UUID formatted ID of the role\n * @param {number} applicationId The ID of the application\n *\n * @returns {Promise}\n * @fulfill {ContxtRoleApplication}\n * @reject {Error}\n *\n * @example\n * contxtSdk.roles\n * .addApplication('36b8421a-cc4a-4204-b839-1397374fb16b', 42)\n * .then((roleApplication) => console.log(roleApplication))\n * .catch((err) => console.log(err));\n */\n addApplication(roleId, applicationId) {\n if (!roleId) {\n return Promise.reject(\n new Error('A roleId is required for adding an application to a role.')\n );\n }\n\n if (!applicationId) {\n return Promise.reject(\n new Error(\n 'An applicationId is required for adding an application to a role.'\n )\n );\n }\n\n return this._request\n .post(`${this._baseUrl}/roles/${roleId}/applications/${applicationId}`)\n .then((response) => toCamelCase(response));\n }\n\n /**\n * Add a project environment to a role\n *\n * API Endpoint: 'roles/:roleId/project_environments/:projectEnvironmentSlug'\n * Method: POST\n *\n * @param {string} roleId The UUID formatted ID of the role\n * @param {string} projectEnvironmentSlug The slug of the project environment\n * @param {'reader' | 'admin'} accessType The level of access for the role\n *\n * @returns {Promise}\n * @fulfill {ContxtRoleProjectEnvironment}\n * @reject {Error}\n *\n * @example\n * contxtSdk.roles\n * .addProjectEnvironment('36b8421a-cc4a-4204-b839-1397374fb16b', 'project-environment-slug', 'admin')\n * .then((roleProject) => console.log(roleProject))\n * .catch((err) => console.log(err));\n */\n addProjectEnvironment(roleId, projectEnvironmentId, accessType) {\n if (!roleId) {\n return Promise.reject(\n new Error(\n 'A roleId is required for adding a project environment to a role.'\n )\n );\n }\n\n if (!projectEnvironmentId) {\n return Promise.reject(\n new Error(\n 'A project environment slug is required for adding a project environment to a role.'\n )\n );\n }\n\n if (['reader', 'admin'].indexOf(accessType) === -1) {\n return Promise.reject(\n new Error(\n 'An accessType of \"reader\" or \"admin\" is required for adding a project environment to a role.'\n )\n );\n }\n\n return this._request\n .post(\n `${\n this._baseUrl\n }/roles/${roleId}/project_environments/${projectEnvironmentId}`,\n {\n access_type: accessType\n }\n )\n .then((response) => toCamelCase(response));\n }\n\n /**\n * Create a new role for an organization\n *\n * @param {string} organizationId The ID of the organization, optional when using the tenant API and an organization ID has been set\n * @param {Object} role\n * @param {string} role.name The name of the new role\n * @param {string} role.description Some text describing the purpose of the role\n *\n * @returns {Promise}\n * @fulfill {ContxtRole} The newly created role\n * @reject {Error}\n *\n * @example\n * contxtSdk.coordinator.roles\n * .create('36b8421a-cc4a-4204-b839-1397374fb16b', {\n * name: 'view-myapp',\n * description: 'Give this role for viewing myapp'\n * })\n * .then((role) => console.log(role))\n * .catch((err) => console.log(err));\n */\n create(organizationId, role = {}) {\n if (this._organizationId) {\n if (!role.name) {\n return Promise.reject(\n new Error(`A name is required to create a new role.`)\n );\n }\n\n if (!role.description) {\n return Promise.reject(\n new Error(`A description is required to create a new role.`)\n );\n }\n\n return this._request\n .post(`${this._baseUrl}/roles`, toSnakeCase(role))\n .then((response) => toCamelCase(response));\n }\n\n if (!organizationId) {\n return Promise.reject(\n new Error(\n 'An organizationId is required for creating roles for an organization.'\n )\n );\n }\n\n if (!role.name) {\n return Promise.reject(\n new Error(`A name is required to create a new role.`)\n );\n }\n\n if (!role.description) {\n return Promise.reject(\n new Error(`A description is required to create a new role.`)\n );\n }\n\n return this._request\n .post(\n `${this._baseUrl}/organizations/${organizationId}/roles`,\n toSnakeCase(role)\n )\n .then((response) => toCamelCase(response));\n }\n\n /**\n * Deletes a role from an organization\n *\n * Legacy API Endpoint: '/organizations/:organizationId/roles/:roleId'\n * API Endpiont: '/roles/:roleId'\n * Method: DELETE\n *\n * @param {string} organizationId The ID of the organization, optional when using the tenant API and an organization ID has been set\n * @param {string} roleId The UUID formatted ID of the role\n *\n * @returns {Promise}\n * @fulfill {undefined}\n * @reject {Error}\n *\n * @example\n * contxtSdk.roles.delete('4f0e51c6-728b-4892-9863-6d002e61204d', '8b64fb12-e649-46be-b330-e672d28eed99s');\n */\n delete(organizationId, roleId) {\n if (this._organizationId) {\n if (!roleId) {\n return Promise.reject(\n new Error('A roleId is required for deleting a role.')\n );\n }\n\n return this._request.delete(`${this._baseUrl}/roles/${roleId}`);\n }\n\n if (!organizationId) {\n return Promise.reject(\n new Error('An organizationId is required for deleting a role.')\n );\n }\n\n if (!roleId) {\n return Promise.reject(\n new Error('A roleId is required for deleting a role.')\n );\n }\n\n return this._request.delete(\n `${this._baseUrl}/organizations/${organizationId}/roles/${roleId}`\n );\n }\n\n /**\n * Gets an organization's list of roles\n *\n * Legacy API Endpoint: '/organizations/:organizationId/roles'\n * API Endpoint: '/roles'\n * Method: GET\n *\n * @param {string} organizationId The ID of the organization, optional when using the tenant API and an organization ID has been set\n *\n * @returns {Promise}\n * @fulfill {ContxtRole[]} A list of roles\n * @reject {Error}\n *\n * @example\n * contxtSdk.coordinator.roles\n * .getByOrganizationId('36b8421a-cc4a-4204-b839-1397374fb16b')\n * .then((roles) => console.log(roles))\n * .catch((err) => console.log(err));\n */\n getByOrganizationId(organizationId) {\n if (this._organizationId) {\n return this._request\n .get(`${this._baseUrl}/roles`)\n .then((roles) => toCamelCase(roles));\n }\n\n if (!organizationId) {\n return Promise.reject(\n new Error(\n 'An organizationId is required for getting roles for an organization.'\n )\n );\n }\n\n return this._request\n .get(`${this._baseUrl}/organizations/${organizationId}/roles`)\n .then((roles) => toCamelCase(roles));\n }\n\n /**\n * Remove an application from a role\n *\n * API Endpoint: '/roles/:roleId/applications/:applicationId'\n * Method: DELETE\n *\n * @param {string} roleId The UUID formatted ID of the role\n * @param {number} applicationId The ID of the application\n *\n * @returns {Promise}\n * @fulfill {undefined}\n * @reject {Error}\n *\n * @example\n * contxtSdk.roles\n * .removeApplication('36b8421a-cc4a-4204-b839-1397374fb16b', 42)\n * .catch((err) => console.log(err));\n */\n removeApplication(roleId, applicationId) {\n if (!roleId) {\n return Promise.reject(\n new Error(\n 'A roleId is required for removing an application from a role.'\n )\n );\n }\n\n if (!applicationId) {\n return Promise.reject(\n new Error(\n 'An applicationId is required for removing an application from a role.'\n )\n );\n }\n\n return this._request.delete(\n `${this._baseUrl}/roles/${roleId}/applications/${applicationId}`\n );\n }\n\n /**\n * Remove a project environment from a role\n *\n * API Endpoint: 'roles/:roleId/project_environments/:projectEnvironmentSlug'\n * Method: DELETE\n *\n * @param {string} roleId The UUID formatted ID of the role\n * @param {string} projectEnvironmentSlug The slug of the project environment\n *\n * @returns {Promise}\n * @fulfill {undefined}\n * @reject {Error}\n *\n * @example\n * contxtSdk.roles\n * .removeProjectEnvironment('36b8421a-cc4a-4204-b839-1397374fb16b', 'project-environment-slug')\n * .catch((err) => console.log(err));\n */\n removeProjectEnvironment(roleId, projectEnvironmentId) {\n if (!roleId) {\n return Promise.reject(\n new Error(\n 'A roleId is required for removing a project environment from a role.'\n )\n );\n }\n\n if (!projectEnvironmentId) {\n return Promise.reject(\n new Error(\n 'A project environment slug is required for removing a project environment from a role.'\n )\n );\n }\n\n return this._request.delete(\n `${\n this._baseUrl\n }/roles/${roleId}/project_environments/${projectEnvironmentId}`\n );\n }\n}\n\nexport default Roles;\n"]}
@@ -249,12 +249,12 @@ var Users = function () {
249
249
 
250
250
  }, {
251
251
  key: 'addProjectEnvironment',
252
- value: function addProjectEnvironment(userId, projectEnvironmentSlug, accessType) {
252
+ value: function addProjectEnvironment(userId, projectEnvironmentId, accessType) {
253
253
  if (!userId) {
254
254
  return Promise.reject(new Error('A user ID is required for adding a project environment to a user'));
255
255
  }
256
256
 
257
- if (!projectEnvironmentSlug) {
257
+ if (!projectEnvironmentId) {
258
258
  return Promise.reject(new Error('A project environment slug is required for adding a project environment to a user.'));
259
259
  }
260
260
 
@@ -262,7 +262,7 @@ var Users = function () {
262
262
  return Promise.reject(new Error('An access type of "reader" or "admin" is required for adding a project environment to a user'));
263
263
  }
264
264
 
265
- return this._request.post(this._getBaseUrl() + '/users/' + userId + '/project_environments/' + projectEnvironmentSlug, {
265
+ return this._request.post(this._getBaseUrl() + '/users/' + userId + '/project_environments/' + projectEnvironmentId, {
266
266
  access_type: accessType
267
267
  }).then(function (response) {
268
268
  return (0, _objects.toCamelCase)(response);
@@ -543,16 +543,16 @@ var Users = function () {
543
543
 
544
544
  }, {
545
545
  key: 'removeProjectEnvironment',
546
- value: function removeProjectEnvironment(userId, projectEnvironmentSlug) {
546
+ value: function removeProjectEnvironment(userId, projectEnvironmentId) {
547
547
  if (!userId) {
548
548
  return Promise.reject(new Error('A user ID is required for removing a project environment from a user'));
549
549
  }
550
550
 
551
- if (!projectEnvironmentSlug) {
551
+ if (!projectEnvironmentId) {
552
552
  return Promise.reject(new Error('A project environment slug is required for removing a project environment from a user.'));
553
553
  }
554
554
 
555
- return this._request.delete(this._getBaseUrl() + '/users/' + userId + '/project_environments/' + projectEnvironmentSlug);
555
+ return this._request.delete(this._getBaseUrl() + '/users/' + userId + '/project_environments/' + projectEnvironmentId);
556
556
  }
557
557
 
558
558
  /**