@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.
- package/.envrc +0 -0
- package/.nvmrc +1 -1
- package/CHANGELOG.md +19 -1
- package/README.md +2 -12
- package/docs/Typedefs.md +1 -0
- package/esm/config/audiences.js +4 -4
- package/esm/config/audiences.js.map +1 -1
- package/esm/config/defaults.js +1 -0
- package/esm/config/defaults.js.map +1 -1
- package/esm/config/index.js +2 -0
- package/esm/config/index.js.map +1 -1
- package/esm/coordinator/roles.js +6 -6
- package/esm/coordinator/roles.js.map +1 -1
- package/esm/coordinator/users.js +6 -6
- package/esm/coordinator/users.js.map +1 -1
- package/esm/sessionTypes/auth0WebAuth.js +1 -1
- package/esm/sessionTypes/auth0WebAuth.js.map +1 -1
- package/esm/sessionTypes/passwordGrantAuth.js +1 -1
- package/esm/sessionTypes/passwordGrantAuth.js.map +1 -1
- package/lib/config/audiences.js +4 -4
- package/lib/config/audiences.js.map +1 -1
- package/lib/config/defaults.js +1 -0
- package/lib/config/defaults.js.map +1 -1
- package/lib/config/index.js +2 -0
- package/lib/config/index.js.map +1 -1
- package/lib/coordinator/roles.js +6 -6
- package/lib/coordinator/roles.js.map +1 -1
- package/lib/coordinator/users.js +6 -6
- package/lib/coordinator/users.js.map +1 -1
- package/lib/sessionTypes/auth0WebAuth.js +1 -1
- package/lib/sessionTypes/auth0WebAuth.js.map +1 -1
- package/lib/sessionTypes/passwordGrantAuth.js +1 -1
- package/lib/sessionTypes/passwordGrantAuth.js.map +1 -1
- package/package.json +5 -2
- package/src/config/audiences.js +4 -4
- package/src/config/defaults.js +1 -0
- package/src/config/index.js +2 -0
- package/src/coordinator/roles.js +6 -6
- package/src/coordinator/roles.spec.js +8 -8
- package/src/coordinator/users.js +6 -6
- package/src/coordinator/users.spec.js +8 -8
- package/src/sessionTypes/auth0WebAuth.js +1 -1
- package/src/sessionTypes/auth0WebAuth.spec.js +17 -1
- package/src/sessionTypes/passwordGrantAuth.js +1 -1
- package/src/sessionTypes/passwordGrantAuth.spec.js +2 -1
- package/tmp/package.json +11 -0
- package/.idea/codeStyles/Project.xml +0 -49
- package/.idea/codeStyles/codeStyleConfig.xml +0 -5
- package/.idea/contxt-sdk-js.iml +0 -15
- package/.idea/inspectionProfiles/Project_Default.xml +0 -7
- package/.idea/inspectionProfiles/profiles_settings.xml +0 -6
- package/.idea/misc.xml +0 -4
- package/.idea/modules.xml +0 -9
- package/.idea/vcs.xml +0 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["coordinator/users.js"],"names":["Users","sdk","request","baseUrl","tenantBaseUrl","legacyBaseUrl","organizationId","_baseUrl","_tenantBaseUrl","_legacyBaseUrl","_request","_sdk","_organizationId","type","userId","user","Promise","reject","Error","requiredFields","i","length","field","axios","post","_getBaseUrl","applicationId","then","response","roleId","projectEnvironmentSlug","accessType","indexOf","access_type","get","orgUsers","delete"],"mappings":";;;;;;;;AAAA;;;;AAEA;;;;;;AAEA;;;;;;;;;;;;;AAaA;;;;;;;;;AASA;;;;;;;;;;AAUA;;;;;;;;;;AAUA;;;;;IAKMA,K;AACJ;;;;;;;;AAQA,iBACEC,GADF,EAEEC,OAFF,EAGEC,OAHF,EAOE;AAAA,QAHAC,aAGA,uEAHgB,IAGhB;AAAA,QAFAC,aAEA,uEAFgB,IAEhB;AAAA,QADAC,cACA,uEADiB,IACjB;;AAAA;;AACA,SAAKC,QAAL,GAAgBJ,OAAhB;AACA,SAAKK,cAAL,GAAsBJ,aAAtB;AACA,SAAKK,cAAL,GAAsBJ,aAAtB;AACA,SAAKK,QAAL,GAAgBR,OAAhB;AACA,SAAKS,IAAL,GAAYV,GAAZ;AACA,SAAKW,eAAL,GAAuBN,cAAvB;AACD;;;;gCAEWO,I,EAAM;AAChB,cAAQA,IAAR;AACE,aAAK,QAAL;AACE,iBAAO,KAAKJ,cAAL,IAAuB,KAAKF,QAAnC;;AAEF,aAA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,QAAL,CAAc0B,MAAd,CACF,KAAKX,WAAL,EADE,eAC0BX,MAD1B,8BACyDgB,sBADzD,CAAP;AAGD;;AAED;;;;;;;;;;;;;;;;;;;;yBAiBKhB,M,EAAQ;AACX,UAAI,CAACA,MAAL,EAAa;AACX,eAAOE,QAAQC,MAAR,CACL,IAAIC,KAAJ,CAAU,oDAAV,CADK,CAAP;AAGD;;AAED,aAAO,KAAKR,QAAL,CAAcwB,GAAd,CACF,KAAKT,WAAL,CAAiB,QAAjB,CADE,eACkCX,MADlC,WAAP;AAGD;;;;;;kBAGYd,K","file":"users.js","sourcesContent":["import axios from 'axios';\n\nimport { toCamelCase, toSnakeCase } from '../utils/objects';\n\n/**\n * @typedef {Object} ContxtUser\n * @property {string} createdAt ISO 8601 Extended Format date/time string\n * @property {string} email\n * @property {string} firstName\n * @property {string} id\n * @property {boolean} isActivated\n * @property {boolean} isSuperuser\n * @property {string} lastName\n * @property {string} [phoneNumber]\n * @property {string} updatedAt ISO 8601 Extended Format date/time string\n */\n\n/**\n * @typedef {Object} ContxtUserApplication\n * @property {string} applicationId\n * @property {string} createdAt ISO 8601 Extended Format date/time string\n * @property {string} id\n * @property {string} userId\n * @property {string} updatedAt ISO 8601 Extended Format date/time string\n */\n\n/**\n * @typedef {Object} ContxtUserRole\n * @property {string} createdAt ISO 8601 Extended Format date/time string\n * @property {string} id\n * @property {boolean} mappedFromExternalGroup\n * @property {string} userId\n * @property {string} roleId\n * @property {string} updatedAt ISO 8601 Extended Format date/time string\n */\n\n/**\n * @typedef {Object} ContxtUserProjectEnvironment\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} id\n * @property {string} userId\n * @property {string} projectEnvironmentId\n * @property {string} updatedAt ISO 8601 Extended Format date/time string\n */\n\n/**\n * Module that provides access to contxt users\n *\n * @typicalname contxtSdk.coordinator.users\n */\nclass Users {\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} [tenantBaseUrl] The tenant base URL provided by the parent module\n * @param {string} [legacyBaseUrl] The legacy base URL provided by the parent module\n * @param {string} [organizationId] The organization ID to be used in tenant url requests\n */\n constructor(\n sdk,\n request,\n baseUrl,\n tenantBaseUrl = null,\n legacyBaseUrl = null,\n organizationId = null\n ) {\n this._baseUrl = baseUrl;\n this._tenantBaseUrl = tenantBaseUrl;\n this._legacyBaseUrl = legacyBaseUrl;\n this._request = request;\n this._sdk = sdk;\n this._organizationId = organizationId;\n }\n\n _getBaseUrl(type) {\n switch (type) {\n case 'legacy':\n return this._legacyBaseUrl || this._baseUrl;\n\n case 'access':\n return this._baseUrl;\n\n default:\n return this._tenantBaseUrl || this._baseUrl;\n }\n }\n\n /**\n * Activates a new user\n *\n * API Endpoint: '/users/:userId/activate'\n * Method: POST\n *\n * Note: Only valid for web users using auth0WebAuth session type\n *\n * @param {string} userId The ID of the user to activate\n * @param {Object} user\n * @param {string} user.email The email address of the user\n * @param {string} user.password The password to set for the user\n * @param {string} user.userToken The JWT token provided by the invite link\n *\n * @returns {Promise}\n * @fulfill {undefined}\n * @reject {Error}\n *\n * @example\n * contxtSdk.coordinator.users\n * .activate('7bb79bdf-7492-45c2-8640-2dde63535827', {\n * email: 'bob.sagat56@gmail.com',\n * password: 'ds32jX32jaMM1Nr',\n * userToken: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'\n * })\n * .then(() => console.log(\"User Activated\"))\n * .catch((err) => console.log(err));\n */\n activate(userId, user = {}) {\n if (!userId) {\n return Promise.reject(\n new Error('A user ID is required for activating a user')\n );\n }\n\n const requiredFields = ['email', 'password', 'userToken'];\n\n for (let i = 0; requiredFields.length > i; i++) {\n const field = requiredFields[i];\n\n if (!user[field]) {\n return Promise.reject(\n new Error(`A ${field} is required to activate a user.`)\n );\n }\n }\n\n // Uses axios directly instead of this.request to bypass authorization interceptors\n return axios.post(\n `${this._getBaseUrl('access')}/users/${userId}/activate`,\n toSnakeCase(user)\n );\n }\n\n /**\n * Adds a application to a user\n *\n * API Endpoint: '/users/:userId/applications/:applicationId'\n * Method: GET\n *\n * @param {string} userId The ID of the user\n * @param {string} applicationId The ID of the application\n *\n * @returns {Promise}\n * @fulfill {ContxtUserApplication} The newly created user application\n * @reject {Error}\n *\n * @example\n * contxtSdk.coordinator.users\n * .addApplication('36b8421a-cc4a-4204-b839-1397374fb16b', '007ca9ee-ece7-4931-9d11-9b4fd97d4d58')\n * .then((userApplication) => console.log(userApplication))\n * .catch((err) => console.log(err));\n */\n addApplication(userId, applicationId) {\n if (!userId) {\n return Promise.reject(\n new Error('A user ID is required for adding a application to a user')\n );\n }\n\n if (!applicationId) {\n return Promise.reject(\n new Error(\n 'An application ID is required for adding a application to a user'\n )\n );\n }\n\n return this._request\n .post(\n `${this._getBaseUrl()}/users/${userId}/applications/${applicationId}`\n )\n .then((response) => toCamelCase(response));\n }\n\n /**\n * Adds a role to a user\n *\n * API Endpoint: '/users/:userId/roles/:roleId'\n * Method: POST\n *\n * @param {string} userId The ID of the user\n * @param {string} roleId The ID of the role\n *\n * @returns {Promise}\n * @fulfill {ContxtUserRole} The newly created user role\n * @reject {Error}\n *\n * @example\n * contxtSdk.coordinator.users\n * .addRole('36b8421a-cc4a-4204-b839-1397374fb16b', '007ca9ee-ece7-4931-9d11-9b4fd97d4d58')\n * .then((userRole) => console.log(userRole))\n * .catch((err) => console.log(err));\n */\n addRole(userId, roleId) {\n if (!userId) {\n return Promise.reject(\n new Error('A user ID is required for adding a role to a user')\n );\n }\n\n if (!roleId) {\n return Promise.reject(\n new Error('A role ID is required for adding a role to a user')\n );\n }\n\n return this._request\n .post(`${this._getBaseUrl()}/users/${userId}/roles/${roleId}`)\n .then((response) => toCamelCase(response));\n }\n\n /**\n * Adds a project environment to a user\n *\n * API Endpoint: '/users/:userId/project_environments/:projectEnvironmentSlug\n * Method: POST\n *\n * @param {string} userId The ID of the user\n * @param {string} projectEnvironmentSlug The slug of the project environment\n * @param {'reader' | 'admin'} accessType The level of access for the user\n *\n * @returns {Promise}\n * @fulfill {ContxtUserProjectEnvironment} The newly created user project environment\n * @reject {Error}\n *\n * @example\n * contxtSdk.coordinator.users\n * .addProjectEnvironment('36b8421a-cc4a-4204-b839-1397374fb16b', 'project-environment-slug', 'admin')\n * .then((userProject) => console.log(userProject))\n * .catch((err) => console.log(err));\n */\n addProjectEnvironment(userId, projectEnvironmentSlug, accessType) {\n if (!userId) {\n return Promise.reject(\n new Error(\n 'A user ID is required for adding a project environment to a user'\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 user.'\n )\n );\n }\n\n if (['reader', 'admin'].indexOf(accessType) === -1) {\n return Promise.reject(\n new Error(\n 'An access type of \"reader\" or \"admin\" is required for adding a project environment to a user'\n )\n );\n }\n\n return this._request\n .post(\n `${this._getBaseUrl()}/users/${userId}/project_environments/${projectEnvironmentSlug}`,\n {\n access_type: accessType\n }\n )\n .then((response) => toCamelCase(response));\n }\n\n /**\n * Gets information about a contxt user\n *\n * API Endpoint: '/users/:userId'\n * Method: GET\n *\n * @param {string} userId The ID of the user\n *\n * @returns {Promise}\n * @fulfill {ContxtUser} Information about a contxt user\n * @reject {Error}\n *\n * @example\n * contxtSdk.coordinator.users\n * .get('auth0|12345')\n * .then((user) => console.log(user))\n * .catch((err) => console.log(err));\n */\n get(userId) {\n if (!userId) {\n return Promise.reject(\n new Error('A user ID is required for getting information about a user')\n );\n }\n\n return this._request\n .get(`${this._getBaseUrl('access')}/users/${userId}`)\n .then((user) => toCamelCase(user));\n }\n\n /**\n * Gets a list of users for a contxt organization\n *\n * Legacy API Endpoint: '/organizations/:organizationId/users'\n * API Endpoint: '/users'\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 {ContxtUser[]} List of users for a contxt organization\n * @reject {Error}\n *\n * @example\n * contxtSdk.coordinator.users\n * .getByOrganizationId('36b8421a-cc4a-4204-b839-1397374fb16b')\n * .then((orgUsers) => console.log(orgUsers))\n * .catch((err) => console.log(err));\n */\n getByOrganizationId(organizationId) {\n if (this._organizationId) {\n return this._request\n .get(`${this._getBaseUrl()}/users`)\n .then((orgUsers) => toCamelCase(orgUsers));\n }\n\n if (!organizationId) {\n return Promise.reject(\n new Error(\n 'An organization ID is required for getting a list of users for an organization'\n )\n );\n }\n\n return this._request\n .get(\n `${this._getBaseUrl('legacy')}/organizations/${organizationId}/users`\n )\n .then((orgUsers) => toCamelCase(orgUsers));\n }\n\n /**\n * Creates a new contxt user, adds them to an organization, and\n * sends them an email invite link to do final account setup.\n *\n * Legacy API Endpoint: '/organizations/:organizationId/users'\n * API Endpoint: '/users'\n * Method: POST\n *\n * Note: Only valid for web users using auth0WebAuth session type\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} user\n * @param {string} user.email The email address of the new user\n * @param {string} user.firstName The first name of the new user\n * @param {string} user.lastName The last name of the new user\n * @param {string} user.redirectUrl The url that the user will be redirected\n * to after using the invite email link. Typically this is an /activate\n * endpoint that accepts url query params userToken and userId and uses them\n * to do final activation on the user's account.\n *\n * @returns {Promise}\n * @fulfill {ContxtUser} The new user\n * @reject {Error}\n *\n * @example\n * contxtSdk.coordinator.users\n * .invite('fdf01507-a26a-4dfe-89a2-bc91861169b8', {\n * email: 'bob.sagat56@gmail.com',\n * firstName: 'Bob',\n * lastName: 'Sagat',\n * redirectUrl: 'https://contxt.ndustrial.io/activate'\n * })\n * .then((newUser) => console.log(newUser))\n * .catch((err) => console.log(err));\n */\n invite(organizationId, user = {}) {\n if (this._organizationId) {\n const requiredFields = ['email', 'firstName', 'lastName', 'redirectUrl'];\n\n for (let i = 0; requiredFields.length > i; i++) {\n const field = requiredFields[i];\n\n if (!user[field]) {\n return Promise.reject(\n new Error(`A ${field} is required to create a new user.`)\n );\n }\n }\n\n return this._request\n .post(`${this._getBaseUrl()}/users`, toSnakeCase(user))\n .then((response) => toCamelCase(response));\n }\n\n if (!organizationId) {\n return Promise.reject(\n new Error('An organization ID is required for inviting a new user')\n );\n }\n\n const requiredFields = ['email', 'firstName', 'lastName', 'redirectUrl'];\n\n for (let i = 0; requiredFields.length > i; i++) {\n const field = requiredFields[i];\n\n if (!user[field]) {\n return Promise.reject(\n new Error(`A ${field} is required to create a new user.`)\n );\n }\n }\n\n return this._request\n .post(\n `${this._getBaseUrl('legacy')}/organizations/${organizationId}/users`,\n toSnakeCase(user)\n )\n .then((response) => toCamelCase(response));\n }\n\n /**\n * Removes a user from an organization\n *\n * Legacy API Endpoint: '/organizations/:organizationId/users/:userId'\n * API Endpoint: '/users/:userId'\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} userId The ID of the user\n *\n * @returns {Promise}\n * @fulfill {undefined}\n * @reject {Error}\n *\n * @example\n * contxtSdk.coordinator.users\n * .remove('ed2e8e24-79ef-4404-bf5f-995ef31b2298', '4a577e87-7437-4342-b183-00c18ec26d52')\n * .catch((err) => console.log(err));\n */\n remove(organizationId, userId) {\n if (this._organizationId) {\n if (!userId) {\n return Promise.reject(\n new Error(\n 'A user ID is required for removing a user from an organization'\n )\n );\n }\n\n return this._request.delete(`${this._getBaseUrl()}/users/${userId}`);\n }\n\n if (!organizationId) {\n return Promise.reject(\n new Error(\n 'An organization ID is required for removing a user from an organization'\n )\n );\n }\n\n if (!userId) {\n return Promise.reject(\n new Error(\n 'A user ID is required for removing a user from an organization'\n )\n );\n }\n\n return this._request.delete(\n `${this._getBaseUrl(\n 'legacy'\n )}/organizations/${organizationId}/users/${userId}`\n );\n }\n\n /**\n * Removes a application from a user\n *\n * API Endpoint: '/users/:userId/applications/:applicationId'\n * Method: DELETE\n *\n * @param {string} userId The ID of the user\n * @param {string} applicationId The ID of the application\n *\n * @returns {Promise}\n * @fulfill {undefined}\n * @reject {Error}\n *\n * @example\n * contxtSdk.coordinator.users\n * .removeApplication('36b8421a-cc4a-4204-b839-1397374fb16b', '007ca9ee-ece7-4931-9d11-9b4fd97d4d58')\n * .catch((err) => console.log(err));\n */\n removeApplication(userId, applicationId) {\n if (!userId) {\n return Promise.reject(\n new Error(\n 'A user ID is required for removing a application from a user'\n )\n );\n }\n\n if (!applicationId) {\n return Promise.reject(\n new Error(\n 'An application ID is required for removing a application from a user'\n )\n );\n }\n\n return this._request.delete(\n `${this._getBaseUrl()}/users/${userId}/applications/${applicationId}`\n );\n }\n\n /**\n * Removes a role from a user\n *\n * API Endpoint: '/users/:userId/roles/:roleId'\n * Method: DELETE\n *\n * @param {string} userId The ID of the user\n * @param {string} roleId The ID of the role\n *\n * @returns {Promise}\n * @fulfill {undefined}\n * @reject {Error}\n *\n * @example\n * contxtSdk.coordinator.users\n * .removeRole('36b8421a-cc4a-4204-b839-1397374fb16b', '007ca9ee-ece7-4931-9d11-9b4fd97d4d58')\n * .catch((err) => console.log(err));\n */\n removeRole(userId, roleId) {\n if (!userId) {\n return Promise.reject(\n new Error('A user ID is required for removing a role from a user')\n );\n }\n\n if (!roleId) {\n return Promise.reject(\n new Error('A role ID is required for removing a role from a user')\n );\n }\n\n return this._request.delete(\n `${this._getBaseUrl()}/users/${userId}/roles/${roleId}`\n );\n }\n\n /**\n * Removes a project environment from a user\n *\n * API Endpoint: 'users/:userId/project_environments/:projectEnvironmentSlug\n * Method: DELETE\n *\n * @param {string} userId The ID of the user\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.coordinator.users\n * .removeProjectEnvironment('36b8421a-cc4a-4204-b839-1397374fb16b', 'project-environment-slug')\n * .catch((err) => console.log(err));\n */\n removeProjectEnvironment(userId, projectEnvironmentSlug) {\n if (!userId) {\n return Promise.reject(\n new Error(\n 'A user ID is required for removing a project environment from a user'\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 user.'\n )\n );\n }\n\n return this._request.delete(\n `${this._getBaseUrl()}/users/${userId}/project_environments/${projectEnvironmentSlug}`\n );\n }\n\n /**\n * Syncs the user's roles and application access with the external auth provider\n *\n * API Endpoint: '/users/:userId/sync'\n * Method: GET\n *\n * @param {string} userId The ID of the user\n *\n * @returns {Promise}\n * @fulfill {undefined}\n * @reject {Error}\n *\n * @example\n * contxtSdk.coordinator.users\n * .sync('36b8421a-cc4a-4204-b839-1397374fb16b')\n * .catch((err) => console.log(err));\n */\n sync(userId) {\n if (!userId) {\n return Promise.reject(\n new Error('A user ID is required for syncing user permissions')\n );\n }\n\n return this._request.get(\n `${this._getBaseUrl('access')}/users/${userId}/sync`\n );\n }\n}\n\nexport default Users;\n"]}
|
|
1
|
+
{"version":3,"sources":["coordinator/users.js"],"names":["Users","sdk","request","baseUrl","tenantBaseUrl","legacyBaseUrl","organizationId","_baseUrl","_tenantBaseUrl","_legacyBaseUrl","_request","_sdk","_organizationId","type","userId","user","Promise","reject","Error","requiredFields","i","length","field","axios","post","_getBaseUrl","applicationId","then","response","roleId","projectEnvironmentId","accessType","indexOf","access_type","get","orgUsers","delete"],"mappings":";;;;;;;;AAAA;;;;AAEA;;;;;;AAEA;;;;;;;;;;;;;AAaA;;;;;;;;;AASA;;;;;;;;;;AAUA;;;;;;;;;;AAUA;;;;;IAKMA,K;AACJ;;;;;;;;AAQA,iBACEC,GADF,EAEEC,OAFF,EAGEC,OAHF,EAOE;AAAA,QAHAC,aAGA,uEAHgB,IAGhB;AAAA,QAFAC,aAEA,uEAFgB,IAEhB;AAAA,QADAC,cACA,uEADiB,IACjB;;AAAA;;AACA,SAAKC,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ce,MAD1C,CAAP;AAGD;;AAED;;;;;;;;;;;;;;;;;;;;;6CAkByBf,M,EAAQgB,oB,EAAsB;AACrD,UAAI,CAAChB,MAAL,EAAa;AACX,eAAOE,QAAQC,MAAR,CACL,IAAIC,KAAJ,CACE,sEADF,CADK,CAAP;AAKD;;AAED,UAAI,CAACY,oBAAL,EAA2B;AACzB,eAAOd,QAAQC,MAAR,CACL,IAAIC,KAAJ,CACE,wFADF,CADK,CAAP;AAKD;;AAED,aAAO,KAAKR,QAAL,CAAc0B,MAAd,CACF,KAAKX,WAAL,EADE,eAC0BX,MAD1B,8BACyDgB,oBADzD,CAAP;AAGD;;AAED;;;;;;;;;;;;;;;;;;;;yBAiBKhB,M,EAAQ;AACX,UAAI,CAACA,MAAL,EAAa;AACX,eAAOE,QAAQC,MAAR,CACL,IAAIC,KAAJ,CAAU,oDAAV,CADK,CAAP;AAGD;;AAED,aAAO,KAAKR,QAAL,CAAcwB,GAAd,CACF,KAAKT,WAAL,CAAiB,QAAjB,CADE,eACkCX,MADlC,WAAP;AAGD;;;;;;kBAGYd,K","file":"users.js","sourcesContent":["import axios from 'axios';\n\nimport { toCamelCase, toSnakeCase } from '../utils/objects';\n\n/**\n * @typedef {Object} ContxtUser\n * @property {string} createdAt ISO 8601 Extended Format date/time string\n * @property {string} email\n * @property {string} firstName\n * @property {string} id\n * @property {boolean} isActivated\n * @property {boolean} isSuperuser\n * @property {string} lastName\n * @property {string} [phoneNumber]\n * @property {string} updatedAt ISO 8601 Extended Format date/time string\n */\n\n/**\n * @typedef {Object} ContxtUserApplication\n * @property {string} applicationId\n * @property {string} createdAt ISO 8601 Extended Format date/time string\n * @property {string} id\n * @property {string} userId\n * @property {string} updatedAt ISO 8601 Extended Format date/time string\n */\n\n/**\n * @typedef {Object} ContxtUserRole\n * @property {string} createdAt ISO 8601 Extended Format date/time string\n * @property {string} id\n * @property {boolean} mappedFromExternalGroup\n * @property {string} userId\n * @property {string} roleId\n * @property {string} updatedAt ISO 8601 Extended Format date/time string\n */\n\n/**\n * @typedef {Object} ContxtUserProjectEnvironment\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} id\n * @property {string} userId\n * @property {string} projectEnvironmentId\n * @property {string} updatedAt ISO 8601 Extended Format date/time string\n */\n\n/**\n * Module that provides access to contxt users\n *\n * @typicalname contxtSdk.coordinator.users\n */\nclass Users {\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} [tenantBaseUrl] The tenant base URL provided by the parent module\n * @param {string} [legacyBaseUrl] The legacy base URL provided by the parent module\n * @param {string} [organizationId] The organization ID to be used in tenant url requests\n */\n constructor(\n sdk,\n request,\n baseUrl,\n tenantBaseUrl = null,\n legacyBaseUrl = null,\n organizationId = null\n ) {\n this._baseUrl = baseUrl;\n this._tenantBaseUrl = tenantBaseUrl;\n this._legacyBaseUrl = legacyBaseUrl;\n this._request = request;\n this._sdk = sdk;\n this._organizationId = organizationId;\n }\n\n _getBaseUrl(type) {\n switch (type) {\n case 'legacy':\n return this._legacyBaseUrl || this._baseUrl;\n\n case 'access':\n return this._baseUrl;\n\n default:\n return this._tenantBaseUrl || this._baseUrl;\n }\n }\n\n /**\n * Activates a new user\n *\n * API Endpoint: '/users/:userId/activate'\n * Method: POST\n *\n * Note: Only valid for web users using auth0WebAuth session type\n *\n * @param {string} userId The ID of the user to activate\n * @param {Object} user\n * @param {string} user.email The email address of the user\n * @param {string} user.password The password to set for the user\n * @param {string} user.userToken The JWT token provided by the invite link\n *\n * @returns {Promise}\n * @fulfill {undefined}\n * @reject {Error}\n *\n * @example\n * contxtSdk.coordinator.users\n * .activate('7bb79bdf-7492-45c2-8640-2dde63535827', {\n * email: 'bob.sagat56@gmail.com',\n * password: 'ds32jX32jaMM1Nr',\n * userToken: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'\n * })\n * .then(() => console.log(\"User Activated\"))\n * .catch((err) => console.log(err));\n */\n activate(userId, user = {}) {\n if (!userId) {\n return Promise.reject(\n new Error('A user ID is required for activating a user')\n );\n }\n\n const requiredFields = ['email', 'password', 'userToken'];\n\n for (let i = 0; requiredFields.length > i; i++) {\n const field = requiredFields[i];\n\n if (!user[field]) {\n return Promise.reject(\n new Error(`A ${field} is required to activate a user.`)\n );\n }\n }\n\n // Uses axios directly instead of this.request to bypass authorization interceptors\n return axios.post(\n `${this._getBaseUrl('access')}/users/${userId}/activate`,\n toSnakeCase(user)\n );\n }\n\n /**\n * Adds a application to a user\n *\n * API Endpoint: '/users/:userId/applications/:applicationId'\n * Method: GET\n *\n * @param {string} userId The ID of the user\n * @param {string} applicationId The ID of the application\n *\n * @returns {Promise}\n * @fulfill {ContxtUserApplication} The newly created user application\n * @reject {Error}\n *\n * @example\n * contxtSdk.coordinator.users\n * .addApplication('36b8421a-cc4a-4204-b839-1397374fb16b', '007ca9ee-ece7-4931-9d11-9b4fd97d4d58')\n * .then((userApplication) => console.log(userApplication))\n * .catch((err) => console.log(err));\n */\n addApplication(userId, applicationId) {\n if (!userId) {\n return Promise.reject(\n new Error('A user ID is required for adding a application to a user')\n );\n }\n\n if (!applicationId) {\n return Promise.reject(\n new Error(\n 'An application ID is required for adding a application to a user'\n )\n );\n }\n\n return this._request\n .post(\n `${this._getBaseUrl()}/users/${userId}/applications/${applicationId}`\n )\n .then((response) => toCamelCase(response));\n }\n\n /**\n * Adds a role to a user\n *\n * API Endpoint: '/users/:userId/roles/:roleId'\n * Method: POST\n *\n * @param {string} userId The ID of the user\n * @param {string} roleId The ID of the role\n *\n * @returns {Promise}\n * @fulfill {ContxtUserRole} The newly created user role\n * @reject {Error}\n *\n * @example\n * contxtSdk.coordinator.users\n * .addRole('36b8421a-cc4a-4204-b839-1397374fb16b', '007ca9ee-ece7-4931-9d11-9b4fd97d4d58')\n * .then((userRole) => console.log(userRole))\n * .catch((err) => console.log(err));\n */\n addRole(userId, roleId) {\n if (!userId) {\n return Promise.reject(\n new Error('A user ID is required for adding a role to a user')\n );\n }\n\n if (!roleId) {\n return Promise.reject(\n new Error('A role ID is required for adding a role to a user')\n );\n }\n\n return this._request\n .post(`${this._getBaseUrl()}/users/${userId}/roles/${roleId}`)\n .then((response) => toCamelCase(response));\n }\n\n /**\n * Adds a project environment to a user\n *\n * API Endpoint: '/users/:userId/project_environments/:projectEnvironmentSlug\n * Method: POST\n *\n * @param {string} userId The ID of the user\n * @param {string} projectEnvironmentSlug The slug of the project environment\n * @param {'reader' | 'admin'} accessType The level of access for the user\n *\n * @returns {Promise}\n * @fulfill {ContxtUserProjectEnvironment} The newly created user project environment\n * @reject {Error}\n *\n * @example\n * contxtSdk.coordinator.users\n * .addProjectEnvironment('36b8421a-cc4a-4204-b839-1397374fb16b', 'project-environment-slug', 'admin')\n * .then((userProject) => console.log(userProject))\n * .catch((err) => console.log(err));\n */\n addProjectEnvironment(userId, projectEnvironmentId, accessType) {\n if (!userId) {\n return Promise.reject(\n new Error(\n 'A user ID is required for adding a project environment to a user'\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 user.'\n )\n );\n }\n\n if (['reader', 'admin'].indexOf(accessType) === -1) {\n return Promise.reject(\n new Error(\n 'An access type of \"reader\" or \"admin\" is required for adding a project environment to a user'\n )\n );\n }\n\n return this._request\n .post(\n `${this._getBaseUrl()}/users/${userId}/project_environments/${projectEnvironmentId}`,\n {\n access_type: accessType\n }\n )\n .then((response) => toCamelCase(response));\n }\n\n /**\n * Gets information about a contxt user\n *\n * API Endpoint: '/users/:userId'\n * Method: GET\n *\n * @param {string} userId The ID of the user\n *\n * @returns {Promise}\n * @fulfill {ContxtUser} Information about a contxt user\n * @reject {Error}\n *\n * @example\n * contxtSdk.coordinator.users\n * .get('auth0|12345')\n * .then((user) => console.log(user))\n * .catch((err) => console.log(err));\n */\n get(userId) {\n if (!userId) {\n return Promise.reject(\n new Error('A user ID is required for getting information about a user')\n );\n }\n\n return this._request\n .get(`${this._getBaseUrl('access')}/users/${userId}`)\n .then((user) => toCamelCase(user));\n }\n\n /**\n * Gets a list of users for a contxt organization\n *\n * Legacy API Endpoint: '/organizations/:organizationId/users'\n * API Endpoint: '/users'\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 {ContxtUser[]} List of users for a contxt organization\n * @reject {Error}\n *\n * @example\n * contxtSdk.coordinator.users\n * .getByOrganizationId('36b8421a-cc4a-4204-b839-1397374fb16b')\n * .then((orgUsers) => console.log(orgUsers))\n * .catch((err) => console.log(err));\n */\n getByOrganizationId(organizationId) {\n if (this._organizationId) {\n return this._request\n .get(`${this._getBaseUrl()}/users`)\n .then((orgUsers) => toCamelCase(orgUsers));\n }\n\n if (!organizationId) {\n return Promise.reject(\n new Error(\n 'An organization ID is required for getting a list of users for an organization'\n )\n );\n }\n\n return this._request\n .get(\n `${this._getBaseUrl('legacy')}/organizations/${organizationId}/users`\n )\n .then((orgUsers) => toCamelCase(orgUsers));\n }\n\n /**\n * Creates a new contxt user, adds them to an organization, and\n * sends them an email invite link to do final account setup.\n *\n * Legacy API Endpoint: '/organizations/:organizationId/users'\n * API Endpoint: '/users'\n * Method: POST\n *\n * Note: Only valid for web users using auth0WebAuth session type\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} user\n * @param {string} user.email The email address of the new user\n * @param {string} user.firstName The first name of the new user\n * @param {string} user.lastName The last name of the new user\n * @param {string} user.redirectUrl The url that the user will be redirected\n * to after using the invite email link. Typically this is an /activate\n * endpoint that accepts url query params userToken and userId and uses them\n * to do final activation on the user's account.\n *\n * @returns {Promise}\n * @fulfill {ContxtUser} The new user\n * @reject {Error}\n *\n * @example\n * contxtSdk.coordinator.users\n * .invite('fdf01507-a26a-4dfe-89a2-bc91861169b8', {\n * email: 'bob.sagat56@gmail.com',\n * firstName: 'Bob',\n * lastName: 'Sagat',\n * redirectUrl: 'https://contxt.ndustrial.io/activate'\n * })\n * .then((newUser) => console.log(newUser))\n * .catch((err) => console.log(err));\n */\n invite(organizationId, user = {}) {\n if (this._organizationId) {\n const requiredFields = ['email', 'firstName', 'lastName', 'redirectUrl'];\n\n for (let i = 0; requiredFields.length > i; i++) {\n const field = requiredFields[i];\n\n if (!user[field]) {\n return Promise.reject(\n new Error(`A ${field} is required to create a new user.`)\n );\n }\n }\n\n return this._request\n .post(`${this._getBaseUrl()}/users`, toSnakeCase(user))\n .then((response) => toCamelCase(response));\n }\n\n if (!organizationId) {\n return Promise.reject(\n new Error('An organization ID is required for inviting a new user')\n );\n }\n\n const requiredFields = ['email', 'firstName', 'lastName', 'redirectUrl'];\n\n for (let i = 0; requiredFields.length > i; i++) {\n const field = requiredFields[i];\n\n if (!user[field]) {\n return Promise.reject(\n new Error(`A ${field} is required to create a new user.`)\n );\n }\n }\n\n return this._request\n .post(\n `${this._getBaseUrl('legacy')}/organizations/${organizationId}/users`,\n toSnakeCase(user)\n )\n .then((response) => toCamelCase(response));\n }\n\n /**\n * Removes a user from an organization\n *\n * Legacy API Endpoint: '/organizations/:organizationId/users/:userId'\n * API Endpoint: '/users/:userId'\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} userId The ID of the user\n *\n * @returns {Promise}\n * @fulfill {undefined}\n * @reject {Error}\n *\n * @example\n * contxtSdk.coordinator.users\n * .remove('ed2e8e24-79ef-4404-bf5f-995ef31b2298', '4a577e87-7437-4342-b183-00c18ec26d52')\n * .catch((err) => console.log(err));\n */\n remove(organizationId, userId) {\n if (this._organizationId) {\n if (!userId) {\n return Promise.reject(\n new Error(\n 'A user ID is required for removing a user from an organization'\n )\n );\n }\n\n return this._request.delete(`${this._getBaseUrl()}/users/${userId}`);\n }\n\n if (!organizationId) {\n return Promise.reject(\n new Error(\n 'An organization ID is required for removing a user from an organization'\n )\n );\n }\n\n if (!userId) {\n return Promise.reject(\n new Error(\n 'A user ID is required for removing a user from an organization'\n )\n );\n }\n\n return this._request.delete(\n `${this._getBaseUrl(\n 'legacy'\n )}/organizations/${organizationId}/users/${userId}`\n );\n }\n\n /**\n * Removes a application from a user\n *\n * API Endpoint: '/users/:userId/applications/:applicationId'\n * Method: DELETE\n *\n * @param {string} userId The ID of the user\n * @param {string} applicationId The ID of the application\n *\n * @returns {Promise}\n * @fulfill {undefined}\n * @reject {Error}\n *\n * @example\n * contxtSdk.coordinator.users\n * .removeApplication('36b8421a-cc4a-4204-b839-1397374fb16b', '007ca9ee-ece7-4931-9d11-9b4fd97d4d58')\n * .catch((err) => console.log(err));\n */\n removeApplication(userId, applicationId) {\n if (!userId) {\n return Promise.reject(\n new Error(\n 'A user ID is required for removing a application from a user'\n )\n );\n }\n\n if (!applicationId) {\n return Promise.reject(\n new Error(\n 'An application ID is required for removing a application from a user'\n )\n );\n }\n\n return this._request.delete(\n `${this._getBaseUrl()}/users/${userId}/applications/${applicationId}`\n );\n }\n\n /**\n * Removes a role from a user\n *\n * API Endpoint: '/users/:userId/roles/:roleId'\n * Method: DELETE\n *\n * @param {string} userId The ID of the user\n * @param {string} roleId The ID of the role\n *\n * @returns {Promise}\n * @fulfill {undefined}\n * @reject {Error}\n *\n * @example\n * contxtSdk.coordinator.users\n * .removeRole('36b8421a-cc4a-4204-b839-1397374fb16b', '007ca9ee-ece7-4931-9d11-9b4fd97d4d58')\n * .catch((err) => console.log(err));\n */\n removeRole(userId, roleId) {\n if (!userId) {\n return Promise.reject(\n new Error('A user ID is required for removing a role from a user')\n );\n }\n\n if (!roleId) {\n return Promise.reject(\n new Error('A role ID is required for removing a role from a user')\n );\n }\n\n return this._request.delete(\n `${this._getBaseUrl()}/users/${userId}/roles/${roleId}`\n );\n }\n\n /**\n * Removes a project environment from a user\n *\n * API Endpoint: 'users/:userId/project_environments/:projectEnvironmentSlug\n * Method: DELETE\n *\n * @param {string} userId The ID of the user\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.coordinator.users\n * .removeProjectEnvironment('36b8421a-cc4a-4204-b839-1397374fb16b', 'project-environment-slug')\n * .catch((err) => console.log(err));\n */\n removeProjectEnvironment(userId, projectEnvironmentId) {\n if (!userId) {\n return Promise.reject(\n new Error(\n 'A user ID is required for removing a project environment from a user'\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 user.'\n )\n );\n }\n\n return this._request.delete(\n `${this._getBaseUrl()}/users/${userId}/project_environments/${projectEnvironmentId}`\n );\n }\n\n /**\n * Syncs the user's roles and application access with the external auth provider\n *\n * API Endpoint: '/users/:userId/sync'\n * Method: GET\n *\n * @param {string} userId The ID of the user\n *\n * @returns {Promise}\n * @fulfill {undefined}\n * @reject {Error}\n *\n * @example\n * contxtSdk.coordinator.users\n * .sync('36b8421a-cc4a-4204-b839-1397374fb16b')\n * .catch((err) => console.log(err));\n */\n sync(userId) {\n if (!userId) {\n return Promise.reject(\n new Error('A user ID is required for syncing user permissions')\n );\n }\n\n return this._request.get(\n `${this._getBaseUrl('access')}/users/${userId}/sync`\n );\n }\n}\n\nexport default Users;\n"]}
|
|
@@ -113,7 +113,7 @@ var Auth0WebAuth = function () {
|
|
|
113
113
|
this._auth0 = new _auth0Js2.default.WebAuth({
|
|
114
114
|
audience: this._sdk.config.audiences.contxtAuth.clientId,
|
|
115
115
|
clientID: this._sdk.config.auth.clientId,
|
|
116
|
-
domain:
|
|
116
|
+
domain: this._sdk.config.auth.domain,
|
|
117
117
|
redirectUri: '' + currentUrl.origin + currentUrl.pathname,
|
|
118
118
|
responseType: 'token',
|
|
119
119
|
scope: 'email profile openid'
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["sessionTypes/auth0WebAuth.js"],"names":["Auth0WebAuth","sdk","_sdk","config","auth","clientId","Error","_onAuthenticate","onAuthenticate","_defaultOnAuthenticate","_onRedirect","onRedirect","_defaultOnRedirect","_sessionInfo","_getStoredSession","_sessionRenewalTimeout","_tokenPromises","currentUrl","URL","window","location","set","authorizationPath","_auth0","auth0","WebAuth","audience","audiences","contxtAuth","clientID","domain","redirectUri","origin","pathname","responseType","scope","isAuthenticated","_scheduleSessionRefresh","audienceName","promise","Promise","resolve","then","reject","_generateUnauthorizedError","accessToken","axios","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;;;;AACA;;;;AACA;;;;;;;;AAEA;;;;;;;;;;;AAWA;;;;;;AAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAmCMA,Y;AACJ;;;;;;;;;;;;;;AAcA,wBAAYC,GAAZ,EAAiB;AAAA;;AACf,SAAKC,IAAL,GAAYD,GAAZ;;AAEA,QAAI,CAAC,KAAKC,IAAL,CAAUC,MAAV,CAAiBC,IAAjB,CAAsBC,QAA3B,EAAqC;AACnC,YAAM,IAAIC,KAAJ,CAAU,6CAAV,CAAN;AACD;;AAED,SAAKC,eAAL,GACE,KAAKL,IAAL,CAAUC,MAAV,CAAiBC,IAAjB,CAAsBI,cAAtB,IAAwC,K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KAAKtF,YAAL,CAAkBwD,SAAlB,GAA8B6B,sBADhC;AAEA,UAAME,QAAQD,oBAAoB7B,KAAKC,GAAL,EAAlC;;AAEA,UAAI,KAAKxD,sBAAT,EAAiC;AAC/BgE,qBAAa,KAAKhE,sBAAlB;AACD;;AAED,WAAKA,sBAAL,GAA8BsF,WAAW,YAAM;AAC7C,eAAKC,kBAAL;AACD,OAF6B,EAE3BF,KAF2B,CAA9B;AAGD;;AAED;;;;;;;;;;;;yCAS0C;AAAA,UAA1BvD,WAA0B,SAA1BA,WAA0B;AAAA,UAAb0D,SAAa,SAAbA,SAAa;;AACxC,UAAMlC,YAAYkC,YAAY,IAAZ,GAAmBjC,KAAKC,GAAL,EAArC;;AAEAM,mBAAa2B,OAAb,CAAqB,cAArB,EAAqC3D,WAArC;AACAgC,mBAAa2B,OAAb,CAAqB,YAArB,EAAmCnB,KAAKoB,SAAL,CAAepC,SAAf,CAAnC;;AAEA,WAAKxD,YAAL,CAAkBgC,WAAlB,GAAgCA,WAAhC;AACA,WAAKhC,YAAL,CAAkBwD,SAAlB,GAA8BA,SAA9B;AACD;;;;;;AAGI,IAAMqC,sBAAO,cAAb;kBACQ1G,Y","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: '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":["Auth0WebAuth","sdk","_sdk","config","auth","clientId","Error","_onAuthenticate","onAuthenticate","_defaultOnAuthenticate","_onRedirect","onRedirect","_defaultOnRedirect","_sessionInfo","_getStoredSession","_sessionRenewalTimeout","_tokenPromises","currentUrl","URL","window","location","set","authorizationPath","_auth0","auth0","WebAuth","audience","audiences","contxtAuth","clientID","domain","redirectUri","origin","pathname","responseType","scope","isAuthenticated","_scheduleSessionRefresh","audienceName","promise","Promise","resolve","then","reject","_generateUnauthorizedError","accessToken","axios","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;;;;AACA;;;;AACA;;;;;;;;AAEA;;;;;;;;;;;AAWA;;;;;;AAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAmCMA,Y;AACJ;;;;;;;;;;;;;;AAcA,wBAAYC,GAAZ,EAAiB;AAAA;;AACf,SAAKC,IAAL,GAAYD,GAAZ;;AAEA,QAAI,CAAC,KAAKC,IAAL,CAAUC,MAAV,CAAiBC,IAAjB,CAAsBC,QAA3B,EAAqC;AACnC,YAAM,IAAIC,KAAJ,CAAU,6CAAV,CAAN;AACD;;AAED,SAAKC,eAAL,GACE,KAAKL,IAAL,CAAUC,MAAV,CAAiBC,IAAjB,CAAsBI,cAAtB,IAAwC,KAAKC,sBAD/C;AAEA,SAAKC,WAAL,GACE,KAAKR,IAAL,CAAUC,MAAV,CAAiBC,IAAjB,CAAsBO,UAAtB,IAAoC,KAAKC,kBAD3C;AAEA,SAAKC,YAAL,GAAoB,KAAKC,iBAAL,EAApB;AACA,SAAKC,sBAAL,GAA8B,IAA9B;AACA,SAAKC,cAAL,GAAsB,EAAtB;;AAEA,QAAMC,aAAa,IAAIC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,YAAM;AAC7C,eAAKC,kBAAL;AACD,OAF6B,EAE3BF,KAF2B,CAA9B;AAGD;;AAED;;;;;;;;;;;;yCAS0C;AAAA,UAA1BvD,WAA0B,SAA1BA,WAA0B;AAAA,UAAb0D,SAAa,SAAbA,SAAa;;AACxC,UAAMlC,YAAYkC,YAAY,IAAZ,GAAmBjC,KAAKC,GAAL,EAArC;;AAEAM,mBAAa2B,OAAb,CAAqB,cAArB,EAAqC3D,WAArC;AACAgC,mBAAa2B,OAAb,CAAqB,YAArB,EAAmCnB,KAAKoB,SAAL,CAAepC,SAAf,CAAnC;;AAEA,WAAKxD,YAAL,CAAkBgC,WAAlB,GAAgCA,WAAhC;AACA,WAAKhC,YAAL,CAAkBwD,SAAlB,GAA8BA,SAA9B;AACD;;;;;;AAGI,IAAMqC,sBAAO,cAAb;kBACQ1G,Y","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"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["sessionTypes/passwordGrantAuth.js"],"names":["PasswordGrantAuth","sdk","_sdk","_sessionInfo","_auth0","auth0","Authentication","domain","
|
|
1
|
+
{"version":3,"sources":["sessionTypes/passwordGrantAuth.js"],"names":["PasswordGrantAuth","sdk","_sdk","_sessionInfo","_auth0","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","axios","post","host","Object","keys","map","audienceName","filter","nonce","headers","Authorization","data","_saveSession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;AADF,SAAlB;;AAIA,eAAOF,KAAKE,YAAZ;AACD,OA5BI,CAAP;AA6BD;;AAED;;;;;;;;;;;iCAQaC,W,EAAa;AACxB,WAAKzC,YAAL,GAAoByC,WAApB;AACD;;;;;;AAGI,IAAMC,sBAAO,mBAAb;kBACQ7C,iB","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"]}
|
package/package.json
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ndustrial/contxt-sdk",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.3.4",
|
|
4
4
|
"description": "",
|
|
5
5
|
"main": "lib/index.js",
|
|
6
6
|
"module": "esm/index.js",
|
|
7
|
+
"publishConfig": {
|
|
8
|
+
"access": "public"
|
|
9
|
+
},
|
|
7
10
|
"browser": {
|
|
8
11
|
"./esm/bus/index.js": "./esm/bus/index.browser.js",
|
|
9
12
|
"./lib/bus/index.js": "./lib/bus/index.browser.js",
|
|
@@ -102,4 +105,4 @@
|
|
|
102
105
|
"sinon": "^7.3.2",
|
|
103
106
|
"sinon-chai": "^3.2.0"
|
|
104
107
|
}
|
|
105
|
-
}
|
|
108
|
+
}
|
package/src/config/audiences.js
CHANGED
|
@@ -27,14 +27,14 @@ export default {
|
|
|
27
27
|
host: 'https://contxt.api.ndustrial.io'
|
|
28
28
|
},
|
|
29
29
|
staging: {
|
|
30
|
-
clientId: '
|
|
31
|
-
host: 'https://contxt-staging.
|
|
30
|
+
clientId: 'qGzdTXcmB57zlTp86rYsivG9qEss1lbF',
|
|
31
|
+
host: 'https://contxt-api.staging.ndustrial.io'
|
|
32
32
|
}
|
|
33
33
|
},
|
|
34
34
|
events: {
|
|
35
35
|
staging: {
|
|
36
36
|
clientId: 'dn4MaocJFdKtsBy9sFFaTeuJWL1nt5xu',
|
|
37
|
-
host: 'https://events
|
|
37
|
+
host: 'https://events.api.staging.ndustrial.io'
|
|
38
38
|
},
|
|
39
39
|
production: {
|
|
40
40
|
clientId: '7jzwfE20O2XZ4aq3cO1wmk63G9GzNc8j',
|
|
@@ -58,7 +58,7 @@ export default {
|
|
|
58
58
|
},
|
|
59
59
|
staging: {
|
|
60
60
|
clientId: 'SLE310LY4nDT5p06sUGPVOLlGXk5osbQ',
|
|
61
|
-
host: 'https://files
|
|
61
|
+
host: 'https://files.api.staging.ndustrial.io'
|
|
62
62
|
}
|
|
63
63
|
},
|
|
64
64
|
health: {
|
package/src/config/defaults.js
CHANGED
package/src/config/index.js
CHANGED
|
@@ -65,6 +65,8 @@ import defaultConfigs from './defaults';
|
|
|
65
65
|
* @property {string} auth.clientId Client Id provided by Auth0 for this application
|
|
66
66
|
* @property {string} [auth.clientSecret] Client secret provided by Auth0 for this application. This
|
|
67
67
|
* is optional for the auth0WebAuth SessionType, but required for the machineAuth SessionType
|
|
68
|
+
* @property {string} [auth.domain] Auth0 domain for this application. This is an optional configuration
|
|
69
|
+
* that defaults to the production Auth0 tenant
|
|
68
70
|
* @property {Object.<string, CustomAudience>} [auth.customModuleConfigs] Custom environment setups
|
|
69
71
|
* for individual modules. Requires clientId/host or env
|
|
70
72
|
* @property {string} [auth.env = 'production'] The environment that every module should use for
|
package/src/coordinator/roles.js
CHANGED
|
@@ -121,7 +121,7 @@ class Roles {
|
|
|
121
121
|
* .then((roleProject) => console.log(roleProject))
|
|
122
122
|
* .catch((err) => console.log(err));
|
|
123
123
|
*/
|
|
124
|
-
addProjectEnvironment(roleId,
|
|
124
|
+
addProjectEnvironment(roleId, projectEnvironmentId, accessType) {
|
|
125
125
|
if (!roleId) {
|
|
126
126
|
return Promise.reject(
|
|
127
127
|
new Error(
|
|
@@ -130,7 +130,7 @@ class Roles {
|
|
|
130
130
|
);
|
|
131
131
|
}
|
|
132
132
|
|
|
133
|
-
if (!
|
|
133
|
+
if (!projectEnvironmentId) {
|
|
134
134
|
return Promise.reject(
|
|
135
135
|
new Error(
|
|
136
136
|
'A project environment slug is required for adding a project environment to a role.'
|
|
@@ -150,7 +150,7 @@ class Roles {
|
|
|
150
150
|
.post(
|
|
151
151
|
`${
|
|
152
152
|
this._baseUrl
|
|
153
|
-
}/roles/${roleId}/project_environments/${
|
|
153
|
+
}/roles/${roleId}/project_environments/${projectEnvironmentId}`,
|
|
154
154
|
{
|
|
155
155
|
access_type: accessType
|
|
156
156
|
}
|
|
@@ -368,7 +368,7 @@ class Roles {
|
|
|
368
368
|
* .removeProjectEnvironment('36b8421a-cc4a-4204-b839-1397374fb16b', 'project-environment-slug')
|
|
369
369
|
* .catch((err) => console.log(err));
|
|
370
370
|
*/
|
|
371
|
-
removeProjectEnvironment(roleId,
|
|
371
|
+
removeProjectEnvironment(roleId, projectEnvironmentId) {
|
|
372
372
|
if (!roleId) {
|
|
373
373
|
return Promise.reject(
|
|
374
374
|
new Error(
|
|
@@ -377,7 +377,7 @@ class Roles {
|
|
|
377
377
|
);
|
|
378
378
|
}
|
|
379
379
|
|
|
380
|
-
if (!
|
|
380
|
+
if (!projectEnvironmentId) {
|
|
381
381
|
return Promise.reject(
|
|
382
382
|
new Error(
|
|
383
383
|
'A project environment slug is required for removing a project environment from a role.'
|
|
@@ -388,7 +388,7 @@ class Roles {
|
|
|
388
388
|
return this._request.delete(
|
|
389
389
|
`${
|
|
390
390
|
this._baseUrl
|
|
391
|
-
}/roles/${roleId}/project_environments/${
|
|
391
|
+
}/roles/${roleId}/project_environments/${projectEnvironmentId}`
|
|
392
392
|
);
|
|
393
393
|
}
|
|
394
394
|
}
|
|
@@ -199,7 +199,7 @@ describe('Coordinator/Roles', function() {
|
|
|
199
199
|
const roles = new Roles(baseSdk, request, expectedHost);
|
|
200
200
|
promise = roles.addProjectEnvironment(
|
|
201
201
|
role.id,
|
|
202
|
-
projectEnvironment.
|
|
202
|
+
projectEnvironment.id,
|
|
203
203
|
expectedRoleProjectEnvironment.accessType
|
|
204
204
|
);
|
|
205
205
|
});
|
|
@@ -207,7 +207,7 @@ describe('Coordinator/Roles', function() {
|
|
|
207
207
|
it('posts the role project environment to the server', function() {
|
|
208
208
|
expect(request.post).to.be.calledWith(
|
|
209
209
|
`${expectedHost}/roles/${role.id}/project_environments/${
|
|
210
|
-
projectEnvironment.
|
|
210
|
+
projectEnvironment.id
|
|
211
211
|
}`,
|
|
212
212
|
{
|
|
213
213
|
access_type: expectedRoleProjectEnvironment.accessType
|
|
@@ -241,7 +241,7 @@ describe('Coordinator/Roles', function() {
|
|
|
241
241
|
const roles = new Roles(baseSdk, baseRequest, expectedHost);
|
|
242
242
|
const promise = roles.addProjectEnvironment(
|
|
243
243
|
null,
|
|
244
|
-
projectEnvironment.
|
|
244
|
+
projectEnvironment.id,
|
|
245
245
|
roleProjectEnvironment.accessType
|
|
246
246
|
);
|
|
247
247
|
|
|
@@ -277,7 +277,7 @@ describe('Coordinator/Roles', function() {
|
|
|
277
277
|
const roles = new Roles(baseSdk, baseRequest, expectedHost);
|
|
278
278
|
const promise = roles.addProjectEnvironment(
|
|
279
279
|
role.id,
|
|
280
|
-
projectEnvironment.
|
|
280
|
+
projectEnvironment.id,
|
|
281
281
|
null
|
|
282
282
|
);
|
|
283
283
|
|
|
@@ -295,7 +295,7 @@ describe('Coordinator/Roles', function() {
|
|
|
295
295
|
const roles = new Roles(baseSdk, baseRequest, expectedHost);
|
|
296
296
|
const promise = roles.addProjectEnvironment(
|
|
297
297
|
role.id,
|
|
298
|
-
projectEnvironment.
|
|
298
|
+
projectEnvironment.id,
|
|
299
299
|
faker.random.word()
|
|
300
300
|
);
|
|
301
301
|
|
|
@@ -900,14 +900,14 @@ describe('Coordinator/Roles', function() {
|
|
|
900
900
|
const roles = new Roles(baseSdk, baseRequest, expectedHost);
|
|
901
901
|
promise = roles.removeProjectEnvironment(
|
|
902
902
|
role.id,
|
|
903
|
-
projectEnvironment.
|
|
903
|
+
projectEnvironment.id
|
|
904
904
|
);
|
|
905
905
|
});
|
|
906
906
|
|
|
907
907
|
it('sends a request to remove the project environment role role from the organization', function() {
|
|
908
908
|
expect(baseRequest.delete).to.be.calledWith(
|
|
909
909
|
`${expectedHost}/roles/${role.id}/project_environments/${
|
|
910
|
-
projectEnvironment.
|
|
910
|
+
projectEnvironment.id
|
|
911
911
|
}`
|
|
912
912
|
);
|
|
913
913
|
});
|
|
@@ -923,7 +923,7 @@ describe('Coordinator/Roles', function() {
|
|
|
923
923
|
const roles = new Roles(baseSdk, baseRequest, expectedHost);
|
|
924
924
|
const promise = roles.removeProjectEnvironment(
|
|
925
925
|
null,
|
|
926
|
-
projectEnvironment.
|
|
926
|
+
projectEnvironment.id
|
|
927
927
|
);
|
|
928
928
|
|
|
929
929
|
return expect(promise).to.be.rejectedWith(
|
package/src/coordinator/users.js
CHANGED
|
@@ -239,7 +239,7 @@ class Users {
|
|
|
239
239
|
* .then((userProject) => console.log(userProject))
|
|
240
240
|
* .catch((err) => console.log(err));
|
|
241
241
|
*/
|
|
242
|
-
addProjectEnvironment(userId,
|
|
242
|
+
addProjectEnvironment(userId, projectEnvironmentId, accessType) {
|
|
243
243
|
if (!userId) {
|
|
244
244
|
return Promise.reject(
|
|
245
245
|
new Error(
|
|
@@ -248,7 +248,7 @@ class Users {
|
|
|
248
248
|
);
|
|
249
249
|
}
|
|
250
250
|
|
|
251
|
-
if (!
|
|
251
|
+
if (!projectEnvironmentId) {
|
|
252
252
|
return Promise.reject(
|
|
253
253
|
new Error(
|
|
254
254
|
'A project environment slug is required for adding a project environment to a user.'
|
|
@@ -266,7 +266,7 @@ class Users {
|
|
|
266
266
|
|
|
267
267
|
return this._request
|
|
268
268
|
.post(
|
|
269
|
-
`${this._getBaseUrl()}/users/${userId}/project_environments/${
|
|
269
|
+
`${this._getBaseUrl()}/users/${userId}/project_environments/${projectEnvironmentId}`,
|
|
270
270
|
{
|
|
271
271
|
access_type: accessType
|
|
272
272
|
}
|
|
@@ -574,7 +574,7 @@ class Users {
|
|
|
574
574
|
* .removeProjectEnvironment('36b8421a-cc4a-4204-b839-1397374fb16b', 'project-environment-slug')
|
|
575
575
|
* .catch((err) => console.log(err));
|
|
576
576
|
*/
|
|
577
|
-
removeProjectEnvironment(userId,
|
|
577
|
+
removeProjectEnvironment(userId, projectEnvironmentId) {
|
|
578
578
|
if (!userId) {
|
|
579
579
|
return Promise.reject(
|
|
580
580
|
new Error(
|
|
@@ -583,7 +583,7 @@ class Users {
|
|
|
583
583
|
);
|
|
584
584
|
}
|
|
585
585
|
|
|
586
|
-
if (!
|
|
586
|
+
if (!projectEnvironmentId) {
|
|
587
587
|
return Promise.reject(
|
|
588
588
|
new Error(
|
|
589
589
|
'A project environment slug is required for removing a project environment from a user.'
|
|
@@ -592,7 +592,7 @@ class Users {
|
|
|
592
592
|
}
|
|
593
593
|
|
|
594
594
|
return this._request.delete(
|
|
595
|
-
`${this._getBaseUrl()}/users/${userId}/project_environments/${
|
|
595
|
+
`${this._getBaseUrl()}/users/${userId}/project_environments/${projectEnvironmentId}`
|
|
596
596
|
);
|
|
597
597
|
}
|
|
598
598
|
|
|
@@ -491,7 +491,7 @@ describe('Coordinator/Users', function() {
|
|
|
491
491
|
|
|
492
492
|
promise = users.addProjectEnvironment(
|
|
493
493
|
user.id,
|
|
494
|
-
projectEnvironment.
|
|
494
|
+
projectEnvironment.id,
|
|
495
495
|
expectedUserProjectEnvironment.accessType
|
|
496
496
|
);
|
|
497
497
|
});
|
|
@@ -503,7 +503,7 @@ describe('Coordinator/Users', function() {
|
|
|
503
503
|
it('posts the user project to the server', function() {
|
|
504
504
|
expect(request.post).to.be.calledWith(
|
|
505
505
|
`${expectedTenantBaseUrl}/users/${user.id}/project_environments/${
|
|
506
|
-
projectEnvironment.
|
|
506
|
+
projectEnvironment.id
|
|
507
507
|
}`,
|
|
508
508
|
{
|
|
509
509
|
access_type: expectedUserProjectEnvironment.accessType
|
|
@@ -535,7 +535,7 @@ describe('Coordinator/Users', function() {
|
|
|
535
535
|
const users = new Users(baseSdk, baseRequest, expectedTenantBaseUrl);
|
|
536
536
|
const promise = users.addProjectEnvironment(
|
|
537
537
|
null,
|
|
538
|
-
projectEnvironment.
|
|
538
|
+
projectEnvironment.id,
|
|
539
539
|
userProjectEnvironment.accessType
|
|
540
540
|
);
|
|
541
541
|
|
|
@@ -571,7 +571,7 @@ describe('Coordinator/Users', function() {
|
|
|
571
571
|
const users = new Users(baseSdk, baseRequest, expectedTenantBaseUrl);
|
|
572
572
|
const promise = users.addProjectEnvironment(
|
|
573
573
|
user.id,
|
|
574
|
-
projectEnvironment.
|
|
574
|
+
projectEnvironment.id,
|
|
575
575
|
null
|
|
576
576
|
);
|
|
577
577
|
|
|
@@ -588,7 +588,7 @@ describe('Coordinator/Users', function() {
|
|
|
588
588
|
const users = new Users(baseSdk, baseRequest, expectedTenantBaseUrl);
|
|
589
589
|
const promise = users.addProjectEnvironment(
|
|
590
590
|
user.id,
|
|
591
|
-
projectEnvironment.
|
|
591
|
+
projectEnvironment.id,
|
|
592
592
|
faker.random.word()
|
|
593
593
|
);
|
|
594
594
|
|
|
@@ -1339,7 +1339,7 @@ describe('Coordinator/Users', function() {
|
|
|
1339
1339
|
|
|
1340
1340
|
promise = users.removeProjectEnvironment(
|
|
1341
1341
|
user.id,
|
|
1342
|
-
projectEnvironment.
|
|
1342
|
+
projectEnvironment.id
|
|
1343
1343
|
);
|
|
1344
1344
|
});
|
|
1345
1345
|
|
|
@@ -1350,7 +1350,7 @@ describe('Coordinator/Users', function() {
|
|
|
1350
1350
|
it('sends a request to removeProjectEnvironment the user from the organization', function() {
|
|
1351
1351
|
expect(baseRequest.delete).to.be.calledWith(
|
|
1352
1352
|
`${expectedTenantBaseUrl}/users/${user.id}/project_environments/${
|
|
1353
|
-
projectEnvironment.
|
|
1353
|
+
projectEnvironment.id
|
|
1354
1354
|
}`
|
|
1355
1355
|
);
|
|
1356
1356
|
});
|
|
@@ -1366,7 +1366,7 @@ describe('Coordinator/Users', function() {
|
|
|
1366
1366
|
const users = new Users(baseSdk, baseRequest, expectedTenantBaseUrl);
|
|
1367
1367
|
const promise = users.removeProjectEnvironment(
|
|
1368
1368
|
null,
|
|
1369
|
-
projectEnvironment.
|
|
1369
|
+
projectEnvironment.id
|
|
1370
1370
|
);
|
|
1371
1371
|
|
|
1372
1372
|
return expect(promise).to.be.rejectedWith(
|
|
@@ -90,7 +90,7 @@ class Auth0WebAuth {
|
|
|
90
90
|
this._auth0 = new auth0.WebAuth({
|
|
91
91
|
audience: this._sdk.config.audiences.contxtAuth.clientId,
|
|
92
92
|
clientID: this._sdk.config.auth.clientId,
|
|
93
|
-
domain:
|
|
93
|
+
domain: this._sdk.config.auth.domain,
|
|
94
94
|
redirectUri: `${currentUrl.origin}${currentUrl.pathname}`,
|
|
95
95
|
responseType: 'token',
|
|
96
96
|
scope: 'email profile openid'
|