From ee4e8eada217e07524f125ca7fad7f7e00708a33 Mon Sep 17 00:00:00 2001 From: hornta Date: Mon, 4 Oct 2021 01:44:45 +0200 Subject: [PATCH 01/22] refactor to es6 syntax with classes --- .eslintignore | 2 + .eslintrc.js | 58 + .jsdoc.json | 54 +- package.json | 21 +- scripts/jsdocs.js | 4 +- src/Auth0RestClient.js | 143 +- src/RetryRestClient.js | 159 +- src/auth/DatabaseAuthenticator.js | 510 ++-- src/auth/OAUthWithIDTokenValidation.js | 89 +- src/auth/OAuthAuthenticator.js | 680 +++--- src/auth/PasswordlessAuthenticator.js | 495 ++-- src/auth/TokensManager.js | 483 ++-- src/auth/UsersManager.js | 313 ++- src/auth/idToken.js | 41 +- src/auth/index.js | 292 +-- src/errors.js | 46 +- src/index.js | 3 +- src/management/ActionsManager.js | 1117 +++++---- src/management/BlacklistedTokensManager.js | 165 +- src/management/BrandingManager.js | 107 +- src/management/ClientGrantsManager.js | 88 +- src/management/ClientsManager.js | 100 +- src/management/ConnectionsManager.js | 121 +- src/management/CustomDomainsManager.js | 97 +- src/management/DeviceCredentialsManager.js | 69 +- src/management/EmailProviderManager.js | 81 +- src/management/EmailTemplatesManager.js | 73 +- src/management/GrantsManager.js | 72 +- src/management/GuardianManager.js | 261 +-- src/management/HooksManager.js | 172 +- src/management/JobsManager.js | 197 +- src/management/LogStreamsManager.js | 94 +- src/management/LogsManager.js | 75 +- src/management/ManagementTokenProvider.js | 81 +- src/management/MigrationsManager.js | 56 +- src/management/OrganizationsManager.js | 446 ++-- src/management/PromptsManager.js | 105 +- src/management/ResourceServersManager.js | 100 +- src/management/RolesManager.js | 211 +- src/management/RulesConfigsManager.js | 73 +- src/management/RulesManager.js | 101 +- src/management/StatsManager.js | 60 +- src/management/TenantManager.js | 182 +- src/management/TicketsManager.js | 222 +- src/management/UserBlocksManager.js | 300 ++- src/management/UsersManager.js | 1585 ++++++------- src/management/index.js | 2056 +++++++---------- src/utils.js | 82 +- test/auth/authentication-client.tests.js | 202 +- test/auth/database-auth.tests.js | 432 ++-- .../oauth-with-idtoken-validation.tests.js | 567 +++-- test/auth/oauth.tests.js | 643 +++--- test/auth/passwordless.tests.js | 539 ++--- test/auth/tokens-manager.tests.js | 370 ++- test/auth/user-profile.tests.js | 19 - test/auth/users-manager.tests.js | 244 +- test/auth0-rest-client.tests.js | 209 +- test/auth0.tests.js | 15 +- test/constants.js | 2 +- test/errors.tests.js | 76 +- test/idToken.tests.js | 156 +- test/management/actions.tests.js | 718 +++--- test/management/blacklisted-tokens.tests.js | 158 +- test/management/branding.tests.js | 305 ++- test/management/client-grants.tests.js | 198 +- test/management/client.tests.js | 209 +- test/management/connections.tests.js | 360 ++- test/management/custom-domains.tests.js | 261 +-- test/management/device-credentials.tests.js | 193 +- test/management/email-provider.tests.js | 245 +- test/management/email-templates.tests.js | 152 +- test/management/grants.tests.js | 124 +- test/management/guardian.tests.js | 725 +++--- test/management/hooks.tests.js | 491 ++-- test/management/jobs.tests.js | 520 ++--- test/management/log-streams.tests.js | 282 +-- test/management/logs.tests.js | 161 +- test/management/management-client.tests.js | 256 +- .../management-token-provider.tests.js | 343 ++- test/management/migrations.tests.js | 158 +- test/management/organizations.tests.js | 1207 +++++----- test/management/prompts.tests.js | 294 ++- test/management/resource-servers.tests.js | 294 +-- test/management/roles.tests.js | 535 ++--- test/management/rules-configs.tests.js | 187 +- test/management/rules.tests.js | 293 +-- test/management/stats.tests.js | 147 +- test/management/tenant.tests.js | 163 +- test/management/tickets.tests.js | 157 +- test/management/user-blocks.tests.js | 235 +- test/management/users.tests.js | 1145 ++++----- test/retry-rest-client.tests.js | 277 +-- test/utils.tests.js | 16 +- test/utils/ensureMethod.js | 6 +- test/utils/ensureProperty.js | 6 +- test/utils/extractParts.js | 14 +- test/utils/index.js | 2 +- webpack.config.js | 38 +- yarn.lock | 1218 +++++++--- 99 files changed, 12841 insertions(+), 14668 deletions(-) create mode 100644 .eslintignore create mode 100644 .eslintrc.js delete mode 100644 test/auth/user-profile.tests.js diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 000000000..3d0cec322 --- /dev/null +++ b/.eslintignore @@ -0,0 +1,2 @@ +!.mocharc.js +docs diff --git a/.eslintrc.js b/.eslintrc.js new file mode 100644 index 000000000..6a2bf37af --- /dev/null +++ b/.eslintrc.js @@ -0,0 +1,58 @@ +module.exports = { + env: { + node: true, + commonjs: true, + es2017: true, + mocha: true, + }, + extends: [ + 'eslint:recommended', + 'plugin:jsdoc/recommended', + 'plugin:node/recommended', + 'plugin:prettier/recommended', + ], + plugins: ['jsdoc'], + parserOptions: { + ecmaVersion: 9, + }, + rules: { + // https://eslint.org/docs/rules/#ecmascript-6 + 'arrow-body-style': 'error', + 'arrow-parens': 'error', + 'arrow-spacing': 'error', + 'constructor-super': 'error', + 'generator-star-spacing': 'error', + 'no-class-assign': 'error', + 'no-confusing-arrow': 'error', + 'no-const-assign': 'error', + 'no-dupe-class-members': 'error', + 'no-duplicate-imports': 'error', + 'no-new-symbol': 'error', + 'no-restricted-exports': 'error', + 'no-restricted-imports': 'error', + 'no-this-before-super': 'error', + 'no-useless-computed-key': 'error', + 'no-useless-constructor': 'error', + 'no-useless-rename': 'error', + 'no-var': 'error', + 'object-shorthand': 'error', + 'prefer-arrow-callback': 'error', + 'prefer-const': 'error', + 'prefer-destructuring': 'error', + 'prefer-numeric-literals': 'error', + 'prefer-rest-params': 'error', + 'prefer-spread': 'error', + 'prefer-template': 'error', + 'require-yield': 'error', + 'rest-spread-spacing': 'error', + 'sort-imports': 'error', + 'symbol-description': 'error', + 'template-curly-spacing': 'error', + 'yield-star-spacing': 'error', + + 'jsdoc/require-jsdoc': ['warn', { publicOnly: true }], + 'jsdoc/require-returns-description': 'off', + 'jsdoc/no-undefined-types': 'off', + 'jsdoc/require-param': 'off', + }, +}; diff --git a/.jsdoc.json b/.jsdoc.json index 05d137a62..1e02225d1 100644 --- a/.jsdoc.json +++ b/.jsdoc.json @@ -1,32 +1,24 @@ { - "tags": { - "allowUnknownTags": true, - "dictionaries": [ - "jsdoc" - ] - }, - "source": { - "include": [ - "src", - "package.json", - "README.md" - ], - "includePattern": ".js$", - "excludePattern": "(node_modules/|docs|test)" - }, - "plugins": [ - "./node_modules/jsdoc/plugins/markdown" - ], - "templates": { - "cleverLinks": false, - "monospaceLinks": true, - "useLongnameInNav": false - }, - "opts": { - "destination": "./out/", - "encoding": "utf8", - "private": false, - "recurse": true, - "template": "./node_modules/minami" - } -} \ No newline at end of file + "tags": { + "allowUnknownTags": true, + "dictionaries": ["jsdoc"] + }, + "source": { + "include": ["src", "package.json", "README.md"], + "includePattern": ".js$", + "excludePattern": "(node_modules/|docs|test)" + }, + "plugins": ["./node_modules/jsdoc/plugins/markdown"], + "templates": { + "cleverLinks": false, + "monospaceLinks": true, + "useLongnameInNav": false + }, + "opts": { + "destination": "./out/", + "encoding": "utf8", + "private": false, + "recurse": true, + "template": "./node_modules/minami" + } +} diff --git a/package.json b/package.json index 7b9764c3e..27c14d820 100644 --- a/package.json +++ b/package.json @@ -7,8 +7,11 @@ "files": [ "src" ], + "engines": { + "node": ">=12" + }, "scripts": { - "test": "mocha --reporter spec ./test/**/*.tests.js ./test/*.tests.js", + "test": "mocha --reporter spec ./test/**/*.tests.js", "test:ci": "nyc npm run test -- --forbid-only --reporter mocha-junit-reporter", "test:coverage": "codecov", "test:watch": "cross-env NODE_ENV=test mocha --timeout 5000 ./test/**/*.tests.js ./test/*.tests.js --watch", @@ -43,21 +46,25 @@ "chai": "^4.2.0", "codecov": "^3.7.2", "cross-env": "^5.2.0", + "eslint": "^7.32.0", + "eslint-config-prettier": "^8.3.0", + "eslint-plugin-jsdoc": "^36.1.0", + "eslint-plugin-node": "^11.1.0", + "eslint-plugin-prettier": "^4.0.0", "husky": "^3.0.1", "jsdoc": "^3.6.3", "json-loader": "^0.5.7", "jws": "^3.2.2", "minami": "^1.2.3", - "mocha": "^6.2.0", - "mocha-junit-reporter": "^1.23.1", - "moment": "^2.24.0", + "mocha": "^9.1.2", + "mocha-junit-reporter": "^2.0.0", "nock": "^10.0.6", "nyc": "^14.1.1", "pem": "^1.14.2", - "prettier": "^1.18.2", + "prettier": "2.4.1", "pretty-quick": "^1.11.1", - "proxyquire": "^2.1.1", - "sinon": "^9.0.3", + "proxyquire": "^2.1.3", + "sinon": "^11.1.2", "string-replace-webpack-plugin": "0.1.3", "webpack": "^4.36.1" } diff --git a/scripts/jsdocs.js b/scripts/jsdocs.js index ed78616a6..e269a592a 100644 --- a/scripts/jsdocs.js +++ b/scripts/jsdocs.js @@ -1,5 +1,5 @@ const fs = require('fs'); -const execSync = require('child_process').execSync; +const { execSync } = require('child_process'); const library = require('../package.json'); execSync('npm run jsdoc:generate', { stdio: 'inherit' }); @@ -7,5 +7,5 @@ if (fs.existsSync('docs')) { execSync('rm -r docs', { stdio: 'inherit' }); } execSync(`mv out/auth0/${library.version}/ docs`, { - stdio: 'inherit' + stdio: 'inherit', }); diff --git a/src/Auth0RestClient.js b/src/Auth0RestClient.js index 3b704d7cc..134220e36 100644 --- a/src/Auth0RestClient.js +++ b/src/Auth0RestClient.js @@ -1,89 +1,90 @@ -var RestClient = require('rest-facade').Client; -var ArgumentError = require('rest-facade').ArgumentError; +const RestClient = require('rest-facade').Client; +const { ArgumentError } = require('rest-facade'); -var utils = require('./utils'); -var SanitizedError = require('./errors').SanitizedError; +const utils = require('./utils'); +const { SanitizedError } = require('./errors'); -var Auth0RestClient = function(resourceUrl, options, provider) { - if (resourceUrl === null || resourceUrl === undefined) { - throw new ArgumentError('Must provide a Resource Url'); - } - - if ('string' !== typeof resourceUrl || resourceUrl.length === 0) { - throw new ArgumentError('The provided Resource Url is invalid'); - } +class Auth0RestClient { + constructor(resourceUrl, options, provider) { + if (resourceUrl === null || resourceUrl === undefined) { + throw new ArgumentError('Must provide a Resource Url'); + } - if (options === null || typeof options !== 'object') { - throw new ArgumentError('Must provide options'); - } + if ('string' !== typeof resourceUrl || resourceUrl.length === 0) { + throw new ArgumentError('The provided Resource Url is invalid'); + } - options.errorCustomizer = options.errorCustomizer || SanitizedError; - options.errorFormatter = options.errorFormatter || { message: 'message', name: 'error' }; + if (options === null || typeof options !== 'object') { + throw new ArgumentError('Must provide options'); + } - this.options = options; - this.provider = provider; - this.restClient = new RestClient(resourceUrl, options); + options.errorCustomizer = options.errorCustomizer || SanitizedError; + options.errorFormatter = options.errorFormatter || { message: 'message', name: 'error' }; + + this.options = options; + this.provider = provider; + this.restClient = new RestClient(resourceUrl, options); + + this.wrappedProvider = function (method, args) { + if (!this.provider) { + return this.restClient[method](...args); + } + + let callback; + if (args && args[args.length - 1] instanceof Function) { + callback = args[args.length - 1]; + } + + return this.provider + .getAccessToken() + .then((access_token) => { + this.restClient.options.headers['Authorization'] = `Bearer ${access_token}`; + return this.restClient[method](...args); + }) + .catch((err) => { + if (callback) { + return callback(err); + } + return Promise.reject(err); + }); + }; + } - this.wrappedProvider = function(method, args) { - if (!this.provider) { - return this.restClient[method].apply(this.restClient, args); - } + getAll(...args) { + return this.wrappedProvider('getAll', args); + } - var callback; - if (args && args[args.length - 1] instanceof Function) { - callback = args[args.length - 1]; + get(params, callback) { + if (typeof params === 'object' && params.id) { + params.id = utils.maybeDecode(`${params.id}`); } - - var self = this; - return this.provider - .getAccessToken() - .then(function(access_token) { - self.restClient.options.headers['Authorization'] = 'Bearer ' + access_token; - return self.restClient[method].apply(self.restClient, args); - }) - .catch(function(err) { - if (callback) { - return callback(err); - } - return Promise.reject(err); - }); - }; -}; - -Auth0RestClient.prototype.getAll = function(params, callback) { - return this.wrappedProvider('getAll', arguments); -}; - -Auth0RestClient.prototype.get = function(params, callback) { - if (typeof params === 'object' && params.id) { - params.id = utils.maybeDecode(`${params.id}`); + return this.wrappedProvider('get', [...[params, callback].filter(Boolean)]); } - return this.wrappedProvider('get', [...[params, callback].filter(Boolean)]); -}; -Auth0RestClient.prototype.create = function(/* [params], [callback] */) { - return this.wrappedProvider('create', arguments); -}; + create(...args) { + return this.wrappedProvider('create', args); + } -Auth0RestClient.prototype.patch = function(params, callback) { - if (typeof params === 'object' && params.id) { - params.id = utils.maybeDecode(`${params.id}`); + patch(params, ...restOfArgs) { + if (typeof params === 'object' && params.id) { + params.id = utils.maybeDecode(`${params.id}`); + } + return this.wrappedProvider('patch', [params, ...restOfArgs]); } - return this.wrappedProvider('patch', arguments); -}; -Auth0RestClient.prototype.update = function(params, callback) { - if (typeof params === 'object' && params.id) { - params.id = utils.maybeDecode(`${params.id}`); + update(params, ...restOfArgs) { + if (typeof params === 'object' && params.id) { + params.id = utils.maybeDecode(`${params.id}`); + } + return this.wrappedProvider('update', [params, ...restOfArgs]); } - return this.wrappedProvider('update', arguments); -}; -Auth0RestClient.prototype.delete = function(params, callback) { - if (typeof params === 'object' && params.id) { - params.id = utils.maybeDecode(`${params.id}`); + delete(params, ...restOfArgs) { + if (typeof params === 'object' && params.id) { + params.id = utils.maybeDecode(`${params.id}`); + } + return this.wrappedProvider('delete', [params, ...restOfArgs]); } - return this.wrappedProvider('delete', arguments); -}; +} module.exports = Auth0RestClient; diff --git a/src/RetryRestClient.js b/src/RetryRestClient.js index 9146ecf9c..65f01b4a1 100644 --- a/src/RetryRestClient.js +++ b/src/RetryRestClient.js @@ -1,108 +1,105 @@ -var retry = require('retry'); -var ArgumentError = require('rest-facade').ArgumentError; +const retry = require('retry'); +const { ArgumentError } = require('rest-facade'); -var DEFAULT_OPTIONS = { +const DEFAULT_OPTIONS = { maxRetries: 3, enabled: true, - randomize: true + randomize: true, }; /** - * @class RetryRestClient * Wrapper Rest Client that adds Retry functionality when requests are failing due to rate limiting (status code 429). - * @constructor - * @memberOf module:management - * @param {Object} restClient RestClient. - * @param {Object} [options] Options for the RetryRestClient. - * @param {Object} [options.enabled:true] Enabled or Disable Retry Policy functionality. - * @param {Number} [options.maxRetries=3] The maximum amount of times to retry the operation. Default is 3. - * @param {*} [options.*] Any options that are available in https://github.com/tim-kos/node-retry#retryoperationoptions */ -var RetryRestClient = function(restClient, options) { - if (restClient === null || typeof restClient !== 'object') { - throw new ArgumentError('Must provide RestClient'); +class RetryRestClient { + /** + * @param {object} restClient RestClient. + * @param {object} [options] Options for the RetryRestClient. It includes all properties from https://github.com/tim-kos/node-retry#retryoperationoptions + * @param {object} [options.enabled=true] Enabled or Disable Retry Policy functionality. + * @param {number} [options.maxRetries=3] The maximum amount of times to retry the operation. + */ + constructor(restClient, options) { + if (restClient === null || typeof restClient !== 'object') { + throw new ArgumentError('Must provide RestClient'); + } + + const params = Object.assign({}, DEFAULT_OPTIONS, options); + + if (typeof params.enabled !== 'boolean') { + throw new ArgumentError('Must provide enabled boolean value'); + } + + if (typeof params.maxRetries !== 'number' || params.maxRetries <= 0) { + throw new ArgumentError('Must provide maxRetries as a positive number'); + } + + this.restClient = restClient; + this.enabled = params.enabled; + this.retryOptions = Object.assign({ retries: params.maxRetries }, params); } - var params = Object.assign({}, DEFAULT_OPTIONS, options); - - if (typeof params.enabled !== 'boolean') { - throw new ArgumentError('Must provide enabled boolean value'); + getAll(...args) { + return this.invoke('getAll', args); } - if (typeof params.maxRetries !== 'number' || params.maxRetries <= 0) { - throw new ArgumentError('Must provide maxRetries as a positive number'); + get(...args) { + return this.invoke('get', args); } - this.restClient = restClient; - this.enabled = params.enabled; - this.retryOptions = Object.assign({ retries: params.maxRetries }, params); -}; - -RetryRestClient.prototype.getAll = function(/* [params], [callback] */) { - return this.invoke('getAll', arguments); -}; - -RetryRestClient.prototype.get = function(/* [params], [callback] */) { - return this.invoke('get', arguments); -}; - -RetryRestClient.prototype.create = function(/* [params], [callback] */) { - return this.invoke('create', arguments); -}; - -RetryRestClient.prototype.patch = function(/* [params], [callback] */) { - return this.invoke('patch', arguments); -}; + create(...args) { + return this.invoke('create', args); + } -RetryRestClient.prototype.update = function(/* [params], [callback] */) { - return this.invoke('update', arguments); -}; + patch(...args) { + return this.invoke('patch', args); + } -RetryRestClient.prototype.delete = function(/* [params], [callback] */) { - return this.invoke('delete', arguments); -}; + update(...args) { + return this.invoke('update', args); + } -RetryRestClient.prototype.invoke = function(method, args) { - var cb; - args = Array.prototype.slice.call(args); // convert array-like object to array. - if (args && args[args.length - 1] instanceof Function) { - cb = args[args.length - 1]; - args.pop(); // Remove the callback + delete(...args) { + return this.invoke('delete', args); } - var promise = this.handleRetry(method, args); + invoke(method, args) { + let cb; + if (args && args[args.length - 1] instanceof Function) { + cb = args[args.length - 1]; + args.pop(); // Remove the callback + } - if (cb instanceof Function) { - promise.then(cb.bind(null, null)).catch(cb); - return; - } + const promise = this.handleRetry(method, args); - return promise; -}; + if (cb instanceof Function) { + promise.then(cb.bind(null, null)).catch(cb); + return; + } -RetryRestClient.prototype.handleRetry = function(method, args) { - if (!this.enabled) { - return this.restClient[method].apply(this.restClient, args); + return promise; } - var self = this; - return new Promise(function(resolve, reject) { - var operation = retry.operation(self.retryOptions); - - operation.attempt(function() { - self.restClient[method] - .apply(self.restClient, args) - .then(function(body) { - resolve(body); - }) - .catch(function(err) { - if (err && err.statusCode === 429 && operation.retry(err)) { - return; - } - reject(err); - }); + handleRetry(method, args) { + if (!this.enabled) { + return this.restClient[method](...args); + } + + return new Promise((resolve, reject) => { + const operation = retry.operation(this.retryOptions); + + operation.attempt(() => { + this.restClient[method](...args) + .then((body) => { + resolve(body); + }) + .catch((err) => { + if (err && err.statusCode === 429 && operation.retry(err)) { + return; + } + reject(err); + }); + }); }); - }); -}; + } +} module.exports = RetryRestClient; diff --git a/src/auth/DatabaseAuthenticator.js b/src/auth/DatabaseAuthenticator.js index 6d642e6d9..82fb5c853 100644 --- a/src/auth/DatabaseAuthenticator.js +++ b/src/auth/DatabaseAuthenticator.js @@ -1,297 +1,289 @@ -var extend = require('util')._extend; - -var ArgumentError = require('rest-facade').ArgumentError; -var RestClient = require('rest-facade').Client; +const { ArgumentError } = require('rest-facade'); +const RestClient = require('rest-facade').Client; /** - * @class * Abstracts the sign-in, sign-up and change-password processes for Database & * Active Directory authentication services. - * @constructor - * @memberOf module:auth - * - * @param {Object} options Authenticator options. - * @param {String} options.baseUrl The auth0 account URL. - * @param {String} [options.clientId] Default client ID. - * @param {OAuthAuthenticator} oauth OAuthAuthenticator instance. */ -var DatabaseAuthenticator = function(options, oauth) { - if (!options) { - throw new ArgumentError('Missing authenticator options'); - } +class DatabaseAuthenticator { + /** + * @memberof module:auth + * @param {object} options Authenticator options. + * @param {string} options.baseUrl The auth0 account URL. + * @param {string} [options.clientId] Default client ID. + * @param {OAuthAuthenticator} oauth OAuthAuthenticator instance. + */ + constructor(options, oauth) { + if (!options) { + throw new ArgumentError('Missing authenticator options'); + } - if (typeof options !== 'object') { - throw new ArgumentError('The authenticator options must be an object'); + if (typeof options !== 'object') { + throw new ArgumentError('The authenticator options must be an object'); + } + + /** + * Options object for the Rest Client instance. + * + * @type {object} + */ + const clientOptions = { + errorFormatter: { message: 'message', name: 'error' }, + headers: options.headers, + }; + + this.oauth = oauth; + this.dbConnections = new RestClient(`${options.baseUrl}/dbconnections/:type`, clientOptions); + this.clientId = options.clientId; } /** - * Options object for the Rest Client instance. + * Sign in using a database or active directory service. + * + * @function signIn + * @memberof module:auth.DatabaseAuthenticator.prototype + * @example + * Given the user credentials and the connection specified, it will do the + * authentication on the provider and return a JSON with the `access_token` + * and `id_token`. Find more information about the structure of the data + * object in the + * API docs. + * * - * @type {Object} + * var data = { + * username: '{USERNAME}', + * password: '{PASSWORD}', + * connection: 'Username-Password-Authentication' // Optional field. + * }; + * + * auth0.database.signIn(data, function (err, userData) { + * if (err) { + * // Handle error. + * } + * + * console.log(userData); + * }); + * @param {object} userData User credentials object. + * @param {string} userData.username Username. + * @param {string} userData.password User password. + * @param {string} userData.connection Identity provider in use. + * @param {Function} [cb] Method callback. + * @returns {Promise|undefined} */ - var clientOptions = { - errorFormatter: { message: 'message', name: 'error' }, - headers: options.headers - }; + signIn(userData, cb) { + if (!userData || typeof userData !== 'object') { + throw new ArgumentError('Missing user data object'); + } - this.oauth = oauth; - this.dbConnections = new RestClient(options.baseUrl + '/dbconnections/:type', clientOptions); - this.clientId = options.clientId; -}; + const data = { + connection: 'Username-Password-Authentication', + ...userData, + }; -/** - * Sign in using a database or active directory service. - * @method signIn - * @memberOf module:auth.DatabaseAuthenticator.prototype - * - * @example - * Given the user credentials and the connection specified, it will do the - * authentication on the provider and return a JSON with the `access_token` - * and `id_token`. Find more information about the structure of the data - * object in the - * API docs. - * - * - * var data = { - * username: '{USERNAME}', - * password: '{PASSWORD}', - * connection: 'Username-Password-Authentication' // Optional field. - * }; - * - * auth0.database.signIn(data, function (err, userData) { - * if (err) { - * // Handle error. - * } - * - * console.log(userData); - * }); - * - * @param {Object} data User credentials object. - * @param {String} data.username Username. - * @param {String} data.password User password. - * @param {String} data.connection Identity provider in use. - * @param {Function} [cb] Method callback. - * - * @return {Promise|undefined} - */ -DatabaseAuthenticator.prototype.signIn = function(userData, cb) { - var defaultFields = { - connection: 'Username-Password-Authentication' - }; - var data = extend(defaultFields, userData); - - if (!userData || typeof userData !== 'object') { - throw new ArgumentError('Missing user data object'); - } + if (typeof data.username !== 'string' || data.username.trim().length === 0) { + throw new ArgumentError('username field is required'); + } - if (typeof data.username !== 'string' || data.username.trim().length === 0) { - throw new ArgumentError('username field is required'); - } + if (typeof data.password !== 'string' || data.password.trim().length === 0) { + throw new ArgumentError('password field is required'); + } - if (typeof data.password !== 'string' || data.password.trim().length === 0) { - throw new ArgumentError('password field is required'); + return this.oauth.signIn(data, cb); } - return this.oauth.signIn(data, cb); -}; + /** + * Sign up using a database or active directory service. + * + * @function signUp + * @memberof module:auth.DatabaseAuthenticator.prototype + * @example + * Given the user credentials, the connection specified and (optionally) the + * client ID, it will create a new user. Find more information in the + * + * API Docs. + * + * + * var data = { + * email: '{EMAIL}', + * password: '{PASSWORD}', + * connection: 'Username-Password-Authentication' // Optional field. + * }; + * + * auth0.database.signUp(data, function (err, userData) { + * if (err) { + * // Handle error. + * } + * + * console.log(userData); + * }); + * @param {object} userData User credentials object. + * @param {string} userData.email User email address. + * @param {string} userData.password User password. + * @param {string} userData.connection Identity provider in use. + * @param {Function} [cb] Method callback. + * @returns {Promise|undefined} + */ + signUp(userData, cb) { + if (!userData || typeof userData !== 'object') { + throw new ArgumentError('Missing user data object'); + } -/** - * Sign up using a database or active directory service. - * @method signUp - * @memberOf module:auth.DatabaseAuthenticator.prototype - * - * @example - * Given the user credentials, the connection specified and (optionally) the - * client ID, it will create a new user. Find more information in the - * - * API Docs. - * - * - * var data = { - * email: '{EMAIL}', - * password: '{PASSWORD}', - * connection: 'Username-Password-Authentication' // Optional field. - * }; - * - * auth0.database.signUp(data, function (err, userData) { - * if (err) { - * // Handle error. - * } - * - * console.log(userData); - * }); - * - * @param {Object} data User credentials object. - * @param {String} data.email User email address. - * @param {String} data.password User password. - * @param {String} data.connection Identity provider in use. - * @param {Function} [cb] Method callback. - * - * @return {Promise|undefined} - */ -DatabaseAuthenticator.prototype.signUp = function(userData, cb) { - var params = { - type: 'signup' - }; - var defaultFields = { - client_id: this.clientId - }; - var data = extend(defaultFields, userData); - - if (!userData || typeof userData !== 'object') { - throw new ArgumentError('Missing user data object'); - } + const data = { + client_id: this.clientId, + ...userData, + }; - if (typeof data.email !== 'string' || data.email.trim().length === 0) { - throw new ArgumentError('email field is required'); - } + if (typeof data.email !== 'string' || data.email.trim().length === 0) { + throw new ArgumentError('email field is required'); + } - if (typeof data.password !== 'string' || data.password.trim().length === 0) { - throw new ArgumentError('password field is required'); - } + if (typeof data.password !== 'string' || data.password.trim().length === 0) { + throw new ArgumentError('password field is required'); + } - if (typeof data.connection !== 'string' || data.connection.trim().length === 0) { - throw new ArgumentError('connection field is required'); - } + if (typeof data.connection !== 'string' || data.connection.trim().length === 0) { + throw new ArgumentError('connection field is required'); + } - if (cb && cb instanceof Function) { - return this.dbConnections.create(params, data, cb); - } + const params = { + type: 'signup', + }; - return this.dbConnections.create(params, data); -}; + if (cb && cb instanceof Function) { + return this.dbConnections.create(params, data, cb); + } -/** - * Change password using a database or active directory service. - * - * @method changePassword - * @memberOf module:auth.DatabaseAuthenticator.prototype - * - * @example - * Given the user email, the connection specified and the new password to - * use, Auth0 will send a forgot password email. Once the user clicks on the - * confirm password change link, the new password specified in this POST will - * be set to this user. Find more information in the - * + * API Docs. + * + * + * var data = { + * email: '{EMAIL}', + * password: '{PASSWORD}', + * connection: 'Username-Password-Authentication' + * }; + * + * auth0.database.changePassword(data, function (err, message) { + * if (err) { + * // Handle error. + * } + * + * console.log(message); + * }); + * @param {object} userData User credentials object. + * @param {string} userData.email User email address. + * @param {string} userData.password New password. + * @param {string} userData.connection Identity provider in use. + * @param {Function} [cb] Method callback. + * @returns {Promise|undefined} + */ + changePassword(userData, cb) { + if (!userData || typeof userData !== 'object') { + throw new ArgumentError('Missing user data object'); + } - if (typeof data.password !== 'string' || data.password.trim().length === 0) { - throw new ArgumentError('password field is required'); - } + const data = { + client_id: this.clientId, + ...userData, + }; - if (typeof data.connection !== 'string' || data.connection.trim().length === 0) { - throw new ArgumentError('connection field is required'); - } + if (typeof data.email !== 'string' || data.email.trim().length === 0) { + throw new ArgumentError('email field is required'); + } - if (cb && cb instanceof Function) { - return this.dbConnections.create(params, data, cb); - } + if (typeof data.password !== 'string' || data.password.trim().length === 0) { + throw new ArgumentError('password field is required'); + } - return this.dbConnections.create(params, data); -}; + if (typeof data.connection !== 'string' || data.connection.trim().length === 0) { + throw new ArgumentError('connection field is required'); + } -/** - * Request a change password email using a database or active directory service. - * - * @method requestChangePasswordEmail - * @memberOf module:auth.DatabaseAuthenticator.prototype - * - * @example - * Given the user email, the connection specified, Auth0 will send a change - * password email. once the user clicks on the confirm password change link, - * the new password specified in this POST will be set to this user. Find more - * information in the + * API Docs. + * + * + * var data = { + * email: '{EMAIL}', + * connection: 'Username-Password-Authentication', + * client_id: 'OS1VzKTVjizL0VCc9Hx2ae2aTPXWy6BD' + * }; + * + * auth0.database.requestChangePasswordEmail(data, function (err, message) { + * if (err) { + * // Handle error. + * } + * + * console.log(message); + * }); + * @param {object} userData User credentials object. + * @param {string} userData.email User email address. + * @param {string} userData.connection Identity provider in use. + * @param {string} userData.client_id Client ID of the Application requesting the password change, to be included in the email template. + * @param {Function} [cb] Method callback. + * @returns {Promise|undefined} + */ + requestChangePasswordEmail(userData, cb) { + if (!userData || typeof userData !== 'object') { + throw new ArgumentError('Missing user data object'); + } - return this.dbConnections.create(params, data); -}; + const data = { + client_id: this.clientId, + ...userData, + }; + + if (typeof data.email !== 'string' || data.email.trim().length === 0) { + throw new ArgumentError('email field is required'); + } + + if (typeof data.connection !== 'string' || data.connection.trim().length === 0) { + throw new ArgumentError('connection field is required'); + } + + const params = { + type: 'change_password', + }; + + if (cb && cb instanceof Function) { + return this.dbConnections.create(params, data, cb); + } + + return this.dbConnections.create(params, data); + } +} module.exports = DatabaseAuthenticator; diff --git a/src/auth/OAUthWithIDTokenValidation.js b/src/auth/OAUthWithIDTokenValidation.js index 3561a9382..59caf7521 100644 --- a/src/auth/OAUthWithIDTokenValidation.js +++ b/src/auth/OAUthWithIDTokenValidation.js @@ -1,27 +1,24 @@ -var jwt = require('jsonwebtoken'); -var jwksClient = require('jwks-rsa'); +const jwt = require('jsonwebtoken'); +const jwksClient = require('jwks-rsa'); +const { ArgumentError } = require('rest-facade'); +const validateIdToken = require('./idToken').validate; -var ArgumentError = require('rest-facade').ArgumentError; -var validateIdToken = require('./idToken').validate; - -var HS256_IGNORE_VALIDATION_MESSAGE = +const HS256_IGNORE_VALIDATION_MESSAGE = 'Validation of `id_token` requires a `clientSecret` when using the HS256 algorithm. To ensure tokens are validated, please switch the signing algorithm to RS256 or provide a `clientSecret` in the constructor.'; /** - * @class * Abstracts the `oauth.create` method with additional id_token validation - * @constructor - * @memberOf module:auth * - * @param {Object} oauth An instance of @type {OAuthAuthenticator} - * @param {Object} options Authenticator options. - * @param {String} options.domain AuthenticationClient server domain - * @param {String} [options.clientId] Default client ID. - * @param {String} [options.clientSecret] Default client Secret. - * @param {String} [options.supportedAlgorithms] Algorithms that your application expects to receive - * @param {Boolean} [options.__bypassIdTokenValidation] Whether the id_token should be validated or not + * @param {object} oauth An instance of @type {OAuthAuthenticator} + * @param {object} options Authenticator options. + * @param {string} options.domain AuthenticationClient server domain + * @param {string} [options.clientId] Default client ID. + * @param {string} [options.clientSecret] Default client Secret. + * @param {string} [options.supportedAlgorithms] Algorithms that your application expects to receive + * @param {boolean} [options.__bypassIdTokenValidation] Whether the id_token should be validated or not + * @param {Function} [options.jwksClient] Dependency injected `jwks-rsa` */ -var OAUthWithIDTokenValidation = function(oauth, options) { +const OAUthWithIDTokenValidation = function (oauth, options) { if (!oauth) { throw new ArgumentError('Missing OAuthAuthenticator param'); } @@ -40,50 +37,48 @@ var OAUthWithIDTokenValidation = function(oauth, options) { this.clientSecret = options.clientSecret; this.domain = options.domain; this.supportedAlgorithms = options.supportedAlgorithms || ['HS256', 'RS256']; - this._jwksClient = jwksClient({ - jwksUri: 'https://' + options.domain + '/.well-known/jwks.json' + this._jwksClient = (options.jwksClient || jwksClient)({ + jwksUri: `https://${options.domain}/.well-known/jwks.json`, }); }; /** * Creates an oauth request and validates the id_token (if any) * - * @method create - * @memberOf module:auth.OAuthWithIDTokenValidation.prototype - * - * @param {Object} params OAuth parameters that are passed through - * @param {Object} data Custom parameters sent to the OAuth endpoint - * @param {Function} [callback] Callback function - * - * @return {Promise|undefined} + * @function create + * @memberof module:auth.OAuthWithIDTokenValidation.prototype + * @param {object} params OAuth parameters that are passed through + * @param {object} data Custom parameters sent to the OAuth endpoint + * @param {Function} [cb] Callback function + * @returns {Promise|undefined} */ -OAUthWithIDTokenValidation.prototype.create = function(params, data, cb) { +OAUthWithIDTokenValidation.prototype.create = function (params, data, cb) { const _this = this; - const createAndValidate = this.oauth.create(params, data).then(r => { + const createAndValidate = this.oauth.create(params, data).then((r) => { if (_this.__bypassIdTokenValidation) { return r; } - if (r.id_token) { - function getKey(header, callback) { - if (header.alg === 'HS256') { - if (!_this.clientSecret) { - return callback({ message: HS256_IGNORE_VALIDATION_MESSAGE }); - } - return callback(null, Buffer.from(_this.clientSecret, 'base64')); + function getKey(header, callback) { + if (header.alg === 'HS256') { + if (!_this.clientSecret) { + return callback({ message: HS256_IGNORE_VALIDATION_MESSAGE }); } - _this._jwksClient.getSigningKey(header.kid, function(err, key) { - if (err) { - return callback(err); - } - var signingKey = key.publicKey || key.rsaPublicKey; - return callback(null, signingKey); - }); + return callback(null, Buffer.from(_this.clientSecret, 'base64')); } + _this._jwksClient.getSigningKey(header.kid, (err, key) => { + if (err) { + return callback(err); + } + const signingKey = key.publicKey || key.rsaPublicKey; + return callback(null, signingKey); + }); + } + if (r.id_token) { return new Promise((res, rej) => { - var options = { + const options = { algorithms: this.supportedAlgorithms, audience: this.clientId, - issuer: 'https://' + this.domain + '/' + issuer: `https://${this.domain}/`, }; if (data.organization) { @@ -98,7 +93,7 @@ OAUthWithIDTokenValidation.prototype.create = function(params, data, cb) { options.maxAge = data.maxAge; } - jwt.verify(r.id_token, getKey, options, function(err) { + jwt.verify(r.id_token, getKey, options, (err) => { if (err) { if (err.message && err.message.includes(HS256_IGNORE_VALIDATION_MESSAGE)) { console.warn(HS256_IGNORE_VALIDATION_MESSAGE); @@ -122,7 +117,7 @@ OAUthWithIDTokenValidation.prototype.create = function(params, data, cb) { if (!cb) { return createAndValidate; } - createAndValidate.then(r => cb(null, r)).catch(e => cb(e)); + createAndValidate.then((r) => cb(null, r)).catch((e) => cb(e)); }; module.exports = OAUthWithIDTokenValidation; diff --git a/src/auth/OAuthAuthenticator.js b/src/auth/OAuthAuthenticator.js index b73719bf7..8a1414a9b 100644 --- a/src/auth/OAuthAuthenticator.js +++ b/src/auth/OAuthAuthenticator.js @@ -1,11 +1,8 @@ -var extend = require('util')._extend; -var sanitizeArguments = require('../utils').sanitizeArguments; - -var ArgumentError = require('rest-facade').ArgumentError; -var RestClient = require('rest-facade').Client; - -var SanitizedError = require('../errors').SanitizedError; -var OAUthWithIDTokenValidation = require('./OAUthWithIDTokenValidation'); +const { sanitizeArguments } = require('../utils'); +const { ArgumentError } = require('rest-facade'); +const RestClient = require('rest-facade').Client; +const { SanitizedError } = require('../errors'); +const OAUthWithIDTokenValidation = require('./OAUthWithIDTokenValidation'); function getParamsFromOptions(options) { const params = {}; @@ -13,7 +10,7 @@ function getParamsFromOptions(options) { return params; } if (options.forwardedFor) { - params._requestCustomizer = function(req) { + params._requestCustomizer = function (req) { req.set('auth0-forwarded-for', options.forwardedFor); }; } @@ -24,387 +21,382 @@ function getParamsFromOptions(options) { } /** - * @class * Abstracts the sign-in, sign-up and change-password processes for Database & * Active Directory authentication services. - * @constructor - * @memberOf module:auth - * - * @param {Object} options Authenticator options. - * @param {String} options.baseUrl The Auth0 account URL. - * @param {String} options.domain AuthenticationClient server domain - * @param {String} [options.clientId] Default client ID. - * @param {String} [options.clientSecret] Default client Secret. - * @param {Boolean} [options.__bypassIdTokenValidation] Whether the id_token should be validated or not */ -var OAuthAuthenticator = function(options) { - if (!options) { - throw new ArgumentError('Missing authenticator options'); - } +class OAuthAuthenticator { + /** + * @memberof module:auth + * @param {object} options Authenticator options. + * @param {string} options.baseUrl The Auth0 account URL. + * @param {string} options.domain AuthenticationClient server domain + * @param {string} [options.clientId] Default client ID. + * @param {string} [options.clientSecret] Default client Secret. + * @param {boolean} [options.__bypassIdTokenValidation] Whether the id_token should be validated or not + */ + constructor(options) { + if (!options) { + throw new ArgumentError('Missing authenticator options'); + } + + if (typeof options !== 'object') { + throw new ArgumentError('The authenticator options must be an object'); + } + + /** + * Options object for the Rest Client instance. + * + * @type {object} + */ + const clientOptions = { + errorCustomizer: SanitizedError, + errorFormatter: { message: 'message', name: 'error' }, + headers: options.headers, + }; - if (typeof options !== 'object') { - throw new ArgumentError('The authenticator options must be an object'); + this.oauth = new RestClient(`${options.baseUrl}/oauth/:type`, clientOptions); + this.oauthWithIDTokenValidation = new OAUthWithIDTokenValidation(this.oauth, options); + this.clientId = options.clientId; + this.clientSecret = options.clientSecret; } /** - * Options object for the Rest Client instance. + * Sign in using a username and password. + * + * @function signIn + * @memberof module:auth.OAuthAuthenticator.prototype + * @example + * Given the user's credentials and the connection specified, it + * will return a JSON with the access_token and id_token. + * More information in the + * + * + * API Docs + * . + * + * + * var data = { + * client_id: '{CLIENT_ID}', // Optional field. + * username: '{USERNAME}', + * password: '{PASSWORD}', + * connection: '{CONNECTION_NAME}', + * scope: 'openid' // Optional field. + * }; + * + * auth0.oauth.signIn(data, function (err, userData) { + * if (err) { + * // Handle error. + * } * - * @type {Object} + * console.log(userData); + * }); + * @param {object} userData User credentials object. + * @param {string} userData.username Username. + * @param {string} userData.password User password. + * @param {string} userData.connection The identity provider in use. + * @param {object} [options] Additional options. + * @param {string} [options.forwardedFor] Value to be used for auth0-forwarded-for header + * @param {Function} cb Callback + * @returns {Promise|undefined} */ - var clientOptions = { - errorCustomizer: SanitizedError, - errorFormatter: { message: 'message', name: 'error' }, - headers: options.headers - }; - - this.oauth = new RestClient(options.baseUrl + '/oauth/:type', clientOptions); - this.oauthWithIDTokenValidation = new OAUthWithIDTokenValidation(this.oauth, options); - this.clientId = options.clientId; - this.clientSecret = options.clientSecret; -}; - -/** - * Sign in using a username and password. - * - * @method signIn - * @memberOf module:auth.OAuthAuthenticator.prototype - * - * @example - * Given the user's credentials and the connection specified, it - * will return a JSON with the access_token and id_token. - * More information in the - * - * API Docs - * . - * - * - * var data = { - * client_id: '{CLIENT_ID}', // Optional field. - * username: '{USERNAME}', - * password: '{PASSWORD}', - * connection: '{CONNECTION_NAME}', - * scope: 'openid' // Optional field. - * }; - * - * auth0.oauth.signIn(data, function (err, userData) { - * if (err) { - * // Handle error. - * } - * - * console.log(userData); - * }); - * - * @param {Object} userData User credentials object. - * @param {String} userData.username Username. - * @param {String} userData.password User password. - * @param {String} userData.connection The identity provider in use. - * @param {Object} [options] Additional options. - * @param {String} [options.forwardedFor] Value to be used for auth0-forwarded-for header - * - * @return {Promise|undefined} - */ -OAuthAuthenticator.prototype.signIn = function(userData, options, cb) { - var { options, cb } = sanitizeArguments(options, cb); - var defaultParams = { - type: 'ro' - }; - var params = extend(defaultParams, getParamsFromOptions(options)); - var defaultFields = { - client_id: this.clientId, - grant_type: 'password', - scope: 'openid' - }; - var data = extend(defaultFields, userData); - - if (!userData || typeof userData !== 'object') { - throw new ArgumentError('Missing user data object'); - } - - if ( - params.type === 'ro' && - (typeof data.connection !== 'string' || data.connection.split().length === 0) - ) { - throw new ArgumentError('connection field is required'); - } + signIn(userData, options, cb) { + if (!userData || typeof userData !== 'object') { + throw new ArgumentError('Missing user data object'); + } + + const { options: sanitizedOptions, cb: sanitizedCb } = sanitizeArguments(options, cb); + const params = { + type: 'ro', + ...getParamsFromOptions(sanitizedOptions), + }; - if (cb && cb instanceof Function) { - return this.oauthWithIDTokenValidation.create(params, data, cb); - } + const data = { + client_id: this.clientId, + grant_type: 'password', + scope: 'openid', + ...userData, + }; - return this.oauthWithIDTokenValidation.create(params, data); -}; + if ( + params.type === 'ro' && + (typeof data.connection !== 'string' || data.connection.split().length === 0) + ) { + throw new ArgumentError('connection field is required'); + } -/** - * Sign in using a username and password - * - * @method passwordGrant - * @memberOf module:auth.OAuthAuthenticator.prototype - * - * @example - * Given the user's credentials perform the OAuth password grant - * or Password Realm grant if a realm is provided, - * it will return a JSON with the access_token and id_token. - * More information in the - * - * API Docs - * . - * - * - * var data = { - * client_id: '{CLIENT_ID}', // Optional field. - * username: '{USERNAME}', - * password: '{PASSWORD}', - * realm: '{CONNECTION_NAME}', // Optional field. - * scope: 'openid' // Optional field. - * }; - * - * auth0.oauth.passwordGrant(data, function (err, userData) { - * if (err) { - * // Handle error. - * } - * - * console.log(userData); - * }); - * - * @param {Object} userData User credentials object. - * @param {String} userData.username Username. - * @param {String} userData.password User password. - * @param {String} [userData.realm] Name of the realm to use to authenticate or the connection name - * @param {Object} [options] Additional options. - * @param {String} [options.forwardedFor] Value to be used for auth0-forwarded-for header - * - * @return {Promise|undefined} - */ -OAuthAuthenticator.prototype.passwordGrant = function(userData, options, cb) { - var { options, cb } = sanitizeArguments(options, cb); - var defaultParams = { - type: 'token' - }; - var params = extend(defaultParams, getParamsFromOptions(options)); - var defaultFields = { - client_id: this.clientId, - client_secret: this.clientSecret, - grant_type: 'password' - }; - var data = extend(defaultFields, userData); - - if (!userData || typeof userData !== 'object') { - throw new ArgumentError('Missing user data object'); - } + if (sanitizedCb && sanitizedCb instanceof Function) { + return this.oauthWithIDTokenValidation.create(params, data, sanitizedCb); + } - if (typeof data.username !== 'string' || data.username.split().length === 0) { - throw new ArgumentError('username field is required'); + return this.oauthWithIDTokenValidation.create(params, data); } - if (typeof data.password !== 'string' || data.password.split().length === 0) { - throw new ArgumentError('password field is required'); - } + /** + * Sign in using a username and password + * + * @function passwordGrant + * @memberof module:auth.OAuthAuthenticator.prototype + * @example + * Given the user's credentials perform the OAuth password grant + * or Password Realm grant if a realm is provided, + * it will return a JSON with the access_token and id_token. + * + * More information in the + * + * API Docs + * . + * + * + * var data = { + * client_id: '{CLIENT_ID}', // Optional field. + * username: '{USERNAME}', + * password: '{PASSWORD}', + * realm: '{CONNECTION_NAME}', // Optional field. + * scope: 'openid' // Optional field. + * }; + * + * auth0.oauth.passwordGrant(data, function (err, userData) { + * if (err) { + * // Handle error. + * } + * + * console.log(userData); + * }); + * @param {object} userData User credentials object. + * @param {string} userData.username Username. + * @param {string} userData.password User password. + * @param {string} [userData.realm] Name of the realm to use to authenticate or the connection name + * @param {object} [options] Additional options. + * @param {string} [options.forwardedFor] Value to be used for auth0-forwarded-for header + * @param {Function} cb Callback + * @returns {Promise|undefined} + */ + passwordGrant(userData, options, cb) { + const { options: sanitizedOptions, cb: sanitizedCb } = sanitizeArguments(options, cb); + + if (!userData || typeof userData !== 'object') { + throw new ArgumentError('Missing user data object'); + } + + const data = { + client_id: this.clientId, + client_secret: this.clientSecret, + grant_type: 'password', + ...userData, + }; - if (typeof data.realm === 'string' && data.realm.split().length !== 0) { - data.grant_type = 'http://auth0.com/oauth/grant-type/password-realm'; - } + if (typeof data.username !== 'string' || data.username.split().length === 0) { + throw new ArgumentError('username field is required'); + } - if (cb && cb instanceof Function) { - return this.oauthWithIDTokenValidation.create(params, data, cb); - } + if (typeof data.password !== 'string' || data.password.split().length === 0) { + throw new ArgumentError('password field is required'); + } - return this.oauthWithIDTokenValidation.create(params, data); -}; + if (typeof data.realm === 'string' && data.realm.split().length !== 0) { + data.grant_type = 'http://auth0.com/oauth/grant-type/password-realm'; + } -/** - * Exchange a refresh token - * - * @method refreshToken - * @memberOf module:auth.OAuthAuthenticator.prototype - * - * @example - * Given a refresh token from a previous authentication request - * it will return a JSON with the access_token and id_token if - * the openid scope was originally included. - * More information in the - * - * API Docs - * . - * - * - * var data = { - * refresh_token: '{REFRESH_TOKEN}', - * }; - * - * auth0.oauth.refreshToken(data, function (err, data) { - * if (err) { - * // Handle error. - * } - * - * console.log(data); - * }); - * - * @param {Object} data Data object. - * @param {String} data.refresh_token Refresh token. - * - * @return {Promise|undefined} - */ -OAuthAuthenticator.prototype.refreshToken = function(data, cb) { - if (!data || typeof data !== 'object') { - throw new ArgumentError('Missing data object'); - } + const params = { + type: 'token', + ...getParamsFromOptions(sanitizedOptions), + }; - var defaultFields = { - client_id: this.clientId, - client_secret: this.clientSecret, - grant_type: 'refresh_token' - }; + if (sanitizedCb && sanitizedCb instanceof Function) { + return this.oauthWithIDTokenValidation.create(params, data, sanitizedCb); + } - var data = extend(defaultFields, data); - if (typeof data.refresh_token !== 'string' || data.refresh_token.split().length === 0) { - throw new ArgumentError('refresh_token is required'); + return this.oauthWithIDTokenValidation.create(params, data); } - var params = { - type: 'token' - }; + /** + * Exchange a refresh token + * + * @function refreshToken + * @memberof module:auth.OAuthAuthenticator.prototype + * @example + * Given a refresh token from a previous authentication request + * it will return a JSON with the access_token and id_token if + * the openid scope was originally included. + * More information in the + * + * API Docs + * . + * + * + * var data = { + * refresh_token: '{REFRESH_TOKEN}', + * }; + * + * auth0.oauth.refreshToken(data, function (err, data) { + * if (err) { + * // Handle error. + * } + * + * console.log(data); + * }); + * @param {object} data Data object. + * @param {string} data.refresh_token Refresh token. + * @param {Function} cb Callback + * @returns {Promise|undefined} + */ + refreshToken(data, cb) { + if (!data || typeof data !== 'object') { + throw new ArgumentError('Missing data object'); + } + + data = { + client_id: this.clientId, + client_secret: this.clientSecret, + grant_type: 'refresh_token', + ...data, + }; - if (cb && cb instanceof Function) { - return this.oauth.create(params, data, cb); - } - return this.oauth.create(params, data); -}; + if (typeof data.refresh_token !== 'string' || data.refresh_token.split().length === 0) { + throw new ArgumentError('refresh_token is required'); + } -/** - * Sign in using a social provider access token. - * - * @method socialSignIn - * @memberOf module:auth.OAuthAuthenticator.prototype - * - * @param {Object} data User credentials object. - * @param {String} data.access_token User access token. - * @param {String} data.connection Identity provider. - * - * @return {Promise|undefined} - */ -OAuthAuthenticator.prototype.socialSignIn = function(data, cb) { - var params = { - type: 'access_token' - }; + const params = { + type: 'token', + }; - if (typeof data !== 'object') { - throw new ArgumentError('Missing user credential objects'); + if (cb && cb instanceof Function) { + return this.oauth.create(params, data, cb); + } + return this.oauth.create(params, data); } - if (typeof data.access_token !== 'string' || data.access_token.trim().length === 0) { - throw new ArgumentError('access_token field is required'); - } + /** + * Sign in using a social provider access token. + * + * @function socialSignIn + * @memberof module:auth.OAuthAuthenticator.prototype + * @param {object} data User credentials object. + * @param {string} data.access_token User access token. + * @param {string} data.connection Identity provider. + * @param {Function} cb Callback + * @returns {Promise|undefined} + */ + socialSignIn(data, cb) { + const params = { + type: 'access_token', + }; - if (typeof data.connection !== 'string' || data.connection.trim().length === 0) { - throw new ArgumentError('connection field is required'); - } + if (typeof data !== 'object') { + throw new ArgumentError('Missing user credential objects'); + } - if (cb && cb instanceof Function) { - return this.oauth.create(params, data, cb); - } + if (typeof data.access_token !== 'string' || data.access_token.trim().length === 0) { + throw new ArgumentError('access_token field is required'); + } - return this.oauth.create(params, data); -}; + if (typeof data.connection !== 'string' || data.connection.trim().length === 0) { + throw new ArgumentError('connection field is required'); + } -OAuthAuthenticator.prototype.clientCredentialsGrant = function(options, cb) { - var params = { - type: 'token' - }; + if (cb && cb instanceof Function) { + return this.oauth.create(params, data, cb); + } - var defaultFields = { - grant_type: 'client_credentials', - client_id: this.clientId, - client_secret: this.clientSecret - }; + return this.oauth.create(params, data); + } - var data = extend(defaultFields, options); + clientCredentialsGrant(options, cb) { + if (!options || typeof options !== 'object') { + throw new ArgumentError('Missing options object'); + } - if (!options || typeof options !== 'object') { - throw new ArgumentError('Missing options object'); - } + const data = { + grant_type: 'client_credentials', + client_id: this.clientId, + client_secret: this.clientSecret, + ...options, + }; - if (!data.client_id || data.client_id.trim().length === 0) { - throw new ArgumentError('client_id field is required'); - } + if (!data.client_id || data.client_id.trim().length === 0) { + throw new ArgumentError('client_id field is required'); + } - if (!data.client_secret || data.client_secret.trim().length === 0) { - throw new ArgumentError('client_secret field is required'); - } + if (!data.client_secret || data.client_secret.trim().length === 0) { + throw new ArgumentError('client_secret field is required'); + } - if (cb && cb instanceof Function) { - return this.oauth.create(params, data, cb); - } + const params = { + type: 'token', + }; - return this.oauth.create(params, data); -}; + if (cb && cb instanceof Function) { + return this.oauth.create(params, data, cb); + } -/** - * Sign in using an authorization code - * - * @method authorizationCodeGrant - * @memberOf module:auth.OAuthAuthenticator.prototype - * - * @example - * Given the code returned in the URL params after the redirect - * from successful authentication, exchange the code for auth0 - * credentials. It will return JSON with the access_token and id_token. - * More information in the - * - * API Docs - * . - * - * - * var options = { - * code: '{CODE}', - * redirect_uri: '{REDIRECT_URI}', - * organization: '{ORGANIZATION_ID}' // Optiional field. - * }; - * - * auth0.oauth.authorizationCodeGrant(options, function (err, userData) { - * if (err) { - * // Handle error. - * } - * - * console.log(userData); - * }); - * - * @param {Object} options Authorization code payload - * @param {String} options.organization Organization ID - * @param {String} options.code Code in URL returned after authentication - * @param {String} options.redirect_uri The URL to which Auth0 will redirect the browser after authorization has been granted by the user. - * - * @return {Promise|undefined} - */ -OAuthAuthenticator.prototype.authorizationCodeGrant = function(options, cb) { - var params = { - type: 'token' - }; + return this.oauth.create(params, data); + } - var defaultFields = { - grant_type: 'authorization_code', - client_id: this.clientId, - client_secret: this.clientSecret - }; + /** + * Sign in using an authorization code + * + * @function authorizationCodeGrant + * @memberof module:auth.OAuthAuthenticator.prototype + * @example + * Given the code returned in the URL params after the redirect + * from successful authentication, exchange the code for auth0 + * credentials. It will return JSON with the access_token and id_token. + * More information in the + * + * API Docs + * . + * + * + * var options = { + * code: '{CODE}', + * redirect_uri: '{REDIRECT_URI}', + * organization: '{ORGANIZATION_ID}' // Optiional field. + * }; + * + * auth0.oauth.authorizationCodeGrant(options, function (err, userData) { + * if (err) { + * // Handle error. + * } + * + * console.log(userData); + * }); + * @param {object} options Authorization code payload + * @param {string} options.organization Organization ID + * @param {string} options.code Code in URL returned after authentication + * @param {string} options.redirect_uri The URL to which Auth0 will redirect the browser after authorization has been granted by the user. + * @param {Function} cb Callback + * @returns {Promise|undefined} + */ + authorizationCodeGrant(options, cb) { + if (!options || typeof options !== 'object') { + throw new ArgumentError('Missing options object'); + } + + const data = { + grant_type: 'authorization_code', + client_id: this.clientId, + client_secret: this.clientSecret, + ...options, + }; - var data = extend(defaultFields, options); + if (!data.code || data.code.trim().length === 0) { + throw new ArgumentError('code field is required'); + } - if (!options || typeof options !== 'object') { - throw new ArgumentError('Missing options object'); - } + if (!data.redirect_uri || data.redirect_uri.trim().length === 0) { + throw new ArgumentError('redirect_uri field is required'); + } - if (!data.code || data.code.trim().length === 0) { - throw new ArgumentError('code field is required'); - } + const params = { + type: 'token', + }; - if (!data.redirect_uri || data.redirect_uri.trim().length === 0) { - throw new ArgumentError('redirect_uri field is required'); - } + if (cb && cb instanceof Function) { + return this.oauthWithIDTokenValidation.create(params, data, cb); + } - if (cb && cb instanceof Function) { - return this.oauthWithIDTokenValidation.create(params, data, cb); + return this.oauthWithIDTokenValidation.create(params, data); } - - return this.oauthWithIDTokenValidation.create(params, data); -}; +} module.exports = OAuthAuthenticator; diff --git a/src/auth/PasswordlessAuthenticator.js b/src/auth/PasswordlessAuthenticator.js index 23b2280bf..03c120739 100644 --- a/src/auth/PasswordlessAuthenticator.js +++ b/src/auth/PasswordlessAuthenticator.js @@ -1,8 +1,6 @@ -var extend = require('util')._extend; - -var ArgumentError = require('rest-facade').ArgumentError; -var RestClient = require('rest-facade').Client; -var sanitizeArguments = require('../utils').sanitizeArguments; +const { ArgumentError } = require('rest-facade'); +const RestClient = require('rest-facade').Client; +const { sanitizeArguments } = require('../utils'); function getParamsFromOptions(options) { const params = {}; @@ -10,7 +8,7 @@ function getParamsFromOptions(options) { return params; } if (options.forwardedFor) { - params._requestCustomizer = function(req) { + params._requestCustomizer = function (req) { req.set('auth0-forwarded-for', options.forwardedFor); }; } @@ -18,283 +16,276 @@ function getParamsFromOptions(options) { } /** - * @class * Handles authenticator with passwordless flows, e.g. SMS, Touch ID, etc. - * @constructor - * @memberOf module:auth - * - * @param {Object} options Authenticator options. - * @param {String} options.baseUrl The auth0 account URL. - * @param {String} [options.clientId] Default client ID. - * @param {String} [options.clientSecret] Default client secret. - * @param {OAuthAuthenticator} oauth OAuthAuthenticator instance. */ -var PasswordlessAuthenticator = function(options, oauth) { - if (!options) { - throw new ArgumentError('Missing authenticator options'); - } - if (typeof options !== 'object') { - throw new ArgumentError('The authenticator options must be an object'); +class PasswordlessAuthenticator { + /** + * @param {object} options Authenticator options. + * @param {string} options.baseUrl The auth0 account URL. + * @param {string} [options.clientId] Default client ID. + * @param {string} [options.clientSecret] Default client secret. + * @param {OAuthAuthenticator} oauth OAuthAuthenticator instance. + */ + constructor(options, oauth) { + if (!options) { + throw new ArgumentError('Missing authenticator options'); + } + + if (typeof options !== 'object') { + throw new ArgumentError('The authenticator options must be an object'); + } + + /** + * Options object for the Rest Client instance. + * + * @type {object} + */ + const clientOptions = { + errorFormatter: { message: 'message', name: 'error' }, + headers: options.headers, + }; + + this.oauth = oauth; + this.passwordless = new RestClient(`${options.baseUrl}/passwordless/start`, clientOptions); + this.clientId = options.clientId; + this.clientSecret = options.clientSecret; } /** - * Options object for the Rest Client instance. + * Sign in with the given user credentials. + * + * @function signIn + * @memberof module:auth.PasswordlessAuthenticator.prototype + * @example + * Once you have a verification code, use this endpoint to login + * the user with their phone number/email and verification code. + * + * https://auth0.com/docs/api/authentication#authenticate-user + * + * + * var data = { + * username: '{PHONE_NUMBER OR EMAIL}', + * otp: '{VERIFICATION_CODE}', + * realm: '{sms or email}' // OPTIONAL DEFAULTS TO SMS + * }; + * + * auth0.passwordless.signIn(data, function (err) { + * if (err) { + * // Handle error. + * } + * }); + * @example + * The user data object has the following structure. + * + * + * { + * id_token: String, + * access_token: String, + * token_type: String + * } + * @example + * LEGACY signIn using the `/oauth/ro` endpoint. When otp is not specified + * password is required. Given the user credentials (`phone_number` and `code`), + * it will do the authentication on the provider and return a JSON with + * the `access_token` and `id_token`. + * + * https://auth0.com/docs/api/authentication#resource-owner + * * - * @type {Object} + * var data = { + * username: '{PHONE_NUMBER}', + * password: '{VERIFICATION_CODE}' + * }; + * + * auth0.passwordless.signIn(data, function (err) { + * if (err) { + * // Handle error. + * } + * }); + * @param {object} userData User credentials object. + * @param {string} userData.username The user's phone number if realm=sms, or the user's email if realm=email + * @param {string} userData.otp The user's verification code. Required + * @param {string} [userData.realm=sms] Realm string: "sms" or "email". + * @param {string} [userData.password] [DEPRECATED] Password required if using legacy /oauth/ro endpoint + * @param {string} [userData.connection=sms] [DEPRECATED] Connection string: "sms" or "email". + * @param {object} [options] Additional options. + * @param {string} [options.forwardedFor] Value to be used for auth0-forwarded-for header + * @param {Function} [cb] Method callback. + * @returns {Promise|undefined} */ - var clientOptions = { - errorFormatter: { message: 'message', name: 'error' }, - headers: options.headers - }; + signIn(userData, options, cb) { + const { options: sanitizedOptions, cb: sanitizedCb } = sanitizeArguments(options, cb); - this.oauth = oauth; - this.passwordless = new RestClient(options.baseUrl + '/passwordless/start', clientOptions); - this.clientId = options.clientId; - this.clientSecret = options.clientSecret; -}; + if (!userData || typeof userData !== 'object') { + throw new ArgumentError('Missing user data object'); + } -/** - * Sign in with the given user credentials. - * - * @method signIn - * @memberOf module:auth.PasswordlessAuthenticator.prototype - * @example - * Once you have a verification code, use this endpoint to login - * the user with their phone number/email and verification code. - * - * https://auth0.com/docs/api/authentication#authenticate-user - * - * - * var data = { - * username: '{PHONE_NUMBER OR EMAIL}', - * otp: '{VERIFICATION_CODE}', - * realm: '{sms or email}' // OPTIONAL DEFAULTS TO SMS - * }; - * - * auth0.passwordless.signIn(data, function (err) { - * if (err) { - * // Handle error. - * } - * }); - * - * @example - * The user data object has the following structure. - * - * - * { - * id_token: String, - * access_token: String, - * token_type: String - * } - * - * @example - * LEGACY signIn using the `/oauth/ro` endpoint. When otp is not specified - * password is required. Given the user credentials (`phone_number` and `code`), - * it will do the authentication on the provider and return a JSON with - * the `access_token` and `id_token`. - * - * https://auth0.com/docs/api/authentication#resource-owner - * - * - * var data = { - * username: '{PHONE_NUMBER}', - * password: '{VERIFICATION_CODE}' - * }; - * - * auth0.passwordless.signIn(data, function (err) { - * if (err) { - * // Handle error. - * } - * }); - * - * @param {Object} userData User credentials object. - * @param {String} userData.username The user's phone number if realm=sms, or the user's email if realm=email - * @param {String} userData.otp The user's verification code. Required - * @param {String} [userData.realm=sms] Realm string: "sms" or "email". - * @param {String} [userData.password] [DEPRECATED] Password required if using legacy /oauth/ro endpoint - * @param {String} [userData.connection=sms] [DEPRECATED] Connection string: "sms" or "email". - * @param {Object} [options] Additional options. - * @param {String} [options.forwardedFor] Value to be used for auth0-forwarded-for header - * @param {Function} [cb] Method callback. - * - * @return {Promise|undefined} - */ -PasswordlessAuthenticator.prototype.signIn = function(userData, options, cb) { - var { options, cb } = sanitizeArguments(options, cb); - var defaultFields = { - client_id: this.clientId, - client_secret: this.clientSecret - }; - var data = extend(defaultFields, userData); + const data = { + client_id: this.clientId, + client_secret: this.clientSecret, + ...userData, + }; - if (!userData || typeof userData !== 'object') { - throw new ArgumentError('Missing user data object'); - } + if (typeof data.username !== 'string' || data.username.trim().length === 0) { + throw new ArgumentError('username field (phone number) is required'); + } - if (typeof data.username !== 'string' || data.username.trim().length === 0) { - throw new ArgumentError('username field (phone number) is required'); - } + // If otp is provided, attempt to sign in using otp grant + if (typeof data.otp === 'string' && data.otp.trim().length > 0) { + if (!data.realm || (data.realm !== 'email' && data.realm !== 'sms')) { + data.realm = 'sms'; + } + data.grant_type = 'http://auth0.com/oauth/grant-type/passwordless/otp'; + return this.oauth.signIn(data, { type: 'token', ...sanitizedOptions }, sanitizedCb); + } - // If otp is provided, attempt to sign in using otp grant - if (typeof data.otp === 'string' && data.otp.trim().length > 0) { - if (!data.realm || (data.realm !== 'email' && data.realm !== 'sms')) { - data.realm = 'sms'; + // Don't let the user override the connection nor the grant type. + if (!data.connection || (data.connection !== 'email' && data.connection !== 'sms')) { + data.connection = 'sms'; } - data.grant_type = 'http://auth0.com/oauth/grant-type/passwordless/otp'; - return this.oauth.signIn(data, extend({ type: 'token' }, options), cb); - } + data.grant_type = 'password'; - // Don't let the user override the connection nor the grant type. - if (!data.connection || (data.connection !== 'email' && data.connection !== 'sms')) { - data.connection = 'sms'; - } - data.grant_type = 'password'; + if (typeof data.password !== 'string' || data.password.trim().length === 0) { + throw new ArgumentError('password field (verification code) is required'); + } - if (typeof data.password !== 'string' || data.password.trim().length === 0) { - throw new ArgumentError('password field (verification code) is required'); + console.warn( + 'The oauth/ro endpoint has been deprecated. Please use the realm and otp parameters in this function.' + ); + return this.oauth.signIn(data, sanitizedOptions, sanitizedCb); } - console.warn( - 'The oauth/ro endpoint has been deprecated. Please use the realm and otp parameters in this function.' - ); - return this.oauth.signIn(data, options, cb); -}; + /** + * Start passwordless flow sending an email. + * + * @function sendEmail + * @memberof module:auth.PasswordlessAuthenticator.prototype + * @example + * Given the user `email` address, it will send an email with: + * + * + * + * Find more information in the + * API Docs + * + * + * var data = { + * email: '{EMAIL}', + * send: 'link', + * authParams: {} // Optional auth params. + * }; + * + * auth0.passwordless.sendEmail(data, function (err) { + * if (err) { + * // Handle error. + * } + * }); + * @param {object} userData User account data. + * @param {string} userData.email User email address. + * @param {string} userData.send The type of email to be sent. + * @param {object} [options] Additional options. + * @param {string} [options.forwardedFor] Value to be used for auth0-forwarded-for header + * @param {Function} [cb] Method callback. + * @returns {Promise|undefined} + */ + sendEmail(userData, options, cb) { + const { options: sanitizedOptions, cb: sanitizedCb } = sanitizeArguments(options, cb); + const data = { + client_id: this.clientId, + client_secret: this.clientSecret, + ...userData, + }; + const params = getParamsFromOptions(sanitizedOptions); -/** - * Start passwordless flow sending an email. - * - * @method sendEmail - * @memberOf module:auth.PasswordlessAuthenticator.prototype - * @example - * Given the user `email` address, it will send an email with: - * - * - * - * Find more information in the - * API Docs - * - * - * var data = { - * email: '{EMAIL}', - * send: 'link', - * authParams: {} // Optional auth params. - * }; - * - * auth0.passwordless.sendEmail(data, function (err) { - * if (err) { - * // Handle error. - * } - * }); - * - * @param {Object} userData User account data. - * @param {String} userData.email User email address. - * @param {String} userData.send The type of email to be sent. - * @param {Object} [options] Additional options. - * @param {String} [options.forwardedFor] Value to be used for auth0-forwarded-for header - * @param {Function} [cb] Method callback. - * - * @return {Promise|undefined} - */ -PasswordlessAuthenticator.prototype.sendEmail = function(userData, options, cb) { - var { options, cb } = sanitizeArguments(options, cb); - var defaultFields = { - client_id: this.clientId, - client_secret: this.clientSecret - }; - var params = getParamsFromOptions(options); - var data = extend(defaultFields, userData); + // Don't let the user override the connection nor the grant type. + data.connection = 'email'; - // Don't let the user override the connection nor the grant type. - data.connection = 'email'; + if (!userData || typeof userData !== 'object') { + throw new ArgumentError('Missing user data object'); + } - if (!userData || typeof userData !== 'object') { - throw new ArgumentError('Missing user data object'); - } + if (typeof data.email !== 'string' || data.email.trim().length === 0) { + throw new ArgumentError('email field is required'); + } - if (typeof data.email !== 'string' || data.email.trim().length === 0) { - throw new ArgumentError('email field is required'); - } + if (typeof data.send !== 'string' || data.send.trim().length === 0) { + throw new ArgumentError('send field is required'); + } - if (typeof data.send !== 'string' || data.send.trim().length === 0) { - throw new ArgumentError('send field is required'); - } + if (sanitizedCb && sanitizedCb instanceof Function) { + return this.passwordless.create(params, data, sanitizedCb); + } - if (cb && cb instanceof Function) { - return this.passwordless.create(params, data, cb); + return this.passwordless.create(params, data); } - return this.passwordless.create(params, data); -}; + /** + * Start passwordless flow sending an SMS. + * + * @function sendSMS + * @memberof module:auth.PasswordlessAuthenticator.prototype + * @example + * Given the user `phone_number`, it will send a SMS message with a + * verification code. You can then authenticate with this user using the + * `/oauth/ro` endpoint specifying `phone_number` as `username` and `code` as + * `password`: + * + * + * var data = { + * phone_number: '{PHONE}' + * }; + * + * auth0.passwordless.sendSMS(data, function (err) { + * if (err) { + * // Handle error. + * } + * }); + * @param {object} userData User account data. + * @param {string} userData.phone_number User phone number. + * @param {object} [options] Additional options. + * @param {string} [options.forwardedFor] Value to be used for auth0-forwarded-for header + * @param {Function} [cb] Method callback. + * @returns {Promise|undefined} + */ + sendSMS(userData, options, cb) { + const { options: sanitizedOptions, cb: sanitizedCb } = sanitizeArguments(options, cb); + const data = { + client_id: this.clientId, + client_secret: this.clientSecret, + ...userData, + }; + const params = getParamsFromOptions(sanitizedOptions); -/** - * Start passwordless flow sending an SMS. - * - * @method sendSMS - * @memberOf module:auth.PasswordlessAuthenticator.prototype - * - * @example - * Given the user `phone_number`, it will send a SMS message with a - * verification code. You can then authenticate with this user using the - * `/oauth/ro` endpoint specifying `phone_number` as `username` and `code` as - * `password`: - * - * - * var data = { - * phone_number: '{PHONE}' - * }; - * - * auth0.passwordless.sendSMS(data, function (err) { - * if (err) { - * // Handle error. - * } - * }); - * - * @param {Object} userData User account data. - * @param {String} userData.phone_number User phone number. - * @param {Object} [options] Additional options. - * @param {String} [options.forwardedFor] Value to be used for auth0-forwarded-for header - * @param {Function} [cb] Method callback. - * - * @return {Promise|undefined} - */ -PasswordlessAuthenticator.prototype.sendSMS = function(userData, options, cb) { - var { options, cb } = sanitizeArguments(options, cb); - var defaultFields = { - client_id: this.clientId, - client_secret: this.clientSecret - }; - var params = getParamsFromOptions(options); - var data = extend(defaultFields, userData); + // Don't let the user override the connection nor the grant type. + data.connection = 'sms'; - // Don't let the user override the connection nor the grant type. - data.connection = 'sms'; + if (!userData || typeof userData !== 'object') { + throw new ArgumentError('Missing user data object'); + } - if (!userData || typeof userData !== 'object') { - throw new ArgumentError('Missing user data object'); - } + if (typeof data.phone_number !== 'string' || data.phone_number.trim().length === 0) { + throw new ArgumentError('phone_number field is required'); + } - if (typeof data.phone_number !== 'string' || data.phone_number.trim().length === 0) { - throw new ArgumentError('phone_number field is required'); - } + if (sanitizedCb && sanitizedCb instanceof Function) { + return this.passwordless.create(params, data, sanitizedCb); + } - if (cb && cb instanceof Function) { - return this.passwordless.create(params, data, cb); + return this.passwordless.create(params, data); } - - return this.passwordless.create(params, data); -}; +} module.exports = PasswordlessAuthenticator; diff --git a/src/auth/TokensManager.js b/src/auth/TokensManager.js index dd658a6ca..e554e718e 100644 --- a/src/auth/TokensManager.js +++ b/src/auth/TokensManager.js @@ -1,257 +1,248 @@ -var extend = require('util')._extend; -var axios = require('axios'); - -var ArgumentError = require('rest-facade').ArgumentError; +const axios = require('axios'); +const { ArgumentError } = require('rest-facade'); /** - * @class TokensManager * Provides methods for getting token data and exchanging tokens. - * @constructor - * @memberOf module:auth - * - * @param {Object} options Manager options. - * @param {String} options.baseUrl The auth0 account URL. - * @param {String} [options.headers] Default request headers. - * @param {String} [options.clientId] Default client ID. - * @param {String} [options.clientSecret] Default client Secret. - */ -var TokensManager = function(options) { - if (typeof options !== 'object') { - throw new ArgumentError('Missing tokens manager options'); - } - - if (typeof options.baseUrl !== 'string') { - throw new ArgumentError('baseUrl field is required'); - } - - this.baseUrl = options.baseUrl; - this.headers = options.headers || {}; - this.clientId = options.clientId || ''; - this.clientSecret = options.clientSecret || ''; -}; - -/** - * Given an ID token get the user profile linked to it. - * - * @method getInfo - * @memberOf module:auth.TokensManager.prototype - * - * @example - * Validates a JSON Web Token (signature and expiration) and returns the user - * information associated with the user id (sub property) of the token. Find - * more information in the - * API Docs. - * - * - * auth0.tokens.getInfo(token, function (err, tokenInfo) { - * if (err) { - * // Handle error. - * } - * - * console.log(tokenInfo); - * }); - * - * @param {String} idToken User ID token. - * @param {Function} [cb] Method callback. - * - * @return {Promise|undefined} */ -TokensManager.prototype.getInfo = function(idToken, cb) { - var headers = extend({}, this.headers); - - if (idToken === null || idToken === undefined) { - throw new ArgumentError('An ID token is required'); - } - - if (typeof idToken !== 'string' || idToken.trim().length === 0) { - throw new ArgumentError('The ID token is not valid'); - } - - // Perform the request. - var promise = axios({ - method: 'POST', - url: this.baseUrl + '/tokeninfo', - data: { id_token: idToken }, - headers: headers - }).then(({ data }) => data); - - // Use callback if given. - if (cb instanceof Function) { - promise.then(cb.bind(null, null)).catch(cb); - return; - } - - return promise; -}; - -/** - * Exchange the token of the logged in user with a token that is valid to call - * the API (signed with the API secret). - * - * @method getDelegationToken - * @memberOf module:auth.TokensManager.prototype - * - * @example - * Given an existing token, this endpoint will generate a new token signed - * with the target client secret. This is used to flow the identity of the - * user from the application to an API or across different APIs that are - * protected with different secrets. Find more information in the - * API Docs. - * - * - * var data = { - * id_token: '{ID_TOKEN}', - * api_type: 'app', - * target: '{TARGET}', - * grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer' - * }; - * - * auth0.tokens.getDelegationToken(data, function (err, token) { - * if (err) { - * // Handle error. - * } - * - * console.log(token); - * }); - * - * @param {Object} data Token data object. - * @param {String} data.id_token User ID token. - * @param {String} data.refresh_token User refresh token. - * @param {String} data.target Target client ID. - * @param {String} data.api_type The API to be used (aws, auth0, etc). - * @param {String} data.grant_type Grant type (password, jwt, etc). - * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} - */ -TokensManager.prototype.getDelegationToken = function(data, cb) { - var body = extend({ client_id: this.clientId }, data); - var headers = this.headers; - - if (!data) { - throw new ArgumentError('Missing token data object'); - } - - var hasIdToken = typeof data.id_token === 'string' && data.id_token.trim().length !== 0; - - var hasRefreshToken = - typeof data.refresh_token === 'string' && data.refresh_token.trim().length !== 0; - - if (!hasIdToken && !hasRefreshToken) { - throw new ArgumentError('one of id_token or refresh_token is required'); - } - - if (hasIdToken && hasRefreshToken) { - throw new ArgumentError('id_token and refresh_token fields cannot be specified simulatenously'); - } - - if (typeof data.target !== 'string' || data.target.trim().length === 0) { - throw new ArgumentError('target field is required'); - } - - if (typeof data.api_type !== 'string' || data.api_type.trim().length === 0) { - throw new ArgumentError('api_type field is required'); - } - - if (typeof data.grant_type !== 'string' || data.grant_type.trim().length === 0) { - throw new ArgumentError('grant_type field is required'); - } - - // Perform the request. - var promise = axios({ - method: 'POST', - url: this.baseUrl + '/delegation', - data: body, - headers: headers - }).then(({ data }) => data); - - // Use callback if given. - if (cb instanceof Function) { - promise.then(cb.bind(null, null)).catch(cb); - return; - } - - return promise; -}; - -/** - * Proactively revoke an issued refresh token. - * - * @method revokeRefreshToken - * @memberOf module:auth.TokensManager.prototype - * - * @example - * Given an existing refresh token, this endpoint will revoke it in order - * to prevent unauthorized silently user authentication tokens refresh. - * Find more information in the API Docs. - * - * - * * var data = { - * token: '{REFRESH_TOKEN}' - * }; - * - * auth0.tokens.revokeRefreshToken(data, function (err, _) { - * if (err) { - * // Handle error. - * } - * - * // Do stuff. - * }); - * - * @param {Object} data Token data object. - * @param {String} data.token User refresh token. - * @param {String} [data.client_id] Target client ID. - * @param {String} [data.client_secret] Target client secret. - * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} - */ -TokensManager.prototype.revokeRefreshToken = function(data, cb) { - if (!data) { - throw new ArgumentError('Missing token data object'); - } - - var hasToken = typeof data.token === 'string' && data.token.trim().length !== 0; +class TokensManager { + /** + * @param {object} options Manager options. + * @param {string} options.baseUrl The auth0 account URL. + * @param {string} [options.headers] Default request headers. + * @param {string} [options.clientId] Default client ID. + * @param {string} [options.clientSecret] Default client Secret. + */ + constructor(options) { + if (typeof options !== 'object') { + throw new ArgumentError('Missing tokens manager options'); + } + + if (typeof options.baseUrl !== 'string') { + throw new ArgumentError('baseUrl field is required'); + } + + this.baseUrl = options.baseUrl; + this.headers = options.headers || {}; + this.clientId = options.clientId || ''; + this.clientSecret = options.clientSecret || ''; + } + + /** + * Given an ID token get the user profile linked to it. + * + * @function getInfo + * @memberof module:auth.TokensManager.prototype + * @example + * Validates a JSON Web Token (signature and expiration) and returns the user + * information associated with the user id (sub property) of the token. Find + * more information in the + * API Docs. + * + * + * auth0.tokens.getInfo(token, function (err, tokenInfo) { + * if (err) { + * // Handle error. + * } + * + * console.log(tokenInfo); + * }); + * @param {string} idToken User ID token. + * @param {Function} [cb] Method callback. + * @returns {Promise|undefined} + */ + getInfo(idToken, cb) { + const headers = { ...this.headers }; + + if (idToken === null || idToken === undefined) { + throw new ArgumentError('An ID token is required'); + } + + if (typeof idToken !== 'string' || idToken.trim().length === 0) { + throw new ArgumentError('The ID token is not valid'); + } + + // Perform the request. + const promise = axios({ + method: 'POST', + url: `${this.baseUrl}/tokeninfo`, + data: { id_token: idToken }, + headers, + }).then(({ data }) => data); + + // Use callback if given. + if (cb instanceof Function) { + promise.then(cb.bind(null, null)).catch(cb); + return; + } + + return promise; + } + + /** + * Exchange the token of the logged in user with a token that is valid to call + * the API (signed with the API secret). + * + * @function getDelegationToken + * @memberof module:auth.TokensManager.prototype + * @example + * Given an existing token, this endpoint will generate a new token signed + * with the target client secret. This is used to flow the identity of the + * user from the application to an API or across different APIs that are + * protected with different secrets. Find more information in the + * API Docs. + * + * + * var data = { + * id_token: '{ID_TOKEN}', + * api_type: 'app', + * target: '{TARGET}', + * grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer' + * }; + * + * auth0.tokens.getDelegationToken(data, function (err, token) { + * if (err) { + * // Handle error. + * } + * + * console.log(token); + * }); + * @param {object} data Token data object. + * @param {string} data.id_token User ID token. + * @param {string} data.refresh_token User refresh token. + * @param {string} data.target Target client ID. + * @param {string} data.api_type The API to be used (aws, auth0, etc). + * @param {string} data.grant_type Grant type (password, jwt, etc). + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getDelegationToken(data, cb) { + const body = { client_id: this.clientId, ...data }; + const { headers } = this; + + if (!data) { + throw new ArgumentError('Missing token data object'); + } + + const hasIdToken = typeof data.id_token === 'string' && data.id_token.trim().length !== 0; + + const hasRefreshToken = + typeof data.refresh_token === 'string' && data.refresh_token.trim().length !== 0; + + if (!hasIdToken && !hasRefreshToken) { + throw new ArgumentError('one of id_token or refresh_token is required'); + } + + if (hasIdToken && hasRefreshToken) { + throw new ArgumentError( + 'id_token and refresh_token fields cannot be specified simulatenously' + ); + } + + if (typeof data.target !== 'string' || data.target.trim().length === 0) { + throw new ArgumentError('target field is required'); + } + + if (typeof data.api_type !== 'string' || data.api_type.trim().length === 0) { + throw new ArgumentError('api_type field is required'); + } + + if (typeof data.grant_type !== 'string' || data.grant_type.trim().length === 0) { + throw new ArgumentError('grant_type field is required'); + } + + // Perform the request. + const promise = axios({ + method: 'POST', + url: `${this.baseUrl}/delegation`, + data: body, + headers, + }).then(({ data }) => data); + + // Use callback if given. + if (cb instanceof Function) { + promise.then(cb.bind(null, null)).catch(cb); + return; + } + + return promise; + } + + /** + * Proactively revoke an issued refresh token. + * + * @function revokeRefreshToken + * @memberof module:auth.TokensManager.prototype + * @example + * Given an existing refresh token, this endpoint will revoke it in order + * to prevent unauthorized silently user authentication tokens refresh. + * Find more information in the API Docs. + * + * + * var data = { + * token: '{REFRESH_TOKEN}' + * }; + * + * auth0.tokens.revokeRefreshToken(data, function (err, _) { + * if (err) { + * // Handle error. + * } + * + * // Do stuff. + * }); + * @param {object} data Token data object. + * @param {string} data.token User refresh token. + * @param {string} [data.client_id] Target client ID. + * @param {string} [data.client_secret] Target client secret. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + revokeRefreshToken(data, cb) { + if (!data) { + throw new ArgumentError('Missing token data object'); + } + + const hasToken = typeof data.token === 'string' && data.token.trim().length !== 0; + + if (!hasToken) { + throw new ArgumentError('token property is required'); + } + + const hasClientId = + (data.client_id && + typeof data.client_id === 'string' && + data.client_id.trim().length !== 0) || + this.clientId !== ''; + + if (!hasClientId) { + throw new ArgumentError( + 'Neither token data client_id property or constructor clientId property has been set' + ); + } + + const body = { + client_id: this.clientId, + client_secret: this.clientSecret, + ...data, + }; - if (!hasToken) { - throw new ArgumentError('token property is required'); - } + const { headers } = this; - var hasClientId = - (data.client_id && typeof data.client_id === 'string' && data.client_id.trim().length !== 0) || - this.clientId !== ''; + // Perform the request. + const promise = axios({ + method: 'POST', + url: `${this.baseUrl}/oauth/revoke`, + data: body, + headers, + }).then(({ data }) => data); - if (!hasClientId) { - throw new ArgumentError( - 'Neither token data client_id property or constructor clientId property has been set' - ); - } + // Use callback if given. + if (cb instanceof Function) { + promise.then(cb.bind(null, null)).catch(cb); + return; + } - var body = extend( - { - client_id: this.clientId, - client_secret: this.clientSecret - }, - data - ); - - var headers = this.headers; - - // Perform the request. - var promise = axios({ - method: 'POST', - url: this.baseUrl + '/oauth/revoke', - data: body, - headers: headers - }).then(({ data }) => data); - - // Use callback if given. - if (cb instanceof Function) { - promise.then(cb.bind(null, null)).catch(cb); - return; + return promise; } - - return promise; -}; +} module.exports = TokensManager; diff --git a/src/auth/UsersManager.js b/src/auth/UsersManager.js index 8150925ca..d730ee661 100644 --- a/src/auth/UsersManager.js +++ b/src/auth/UsersManager.js @@ -1,172 +1,165 @@ -var extend = require('util')._extend; -var axios = require('axios'); +const axios = require('axios'); -var ArgumentError = require('rest-facade').ArgumentError; +const { ArgumentError } = require('rest-facade'); /** - * @class UsersManager * Provides methods for getting user information and impersonating users. - * @constructor - * @memberOf module:auth - * - * @param {Object} options Manager options. - * @param {String} options.baseUrl The auth0 account URL. - * @param {String} [options.headers] Default request headers. - * @param {String} [options.clientId] Default client ID. */ -var UsersManager = function(options) { - if (typeof options !== 'object') { - throw new ArgumentError('Missing users manager options'); +class UsersManager { + /** + * @param {object} options Manager options. + * @param {string} options.baseUrl The auth0 account URL. + * @param {string} [options.headers] Default request headers. + * @param {string} [options.clientId] Default client ID. + */ + constructor(options) { + if (typeof options !== 'object') { + throw new ArgumentError('Missing users manager options'); + } + + if (typeof options.baseUrl !== 'string') { + throw new ArgumentError('baseUrl field is required'); + } + + this.baseUrl = options.baseUrl; + this.headers = options.headers; + this.clientId = options.clientId; } - if (typeof options.baseUrl !== 'string') { - throw new ArgumentError('baseUrl field is required'); + /** + * Given an access token get the user profile linked to it. + * + * @function getInfo + * @memberof module:auth.UsersManager.prototype + * @example + * Get the user information based on the Auth0 access token (obtained during + * login). Find more information in the + * API Docs. + * + * + * auth0.users.getInfo(accessToken, function (err, userInfo) { + * if (err) { + * // Handle error. + * } + * + * console.log(userInfo); + * }); + * @param {string} accessToken User access token. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getInfo(accessToken, cb) { + const url = `${this.baseUrl}/userinfo`; + const headers = { ...this.headers }; + + if (accessToken === null || accessToken === undefined) { + throw new ArgumentError('An access token is required'); + } + + if (typeof accessToken !== 'string' || accessToken.trim().length === 0) { + throw new ArgumentError('Invalid access token'); + } + + // Send the user access token in the Authorization header. + headers['Authorization'] = `Bearer ${accessToken}`; + + // Perform the request. + const promise = axios({ + method: 'GET', + url, + headers, + }).then(({ data }) => data); + + // Use callback if given. + if (cb instanceof Function) { + promise.then(cb.bind(null, null)).catch(cb); + return; + } + + return promise; } - this.baseUrl = options.baseUrl; - this.headers = options.headers; - this.clientId = options.clientId; -}; - -/** - * Given an access token get the user profile linked to it. - * - * @method getInfo - * @memberOf module:auth.UsersManager.prototype - * - * @example - * Get the user information based on the Auth0 access token (obtained during - * login). Find more information in the - * API Docs. - * - * - * auth0.users.getInfo(accessToken, function (err, userInfo) { - * if (err) { - * // Handle error. - * } - * - * console.log(userInfo); - * }); - * - * @param {String} accessToken User access token. - * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} - */ -UsersManager.prototype.getInfo = function(accessToken, cb) { - var url = this.baseUrl + '/userinfo'; - var headers = extend({}, this.headers); - - if (accessToken === null || accessToken === undefined) { - throw new ArgumentError('An access token is required'); + /** + * Impersonate the user with the given user ID. + * + * @function impersonate + * @memberof module:auth.UsersManager.prototype + * @example + * Gets a link that can be used once to log in as a specific user. Useful for + * troubleshooting. Find more information in the + * [API Docs](https://auth0.com/docs/auth-api#!#post--users--user_id--impersonate). + * + * + * var settings = { + * impersonator_id: '{IMPERSONATOR_ID}', + * protocol: 'oauth2', + * additionalParameters: {} // Optional additional params. + * }; + * + * auth0.users.impersonate(userId, settings, function (err, link) { + * if (err) { + * // Handle error. + * } + * + * console.log(link); + * }); + * @param {string} userId User ID token. + * @param {object} settings Impersonation settings. + * @param {string} settings.impersonator_id Impersonator user ID. + * @param {string} settings.protocol The authentication protocol. + * @param {string} settings.token API v1 token obtained for impersonation + * @param {string} [settings.clientId] Client id used for impersonation. Uses the one supplied in the constructor by default. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + impersonate(userId, settings, cb) { + const url = `${this.baseUrl}/users/${userId}/impersonate`; + + if (userId === null || userId === undefined) { + throw new ArgumentError('You must specify a user ID'); + } + + if (typeof userId !== 'string' || userId.trim().length === 0) { + throw new ArgumentError('The user ID is not valid'); + } + + if (typeof settings !== 'object') { + throw new ArgumentError('Missing impersonation settings object'); + } + + if ( + typeof settings.impersonator_id !== 'string' || + settings.impersonator_id.trim().length === 0 + ) { + throw new ArgumentError('impersonator_id field is required'); + } + + if (typeof settings.protocol !== 'string' || settings.protocol.trim().length === 0) { + throw new ArgumentError('protocol field is required'); + } + + if (typeof settings.token !== 'string' || settings.token.trim().length === 0) { + throw new ArgumentError('token field is required'); + } + + const data = { client_id: settings.clientId || this.clientId, ...settings }; + const headers = { Authorization: `Bearer ${settings.token}`, ...this.headers }; + // Perform the request. + const promise = axios({ + method: 'POST', + headers, + data, + url, + }).then(({ data }) => data); + + // Use callback if given. + if (cb instanceof Function) { + promise.then(cb.bind(null, null)).catch(cb); + return; + } + + return promise; } - - if (typeof accessToken !== 'string' || accessToken.trim().length === 0) { - throw new ArgumentError('Invalid access token'); - } - - // Send the user access token in the Authorization header. - headers['Authorization'] = 'Bearer ' + accessToken; - - // Perform the request. - var promise = axios({ - method: 'GET', - url: url, - headers: headers - }).then(({ data }) => data); - - // Use callback if given. - if (cb instanceof Function) { - promise.then(cb.bind(null, null)).catch(cb); - return; - } - - return promise; -}; - -/** - * Impersonate the user with the given user ID. - * - * @method impersonate - * @memberOf module:auth.UsersManager.prototype - * - * @example - * Gets a link that can be used once to log in as a specific user. Useful for - * troubleshooting. Find more information in the - * [API Docs](https://auth0.com/docs/auth-api#!#post--users--user_id--impersonate). - * - * - * var settings = { - * impersonator_id: '{IMPERSONATOR_ID}', - * protocol: 'oauth2', - * additionalParameters: {} // Optional additional params. - * }; - * - * auth0.users.impersonate(userId, settings, function (err, link) { - * if (err) { - * // Handle error. - * } - * - * console.log(link); - * }); - * - * @param {String} userId User ID token. - * @param {Object} settings Impersonation settings. - * @param {String} settings.impersonator_id Impersonator user ID. - * @param {String} settings.protocol The authentication protocol. - * @param {String} settings.token API v1 token obtained for impersonation - * @param {String} [settings.clientId] Client id used for impersonation. Uses the one supplied in the constructor by default. - * @param {Function} [cb]] Callback function. - * - * @return {Promise|undefined} - */ -UsersManager.prototype.impersonate = function(userId, settings, cb) { - var url = this.baseUrl + '/users/' + userId + '/impersonate'; - - if (userId === null || userId === undefined) { - throw new ArgumentError('You must specify a user ID'); - } - - if (typeof userId !== 'string' || userId.trim().length === 0) { - throw new ArgumentError('The user ID is not valid'); - } - - if (typeof settings !== 'object') { - throw new ArgumentError('Missing impersonation settings object'); - } - - if ( - typeof settings.impersonator_id !== 'string' || - settings.impersonator_id.trim().length === 0 - ) { - throw new ArgumentError('impersonator_id field is required'); - } - - if (typeof settings.protocol !== 'string' || settings.protocol.trim().length === 0) { - throw new ArgumentError('protocol field is required'); - } - - if (typeof settings.token !== 'string' || settings.token.trim().length === 0) { - throw new ArgumentError('token field is required'); - } - - var data = extend({ client_id: settings.clientId || this.clientId }, settings); - var headers = extend({ Authorization: `Bearer ${settings.token}` }, this.headers); - // Perform the request. - var promise = axios({ - method: 'POST', - headers: headers, - data: data, - url: url - }).then(({ data }) => data); - - // Use callback if given. - if (cb instanceof Function) { - promise.then(cb.bind(null, null)).catch(cb); - return; - } - - return promise; -}; +} module.exports = UsersManager; diff --git a/src/auth/idToken.js b/src/auth/idToken.js index 8ceff21f0..36074af64 100644 --- a/src/auth/idToken.js +++ b/src/auth/idToken.js @@ -1,13 +1,15 @@ -var urlDecodeB64 = function(data) { +const urlDecodeB64 = function (data) { return Buffer.from(data, 'base64').toString('utf8'); }; /** * Decodes a string token into the 3 parts, throws if the format is invalid - * @param token + * + * @param {string} token token + * @returns {object} */ -var decode = function(token) { - var parts = token.split('.'); +const decode = function (token) { + const parts = token.split('.'); if (parts.length !== 3) { throw new Error('ID token could not be decoded'); @@ -17,34 +19,35 @@ var decode = function(token) { _raw: token, header: JSON.parse(urlDecodeB64(parts[0])), payload: JSON.parse(urlDecodeB64(parts[1])), - signature: parts[2] + signature: parts[2], }; }; -var DEFAULT_LEEWAY = 60; //default clock-skew, in seconds +const DEFAULT_LEEWAY = 60; //default clock-skew, in seconds /** * Validator for ID Tokens following OIDC spec. - * @param token the string token to verify - * @param options the options required to run this verification - * @returns A promise containing the decoded token payload, or throws an exception if validation failed + * + * @param {string} token the string token to verify + * @param {object} options the options required to run this verification + * @returns {Promise} A promise containing the decoded token payload, or throws an exception if validation failed */ -var validate = function(token, options) { +const validate = function (token, options) { if (!token) { throw new Error('ID token is required but missing'); } - var decodedToken = decode(token); + const decodedToken = decode(token); // Check algorithm - var header = decodedToken.header; + const { header } = decodedToken; if (header.alg !== 'RS256' && header.alg !== 'HS256') { throw new Error( `Signature algorithm of "${header.alg}" is not supported. Expected the ID token to be signed with "RS256" or "HS256".` ); } - var payload = decodedToken.payload; + const { payload } = decodedToken; // Issuer if (!payload.iss || typeof payload.iss !== 'string') { @@ -93,14 +96,14 @@ var validate = function(token, options) { } // --Time validation (epoch)-- - var now = Math.floor(Date.now() / 1000); - var leeway = options.leeway || DEFAULT_LEEWAY; + const now = Math.floor(Date.now() / 1000); + const leeway = options.leeway || DEFAULT_LEEWAY; // Expires at if (!payload.exp || typeof payload.exp !== 'number') { throw new Error('Expiration Time (exp) claim must be a number present in the ID token'); } - var expTime = payload.exp + leeway; + const expTime = payload.exp + leeway; if (now > expTime) { throw new Error( @@ -147,7 +150,7 @@ var validate = function(token, options) { ); } - var authValidUntil = payload.auth_time + options.maxAge + leeway; + const authValidUntil = payload.auth_time + options.maxAge + leeway; if (now > authValidUntil) { throw new Error( `Authentication Time (auth_time) claim in the ID token indicates that too much time has passed since the last end-user authentication. Currrent time (${now}) is after last auth at ${authValidUntil}` @@ -159,6 +162,6 @@ var validate = function(token, options) { }; module.exports = { - decode: decode, - validate: validate + decode, + validate, }; diff --git a/src/auth/index.js b/src/auth/index.js index c159b14ed..cb726682c 100644 --- a/src/auth/index.js +++ b/src/auth/index.js @@ -1,20 +1,18 @@ -/** @module auth **/ - -var util = require('util'); -var utils = require('../utils'); -var jsonToBase64 = utils.jsonToBase64; -var ArgumentError = require('rest-facade').ArgumentError; +const util = require('util'); +const utils = require('../utils'); +const { jsonToBase64 } = utils; +const { ArgumentError } = require('rest-facade'); // Authenticators. -var OAuthAuthenticator = require('./OAuthAuthenticator'); -var DatabaseAuthenticator = require('./DatabaseAuthenticator'); -var PasswordlessAuthenticator = require('./PasswordlessAuthenticator'); +const OAuthAuthenticator = require('./OAuthAuthenticator'); +const DatabaseAuthenticator = require('./DatabaseAuthenticator'); +const PasswordlessAuthenticator = require('./PasswordlessAuthenticator'); // Managers -var UsersManager = require('./UsersManager'); -var TokensManager = require('./TokensManager'); +const UsersManager = require('./UsersManager'); +const TokensManager = require('./TokensManager'); -var BASE_URL_FORMAT = 'https://%s'; +const BASE_URL_FORMAT = 'https://%s'; /** * @class @@ -22,9 +20,8 @@ var BASE_URL_FORMAT = 'https://%s'; * * This client must used to access Auth0's * Authentication API. - * @constructor - * @memberOf module:auth - * + * @class + * @memberof module:auth * @example * The AuthenticationClient constructor takes an optional client * ID, if specified it will be used as default value for all endpoints that @@ -36,16 +33,15 @@ var BASE_URL_FORMAT = 'https://%s'; * domain: '{YOUR_ACCOUNT}.auth0.com', * clientId: '{OPTIONAL_CLIENT_ID}' * }); - * - * @param {Object} options Options for the Authentication Client SDK. - * @param {String} options.domain AuthenticationClient server domain. - * @param {String} [options.clientId] Default client ID. - * @param {String} [options.clientSecret] Default client Secret. - * @param {String} [options.supportedAlgorithms] Algorithms that your application expects to receive - * @param {Boolean} [options.__bypassIdTokenValidation] Whether the id_token should be validated or not - * @param {Object} [options.headers] Additional headers that will be added to the outgoing requests. + * @param {object} options Options for the Authentication Client SDK. + * @param {string} options.domain AuthenticationClient server domain. + * @param {string} [options.clientId] Default client ID. + * @param {string} [options.clientSecret] Default client Secret. + * @param {string} [options.supportedAlgorithms] Algorithms that your application expects to receive + * @param {boolean} [options.__bypassIdTokenValidation] Whether the id_token should be validated or not + * @param {object} [options.headers] Additional headers that will be added to the outgoing requests. */ -var AuthenticationClient = function(options) { +const AuthenticationClient = function (options) { if (!options || typeof options !== 'object') { throw new ArgumentError('Authentication Client SDK options must be an object'); } @@ -54,25 +50,25 @@ var AuthenticationClient = function(options) { throw new ArgumentError('Must provide a domain'); } - var defaultHeaders = { - 'User-Agent': 'node.js/' + process.version.replace('v', ''), - 'Content-Type': 'application/json' + const defaultHeaders = { + 'User-Agent': `node.js/${process.version.replace('v', '')}`, + 'Content-Type': 'application/json', }; - var managerOptions = { + const managerOptions = { clientId: options.clientId, domain: options.domain, clientSecret: options.clientSecret, headers: Object.assign(defaultHeaders, options.headers || {}), baseUrl: util.format(BASE_URL_FORMAT, options.domain), supportedAlgorithms: options.supportedAlgorithms, - __bypassIdTokenValidation: options.__bypassIdTokenValidation + __bypassIdTokenValidation: options.__bypassIdTokenValidation, }; if (options.telemetry !== false) { - var clientInfo = options.clientInfo || utils.generateClientInfo(); + const clientInfo = options.clientInfo || utils.generateClientInfo(); if ('string' === typeof clientInfo.name && clientInfo.name) { - var telemetry = jsonToBase64(clientInfo); + const telemetry = jsonToBase64(clientInfo); managerOptions.headers['Auth0-Client'] = telemetry; } } @@ -116,9 +112,8 @@ var AuthenticationClient = function(options) { /** * Start passwordless flow sending an email. * - * @method requestMagicLink - * @memberOf module:auth.AuthenticationClient.prototype - * + * @function requestMagicLink + * @memberof module:auth.AuthenticationClient.prototype * @example * Given the user `email` address, it will send an email with a link. You can * then authenticate with this user opening the link and he will be @@ -140,15 +135,13 @@ var AuthenticationClient = function(options) { * // Handle error. * } * }; - * - * @param {Object} data User data object. - * @param {String} data.email User email address. - * @param {Object} [data.authParams] Authentication parameters. + * @param {object} data User data object. + * @param {string} data.email User email address. + * @param {object} [data.authParams] Authentication parameters. * @param {Function} [cb] Method callback. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -AuthenticationClient.prototype.requestMagicLink = function(data, cb) { +AuthenticationClient.prototype.requestMagicLink = function (data, cb) { data.send = 'link'; return this.passwordless.sendEmail(data, cb); @@ -157,9 +150,8 @@ AuthenticationClient.prototype.requestMagicLink = function(data, cb) { /** * Start passwordless flow sending an email. * - * @method requestEmailCode - * @memberOf module:auth.AuthenticationClient.prototype - * + * @function requestEmailCode + * @memberof module:auth.AuthenticationClient.prototype * @example * Given the user `email` address, it will send an email with a verification * code. You can then authenticate with this user using the `/oauth/ro` @@ -179,15 +171,13 @@ AuthenticationClient.prototype.requestMagicLink = function(data, cb) { * // Handle error. * } * }; - * - * @param {Object} data User data object. - * @param {String} data.email User email address. - * @param {Object} [data.authParams] Authentication parameters. + * @param {object} data User data object. + * @param {string} data.email User email address. + * @param {object} [data.authParams] Authentication parameters. * @param {Function} [cb] Method callback. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -AuthenticationClient.prototype.requestEmailCode = function(data, cb) { +AuthenticationClient.prototype.requestEmailCode = function (data, cb) { data.send = 'code'; return this.passwordless.sendEmail(data, cb); @@ -196,9 +186,8 @@ AuthenticationClient.prototype.requestEmailCode = function(data, cb) { /** * Verify the given OTP which was sent on the given email. * - * @method verifyEmailCode - * @memberOf module:auth.AuthenticationClient.prototype - * + * @function verifyEmailCode + * @memberof module:auth.AuthenticationClient.prototype * @example * Given the user credentials (`email` and `otp`), authenticates * with the provider using the `/oauth/token` endpoint. Upon successful @@ -216,7 +205,6 @@ AuthenticationClient.prototype.requestEmailCode = function(data, cb) { * // Handle error. * } * }); - * * @example * The user data object has the following structure. * @@ -226,19 +214,17 @@ AuthenticationClient.prototype.requestEmailCode = function(data, cb) { * access_token: String, * token_type: String * } - * - * @param {Object} data Credentials object. - * @param {String} data.email Email. - * @param {String} data.otp Verification code. + * @param {object} data Credentials object. + * @param {string} data.email Email. + * @param {string} data.otp Verification code. * @param {Function} [cb] Method callback. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -AuthenticationClient.prototype.verifyEmailCode = function(data, cb) { - var translatedData = { +AuthenticationClient.prototype.verifyEmailCode = function (data, cb) { + const translatedData = { username: data.email, realm: 'email', - otp: data.otp + otp: data.otp, }; return this.passwordless.signIn(translatedData, cb); @@ -247,9 +233,8 @@ AuthenticationClient.prototype.verifyEmailCode = function(data, cb) { /** * Start passwordless flow sending an SMS. * - * @method requestSMSCode - * @memberOf module:auth.AuthenticationClient.prototype - * + * @function requestSMSCode + * @memberof module:auth.AuthenticationClient.prototype * @example * Given the user `phone_number`, it will send a SMS message with a * verification code. You can then authenticate with this user using the @@ -267,16 +252,14 @@ AuthenticationClient.prototype.verifyEmailCode = function(data, cb) { * } * * }); - * - * @param {Object} data User data object. - * @param {String} data.phone_number The user phone number. + * @param {object} data User data object. + * @param {string} data.phone_number The user phone number. * @param {Function} [cb] Method callback. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -AuthenticationClient.prototype.requestSMSCode = function(data, cb) { - var translatedData = { - phone_number: data.phoneNumber || data.phone_number +AuthenticationClient.prototype.requestSMSCode = function (data, cb) { + const translatedData = { + phone_number: data.phoneNumber || data.phone_number, }; return this.passwordless.sendSMS(translatedData, cb); @@ -285,9 +268,8 @@ AuthenticationClient.prototype.requestSMSCode = function(data, cb) { /** * Sign in with the given user credentials. * - * @method verifySMSCode - * @memberOf module:auth.AuthenticationClient.prototype - * + * @function verifySMSCode + * @memberof module:auth.AuthenticationClient.prototype * @example * Given the user credentials (`phone_number` and `otp`), authenticates * with the provider using the `/oauth/token` endpoint. Upon successful @@ -305,7 +287,6 @@ AuthenticationClient.prototype.requestSMSCode = function(data, cb) { * // Handle error. * } * }); - * * @example * Given the user credentials (`phone_number` and `password`), authenticates * with the provider using the deprecated `/oauth/ro` endpoint. Upon successful @@ -323,7 +304,6 @@ AuthenticationClient.prototype.requestSMSCode = function(data, cb) { * // Handle error. * } * }); - * * @example * The user data object has the following structure. * @@ -333,18 +313,16 @@ AuthenticationClient.prototype.requestSMSCode = function(data, cb) { * access_token: String, * token_type: String * } - * - * @param {Object} data Credentials object. - * @param {String} data.username Phone number. - * @param {String} data.otp Verification code. Use this instead of `password` to use the `/oauth/token` endpoint. - * @param {String} data.password Verification code. Use this instead of `otp` to use the `/oauth/ro` endpoint. + * @param {object} data Credentials object. + * @param {string} data.username Phone number. + * @param {string} data.otp Verification code. Use this instead of `password` to use the `/oauth/token` endpoint. + * @param {string} data.password Verification code. Use this instead of `otp` to use the `/oauth/ro` endpoint. * @param {Function} [cb] Method callback. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -AuthenticationClient.prototype.verifySMSCode = function(data, cb) { - var translatedData = { - username: data.phoneNumber || data.phone_number || data.username +AuthenticationClient.prototype.verifySMSCode = function (data, cb) { + const translatedData = { + username: data.phoneNumber || data.phone_number || data.username, }; if (data.otp) { @@ -360,9 +338,8 @@ AuthenticationClient.prototype.verifySMSCode = function(data, cb) { * Exchange the token of the logged in user with a token that is valid to call * the API (signed with the API secret). * - * @method getDelegationToken - * @memberOf module:auth.AuthenticationClient.prototype - * + * @function getDelegationToken + * @memberof module:auth.AuthenticationClient.prototype * @example * Given an existing token, this endpoint will generate a new token signed * with the target client secret. This is used to flow the identity of the @@ -385,23 +362,21 @@ AuthenticationClient.prototype.verifySMSCode = function(data, cb) { * * console.log(token); * }); - * - * @param {Object} data Token data object. - * @param {String} data.id_token The user ID token. - * @param {String} data.api_type The API type (aws, firebase, etc). - * @param {String} data.target The target client ID. - * @param {String} data.grant_type The grant type. + * @param {object} data Token data object. + * @param {string} data.id_token The user ID token. + * @param {string} data.api_type The API type (aws, firebase, etc). + * @param {string} data.target The target client ID. + * @param {string} data.grant_type The grant type. * @param {Function} [cb] Method callback. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -AuthenticationClient.prototype.getDelegationToken = function(data, cb) { - var translatedData = { +AuthenticationClient.prototype.getDelegationToken = function (data, cb) { + const translatedData = { id_token: data.id_token, api_type: data.api || data.api_type, scope: data.scope, target: data.targetClientId || data.target, - grant_type: data.grant_type + grant_type: data.grant_type, }; return this.tokens.getDelegationToken(translatedData, cb); @@ -410,9 +385,8 @@ AuthenticationClient.prototype.getDelegationToken = function(data, cb) { /** * Change password using a database or active directory service. * - * @method changePassword - * @memberOf module:auth.AuthenticationClient.prototype - * + * @function changePassword + * @memberof module:auth.AuthenticationClient.prototype * @example * Given the user email, the connection specified and the new password to * use, Auth0 will send a forgot password email. Once the user clicks on the @@ -435,31 +409,22 @@ AuthenticationClient.prototype.getDelegationToken = function(data, cb) { * * console.log(message); * }); - * - * @param {Object} data User data object. - * @param {String} data.email User email. - * @param {String} data.password User password. - * @param {String} data.connection Identity provider for the user. + * @param {object} data User data object. + * @param {string} data.email User email. + * @param {string} data.password User password. + * @param {string} data.connection Identity provider for the user. * @param {Function} [cb] Method callback. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -AuthenticationClient.prototype.changePassword = function(data, cb) { - var translatedData = { - connection: data.connection, - email: data.email || data.username, - password: data.password - }; - +AuthenticationClient.prototype.changePassword = function (data, cb) { return this.database.changePassword(data, cb); }; /** * Request a change password email using a database or active directory service. * - * @method requestChangePasswordEmail - * @memberOf module:auth.AuthenticationClient.prototype - * + * @function requestChangePasswordEmail + * @memberof module:auth.AuthenticationClient.prototype * @example * Given the user email, the connection specified, Auth0 will send a change * password email. once the user clicks on the confirm password change link, @@ -481,30 +446,22 @@ AuthenticationClient.prototype.changePassword = function(data, cb) { * * console.log(message); * }); - * - * @param {Object} data User data object. - * @param {String} data.email User email. - * @param {String} data.connection Identity provider for the user. - * @param {String} data.client_id Client ID of the Application requesting the password change, to be included in the email template. + * @param {object} data User data object. + * @param {string} data.email User email. + * @param {string} data.connection Identity provider for the user. + * @param {string} data.client_id Client ID of the Application requesting the password change, to be included in the email template. * @param {Function} [cb] Method callback. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -AuthenticationClient.prototype.requestChangePasswordEmail = function(data, cb) { - var translatedData = { - connection: data.connection, - email: data.email || data.username - }; - +AuthenticationClient.prototype.requestChangePasswordEmail = function (data, cb) { return this.database.requestChangePasswordEmail(data, cb); }; /** * Given an access token get the user profile linked to it. * - * @method getProfile - * @memberOf module:auth.AuthenticationClient.prototype - * + * @function getProfile + * @memberof module:auth.AuthenticationClient.prototype * @example * Get the user information based on the Auth0 access token (obtained during * login). Find more information in the @@ -518,19 +475,16 @@ AuthenticationClient.prototype.requestChangePasswordEmail = function(data, cb) { * * console.log(userInfo); * }); - * - * @param {String} accessToken The user access token. - * - * @return {Promise|undefined} + * @param {string} accessToken The user access token. + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(AuthenticationClient, 'getProfile', 'users.getInfo'); /** * Gets an access token using the client credentials grant flow. * - * @method clientCredentialsGrant - * @memberOf module:auth.AuthenticationClient.prototype - * + * @function clientCredentialsGrant + * @memberof module:auth.AuthenticationClient.prototype * @example * Gets an access token using the client credentials grant flow. Find more information in the * API Docs. @@ -546,12 +500,10 @@ utils.wrapPropertyMethod(AuthenticationClient, 'getProfile', 'users.getInfo'); * * console.log(response); * }); - * - * @param {Object} options - * @param {String} [options.scope] scopes to request to be added to the returned access token - * @param {String} [options.audience] audience or identifier of the API where the access token will be used, e.g. Auth0 Management API - * - * @return {Promise|undefined} + * @param {object} options + * @param {string} [options.scope] scopes to request to be added to the returned access token + * @param {string} [options.audience] audience or identifier of the API where the access token will be used, e.g. Auth0 Management API + * @returns {Promise|undefined} */ utils.wrapPropertyMethod( AuthenticationClient, @@ -562,9 +514,8 @@ utils.wrapPropertyMethod( /** * Sign in using a username and password * - * @method passwordGrant - * @memberOf module:auth.AuthenticationClient.prototype - * + * @function passwordGrant + * @memberof module:auth.AuthenticationClient.prototype * @example * Given the user's credentials perform the OAuth password grant * or Password Realm grant if a realm is provided, @@ -590,24 +541,21 @@ utils.wrapPropertyMethod( * * console.log(userData); * }); - * - * @param {Object} userData User credentials object. - * @param {String} userData.username Username. - * @param {String} userData.password User password. - * @param {String} [userData.realm] Name of the realm to use to authenticate or the connection name - * @param {Object} [options] Additional options. - * @param {String} [options.forwardedFor] Value to be used for auth0-forwarded-for header - * - * @return {Promise|undefined} + * @param {object} userData User credentials object. + * @param {string} userData.username Username. + * @param {string} userData.password User password. + * @param {string} [userData.realm] Name of the realm to use to authenticate or the connection name + * @param {object} [options] Additional options. + * @param {string} [options.forwardedFor] Value to be used for auth0-forwarded-for header + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(AuthenticationClient, 'passwordGrant', 'oauth.passwordGrant'); /** * Sign in using a refresh token * - * @method refreshToken - * @memberOf module:auth.AuthenticationClient.prototype - * + * @function refreshToken + * @memberof module:auth.AuthenticationClient.prototype * @example * Given a refresh token from a previous authentication request, * it will return a JSON with the access_token and id_token. @@ -629,11 +577,9 @@ utils.wrapPropertyMethod(AuthenticationClient, 'passwordGrant', 'oauth.passwordG * * console.log(userData); * }); - * - * @param {Object} userData User credentials object. - * @param {String} userData.refresh_token Refresh token. - * - * @return {Promise|undefined} + * @param {object} userData User credentials object. + * @param {string} userData.refresh_token Refresh token. + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(AuthenticationClient, 'refreshToken', 'oauth.refreshToken'); diff --git a/src/errors.js b/src/errors.js index 0176c332f..0b53e4b08 100644 --- a/src/errors.js +++ b/src/errors.js @@ -1,17 +1,26 @@ -var util = require('util'); +const util = require('util'); -/** - * @module errors - */ -var errors = (module.exports = {}); +const errors = (module.exports = {}); + +const sanitizeErrors = function (collection) { + if (!collection) { + return; + } + + Object.keys(collection).forEach((key) => { + if (key.toLowerCase().match('password|secret|authorization')) { + collection[key] = '[REDACTED]'; + } + }); +}; /** * Given a response request error, sanitize sensitive data. * - * @method sanitizeErrorRequestData - * @memberOf module:errors + * @param {Error} error Error object + * @returns {Error} */ -errors.sanitizeErrorRequestData = function(error) { +errors.sanitizeErrorRequestData = function (error) { if ( !error.response || !error.response.request || @@ -26,26 +35,17 @@ errors.sanitizeErrorRequestData = function(error) { return error; }; -var sanitizeErrors = function(collection) { - if (!collection) { - return; - } - - Object.keys(collection).forEach(function(key) { - if (key.toLowerCase().match('password|secret|authorization')) { - collection[key] = '[REDACTED]'; - } - }); -}; - /** * Given an Api Error, modify the original error and sanitize * sensitive information using sanitizeErrorRequestData * - * @method SanitizedError - * @memberOf module:errors + * @param {string} name New error name + * @param {string} message New error message + * @param {number} status New error status + * @param {any} requestInfo Request info to be attached on the error + * @param {any} originalError Original error to be attached on the error */ -var SanitizedError = function(name, message, status, requestInfo, originalError) { +const SanitizedError = function (name, message, status, requestInfo, originalError) { this.name = name || this.constructor.name || this.constructor.prototype.name || ''; this.message = message || ''; this.statusCode = status || (originalError && originalError.code); diff --git a/src/index.js b/src/index.js index b36054859..e2a7d9c61 100644 --- a/src/index.js +++ b/src/index.js @@ -1,10 +1,11 @@ /** * Simple facade for consuming a REST API endpoint. + * * @external RestClient * @see https://github.com/ngonzalvez/rest-facade */ module.exports = { ManagementClient: require('./management'), - AuthenticationClient: require('./auth') + AuthenticationClient: require('./auth'), }; diff --git a/src/management/ActionsManager.js b/src/management/ActionsManager.js index dec903b66..aacf6254b 100644 --- a/src/management/ActionsManager.js +++ b/src/management/ActionsManager.js @@ -1,661 +1,618 @@ -var ArgumentError = require('rest-facade').ArgumentError; -var utils = require('../utils'); -var Auth0RestClient = require('../Auth0RestClient'); -var RetryRestClient = require('../RetryRestClient'); +const { ArgumentError } = require('rest-facade'); +const Auth0RestClient = require('../Auth0RestClient'); +const RetryRestClient = require('../RetryRestClient'); /** * Simple facade for consuming a REST API endpoint. + * * @external RestClient - * @see https://github.com/ngonzalvez/rest-facade + * {@link https://github.com/ngonzalvez/rest-facade} */ /** - * @class ActionsManager * {@link https://auth0.com/docs/api/v2#!/Actions/get_actions Actions} provide a way to extend * Auth0 flows with custom logic. * See the {@link https://auth0.com/docs/actions Actions documentation} for more information. - * @constructor - * @memberOf module:management - * - * @param {Object} options The client options. - * @param {String} options.baseUrl The URL of the API. - * @param {Object} [options.headers] Headers to be included in all requests. - * @param {Object} [options.retry] Retry Policy Config */ -var ActionsManager = function(options) { - if (options === null || typeof options !== 'object') { - throw new ArgumentError('Must provide client options'); - } - - if (options.baseUrl === null || options.baseUrl === undefined) { - throw new ArgumentError('Must provide a base URL for the API'); - } - - if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { - throw new ArgumentError('The provided base URL is invalid'); - } - +class ActionsManager { /** - * Options object for the Rest Client instance. - * - * @type {Object} + * @class + * @memberof module:management + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config */ - var clientOptions = { - errorFormatter: { message: 'message', name: 'error' }, - headers: options.headers, - query: { repeatParams: false } - }; + constructor(options) { + if (options === null || typeof options !== 'object') { + throw new ArgumentError('Must provide client options'); + } + + if (options.baseUrl === null || options.baseUrl === undefined) { + throw new ArgumentError('Must provide a base URL for the API'); + } + + if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { + throw new ArgumentError('The provided base URL is invalid'); + } + + /** + * Options object for the Rest Client instance. + * + * @type {object} + */ + const clientOptions = { + errorFormatter: { message: 'message', name: 'error' }, + headers: options.headers, + query: { repeatParams: false }, + }; + + /** + * Provides an abstraction layer for consuming the + * [Auth0 Actions endpoint]{@link https://auth0.com/docs/api/v2#!/actions}. + * + * @type {external:RestClient} + */ + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/actions/actions/:id`, + clientOptions, + options.tokenProvider + ); + this.resource = new RetryRestClient(auth0RestClient, options.retry); + + const actionsDeployRestClient = new Auth0RestClient( + `${options.baseUrl}/actions/actions/:id/deploy`, + clientOptions, + options.tokenProvider + ); + this.actionsDeploy = new RetryRestClient(actionsDeployRestClient, options.retry); + + const actionsTestRestClient = new Auth0RestClient( + `${options.baseUrl}/actions/actions/:id/test`, + clientOptions, + options.tokenProvider + ); + this.actionsTest = new RetryRestClient(actionsTestRestClient, options.retry); + + const triggersRestClient = new Auth0RestClient( + `${options.baseUrl}/actions/triggers/:trigger_id`, + clientOptions, + options.tokenProvider + ); + this.triggers = new RetryRestClient(triggersRestClient, options.retry); + + const triggerBindingsRestClient = new Auth0RestClient( + `${options.baseUrl}/actions/triggers/:trigger_id/bindings`, + clientOptions, + options.tokenProvider + ); + this.triggerBindings = new RetryRestClient(triggerBindingsRestClient, options.retry); + + const executionsRestClient = new Auth0RestClient( + `${options.baseUrl}/actions/executions/:execution_id`, + clientOptions, + options.tokenProvider + ); + this.executions = new RetryRestClient(executionsRestClient, options.retry); + + const actionVersionRestClient = new Auth0RestClient( + `${options.baseUrl}/actions/actions/:id/versions/:version_id`, + clientOptions, + options.tokenProvider + ); + this.actionVersions = new RetryRestClient(actionVersionRestClient, options.retry); + + const deployActionVersionRestClient = new Auth0RestClient( + `${options.baseUrl}/actions/actions/:id/versions/:version_id/deploy`, + clientOptions, + options.tokenProvider + ); + this.actionVersionDeploy = new RetryRestClient(deployActionVersionRestClient, options.retry); + } /** - * Provides an abstraction layer for consuming the - * [Auth0 Actions endpoint]{@link https://auth0.com/docs/api/v2#!/actions}. + * Get all Triggers. + * + * @function getAllTriggers + * @memberof module:management.ActionsManager.prototype + * @example + * This method takes an optional object as first argument that may be used to + * specify pagination settings. If pagination options are not present, + * the first page of a limited number of results will be returned. + * + * // Pagination settings. + * var params = { + * per_page: 10, + * page: 0 + * }; * - * @type {external:RestClient} + * management.actions.getAllTriggers(params, function (err, actions) { + * console.log(actions.length); + * }); + * @param {object} [params] Actions parameters. + * @param {number} [params.per_page] Number of results per page. + * @param {number} [params.page] Page number, zero indexed. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - var auth0RestClient = new Auth0RestClient( - options.baseUrl + '/actions/actions/:id', - clientOptions, - options.tokenProvider - ); - this.resource = new RetryRestClient(auth0RestClient, options.retry); - - var actionsDeployRestClient = new Auth0RestClient( - options.baseUrl + '/actions/actions/:id/deploy', - clientOptions, - options.tokenProvider - ); - this.actionsDeploy = new RetryRestClient(actionsDeployRestClient, options.retry); - - var actionsTestRestClient = new Auth0RestClient( - options.baseUrl + '/actions/actions/:id/test', - clientOptions, - options.tokenProvider - ); - this.actionsTest = new RetryRestClient(actionsTestRestClient, options.retry); - - var triggersRestClient = new Auth0RestClient( - options.baseUrl + '/actions/triggers/:trigger_id', - clientOptions, - options.tokenProvider - ); - this.triggers = new RetryRestClient(triggersRestClient, options.retry); - - var triggerBindingsRestClient = new Auth0RestClient( - options.baseUrl + '/actions/triggers/:trigger_id/bindings', - clientOptions, - options.tokenProvider - ); - this.triggerBindings = new RetryRestClient(triggerBindingsRestClient, options.retry); - - var executionsRestClient = new Auth0RestClient( - options.baseUrl + '/actions/executions/:execution_id', - clientOptions, - options.tokenProvider - ); - this.executions = new RetryRestClient(executionsRestClient, options.retry); - - var actionVersionRestClient = new Auth0RestClient( - options.baseUrl + '/actions/actions/:id/versions/:version_id', - clientOptions, - options.tokenProvider - ); - this.actionVersions = new RetryRestClient(actionVersionRestClient, options.retry); - - var deployActionVersionRestClient = new Auth0RestClient( - options.baseUrl + '/actions/actions/:id/versions/:version_id/deploy', - clientOptions, - options.tokenProvider - ); - this.actionVersionDeploy = new RetryRestClient(deployActionVersionRestClient, options.retry); -}; + getAllTriggers(params, cb) { + params = params || {}; -/** - * Get all Triggers. - * - * @method getAllTriggers - * @memberOf module:management.ActionsManager.prototype - * - * @example - * This method takes an optional object as first argument that may be used to - * specify pagination settings. If pagination options are not present, - * the first page of a limited number of results will be returned. - * - * // Pagination settings. - * var params = { - * per_page: 10, - * page: 0 - * }; - * - * management.actions.getAllTriggers(params, function (err, actions) { - * console.log(actions.length); - * }); - * - * @param {Object} [params] Actions parameters. - * @param {Number} [params.per_page] Number of results per page. - * @param {Number} [params.page] Page number, zero indexed. - * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} - */ -ActionsManager.prototype.getAllTriggers = function(params, cb) { - params = params || {}; + if (cb && cb instanceof Function) { + return this.triggers.getAll(params, cb); + } - if (cb && cb instanceof Function) { - return this.triggers.getAll(params, cb); + return this.triggers.getAll(params); } - return this.triggers.getAll(params); -}; + /** + * Update the actions bound to a trigger . + * + * @function updateTriggerBindings + * @memberof module:management.ActionsManager.prototype + * @example + * var data = { bindings: [{ id_type: "action_id", id_value: ACTION_ID1},{id_type: "action_name", id_value: ACTION_NAME2}]; + * var params = { trigger_id: TRIGGER_ID }; + * + * // Using auth0 instance. + * management.actions.updateTriggerBindings(params, data, function (err, bindings) { + * if (err) { + * // Handle error. + * } + * + * console.log(bindings.length); // 2 + * }); + * @param {object} params Actions Binding parameters. + * @param {string} params.trigger_id Actions Trigger ID. + * @param {object} data bindings array + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + updateTriggerBindings(params, data, cb) { + params = params || {}; -/** - * Update the actions bound to a trigger . - * - * @method updateTriggerBindings - * @memberOf module:management.ActionsManager.prototype - * - * @example - * var data = { bindings: [{ id_type: "action_id", id_value: ACTION_ID1},{id_type: "action_name", id_value: ACTION_NAME2}]; - * var params = { trigger_id: TRIGGER_ID }; - * - * // Using auth0 instance. - * management.actions.updateTriggerBindings(params, data, function (err, bindings) { - * if (err) { - * // Handle error. - * } - * - * console.log(bindings.length); // 2 - * }); - * - * @param {Object} params Actions Binding parameters. - * @param {String} params.trigger_id Actions Trigger ID. - * @param {Object} data bindings array - * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} - */ -ActionsManager.prototype.updateTriggerBindings = function(params, data, cb) { - params = params || {}; + if (cb && cb instanceof Function) { + return this.triggerBindings.patch(params, data, cb); + } - if (cb && cb instanceof Function) { - return this.triggerBindings.patch(params, data, cb); + return this.triggerBindings.patch(params, data); } - return this.triggerBindings.patch(params, data); -}; + /** + * Get the actions bound to a trigger . + * + * @function getTriggerBindings + * @memberof module:management.ActionsManager.prototype + * @example + * var params = { trigger_id: TRIGGER_ID }; + * + * // Using auth0 instance. + * management.actions.getTriggerBindings(params, function (err, bindings) { + * if (err) { + * // Handle error. + * } + * + * console.log(bindings.length); // 2 + * }); + * @param {object} params Actions Binding parameters. + * @param {string} params.trigger_id Actions Trigger ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getTriggerBindings(params, cb) { + params = params || {}; -/** - * Get the actions bound to a trigger . - * - * @method getTriggerBindings - * @memberOf module:management.ActionsManager.prototype - * - * @example - * var params = { trigger_id: TRIGGER_ID }; - * - * // Using auth0 instance. - * management.actions.getTriggerBindings(params, function (err, bindings) { - * if (err) { - * // Handle error. - * } - * - * console.log(bindings.length); // 2 - * }); - * - * @param {Object} params Actions Binding parameters. - * @param {String} params.trigger_id Actions Trigger ID. - * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} - */ -ActionsManager.prototype.getTriggerBindings = function(params, cb) { - params = params || {}; + if (cb && cb instanceof Function) { + return this.triggerBindings.getAll(params, cb); + } - if (cb && cb instanceof Function) { - return this.triggerBindings.getAll(params, cb); + return this.triggerBindings.getAll(params); } - return this.triggerBindings.getAll(params); -}; + /** + * Create a new Action. + * + * @function create + * @memberof module:management.ActionsManager.prototype + * @example + * management.actions.create(data, function (err) { + * if (err) { + * // Handle error. + * } + * + * // Action created. + * }); + * @param {object} data Action data object. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + create(...args) { + return this.resource.create(...args); + } -/** - * Create a new Action. - * - * @method create - * @memberOf module:management.ActionsManager.prototype - * - * @example - * management.actions.create(data, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Action created. - * }); - * - * @param {Object} data Action data object. - * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} - */ -utils.wrapPropertyMethod(ActionsManager, 'create', 'resource.create'); + /** + * Get all actions. + * + * @function getAll + * @memberof module:management.ActionsManager.prototype + * @example + * This method takes an optional object as first argument that may be used to + * specify pagination settings. If pagination options are not present, + * the first page of a limited number of results will be returned. + * + * // Pagination settings. + * var params = { + * per_page: 10, + * page: 0, + * triggerId:'TRIGGER_ID', + * actionName: 'ACTION_NAME' + * }; + * + * management.actions.getAll(params, function (err, actions) { + * console.log(actions.length); + * }); + * @param {object} [params] Actions parameters. + * @param {number} [params.per_page] Number of results per page. + * @param {number} [params.page] Page number, zero indexed. + * @param {string} [params.triggerId] The trigger ID of the actions to retrieve. + * @param {string} [params.actionName] The name of the actions to retrieve. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getAll(...args) { + return this.resource.getAll(...args); + } -/** - * Get all actions. - * - * @method getAll - * @memberOf module:management.ActionsManager.prototype - * - * @example - * This method takes an optional object as first argument that may be used to - * specify pagination settings. If pagination options are not present, - * the first page of a limited number of results will be returned. - * - * // Pagination settings. - * var params = { - * per_page: 10, - * page: 0, - * triggerId:'TRIGGER_ID', - * actionName: 'ACTION_NAME' - * }; - * - * management.actions.getAll(params, function (err, actions) { - * console.log(actions.length); - * }); - * - * @param {Object} [params] Actions parameters. - * @param {Number} [params.per_page] Number of results per page. - * @param {Number} [params.page] Page number, zero indexed. - * @param {String} [params.triggerId] The trigger ID of the actions to retrieve. - * @param {String} [params.actionName] The name of the actions to retrieve. - * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} - */ -utils.wrapPropertyMethod(ActionsManager, 'getAll', 'resource.getAll'); + /** + * Get an Auth0 action. + * + * @function get + * @memberof module:management.ActionsManager.prototype + * @example + * management.actions.get({ id: ACTION_ID }, function (err, action) { + * if (err) { + * // Handle error. + * } + * + * console.log(action); + * }); + * @param {object} params Action parameters. + * @param {string} params.id Action ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + get(params, cb) { + params = params || {}; -/** - * Get an Auth0 action. - * - * @method get - * @memberOf module:management.ActionsManager.prototype - * - * @example - * management.actions.get({ id: ACTION_ID }, function (err, action) { - * if (err) { - * // Handle error. - * } - * - * console.log(action); - * }); - * - * @param {Object} params Action parameters. - * @param {String} params.id Action ID. - * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} - */ -ActionsManager.prototype.get = function(params, cb) { - params = params || {}; + if (params.action_id) { + params.id = params.action_id; + delete params.action_id; + } - if (params.action_id) { - params.id = params.action_id; - delete params.action_id; - } + if (cb && cb instanceof Function) { + return this.resource.get(params, cb); + } - if (cb && cb instanceof Function) { - return this.resource.get(params, cb); + return this.resource.get(params); } - return this.resource.get(params); -}; + /** + * Update an existing action. + * + * @function update + * @memberof module:management.ActionsManager.prototype + * @example + * var data = { name: 'new-name' }; + * var params = { id: ACTION_ID }; + * + * // Using auth0 instance. + * management.updateAction(params, data, function (err, action) { + * if (err) { + * // Handle error. + * } + * + * console.log(action.name); // 'new-name' + * }); + * + * // Using the Actions manager directly. + * management.actions.update(params, data, function (err, action) { + * if (err) { + * // Handle error. + * } + * + * console.log(action.name); // 'new-name' + * }); + * @param {object} params Action parameters. + * @param {string} params.id Action ID. + * @param {object} data Updated action data. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + update(params, data, cb) { + params = params || {}; -/** - * Update an existing action. - * - * @method update - * @memberOf module:management.ActionsManager.prototype - * - * @example - * var data = { name: 'new-name' }; - * var params = { id: ACTION_ID }; - * - * // Using auth0 instance. - * management.updateAction(params, data, function (err, action) { - * if (err) { - * // Handle error. - * } - * - * console.log(action.name); // 'new-name' - * }); - * - * // Using the Actions manager directly. - * management.actions.update(params, data, function (err, action) { - * if (err) { - * // Handle error. - * } - * - * console.log(action.name); // 'new-name' - * }); - * - * @param {Object} params Action parameters. - * @param {String} params.id Action ID. - * @param {Object} data Updated action data. - * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} - */ -ActionsManager.prototype.update = function(params, data, cb) { - params = params || {}; + if (params.action_id) { + params.id = params.action_id; + delete params.action_id; + } - if (params.action_id) { - params.id = params.action_id; - delete params.action_id; - } + if (cb && cb instanceof Function) { + return this.resource.patch(params, data, cb); + } - if (cb && cb instanceof Function) { - return this.resource.patch(params, data, cb); + return this.resource.patch(params, data); } - return this.resource.patch(params, data); -}; + /** + * Delete an existing action. Deleting an Action deletes all the action's versions + * + * @function delete + * @memberof module:management.ActionsManager.prototype + * @example + * management.actions.delete({ id: ACTION_ID }, function (err) { + * if (err) { + * // Handle error. + * } + * + * // Action deleted. + * }); + * @param {object} params Action parameters. + * @param {string} params.id Action ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + delete(params, cb) { + params = params || {}; -/** - * Delete an existing action. Deleting an Action deletes all the action's versions - * - * @method delete - * @memberOf module:management.ActionsManager.prototype - * - * @example - * management.actions.delete({ id: ACTION_ID }, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Action deleted. - * }); - * - * @param {Object} params Action parameters. - * @param {String} params.id Action ID. - * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} - */ -ActionsManager.prototype.delete = function(params, cb) { - params = params || {}; + if (params.action_id) { + params.id = params.action_id; + delete params.action_id; + } - if (params.action_id) { - params.id = params.action_id; - delete params.action_id; - } + if (cb && cb instanceof Function) { + return this.resource.delete(params, cb); + } - if (cb && cb instanceof Function) { - return this.resource.delete(params, cb); + return this.resource.delete(params); } - return this.resource.delete(params); -}; + /** + * test an Action. + * + * @function test + * @memberof module:management.ActionsManager.prototype + * @example + * var params = { id: ACTION_ID}; + * management.actions.test(params, payload, function (err) { + * if (err) { + * // Handle error. + * } + * }); + * @param {object} params Action parameters. + * @param {string} params.id Action ID. + * @param {object} payload Payload represents the entire structure necessary to test a particular trigger + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + test(params, payload, cb) { + params = params || {}; + payload = payload || {}; -/** - * test an Action. - * - * @method test - * @memberOf module:management.ActionsManager.prototype - * - * @example - * var params = { id: ACTION_ID}; - * management.actions.test(params, payload, function (err) { - * if (err) { - * // Handle error. - * } - - * }); - * - * @param {Object} params Action parameters. - * @param {String} params.id Action ID. - * @param {Object} payload Payload represents the entire structure necessary to test a particular trigger - * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} - */ -ActionsManager.prototype.test = function(params, payload, cb) { - params = params || {}; - payload = payload || {}; + if (params.action_id) { + params.id = params.action_id; + delete params.action_id; + } - if (params.action_id) { - params.id = params.action_id; - delete params.action_id; - } + if (cb && cb instanceof Function) { + return this.actionsTest.create(params, payload, cb); + } - if (cb && cb instanceof Function) { - return this.actionsTest.create(params, payload, cb); + return this.actionsTest.create(params, payload); } - return this.actionsTest.create(params, payload); -}; + /** + * deploy an Action. + * The action must be in a state of 'built' before it can be deployed. + * + * @function deploy + * @memberof module:management.ActionsManager.prototype + * @example + * var params = { id: ACTION_ID}; + * mangement.actions.deploy(params, function (err, actionVersion) { + * if (err) { + * // Handle error. + * } + * }); + * @param {object} params Action parameters. + * @param {string} params.id Action ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + deploy(params, cb) { + params = params || {}; -/** - * deploy an Action. - * The action must be in a state of 'built' before it can be deployed. - * - * @method deploy - * @memberOf module:management.ActionsManager.prototype - * - * @example - * var params = { id: ACTION_ID}; - * mangement.actions.deploy(params, function (err, actionVersion) { - * if (err) { - * // Handle error. - * } - - * }); - * - * @param {Object} params Action parameters. - * @param {String} params.id Action ID. - * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} - */ -ActionsManager.prototype.deploy = function(params, cb) { - params = params || {}; + if (params.action_id) { + params.id = params.action_id; + delete params.action_id; + } - if (params.action_id) { - params.id = params.action_id; - delete params.action_id; - } + if (cb && cb instanceof Function) { + return this.actionsDeploy.create(params, {}, cb); + } - if (cb && cb instanceof Function) { - return this.actionsDeploy.create(params, {}, cb); + return this.actionsDeploy.create(params, {}); } - return this.actionsDeploy.create(params, {}); -}; + /** + * Get all action versions + * + * @function getVersions + * @memberof module:management.ActionsManager.prototype + * @example + * This method takes an optional object as first argument that may be used to + * specify pagination settings. If pagination options are not present, + * the first page of a limited number of results will be returned. + * + * // Pagination settings. + * var params = { + * per_page: 10, + * page: 0 + * }; + * + * management.actions.getVersions({ id: ACTION_ID }, function (err, actionVersions) { + * console.log(actionVersions.length); + * }); + * @param {object} [params] ActionVersions parameters. + * @param {number} [params.per_page] Number of results per page. + * @param {number} [params.page] Page number, zero indexed. + * @param {string} [params.id] Action ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getVersions(params, cb) { + params = params || {}; -/** - * Get all action versions - * - * @method getVersions - * @memberOf module:management.ActionsManager.prototype - * - * @example - * This method takes an optional object as first argument that may be used to - * specify pagination settings. If pagination options are not present, - * the first page of a limited number of results will be returned. - * - * // Pagination settings. - * var params = { - * per_page: 10, - * page: 0 - * }; - * - * management.actions.getVersions({ id: ACTION_ID }, function (err, actionVersions) { - * console.log(actionVersions.length); - * }); - * - * @param {Object} [params] ActionVersions parameters. - * @param {Number} [params.per_page] Number of results per page. - * @param {Number} [params.page] Page number, zero indexed. - * @param {String} [params.id] Action ID. - * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} - */ -ActionsManager.prototype.getVersions = function(params, cb) { - params = params || {}; + if (params.action_id) { + params.id = params.action_id; + delete params.action_id; + } - if (params.action_id) { - params.id = params.action_id; - delete params.action_id; - } + if (cb && cb instanceof Function) { + return this.actionVersions.getAll(params, cb); + } - if (cb && cb instanceof Function) { - return this.actionVersions.getAll(params, cb); + return this.actionVersions.getAll(params); } - return this.actionVersions.getAll(params); -}; + /** + * Get an Action Version. + * + * @function getVersion + * @memberof module:management.ActionsManager.prototype + * @example + * var params = { id: ACTION_ID, version_id: VERSION_ID }; + * management.actions.getVersion(params, function (err, actionVersion) { + * if (err) { + * // Handle error. + * } + * }); + * @param {object} params Action parameters. + * @param {string} params.id Action ID. + * @param {string} params.version_id ActionVersion ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getVersion(params, cb) { + params = params || {}; -/** - * Get an Action Version. - * - * @method getVersion - * @memberOf module:management.ActionsManager.prototype - * - * @example - * var params = { id: ACTION_ID, version_id: VERSION_ID }; - * management.actions.getVersion(params, function (err, actionVersion) { - * if (err) { - * // Handle error. - * } - - * }); - * - * @param {Object} params Action parameters. - * @param {String} params.id Action ID. - * @param {String} params.version_id ActionVersion ID. - * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} - */ -ActionsManager.prototype.getVersion = function(params, cb) { - params = params || {}; + if (params.action_id) { + params.id = params.action_id; + delete params.action_id; + } - if (params.action_id) { - params.id = params.action_id; - delete params.action_id; - } + if (cb && cb instanceof Function) { + return this.actionVersions.get(params, cb); + } - if (cb && cb instanceof Function) { - return this.actionVersions.get(params, cb); + return this.actionVersions.get(params); } - return this.actionVersions.get(params); -}; + /** + * Create an Action Version. In general, updating an action and then + * deploying it is the preferred way of creating an action version, but + * this operation is supported as a way of creating versions without + * updating the action's code (which can be useful in some CI/CD scenarios). + * + * @function createVersion + * @memberof module:management.ActionsManager.prototype + * @example + * var params = { id: ACTION_ID }; + * management.actions.createActionVersion(params, data, function (err, actionVersion) { + * if (err) { + * // Handle error. + * } + * }); + * @param {object} params Action parameters. + * @param {string} params.id Action ID. + * @param {object} data ActionVersion parameters. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + createVersion(params, data, cb) { + params = params || {}; -/** - * Create an Action Version. In general, updating an action and then - * deploying it is the preferred way of creating an action version, but - * this operation is supported as a way of creating versions without - * updating the action's code (which can be useful in some CI/CD scenarios). - * - * @method createVersion - * @memberOf module:management.ActionsManager.prototype - * - * @example - * var params = { id: ACTION_ID }; - * management.actions.createActionVersion(params, data, function (err, actionVersion) { - * if (err) { - * // Handle error. - * } - * }); - * - * @param {Object} params Action parameters. - * @param {String} params.id Action ID. - * @param {Object} data ActionVersion parameters. - * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} - */ -ActionsManager.prototype.createVersion = function(params, data, cb) { - params = params || {}; + if (params.action_id) { + params.id = params.action_id; + delete params.action_id; + } - if (params.action_id) { - params.id = params.action_id; - delete params.action_id; - } + if (cb && cb instanceof Function) { + return this.actionVersions.create(params, data, cb); + } - if (cb && cb instanceof Function) { - return this.actionVersions.create(params, data, cb); + return this.actionVersions.create(params, data); } - return this.actionVersions.create(params, data); -}; + /** + * deploy an Action Version to roll back to a previous version. + * + * @function deployVersion + * @memberof module:management.ActionsManager.prototype + * @example + * var params = { id: ACTION_ID, version_id: VERSION_ID }; + * management.actions.deployVersion(params, function (err, actionVersion) { + * if (err) { + * // Handle error. + * } + * }); + * @param {object} params Action parameters. + * @param {string} params.id Action ID. + * @param {string} params.version_id Action ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + deployVersion(params, cb) { + params = params || {}; -/** - * deploy an Action Version to roll back to a previous version. - * - * @method deployVersion - * @memberOf module:management.ActionsManager.prototype - * - * @example - * var params = { id: ACTION_ID, version_id: VERSION_ID }; - * management.actions.deployVersion(params, function (err, actionVersion) { - * if (err) { - * // Handle error. - * } - - * }); - * - * @param {Object} params Action parameters. - * @param {String} params.id Action ID. - * @param {String} params.version_id Action ID. - * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} - */ -ActionsManager.prototype.deployVersion = function(params, cb) { - params = params || {}; + if (params.action_id) { + params.id = params.action_id; + delete params.action_id; + } - if (params.action_id) { - params.id = params.action_id; - delete params.action_id; - } + if (cb && cb instanceof Function) { + return this.actionVersionDeploy.create(params, {}, cb); + } - if (cb && cb instanceof Function) { - return this.actionVersionDeploy.create(params, {}, cb); + return this.actionVersionDeploy.create(params, {}); } - return this.actionVersionDeploy.create(params, {}); -}; + /** + * Get an execution by ID. + * + * @function getExecution + * @memberof module:management.ActionExecutionsManager.prototype + * @example + * management.actions.getExecution({ execution_id: EXECUTION_ID }, function (err, action) { + * if (err) { + * // Handle error. + * } + * + * console.log(ActionExecution); + * }); + * @param {object} params Action Execution parameters. + * @param {string} params.id Action Execution ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getExecution(params, cb) { + params = params || {}; -/** - * Get an execution by ID. - * - * @method getExecution - * @memberOf module:management.ActionExecutionsManager.prototype - * - * @example - * management.actions.getExecution({ execution_id: EXECUTION_ID }, function (err, action) { - * if (err) { - * // Handle error. - * } - * - * console.log(ActionExecution); - * }); - * - * @param {Object} params Action Execution parameters. - * @param {String} params.id Action Execution ID. - * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} - */ -ActionsManager.prototype.getExecution = function(params, cb) { - params = params || {}; + if (cb && cb instanceof Function) { + return this.executions.get(params, cb); + } - if (cb && cb instanceof Function) { - return this.executions.get(params, cb); + return this.executions.get(params); } - - return this.executions.get(params); -}; +} module.exports = ActionsManager; diff --git a/src/management/BlacklistedTokensManager.js b/src/management/BlacklistedTokensManager.js index 102ff721d..7d3e6da9d 100644 --- a/src/management/BlacklistedTokensManager.js +++ b/src/management/BlacklistedTokensManager.js @@ -1,102 +1,99 @@ -var ArgumentError = require('rest-facade').ArgumentError; -var utils = require('../utils'); -var Auth0RestClient = require('../Auth0RestClient'); -var RetryRestClient = require('../RetryRestClient'); +const { ArgumentError } = require('rest-facade'); +const Auth0RestClient = require('../Auth0RestClient'); +const RetryRestClient = require('../RetryRestClient'); /** - * @class BlacklistedTokensManager * The BlacklistedTokensManager class provides methods to retrieve the list of * blacklisted tokens and blacklist new ones.. - * @constructor - * @memberOf module:management - * - * @param {Object} options The client options. - * @param {String} options.baseUrl The URL of the API. - * @param {Object} [options.headers] Headers to be included in all requests. - * @param {Object} [options.retry] Retry Policy Config */ -var BlacklistedTokensManager = function(options) { - if (options === null || typeof options !== 'object') { - throw new ArgumentError('Must provide client options'); - } +class BlacklistedTokensManager { + /** + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config + */ + constructor(options) { + if (options === null || typeof options !== 'object') { + throw new ArgumentError('Must provide client options'); + } - if (options.baseUrl === null || options.baseUrl === undefined) { - throw new ArgumentError('Must provide a base URL for the API'); - } + if (options.baseUrl === null || options.baseUrl === undefined) { + throw new ArgumentError('Must provide a base URL for the API'); + } - if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { - throw new ArgumentError('The provided base URL is invalid'); + if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { + throw new ArgumentError('The provided base URL is invalid'); + } + + /** + * Options object for the Rest Client instance. + * + * @type {object} + */ + const clientOptions = { + errorFormatter: { message: 'message', name: 'error' }, + headers: options.headers, + query: { repeatParams: false }, + }; + + /** + * Provides an abstraction layer for consuming the + * [Auth0 Blacklisted Tokens endpoint]{@link https://auth0.com/docs/api/v2#!/Clients}. + * + * @type {external:RestClient} + */ + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/blacklists/tokens`, + clientOptions, + options.tokenProvider + ); + this.resource = new RetryRestClient(auth0RestClient, options.retry); } /** - * Options object for the Rest Client instance. + * Blacklist a new token. + * + * @function add + * @memberof module:management.BlacklistedTokensManager.prototype + * @example + * var token = { + * aud: 'aud', + * jti: 'jti' + * }; + * + * management.blacklistedTokens.add(token, function (err) { + * if (err) { + * // Handle error. + * } * - * @type {Object} + * // Token blacklisted. + * }); + * @param {object} token Token data. + * @param {string} token.aud Audience (your app client ID). + * @param {string} token.jti The JWT ID claim. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - var clientOptions = { - errorFormatter: { message: 'message', name: 'error' }, - headers: options.headers, - query: { repeatParams: false } - }; + add(...args) { + return this.resource.create(...args); + } /** - * Provides an abstraction layer for consuming the - * [Auth0 Blacklisted Tokens endpoint]{@link https://auth0.com/docs/api/v2#!/Clients}. + * Get all blacklisted tokens. * - * @type {external:RestClient} + * @function getAll + * @memberof module:management.BlacklistedTokensManager.prototype + * @example + * management.blacklistedTokens.getAll(function (err, tokens) { + * console.log(tokens.length); + * }); + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - var auth0RestClient = new Auth0RestClient( - options.baseUrl + '/blacklists/tokens', - clientOptions, - options.tokenProvider - ); - this.resource = new RetryRestClient(auth0RestClient, options.retry); -}; - -/** - * Blacklist a new token. - * - * @method add - * @memberOf module:management.BlacklistedTokensManager.prototype - * - * @example - * var token = { - * aud: 'aud', - * jti: 'jti' - * }; - * - * management.blacklistedTokens.add(token, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Token blacklisted. - * }); - * - * @param {Object} token Token data. - * @param {String} token.aud Audience (your app client ID). - * @param {String} token.jti The JWT ID claim. - * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} - */ -utils.wrapPropertyMethod(BlacklistedTokensManager, 'add', 'resource.create'); - -/** - * Get all blacklisted tokens. - * - * @method getAll - * @memberOf module:management.BlacklistedTokensManager.prototype - * - * @example - * management.blacklistedTokens.getAll(function (err, tokens) { - * console.log(tokens.length); - * }); - * - * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} - */ -utils.wrapPropertyMethod(BlacklistedTokensManager, 'getAll', 'resource.getAll'); + getAll(...args) { + return this.resource.getAll(...args); + } +} module.exports = BlacklistedTokensManager; diff --git a/src/management/BrandingManager.js b/src/management/BrandingManager.js index 899575a71..5c12d5dc8 100644 --- a/src/management/BrandingManager.js +++ b/src/management/BrandingManager.js @@ -1,10 +1,11 @@ -var ArgumentError = require('rest-facade').ArgumentError; -var utils = require('../utils'); -var Auth0RestClient = require('../Auth0RestClient'); -var RetryRestClient = require('../RetryRestClient'); +const { ArgumentError } = require('rest-facade'); +const utils = require('../utils'); +const Auth0RestClient = require('../Auth0RestClient'); +const RetryRestClient = require('../RetryRestClient'); /** * Simple facade for consuming a REST API endpoint. + * * @external RestClient * @see https://github.com/ngonzalvez/rest-facade */ @@ -12,15 +13,14 @@ var RetryRestClient = require('../RetryRestClient'); /** * @class BrandingManager * Manages settings related to branding. - * @constructor - * @memberOf module:management - * - * @param {Object} options The client options. - * @param {String} options.baseUrl The URL of the API. - * @param {Object} [options.headers] Headers to be included in all requests. - * @param {Object} [options.retry] Retry Policy Config + * @class + * @memberof module:management + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config */ -var BrandingManager = function(options) { +const BrandingManager = function (options) { if (options === null || typeof options !== 'object') { throw new ArgumentError('Must provide manager options'); } @@ -33,10 +33,10 @@ var BrandingManager = function(options) { throw new ArgumentError('The provided base URL is invalid'); } - var clientOptions = { + const clientOptions = { errorFormatter: { message: 'message', name: 'error' }, headers: options.headers, - query: { repeatParams: false } + query: { repeatParams: false }, }; /** @@ -45,8 +45,8 @@ var BrandingManager = function(options) { * * @type {external:RestClient} */ - var auth0RestClient = new Auth0RestClient( - options.baseUrl + '/branding', + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/branding`, clientOptions, options.tokenProvider ); @@ -58,8 +58,8 @@ var BrandingManager = function(options) { * * @type {external:RestClient} */ - var brandingTemplateAuth0RestClient = new Auth0RestClient( - options.baseUrl + '/branding/templates/universal-login', + const brandingTemplateAuth0RestClient = new Auth0RestClient( + `${options.baseUrl}/branding/templates/universal-login`, clientOptions, options.tokenProvider ); @@ -69,9 +69,8 @@ var BrandingManager = function(options) { /** * Update the branding settings. * - * @method updateSettings - * @memberOf module:management.BrandingManager.prototype - * + * @function updateSettings + * @memberof module:management.BrandingManager.prototype * @example * management.branding.updateSettings(params, data, function (err, branding) { * if (err) { @@ -81,21 +80,18 @@ var BrandingManager = function(options) { * // Updated branding * console.log(branding); * }); - * - * @param {Object} params Branding parameters (leavy empty). - * @param {Object} data Updated branding data. + * @param {object} params Branding parameters (leavy empty). + * @param {object} data Updated branding data. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(BrandingManager, 'updateSettings', 'resource.patch'); /** * Get the branding settings.. * - * @method getSettings - * @memberOf module:management.BrandingManager.prototype - * + * @function getSettings + * @memberof module:management.BrandingManager.prototype * @example * management.branding.getSettings(data, function (err, branding) { * if (err) { @@ -105,21 +101,18 @@ utils.wrapPropertyMethod(BrandingManager, 'updateSettings', 'resource.patch'); * // Branding * console.log(branding); * }); - * - * @param {Object} params Branding parameters. - * @param {Object} data Branding data. + * @param {object} params Branding parameters. + * @param {object} data Branding data. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(BrandingManager, 'getSettings', 'resource.get'); /** * Get the new universal login template. * - * @method getUniversalLoginTemplate - * @memberOf module:management.BrandingManager.prototype - * + * @function getUniversalLoginTemplate + * @memberof module:management.BrandingManager.prototype * @example * management.branding.getUniversalLoginTemplate(data, function (err, template) { * if (err) { @@ -129,55 +122,51 @@ utils.wrapPropertyMethod(BrandingManager, 'getSettings', 'resource.get'); * // Branding * console.log(template); * }); - * - * @param {Object} params Branding parameters (leave empty). - * @param {Object} data Branding data (leave empty). + * @param {object} params Branding parameters (leave empty). + * @param {object} data Branding data (leave empty). * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(BrandingManager, 'getUniversalLoginTemplate', 'brandingTemplates.get'); /** * Set the new universal login template. * - * @method setUniversalLoginTemplate - * @memberOf module:management.BrandingManager.prototype - * + * @function setUniversalLoginTemplate + * @memberof module:management.BrandingManager.prototype * @example * management.branding.setUniversalLoginTemplate(params, data, function (err) { * if (err) { * // Handle error. * } * }); - * - * @param {Object} params Branding parameters (leavy empty). - * @param {Object} data Branding data (object with template field). + * @param {object} params Branding parameters (leavy empty). + * @param {object} data Branding data (object with template field). * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(BrandingManager, 'setUniversalLoginTemplate', 'brandingTemplates.update'); /** * Delete the new universal login template (revert to default). * - * @method deleteUniversalLoginTemplate - * @memberOf module:management.BrandingManager.prototype - * + * @function deleteUniversalLoginTemplate + * @memberof module:management.BrandingManager.prototype * @example * management.branding.deleteUniversalLoginTemplate(data, function (err) { * if (err) { * // Handle error. * } * }); - * - * @param {Object} params Branding parameters (leavy empty). - * @param {Object} data Branding data (leave empty). + * @param {object} params Branding parameters (leavy empty). + * @param {object} data Branding data (leave empty). * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -utils.wrapPropertyMethod(BrandingManager, 'deleteUniversalLoginTemplate', 'brandingTemplates.delete'); +utils.wrapPropertyMethod( + BrandingManager, + 'deleteUniversalLoginTemplate', + 'brandingTemplates.delete' +); module.exports = BrandingManager; diff --git a/src/management/ClientGrantsManager.js b/src/management/ClientGrantsManager.js index 7cafa6df3..76829d7b2 100644 --- a/src/management/ClientGrantsManager.js +++ b/src/management/ClientGrantsManager.js @@ -1,22 +1,20 @@ -var ArgumentError = require('rest-facade').ArgumentError; -var utils = require('../utils'); -var Auth0RestClient = require('../Auth0RestClient'); -var RetryRestClient = require('../RetryRestClient'); +const { ArgumentError } = require('rest-facade'); +const utils = require('../utils'); +const Auth0RestClient = require('../Auth0RestClient'); +const RetryRestClient = require('../RetryRestClient'); /** * @class ClientGrantsManager * Auth0 Client Grants Manager. * * See {@link https://auth0.com/docs/api/v2#!/Client_Grants Client Grants} - * - * @constructor - * @memberOf module:management - * - * @param {Object} options The client options. - * @param {String} options.baseUrl The URL of the API. - * @param {Object} [options.headers] Headers to be included in all requests. - * @param {Object} [options.retry] Retry Policy Config + * @class + * @memberof module:management + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config */ -var ClientGrantsManager = function(options) { +const ClientGrantsManager = function (options) { if (options === null || typeof options !== 'object') { throw new ArgumentError('Must provide client options'); } @@ -32,12 +30,12 @@ var ClientGrantsManager = function(options) { /** * Options object for the Rest Client instance. * - * @type {Object} + * @type {object} */ - var clientOptions = { + const clientOptions = { errorFormatter: { message: 'message', name: 'error' }, headers: options.headers, - query: { repeatParams: false } + query: { repeatParams: false }, }; /** @@ -46,8 +44,8 @@ var ClientGrantsManager = function(options) { * * @type {external:RestClient} */ - var auth0RestClient = new Auth0RestClient( - options.baseUrl + '/client-grants/:id', + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/client-grants/:id`, clientOptions, options.tokenProvider ); @@ -57,9 +55,8 @@ var ClientGrantsManager = function(options) { /** * Create an Auth0 client grant. * - * @method create - * @memberOf module:management.ClientGrantsManager.prototype - * + * @function create + * @memberof module:management.ClientGrantsManager.prototype * @example * management.clientGrants.create(data, function (err) { * if (err) { @@ -68,20 +65,17 @@ var ClientGrantsManager = function(options) { * * // Client grant created. * }); - * - * @param {Object} data The client data object. + * @param {object} data The client data object. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ClientGrantsManager, 'create', 'resource.create'); /** * Get all Auth0 Client Grants. * - * @method getAll - * @memberOf module:management.ClientGrantsManager.prototype - * + * @function getAll + * @memberof module:management.ClientGrantsManager.prototype * @example * This method takes an optional object as first argument that may be used to * specify pagination settings. If pagination options are not present, @@ -98,22 +92,19 @@ utils.wrapPropertyMethod(ClientGrantsManager, 'create', 'resource.create'); * management.clientGrants.getAll(params, function (err, grants) { * console.log(grants.length); * }); - * - * @param {Object} [params] Client Grants parameters. - * @param {Number} [params.per_page] Number of results per page. - * @param {Number} [params.page] Page number, zero indexed. + * @param {object} [params] Client Grants parameters. + * @param {number} [params.per_page] Number of results per page. + * @param {number} [params.page] Page number, zero indexed. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ClientGrantsManager, 'getAll', 'resource.getAll'); /** * Update an Auth0 client grant. * - * @method update - * @memberOf module:management.ClientGrantsManager.prototype - * + * @function update + * @memberof module:management.ClientGrantsManager.prototype * @example * var data = { * client_id: CLIENT_ID, @@ -129,22 +120,19 @@ utils.wrapPropertyMethod(ClientGrantsManager, 'getAll', 'resource.getAll'); * * console.log(grant.id); * }); - * - * @param {Object} params Client parameters. - * @param {String} params.id Client grant ID. - * @param {Object} data Updated client data. + * @param {object} params Client parameters. + * @param {string} params.id Client grant ID. + * @param {object} data Updated client data. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ClientGrantsManager, 'update', 'resource.patch'); /** * Delete an Auth0 client grant. * - * @method delete - * @memberOf module:management.ClientGrantsManager.prototype - * + * @function delete + * @memberof module:management.ClientGrantsManager.prototype * @example * management.clientGrants.delete({ id: GRANT_ID }, function (err) { * if (err) { @@ -153,12 +141,10 @@ utils.wrapPropertyMethod(ClientGrantsManager, 'update', 'resource.patch'); * * // Grant deleted. * }); - * - * @param {Object} params Client parameters. - * @param {String} params.id Client grant ID. + * @param {object} params Client parameters. + * @param {string} params.id Client grant ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ClientGrantsManager, 'delete', 'resource.delete'); diff --git a/src/management/ClientsManager.js b/src/management/ClientsManager.js index 4acf3ce3a..9abd3da37 100644 --- a/src/management/ClientsManager.js +++ b/src/management/ClientsManager.js @@ -1,7 +1,7 @@ -var ArgumentError = require('rest-facade').ArgumentError; -var utils = require('../utils'); -var Auth0RestClient = require('../Auth0RestClient'); -var RetryRestClient = require('../RetryRestClient'); +const { ArgumentError } = require('rest-facade'); +const utils = require('../utils'); +const Auth0RestClient = require('../Auth0RestClient'); +const RetryRestClient = require('../RetryRestClient'); /** * @class ClientsManager @@ -12,15 +12,14 @@ var RetryRestClient = require('../RetryRestClient'); * You can learn more about this in the * {@link https://auth0.com/docs/applications Applications} section of the * documentation. - * @constructor - * @memberOf module:management - * - * @param {Object} options The client options. - * @param {String} options.baseUrl The URL of the API. - * @param {Object} [options.headers] Headers to be included in all requests. - * @param {Object} [options.retry] Retry Policy Config + * @class + * @memberof module:management + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config */ -var ClientsManager = function(options) { +const ClientsManager = function (options) { if (options === null || typeof options !== 'object') { throw new ArgumentError('Must provide client options'); } @@ -36,12 +35,12 @@ var ClientsManager = function(options) { /** * Options object for the Rest Client instance. * - * @type {Object} + * @type {object} */ - var clientOptions = { + const clientOptions = { errorFormatter: { message: 'message', name: 'error' }, headers: options.headers, - query: { repeatParams: false } + query: { repeatParams: false }, }; /** @@ -50,8 +49,8 @@ var ClientsManager = function(options) { * * @type {external:RestClient} */ - var auth0RestClient = new Auth0RestClient( - options.baseUrl + '/clients/:client_id', + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/clients/:client_id`, clientOptions, options.tokenProvider ); @@ -61,9 +60,8 @@ var ClientsManager = function(options) { /** * Create an Auth0 client. * - * @method create - * @memberOf module:management.ClientsManager.prototype - * + * @function create + * @memberof module:management.ClientsManager.prototype * @example * management.clients.create(data, function (err) { * if (err) { @@ -72,20 +70,17 @@ var ClientsManager = function(options) { * * // Client created. * }); - * - * @param {Object} data The client data object. + * @param {object} data The client data object. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ClientsManager, 'create', 'resource.create'); /** * Get all Auth0 clients. * - * @method getAll - * @memberOf module:management.ClientsManager.prototype - * + * @function getAll + * @memberof module:management.ClientsManager.prototype * @example * This method takes an optional object as first argument that may be used to * specify pagination settings. If pagination options are not present, @@ -101,22 +96,19 @@ utils.wrapPropertyMethod(ClientsManager, 'create', 'resource.create'); * management.clients.getAll(params, function (err, clients) { * console.log(clients.length); * }); - * - * @param {Object} [params] Clients parameters. - * @param {Number} [params.per_page] Number of results per page. - * @param {Number} [params.page] Page number, zero indexed. + * @param {object} [params] Clients parameters. + * @param {number} [params.per_page] Number of results per page. + * @param {number} [params.page] Page number, zero indexed. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ClientsManager, 'getAll', 'resource.getAll'); /** * Get an Auth0 client. * - * @method get - * @memberOf module:management.ClientsManager.prototype - * + * @function get + * @memberof module:management.ClientsManager.prototype * @example * management.clients.get({ client_id: CLIENT_ID }, function (err, client) { * if (err) { @@ -125,21 +117,18 @@ utils.wrapPropertyMethod(ClientsManager, 'getAll', 'resource.getAll'); * * console.log(client); * }); - * - * @param {Object} params Client parameters. - * @param {String} params.client_id Application client ID. + * @param {object} params Client parameters. + * @param {string} params.client_id Application client ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ClientsManager, 'get', 'resource.get'); /** * Update an Auth0 client. * - * @method update - * @memberOf module:management.ClientsManager.prototype - * + * @function update + * @memberof module:management.ClientsManager.prototype * @example * var data = { name: 'newClientName' }; * var params = { client_id: CLIENT_ID }; @@ -151,22 +140,19 @@ utils.wrapPropertyMethod(ClientsManager, 'get', 'resource.get'); * * console.log(client.name); // 'newClientName' * }); - * - * @param {Object} params Client parameters. - * @param {String} params.client_id Application client ID. - * @param {Object} data Updated client data. + * @param {object} params Client parameters. + * @param {string} params.client_id Application client ID. + * @param {object} data Updated client data. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ClientsManager, 'update', 'resource.patch'); /** * Delete an Auth0 client. * - * @method delete - * @memberOf module:management.ClientsManager.prototype - * + * @function delete + * @memberof module:management.ClientsManager.prototype * @example * management.clients.delete({ client_id: CLIENT_ID }, function (err) { * if (err) { @@ -175,12 +161,10 @@ utils.wrapPropertyMethod(ClientsManager, 'update', 'resource.patch'); * * // Client deleted. * }); - * - * @param {Object} params Client parameters. - * @param {String} params.client_id Application client ID. + * @param {object} params Client parameters. + * @param {string} params.client_id Application client ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ClientsManager, 'delete', 'resource.delete'); diff --git a/src/management/ConnectionsManager.js b/src/management/ConnectionsManager.js index 87ebd6e5a..f486bbc69 100644 --- a/src/management/ConnectionsManager.js +++ b/src/management/ConnectionsManager.js @@ -1,20 +1,19 @@ -var ArgumentError = require('rest-facade').ArgumentError; -var utils = require('../utils'); -var Auth0RestClient = require('../Auth0RestClient'); -var RetryRestClient = require('../RetryRestClient'); +const { ArgumentError } = require('rest-facade'); +const utils = require('../utils'); +const Auth0RestClient = require('../Auth0RestClient'); +const RetryRestClient = require('../RetryRestClient'); /** * @class ConnectionsManager * Represents the relationship between Auth0 and an Identity provider. - * @constructor - * @memberOf module:management - * - * @param {Object} options The client options. - * @param {String} options.baseUrl The URL of the API. - * @param {Object} [options.headers] Headers to be included in all requests. - * @param {Object} [options.retry] Retry Policy Config + * @class + * @memberof module:management + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config */ -var ConnectionsManager = function(options) { +const ConnectionsManager = function (options) { if (options === null || typeof options !== 'object') { throw new ArgumentError('Must provide client options'); } @@ -30,11 +29,11 @@ var ConnectionsManager = function(options) { /** * Options object for the Rest Client instance. * - * @type {Object} + * @type {object} */ - var clientOptions = { + const clientOptions = { headers: options.headers, - query: { repeatParams: false } + query: { repeatParams: false }, }; /** @@ -44,8 +43,8 @@ var ConnectionsManager = function(options) { * * @type {external:RestClient} */ - var auth0RestClient = new Auth0RestClient( - options.baseUrl + '/connections/:id ', + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/connections/:id `, clientOptions, options.tokenProvider ); @@ -58,8 +57,8 @@ var ConnectionsManager = function(options) { * * @type {external:RestClient} */ - var userAuth0RestClient = new Auth0RestClient( - options.baseUrl + '/connections/:id/users', + const userAuth0RestClient = new Auth0RestClient( + `${options.baseUrl}/connections/:id/users`, clientOptions, options.tokenProvider ); @@ -69,9 +68,8 @@ var ConnectionsManager = function(options) { /** * Create a new connection. * - * @method create - * @memberOf module:management.ConnectionsManager.prototype - * + * @function create + * @memberof module:management.ConnectionsManager.prototype * @example * management.connections.create(data, function (err) { * if (err) { @@ -80,20 +78,17 @@ var ConnectionsManager = function(options) { * * // Connection created. * }); - * - * @param {Object} data Connection data object. + * @param {object} data Connection data object. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ConnectionsManager, 'create', 'resource.create'); /** * Get all connections. * - * @method getAll - * @memberOf module:management.ConnectionsManager.prototype - * + * @function getAll + * @memberof module:management.ConnectionsManager.prototype * @example * This method takes an optional object as first argument that may be used to * specify pagination settings. If pagination options are not present, @@ -109,22 +104,19 @@ utils.wrapPropertyMethod(ConnectionsManager, 'create', 'resource.create'); * management.connections.getAll(params, function (err, connections) { * console.log(connections.length); * }); - * - * @param {Object} [params] Connections params. - * @param {Number} [params.per_page] Number of results per page. - * @param {Number} [params.page] Page number, zero indexed. + * @param {object} [params] Connections params. + * @param {number} [params.per_page] Number of results per page. + * @param {number} [params.page] Page number, zero indexed. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ConnectionsManager, 'getAll', 'resource.getAll'); /** * Get an Auth0 connection. * - * @method get - * @memberOf module:management.ConnectionsManager.prototype - * + * @function get + * @memberof module:management.ConnectionsManager.prototype * @example * management.connections.get({ id: CONNECTION_ID }, function (err, connection) { * if (err) { @@ -133,21 +125,18 @@ utils.wrapPropertyMethod(ConnectionsManager, 'getAll', 'resource.getAll'); * * console.log(connection); * }); - * - * @param {Object} params Connection parameters. - * @param {String} params.id Connection ID. + * @param {object} params Connection parameters. + * @param {string} params.id Connection ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ConnectionsManager, 'get', 'resource.get'); /** * Update an existing connection. * - * @method update - * @memberOf module:management.ConnectionsManager.prototype - * + * @function update + * @memberof module:management.ConnectionsManager.prototype * @example * var data = { name: 'newConnectionName' }; * var params = { id: CONNECTION_ID }; @@ -159,22 +148,19 @@ utils.wrapPropertyMethod(ConnectionsManager, 'get', 'resource.get'); * * console.log(connection.name); // 'newConnectionName' * }); - * - * @param {Object} params Connection parameters. - * @param {String} params.id Connection ID. - * @param {Object} data Updated connection data. + * @param {object} params Connection parameters. + * @param {string} params.id Connection ID. + * @param {object} data Updated connection data. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ConnectionsManager, 'update', 'resource.patch'); /** * Delete an existing connection. * - * @method delete - * @memberOf module:management.ConnectionsManager.prototype - * + * @function delete + * @memberof module:management.ConnectionsManager.prototype * @example * management.connections.delete({ id: CONNECTION_ID }, function (err) { * if (err) { @@ -183,21 +169,18 @@ utils.wrapPropertyMethod(ConnectionsManager, 'update', 'resource.patch'); * * // Connection deleted. * }); - * - * @param {Object} params Connection parameters. - * @param {String} params.id Connection ID. + * @param {object} params Connection parameters. + * @param {string} params.id Connection ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ConnectionsManager, 'delete', 'resource.delete'); /** * Delete a connection user by email. * - * @method delete - * @memberOf module:management.ConnectionsManager.prototype - * + * @function delete + * @memberof module:management.ConnectionsManager.prototype * @example * management.connections.deleteUserByEmail({ id: CONNECTION_ID, email:USER_EMAIL }, function (err) { * if (err) { @@ -206,15 +189,13 @@ utils.wrapPropertyMethod(ConnectionsManager, 'delete', 'resource.delete'); * * // User deleted. * }); - * - * @param {Object} params Connection parameters. - * @param {String} params.id Connection ID. - * @param {String} params.email User Email. + * @param {object} params Connection parameters. + * @param {string} params.id Connection ID. + * @param {string} params.email User Email. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -ConnectionsManager.prototype.deleteUserByEmail = function(params, cb) { +ConnectionsManager.prototype.deleteUserByEmail = function (params, cb) { if (typeof params !== 'object' || typeof params.email !== 'string' || params.email.length < 1) { throw new ArgumentError('You must provide an email for the deleteUserByEmail method'); } diff --git a/src/management/CustomDomainsManager.js b/src/management/CustomDomainsManager.js index fea099afc..75d3f483a 100644 --- a/src/management/CustomDomainsManager.js +++ b/src/management/CustomDomainsManager.js @@ -1,7 +1,7 @@ -var ArgumentError = require('rest-facade').ArgumentError; -var utils = require('../utils'); -var Auth0RestClient = require('../Auth0RestClient'); -var RetryRestClient = require('../RetryRestClient'); +const { ArgumentError } = require('rest-facade'); +const utils = require('../utils'); +const Auth0RestClient = require('../Auth0RestClient'); +const RetryRestClient = require('../RetryRestClient'); /** * @class CustomDomainsManager @@ -12,15 +12,14 @@ var RetryRestClient = require('../RetryRestClient'); * You can learn more about this in the * {@link https://auth0.com/docs/custom-domains CustomDomains} section of the * documentation. - * @constructor - * @memberOf module:management - * - * @param {Object} options The client options. - * @param {String} options.baseUrl The URL of the API. - * @param {Object} [options.headers] Headers to be included in all requests. - * @param {Object} [options.retry] Retry Policy Config + * @class + * @memberof module:management + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config */ -var CustomDomainsManager = function(options) { +const CustomDomainsManager = function (options) { if (options === null || typeof options !== 'object') { throw new ArgumentError('Must provide manager options'); } @@ -36,12 +35,12 @@ var CustomDomainsManager = function(options) { /** * Options object for the Rest Client instance. * - * @type {Object} + * @type {object} */ - var clientOptions = { + const clientOptions = { errorFormatter: { message: 'message', name: 'error' }, headers: options.headers, - query: { repeatParams: false } + query: { repeatParams: false }, }; /** @@ -50,8 +49,8 @@ var CustomDomainsManager = function(options) { * * @type {external:RestClient} */ - var auth0CustomDomainsRestClient = new Auth0RestClient( - options.baseUrl + '/custom-domains/:id', + const auth0CustomDomainsRestClient = new Auth0RestClient( + `${options.baseUrl}/custom-domains/:id`, clientOptions, options.tokenProvider ); @@ -63,8 +62,8 @@ var CustomDomainsManager = function(options) { * * @type {external:RestClient} */ - var auth0VerifyRestClient = new Auth0RestClient( - options.baseUrl + '/custom-domains/:id/verify', + const auth0VerifyRestClient = new Auth0RestClient( + `${options.baseUrl}/custom-domains/:id/verify`, clientOptions, options.tokenProvider ); @@ -74,9 +73,8 @@ var CustomDomainsManager = function(options) { /** * Create an Auth0 Custom Domain. * - * @method create - * @memberOf module:management.CustomDomainsManager.prototype - * + * @function create + * @memberof module:management.CustomDomainsManager.prototype * @example * management.customDomains.create(data, function (err) { * if (err) { @@ -85,35 +83,30 @@ var CustomDomainsManager = function(options) { * * // CustomDomain created. * }); - * - * @param {Object} data The custom domain data object. + * @param {object} data The custom domain data object. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(CustomDomainsManager, 'create', 'resource.create'); /** * Get all Auth0 CustomDomains. * - * @method getAll - * @memberOf module:management.CustomDomainsManager.prototype - * + * @function getAll + * @memberof module:management.CustomDomainsManager.prototype * @example * management.customDomains.getAll(function (err, customDomains) { * console.log(customDomains.length); * }); - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(CustomDomainsManager, 'getAll', 'resource.getAll'); /** * Get a Custom Domain. * - * @method get - * @memberOf module:management.CustomDomainsManager.prototype - * + * @function get + * @memberof module:management.CustomDomainsManager.prototype * @example * management.customDomains.get({ id: CUSTOM_DOMAIN_ID }, function (err, customDomain) { * if (err) { @@ -122,21 +115,18 @@ utils.wrapPropertyMethod(CustomDomainsManager, 'getAll', 'resource.getAll'); * * console.log(customDomain); * }); - * - * @param {Object} params Custom Domain parameters. - * @param {String} params.id Custom Domain ID. + * @param {object} params Custom Domain parameters. + * @param {string} params.id Custom Domain ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(CustomDomainsManager, 'get', 'resource.get'); /** * Verify a Custom Domain. * - * @method verify - * @memberOf module:management.CustomDomainsManager.prototype - * + * @function verify + * @memberof module:management.CustomDomainsManager.prototype * @example * management.customDomains.verify({ id: CUSTOM_DOMAIN_ID }, function (err, customDomain) { * if (err) { @@ -145,14 +135,12 @@ utils.wrapPropertyMethod(CustomDomainsManager, 'get', 'resource.get'); * * console.log(customDomain); * }); - * - * @param {Object} params Custom Domain parameters. - * @param {String} params.id Custom Domain ID. + * @param {object} params Custom Domain parameters. + * @param {string} params.id Custom Domain ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -CustomDomainsManager.prototype.verify = function(params, cb) { +CustomDomainsManager.prototype.verify = function (params, cb) { if (!params || !params.id) { throw new ArgumentError('The custom domain id cannot be null or undefined'); } @@ -167,9 +155,8 @@ CustomDomainsManager.prototype.verify = function(params, cb) { /** * Delete a Custom Domain. * - * @method delete - * @memberOf module:management.CustomDomainsManager.prototype - * + * @function delete + * @memberof module:management.CustomDomainsManager.prototype * @example * management.customDomains.delete({ id: CUSTOM_DOMAIN_ID }, function (err) { * if (err) { @@ -178,12 +165,10 @@ CustomDomainsManager.prototype.verify = function(params, cb) { * * // CustomDomain deleted. * }); - * - * @param {Object} params Custom Domain parameters. - * @param {String} params.id Custom Domain ID. + * @param {object} params Custom Domain parameters. + * @param {string} params.id Custom Domain ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(CustomDomainsManager, 'delete', 'resource.delete'); diff --git a/src/management/DeviceCredentialsManager.js b/src/management/DeviceCredentialsManager.js index 1cff47c31..aaa5b51b6 100644 --- a/src/management/DeviceCredentialsManager.js +++ b/src/management/DeviceCredentialsManager.js @@ -1,10 +1,11 @@ -var ArgumentError = require('rest-facade').ArgumentError; -var utils = require('../utils'); -var Auth0RestClient = require('../Auth0RestClient'); -var RetryRestClient = require('../RetryRestClient'); +const { ArgumentError } = require('rest-facade'); +const utils = require('../utils'); +const Auth0RestClient = require('../Auth0RestClient'); +const RetryRestClient = require('../RetryRestClient'); /** * Simple facade for consuming a REST API endpoint. + * * @external RestClient * @see https://github.com/ngonzalvez/rest-facade */ @@ -12,15 +13,14 @@ var RetryRestClient = require('../RetryRestClient'); /** * @class DeviceCredentialsManager * Manages Auth0 Device Credentials. - * @constructor - * @memberOf module:management - * - * @param {Object} options The client options. - * @param {String} options.baseUrl The URL of the API. - * @param {Object} [options.headers] Headers to be included in all requests. - * @param {Object} [options.retry] Retry Policy Config + * @class + * @memberof module:management + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config */ -var DeviceCredentialsManager = function(options) { +const DeviceCredentialsManager = function (options) { if (options === null || typeof options !== 'object') { throw new ArgumentError('Must provide manager options'); } @@ -36,12 +36,12 @@ var DeviceCredentialsManager = function(options) { /** * Options object for the RestClient instance. * - * @type {Object} + * @type {object} */ - var clientOptions = { + const clientOptions = { errorFormatter: { message: 'message', name: 'error' }, headers: options.headers, - query: { repeatParams: false } + query: { repeatParams: false }, }; /** @@ -51,8 +51,8 @@ var DeviceCredentialsManager = function(options) { * * @type {external:RestClient} */ - var auth0RestClient = new Auth0RestClient( - options.baseUrl + '/device-credentials/:id', + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/device-credentials/:id`, clientOptions, options.tokenProvider ); @@ -62,9 +62,8 @@ var DeviceCredentialsManager = function(options) { /** * Create an Auth0 credential. * - * @method create - * @memberOf module:management.DeviceCredentialsManager.prototype - * + * @function create + * @memberof module:management.DeviceCredentialsManager.prototype * @example * management.deviceCredentials.create(data, function (err) { * if (err) { @@ -73,40 +72,34 @@ var DeviceCredentialsManager = function(options) { * * // Credential created. * }); - * - * @param {Object} data The device credential data object. + * @param {object} data The device credential data object. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(DeviceCredentialsManager, 'createPublicKey', 'resource.create'); /** * Get all Auth0 credentials. * - * @method getAll - * @memberOf module:management.DeviceCredentialsManager.prototype - * + * @function getAll + * @memberof module:management.DeviceCredentialsManager.prototype * @example * var params = {user_id: "USER_ID"}; * * management.deviceCredentials.getAll(params, function (err, credentials) { * console.log(credentials.length); * }); - * - * @param {Object} params Credential parameters. + * @param {object} params Credential parameters. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(DeviceCredentialsManager, 'getAll', 'resource.getAll'); /** * Delete an Auth0 device credential. * - * @method delete - * @memberOf module:management.DeviceCredentialsManager.prototype - * + * @function delete + * @memberof module:management.DeviceCredentialsManager.prototype * @example * var params = { id: CREDENTIAL_ID }; * @@ -117,12 +110,10 @@ utils.wrapPropertyMethod(DeviceCredentialsManager, 'getAll', 'resource.getAll'); * * // Credential deleted. * }); - * - * @param {Object} params Credential parameters. - * @param {String} params.id Device credential ID. + * @param {object} params Credential parameters. + * @param {string} params.id Device credential ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(DeviceCredentialsManager, 'delete', 'resource.delete'); diff --git a/src/management/EmailProviderManager.js b/src/management/EmailProviderManager.js index b99d9fd25..45849124d 100644 --- a/src/management/EmailProviderManager.js +++ b/src/management/EmailProviderManager.js @@ -1,10 +1,11 @@ -var ArgumentError = require('rest-facade').ArgumentError; -var utils = require('../utils'); -var Auth0RestClient = require('../Auth0RestClient'); -var RetryRestClient = require('../RetryRestClient'); +const { ArgumentError } = require('rest-facade'); +const utils = require('../utils'); +const Auth0RestClient = require('../Auth0RestClient'); +const RetryRestClient = require('../RetryRestClient'); /** * Simple facade for consuming a REST API endpoint. + * * @external RestClient * @see https://github.com/ngonzalvez/rest-facade */ @@ -12,15 +13,14 @@ var RetryRestClient = require('../RetryRestClient'); /** * @class EmailProviderManager * Auth0 Email Provider. - * @constructor - * @memberOf module:management - * - * @param {Object} options The client options. - * @param {String} options.baseUrl The URL of the API. - * @param {Object} [options.headers] Headers to be included in all requests. - * @param {Object} [options.retry] Retry Policy Config + * @class + * @memberof module:management + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config */ -var EmailProviderManager = function(options) { +const EmailProviderManager = function (options) { if (options === null || typeof options !== 'object') { throw new ArgumentError('Must provide client options'); } @@ -36,12 +36,12 @@ var EmailProviderManager = function(options) { /** * Options object for the Rest Client instance. * - * @type {Object} + * @type {object} */ - var clientOptions = { + const clientOptions = { errorFormatter: { message: 'message', name: 'error' }, headers: options.headers, - query: { repeatParams: false } + query: { repeatParams: false }, }; /** @@ -50,8 +50,8 @@ var EmailProviderManager = function(options) { * * @type {external:RestClient} */ - var auth0RestClient = new Auth0RestClient( - options.baseUrl + '/emails/provider', + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/emails/provider`, clientOptions, options.tokenProvider ); @@ -61,9 +61,8 @@ var EmailProviderManager = function(options) { /** * Configure the email provider. * - * @method configure - * @memberOf module:management.EmailProviderManager.prototype - * + * @function configure + * @memberof module:management.EmailProviderManager.prototype * @example * management.emailProvider.configure(data, function (err) { * if (err) { @@ -72,39 +71,34 @@ var EmailProviderManager = function(options) { * * // Email provider configured. * }); - * @param {Object} data The email provider data object. + * @param {object} data The email provider data object. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(EmailProviderManager, 'configure', 'resource.create'); /** * Get the email provider. * - * @method get - * @memberOf module:management.EmailProviderManager.prototype - * + * @function get + * @memberof module:management.EmailProviderManager.prototype * @example * management.emailProvider.get(function (err, provider) { * console.log(provider); * }); - * * @param {Function} [cb] Callback function. - * @param {Object} [params] Clients parameters. - * @param {Number} [params.fields] A comma separated list of fields to include or exclude (depending on include_fields) from the result, empty to retrieve: name, enabled, settings fields. - * @param {Number} [params.include_fields] true if the fields specified are to be excluded from the result, false otherwise (defaults to true) - - * @return {Promise|undefined} + * @param {object} [params] Clients parameters. + * @param {number} [params.fields] A comma separated list of fields to include or exclude (depending on include_fields) from the result, empty to retrieve: name, enabled, settings fields. + * @param {number} [params.include_fields] true if the fields specified are to be excluded from the result, false otherwise (defaults to true) + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(EmailProviderManager, 'get', 'resource.getAll'); /** * Update the email provider. * - * @method update - * @memberOf module:management.EmailProviderManager.prototype - * + * @function update + * @memberof module:management.EmailProviderManager.prototype * @example * management.emailProvider.update(params, data, function (err, provider) { * if (err) { @@ -114,21 +108,18 @@ utils.wrapPropertyMethod(EmailProviderManager, 'get', 'resource.getAll'); * // Updated email provider. * console.log(provider); * }); - * - * @param {Object} params Email provider parameters. - * @param {Object} data Updated email provider data. + * @param {object} params Email provider parameters. + * @param {object} data Updated email provider data. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(EmailProviderManager, 'update', 'resource.patch'); /** * Delete email provider. * - * @method delete - * @memberOf module:management.EmailProviderManager.prototype - * + * @function delete + * @memberof module:management.EmailProviderManager.prototype * @example * management.emailProvider.delete(function (err) { * if (err) { @@ -137,10 +128,8 @@ utils.wrapPropertyMethod(EmailProviderManager, 'update', 'resource.patch'); * * // Email provider configured. * }); - * * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(EmailProviderManager, 'delete', 'resource.delete'); diff --git a/src/management/EmailTemplatesManager.js b/src/management/EmailTemplatesManager.js index c92ea85c8..7607c901f 100644 --- a/src/management/EmailTemplatesManager.js +++ b/src/management/EmailTemplatesManager.js @@ -1,10 +1,11 @@ -var ArgumentError = require('rest-facade').ArgumentError; -var utils = require('../utils'); -var Auth0RestClient = require('../Auth0RestClient'); -var RetryRestClient = require('../RetryRestClient'); +const { ArgumentError } = require('rest-facade'); +const utils = require('../utils'); +const Auth0RestClient = require('../Auth0RestClient'); +const RetryRestClient = require('../RetryRestClient'); /** * Simple facade for consuming a REST API endpoint. + * * @external RestClient * @see https://github.com/ngonzalvez/rest-facade */ @@ -13,15 +14,14 @@ var RetryRestClient = require('../RetryRestClient'); * @class EmailTemplatesManager * This class provides a simple abstraction for performing CRUD operations * on Auth0's Email Templates. {@see https://auth0.com/docs/api/management/v2#!/Email_Templates/get_email_templates_by_templateName} - * @constructor - * @memberOf module:management - * - * @param {Object} options The client options. - * @param {String} options.baseUrl The URL of the API. - * @param {Object} [options.headers] Headers to be included in all requests. - * @param {Object} [options.retry] Retry Policy Config + * @class + * @memberof module:management + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config */ -var EmailTemplatesManager = function(options) { +const EmailTemplatesManager = function (options) { if (!options || 'object' !== typeof options) { throw new ArgumentError('Must provide manager options'); } @@ -33,11 +33,11 @@ var EmailTemplatesManager = function(options) { /** * Options object for the Rest Client instance. * - * @type {Object} + * @type {object} */ - var clientOptions = { + const clientOptions = { headers: options.headers, - query: { repeatParams: false } + query: { repeatParams: false }, }; /** @@ -46,8 +46,8 @@ var EmailTemplatesManager = function(options) { * * @type {external:RestClient} */ - var auth0RestClient = new Auth0RestClient( - options.baseUrl + '/email-templates/:name', + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/email-templates/:name`, clientOptions, options.tokenProvider ); @@ -57,9 +57,8 @@ var EmailTemplatesManager = function(options) { /** * Create a new Email Template. * - * @method create - * @memberOf module:management.EmailTemplatesManager.prototype - * + * @function create + * @memberof module:management.EmailTemplatesManager.prototype * @example * management.emailTemplates.create(data, function (err) { * if (err) { @@ -68,20 +67,17 @@ var EmailTemplatesManager = function(options) { * * // Email Template created. * }); - * - * @param {Object} data Email Template data object. + * @param {object} data Email Template data object. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(EmailTemplatesManager, 'create', 'resource.create'); /** * Get an Auth0 Email Template. * - * @method get - * @memberOf module:management.EmailTemplatesManager.prototype - * + * @function get + * @memberof module:management.EmailTemplatesManager.prototype * @example * management.emailTemplates.get({ name: EMAIL_TEMPLATE_NAME }, function (err, emailTemplate) { * if (err) { @@ -90,21 +86,18 @@ utils.wrapPropertyMethod(EmailTemplatesManager, 'create', 'resource.create'); * * console.log(emailTemplate); * }); - * - * @param {Object} params Email Template parameters. - * @param {String} params.name Template Name + * @param {object} params Email Template parameters. + * @param {string} params.name Template Name * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(EmailTemplatesManager, 'get', 'resource.get'); /** * Update an existing Email Template. * - * @method update - * @memberOf module:management.EmailTemplatesManager.prototype - * + * @function update + * @memberof module:management.EmailTemplatesManager.prototype * @example * var data = { from: 'new@email.com' }; * var params = { name: EMAIL_TEMPLATE_NAME }; @@ -116,13 +109,11 @@ utils.wrapPropertyMethod(EmailTemplatesManager, 'get', 'resource.get'); * * console.log(emailTemplate.from); // 'new@email.com' * }); - * - * @param {Object} params Email Template parameters. - * @param {String} params.name Template Name - * @param {Object} data Updated Email Template data. + * @param {object} params Email Template parameters. + * @param {string} params.name Template Name + * @param {object} data Updated Email Template data. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(EmailTemplatesManager, 'update', 'resource.patch'); diff --git a/src/management/GrantsManager.js b/src/management/GrantsManager.js index 9ccaf09a7..f2a281ea0 100644 --- a/src/management/GrantsManager.js +++ b/src/management/GrantsManager.js @@ -1,22 +1,20 @@ -var ArgumentError = require('rest-facade').ArgumentError; -var utils = require('../utils'); -var Auth0RestClient = require('../Auth0RestClient'); -var RetryRestClient = require('../RetryRestClient'); +const { ArgumentError } = require('rest-facade'); +const utils = require('../utils'); +const Auth0RestClient = require('../Auth0RestClient'); +const RetryRestClient = require('../RetryRestClient'); /** * @class GrantsManager * Auth0 Grants Manager. * * See {@link https://auth0.com/docs/api/v2#!/Grants Grants} - * - * @constructor - * @memberOf module:management - * - * @param {Object} options The client options. - * @param {String} options.baseUrl The URL of the API. - * @param {Object} [options.headers] Headers to be included in all requests. - * @param {Object} [options.retry] Retry Policy Config + * @class + * @memberof module:management + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config */ -var GrantsManager = function(options) { +const GrantsManager = function (options) { if (options === null || typeof options !== 'object') { throw new ArgumentError('Must provide client options'); } @@ -32,12 +30,12 @@ var GrantsManager = function(options) { /** * Options object for the Rest Client instance. * - * @type {Object} + * @type {object} */ - var clientOptions = { + const clientOptions = { errorFormatter: { message: 'message', name: 'error' }, headers: options.headers, - query: { repeatParams: false } + query: { repeatParams: false }, }; /** @@ -46,8 +44,8 @@ var GrantsManager = function(options) { * * @type {external:RestClient} */ - var auth0RestClient = new Auth0RestClient( - options.baseUrl + '/grants/:id', + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/grants/:id`, clientOptions, options.tokenProvider ); @@ -57,9 +55,8 @@ var GrantsManager = function(options) { /** * Get all Auth0 Grants. * - * @method getAll - * @memberOf module:management.GrantsManager.prototype - * + * @function getAll + * @memberof module:management.GrantsManager.prototype * @example * var params = { * per_page: 10, @@ -73,26 +70,23 @@ var GrantsManager = function(options) { * management.getGrants(params, function (err, grants) { * console.log(grants.length); * }); - * - * @param {Object} params Grants parameters. - * @param {Number} params.per_page Number of results per page. - * @param {Number} params.page Page number, zero indexed. - * @param {Boolean} params.include_totals true if a query summary must be included in the result, false otherwise. Default false; - * @param {String} params.user_id The user_id of the grants to retrieve. - * @param {String} params.client_id The client_id of the grants to retrieve. - * @param {String} params.audience The audience of the grants to retrieve. + * @param {object} params Grants parameters. + * @param {number} params.per_page Number of results per page. + * @param {number} params.page Page number, zero indexed. + * @param {boolean} params.include_totals true if a query summary must be included in the result, false otherwise. Default false; + * @param {string} params.user_id The user_id of the grants to retrieve. + * @param {string} params.client_id The client_id of the grants to retrieve. + * @param {string} params.audience The audience of the grants to retrieve. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(GrantsManager, 'getAll', 'resource.getAll'); /** * Delete an Auth0 grant. * - * @method delete - * @memberOf module:management.GrantsManager.prototype - * + * @function delete + * @memberof module:management.GrantsManager.prototype * @example * var params = { * id: 'GRANT_ID', @@ -106,13 +100,11 @@ utils.wrapPropertyMethod(GrantsManager, 'getAll', 'resource.getAll'); * * // Grant deleted. * }); - * - * @param {Object} params Grant parameters. - * @param {String} params.id Grant ID. - * @param {String} params.user_id The user_id of the grants to delete. + * @param {object} params Grant parameters. + * @param {string} params.id Grant ID. + * @param {string} params.user_id The user_id of the grants to delete. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(GrantsManager, 'delete', 'resource.delete'); diff --git a/src/management/GuardianManager.js b/src/management/GuardianManager.js index 12393a338..157b62e14 100644 --- a/src/management/GuardianManager.js +++ b/src/management/GuardianManager.js @@ -1,10 +1,11 @@ -var ArgumentError = require('rest-facade').ArgumentError; -var utils = require('../utils'); -var Auth0RestClient = require('../Auth0RestClient'); -var RetryRestClient = require('../RetryRestClient'); +const { ArgumentError } = require('rest-facade'); +const utils = require('../utils'); +const Auth0RestClient = require('../Auth0RestClient'); +const RetryRestClient = require('../RetryRestClient'); /** * Simple facade for consuming a REST API endpoint. + * * @external RestClient * @see https://github.com/ngonzalvez/rest-facade */ @@ -12,15 +13,14 @@ var RetryRestClient = require('../RetryRestClient'); /** * @class * Abstracts interaction with the Guardian endpoint. - * @constructor - * @memberOf module:management - * - * @param {Object} options The client options. - * @param {String} options.baseUrl The URL of the API. - * @param {Object} [options.headers] Headers to be included in all requests. - * @param {Object} [options.retry] Retry Policy Config + * @class + * @memberof module:management + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config */ -var GuardianManager = function(options) { +const GuardianManager = function (options) { if (options === null || typeof options !== 'object') { throw new ArgumentError('Must provide manager options'); } @@ -33,10 +33,10 @@ var GuardianManager = function(options) { throw new ArgumentError('The provided base URL is invalid'); } - var clientOptions = { + const clientOptions = { errorFormatter: { message: 'message', name: 'error' }, headers: options.headers, - query: { repeatParams: false } + query: { repeatParams: false }, }; /** @@ -44,8 +44,8 @@ var GuardianManager = function(options) { * * @type {external:RestClient} */ - var guardianEnrollmentsAuth0RestClient = new Auth0RestClient( - options.baseUrl + '/guardian/enrollments/:id', + const guardianEnrollmentsAuth0RestClient = new Auth0RestClient( + `${options.baseUrl}/guardian/enrollments/:id`, clientOptions, options.tokenProvider ); @@ -56,8 +56,8 @@ var GuardianManager = function(options) { * * @type {external:RestClient} */ - var guardianTicketsAuth0RestClient = new Auth0RestClient( - options.baseUrl + '/guardian/enrollments/ticket', + const guardianTicketsAuth0RestClient = new Auth0RestClient( + `${options.baseUrl}/guardian/enrollments/ticket`, clientOptions, options.tokenProvider ); @@ -68,8 +68,8 @@ var GuardianManager = function(options) { * * @type {external:RestClient} */ - var guardianFactorsAuth0RestClient = new Auth0RestClient( - options.baseUrl + '/guardian/factors/:name', + const guardianFactorsAuth0RestClient = new Auth0RestClient( + `${options.baseUrl}/guardian/factors/:name`, clientOptions, options.tokenProvider ); @@ -80,8 +80,8 @@ var GuardianManager = function(options) { * * @type {external:RestClient} */ - var guardianFactorSettingsAuth0RestClient = new Auth0RestClient( - options.baseUrl + '/guardian/factors/:name/settings', + const guardianFactorSettingsAuth0RestClient = new Auth0RestClient( + `${options.baseUrl}/guardian/factors/:name/settings`, clientOptions, options.tokenProvider ); @@ -92,8 +92,8 @@ var GuardianManager = function(options) { * * @type {external:RestClient} */ - var guardianFactorsTemplatesAuth0RestClient = new Auth0RestClient( - options.baseUrl + '/guardian/factors/:name/templates', + const guardianFactorsTemplatesAuth0RestClient = new Auth0RestClient( + `${options.baseUrl}/guardian/factors/:name/templates`, clientOptions, options.tokenProvider ); @@ -107,8 +107,8 @@ var GuardianManager = function(options) { * * @type {external:RestClient} */ - var guardianFactorsProvidersAuth0RestClient = new Auth0RestClient( - options.baseUrl + '/guardian/factors/:name/providers/:provider', + const guardianFactorsProvidersAuth0RestClient = new Auth0RestClient( + `${options.baseUrl}/guardian/factors/:name/providers/:provider`, clientOptions, options.tokenProvider ); @@ -122,8 +122,8 @@ var GuardianManager = function(options) { * * @type {external:RestClient} */ - var guardianPoliciesAuth0RestClient = new Auth0RestClient( - options.baseUrl + '/guardian/policies', + const guardianPoliciesAuth0RestClient = new Auth0RestClient( + `${options.baseUrl}/guardian/policies`, clientOptions, options.tokenProvider ); @@ -134,8 +134,8 @@ var GuardianManager = function(options) { * * @type {external:RestClient} */ - var guardianFactorsPhoneSelectedProviderAuth0RestClient = new Auth0RestClient( - options.baseUrl + '/guardian/factors/sms/selected-provider', + const guardianFactorsPhoneSelectedProviderAuth0RestClient = new Auth0RestClient( + `${options.baseUrl}/guardian/factors/sms/selected-provider`, clientOptions, options.tokenProvider ); @@ -149,8 +149,8 @@ var GuardianManager = function(options) { * * @type {external:RestClient} */ - var guardianFactorsPhoneMessageTypesAuth0RestClient = new Auth0RestClient( - options.baseUrl + '/guardian/factors/phone/message-types', + const guardianFactorsPhoneMessageTypesAuth0RestClient = new Auth0RestClient( + `${options.baseUrl}/guardian/factors/phone/message-types`, clientOptions, options.tokenProvider ); @@ -163,99 +163,83 @@ var GuardianManager = function(options) { /** * Get a single Guardian enrollment. * - * @method getGuardianEnrollment - * @memberOf module:management.GuardianManager.prototype - * + * @function getGuardianEnrollment + * @memberof module:management.GuardianManager.prototype * @example * management.guardian.getGuardianEnrollment({ id: ENROLLMENT_ID }, function (err, enrollment) { * console.log(enrollment); * }); - * - * @param {Object} data The user data object. - * @param {String} data.id The user id. + * @param {object} data The user data object. + * @param {string} data.id The user id. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(GuardianManager, 'getGuardianEnrollment', 'enrollments.get'); /** * Delete a Guardian enrollment. * - * @method deleteGuardianEnrollment - * @memberOf module:management.GuardianManager.prototype - * + * @function deleteGuardianEnrollment + * @memberof module:management.GuardianManager.prototype * @example * management.guardian.deleteGuardianEnrollment({ id: ENROLLMENT_ID }, function (err, enrollments) { * console.log(enrollments); * }); - * - * @param {Object} data The user data object. - * @param {String} data.id The user id. + * @param {object} data The user data object. + * @param {string} data.id The user id. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(GuardianManager, 'deleteGuardianEnrollment', 'enrollments.delete'); /** * Create a Guardian enrollment ticket. * - * @method createEnrollmentTicket - * @memberOf module:management.GuardianManager.prototype - * + * @function createEnrollmentTicket + * @memberof module:management.GuardianManager.prototype * @example * management.guardian.createEnrollmentTicket(function (err, ticket) { * console.log(ticket); * }); - * * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(GuardianManager, 'createEnrollmentTicket', 'tickets.create'); /** * Get a list of factors and statuses. * - * @method getFactors - * @memberOf module:management.GuardianManager.prototype - * + * @function getFactors + * @memberof module:management.GuardianManager.prototype * @example * management.guardian.getFactors(function (err, factors) { * console.log(factors.length); * }); - * * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(GuardianManager, 'getFactors', 'factors.getAll'); /** * Get Guardian factor configuration * - * @method getFactorSettings - * @memberOf module:management.GuardianManager.prototype - * + * @function getFactorSettings + * @memberof module:management.GuardianManager.prototype * @example * management.guardian.getFactorSettings({ name: 'webauthn-roaming' }, function (err, settings) { * console.log(settings); * }); - * - * @param {Object} params Factor parameters. + * @param {object} params Factor parameters. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(GuardianManager, 'getFactorSettings', 'factorSettings.get'); /** * Update Guardian factor configuration * - * @method updateFactorSettings - * @memberOf module:management.GuardianManager.prototype - * + * @function updateFactorSettings + * @memberof module:management.GuardianManager.prototype * @example * management.guardian.updateFactorSettings( * { name: 'webauthn-roaming' }, @@ -263,38 +247,32 @@ utils.wrapPropertyMethod(GuardianManager, 'getFactorSettings', 'factorSettings.g * function (err, settings) { * console.log(settings); * }); - * - * @param {Object} params Factor parameters. + * @param {object} params Factor parameters. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(GuardianManager, 'updateFactorSettings', 'factorSettings.update'); /** * Get Guardian factor provider configuration * - * @method getFactorProvider - * @memberOf module:management.GuardianManager.prototype - * + * @function getFactorProvider + * @memberof module:management.GuardianManager.prototype * @example * management.guardian.getFactorProvider({ name: 'sms', provider: 'twilio'}, function (err, provider) { * console.log(provider); * }); - * - * @param {Object} params Factor provider parameters. + * @param {object} params Factor provider parameters. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(GuardianManager, 'getFactorProvider', 'factorsProviders.get'); /** * Update Guardian's factor provider * - * @method updateFactorProvider - * @memberOf module:management.GuardianManager.prototype - * + * @function updateFactorProvider + * @memberof module:management.GuardianManager.prototype * @example * management.guardian.updateFactorProvider({ name: 'sms', provider: 'twilio' }, { * messaging_service_sid: 'XXXXXXXXXXXXXX', @@ -303,39 +281,33 @@ utils.wrapPropertyMethod(GuardianManager, 'getFactorProvider', 'factorsProviders * }, function (err, provider) { * console.log(provider); * }); - * - * @param {Object} params Factor provider parameters. - * @param {Object} data Updated Factor provider data. + * @param {object} params Factor provider parameters. + * @param {object} data Updated Factor provider data. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(GuardianManager, 'updateFactorProvider', 'factorsProviders.update'); /** * Get Guardian enrollment and verification factor templates * - * @method getFactorTemplates - * @memberOf module:management.GuardianManager.prototype - * + * @function getFactorTemplates + * @memberof module:management.GuardianManager.prototype * @example * management.guardian.getFactorTemplates({ name: 'sms' }, function (err, templates) { * console.log(templates); * }); - * - * @param {Object} params Factor parameters. + * @param {object} params Factor parameters. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(GuardianManager, 'getFactorTemplates', 'factorsTemplates.get'); /** * Update Guardian enrollment and verification factor templates * - * @method updateFactorTemplates - * @memberOf module:management.GuardianManager.prototype - * + * @function updateFactorTemplates + * @memberof module:management.GuardianManager.prototype * @example * management.guardian.updateFactorProvider({ name: 'sms' }, { * enrollment_message: "{{code}} is your verification code for {{tenant.friendly_name}}. Please enter this code to verify your enrollment.", @@ -343,88 +315,74 @@ utils.wrapPropertyMethod(GuardianManager, 'getFactorTemplates', 'factorsTemplate * }, function (err, templates) { * console.log(templates); * }); - * - * @param {Object} params Factor parameters. - * @param {Object} data Updated factor templates data. + * @param {object} params Factor parameters. + * @param {object} data Updated factor templates data. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(GuardianManager, 'updateFactorTemplates', 'factorsTemplates.update'); /** * Update Guardian Factor * - * @method updateFactor - * @memberOf module:management.GuardianManager.prototype - * + * @function updateFactor + * @memberof module:management.GuardianManager.prototype * @example * management.guardian.updateFactor({ name: 'sms' }, { * enabled: true * }, function (err, factor) { * console.log(factor); * }); - * - * @param {Object} params Factor parameters. - * @param {Object} data Updated factor data. + * @param {object} params Factor parameters. + * @param {object} data Updated factor data. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(GuardianManager, 'updateFactor', 'factors.update'); /** * Get enabled Guardian policies * - * @method getPolicies - * @memberOf module:management.GuardianManager.prototype - * + * @function getPolicies + * @memberof module:management.GuardianManager.prototype * @example * management.guardian.getPolicies(function (err, policies) { * console.log(policies); * }); - * * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(GuardianManager, 'getPolicies', 'policies.get'); /** * Update enabled Guardian policies * - * @method updatePolicies - * @memberOf module:management.GuardianManager.prototype - * + * @function updatePolicies + * @memberof module:management.GuardianManager.prototype * @example * management.guardian.updatePolicies({}, [ * 'all-applications' * ], function (err, policies) { * console.log(policies); * }); - * - * @param {Object} params Parameters. - * @param {String[]} data Policies to enable. Empty array disables all policies. + * @param {object} params Parameters. + * @param {string[]} data Policies to enable. Empty array disables all policies. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(GuardianManager, 'updatePolicies', 'policies.update'); /** * Get the Guardian phone factor's selected provider * - * @method getPhoneFactorSelectedProvider - * @memberOf module:management.GuardianManager.prototype - * + * @function getPhoneFactorSelectedProvider + * @memberof module:management.GuardianManager.prototype * @example * management.guardian.getPhoneFactorSelectedProvider(function (err, selectedProvider) { * console.log(selectedProvider); * }); - * * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod( GuardianManager, @@ -435,22 +393,19 @@ utils.wrapPropertyMethod( /** * Update the Guardian phone factor's selected provider * - * @method updatePhoneFactorSelectedProvider - * @memberOf module:management.GuardianManager.prototype - * + * @function updatePhoneFactorSelectedProvider + * @memberof module:management.GuardianManager.prototype * @example * management.guardian.updatePhoneFactorSelectedProvider({}, { * provider: 'twilio' * }, function (err, factor) { * console.log(factor); * }); - * - * @param {Object} params Parameters. - * @param {Object} data Updated selected provider data. - * @param {String} data.provider Name of the selected provider + * @param {object} params Parameters. + * @param {object} data Updated selected provider data. + * @param {string} data.provider Name of the selected provider * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod( GuardianManager, @@ -461,17 +416,14 @@ utils.wrapPropertyMethod( /** * Get the Guardian phone factor's message types * - * @method getPhoneFactorMessageTypes - * @memberOf module:management.GuardianManager.prototype - * + * @function getPhoneFactorMessageTypes + * @memberof module:management.GuardianManager.prototype * @example * management.guardian.getPhoneFactorMessageTypes(function (err, messageTypes) { * console.log(messageTypes); * }); - * * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod( GuardianManager, @@ -482,22 +434,19 @@ utils.wrapPropertyMethod( /** * Update the Guardian phone factor's message types * - * @method updatePhoneFactorMessageTypes - * @memberOf module:management.GuardianManager.prototype - * + * @function updatePhoneFactorMessageTypes + * @memberof module:management.GuardianManager.prototype * @example * management.guardian.updatePhoneFactorMessageTypes({}, { * message_types: ['sms', 'voice'] * }, function (err, factor) { * console.log(factor); * }); - * - * @param {Object} params Parameters. - * @param {Object} data Updated selected provider data. - * @param {String[]} data.message_types Message types (only `"sms"` and `"voice"` are supported). + * @param {object} params Parameters. + * @param {object} data Updated selected provider data. + * @param {string[]} data.message_types Message types (only `"sms"` and `"voice"` are supported). * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod( GuardianManager, diff --git a/src/management/HooksManager.js b/src/management/HooksManager.js index 53276ac03..729acf894 100644 --- a/src/management/HooksManager.js +++ b/src/management/HooksManager.js @@ -1,10 +1,11 @@ -var ArgumentError = require('rest-facade').ArgumentError; -var utils = require('../utils'); -var Auth0RestClient = require('../Auth0RestClient'); -var RetryRestClient = require('../RetryRestClient'); +const { ArgumentError } = require('rest-facade'); +const utils = require('../utils'); +const Auth0RestClient = require('../Auth0RestClient'); +const RetryRestClient = require('../RetryRestClient'); /** * Simple facade for consuming a REST API endpoint. + * * @external RestClient * @see https://github.com/ngonzalvez/rest-facade */ @@ -13,15 +14,14 @@ var RetryRestClient = require('../RetryRestClient'); * @class HooksManager * The hooks manager class provides a simple abstraction for performing CRUD operations * on Auth0 HooksManagers. - * @constructor - * @memberOf module:management - * - * @param {Object} options The client options. - * @param {String} options.baseUrl The URL of the API. - * @param {Object} [options.headers] Headers to be included in all requests. - * @param {Object} [options.retry] Retry Policy Config + * @class + * @memberof module:management + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config */ -var HooksManager = function(options) { +const HooksManager = function (options) { if (options === null || typeof options !== 'object') { throw new ArgumentError('Must provide manager options'); } @@ -37,11 +37,11 @@ var HooksManager = function(options) { /** * Options object for the Rest Client instance. * - * @type {Object} + * @type {object} */ - var clientOptions = { + const clientOptions = { headers: options.headers, - query: { repeatParams: false } + query: { repeatParams: false }, }; /** @@ -50,15 +50,15 @@ var HooksManager = function(options) { * * @type {external:RestClient} */ - var auth0RestClient = new Auth0RestClient( - options.baseUrl + '/hooks/:id', + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/hooks/:id`, clientOptions, options.tokenProvider ); this.resource = new RetryRestClient(auth0RestClient, options.retry); - var hookSecretsClient = new Auth0RestClient( - options.baseUrl + '/hooks/:id/secrets', + const hookSecretsClient = new Auth0RestClient( + `${options.baseUrl}/hooks/:id/secrets`, clientOptions, options.tokenProvider ); @@ -68,9 +68,8 @@ var HooksManager = function(options) { /** * Create a new hook. * - * @method create - * @memberOf module:management.HooksManager.prototype - * + * @function create + * @memberof module:management.HooksManager.prototype * @example * management.hooks.create(data, function (err) { * if (err) { @@ -79,20 +78,17 @@ var HooksManager = function(options) { * * // Hook created. * }); - * - * @param {Object} data Hook data object. + * @param {object} data Hook data object. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(HooksManager, 'create', 'resource.create'); /** * Get all hooks. * - * @method getAll - * @memberOf module:management.HooksManager.prototype - * + * @function getAll + * @memberof module:management.HooksManager.prototype * @example * This method takes an optional object as first argument that may be used to * specify pagination settings. If pagination options are not present, @@ -108,22 +104,19 @@ utils.wrapPropertyMethod(HooksManager, 'create', 'resource.create'); * management.hooks.getAll(params, function (err, hooks) { * console.log(hooks.length); * }); - * - * @param {Object} [params] Hooks parameters. - * @param {Number} [params.per_page] Number of results per page. - * @param {Number} [params.page] Page number, zero indexed. + * @param {object} [params] Hooks parameters. + * @param {number} [params.per_page] Number of results per page. + * @param {number} [params.page] Page number, zero indexed. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(HooksManager, 'getAll', 'resource.getAll'); /** * Get an Auth0 hook. * - * @method get - * @memberOf module:management.HooksManager.prototype - * + * @function get + * @memberof module:management.HooksManager.prototype * @example * management.hooks.get({ id: HOOK_ID }, function (err, hook) { * if (err) { @@ -132,21 +125,18 @@ utils.wrapPropertyMethod(HooksManager, 'getAll', 'resource.getAll'); * * console.log(hook); * }); - * - * @param {Object} params Hook parameters. - * @param {String} params.id Hook ID. + * @param {object} params Hook parameters. + * @param {string} params.id Hook ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(HooksManager, 'get', 'resource.get'); /** * Update an existing hook. * - * @method update - * @memberOf module:management.HooksManager.prototype - * + * @function update + * @memberof module:management.HooksManager.prototype * @example * var data = { name: 'New name' }; * var params = { id: HOOK_ID }; @@ -168,22 +158,19 @@ utils.wrapPropertyMethod(HooksManager, 'get', 'resource.get'); * * console.log(hook.name); // 'New name' * }); - * - * @param {Object} params Hook parameters. - * @param {String} params.id Hook ID. - * @param {Object} data Updated hook data. + * @param {object} params Hook parameters. + * @param {string} params.id Hook ID. + * @param {object} data Updated hook data. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(HooksManager, 'update', 'resource.patch'); /** * Delete an existing hook. * - * @method delete - * @memberOf module:management.HooksManager.prototype - * + * @function delete + * @memberof module:management.HooksManager.prototype * @example * management.hooks.delete({ id: HOOK_ID }, function (err) { * if (err) { @@ -192,22 +179,20 @@ utils.wrapPropertyMethod(HooksManager, 'update', 'resource.patch'); * * // Hook deleted. * }); - * - * @param {Object} params Hook parameters. - * @param {String} params.id Hook ID. + * @param {object} params Hook parameters. + * @param {string} params.id Hook ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(HooksManager, 'delete', 'resource.delete'); /** * Get Hook secrets * - * @method getSecrets - * @memberOf module:management.HooksManager.prototype - * + * @function getSecrets + * @memberof module:management.HooksManager.prototype * @example + * @param callback * var params = {id : 'HOOK_ID'} * @example * This method takes a first argument as the hookId and returns the secrets for the hook. The secret values will be hidden. @@ -216,23 +201,20 @@ utils.wrapPropertyMethod(HooksManager, 'delete', 'resource.delete'); * management.hooks.getSecrets( {id : 'HOOK_ID'}, function (err, secrets) { * console.log(secrets); * }); - * - * @param {Object} params Hook parameters. - * @param {String} params.id ID of the Hook. + * @param {object} params Hook parameters. + * @param {string} params.id ID of the Hook. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -HooksManager.prototype.getSecrets = function(params, callback) { +HooksManager.prototype.getSecrets = function (params, callback) { return this.secrets.getAll(params, callback); }; /** * Add secrets in a hook * - * @method addSecrets - * @memberOf module:management.HooksManager.prototype - * + * @function addSecrets + * @memberof module:management.HooksManager.prototype * @example * var params = { id :'HOOK_ID'}; * var data = { "DB_USER" : "jdoe", "DB_PASS": "password123!"}; @@ -244,16 +226,14 @@ HooksManager.prototype.getSecrets = function(params, callback) { * * // secrets added. * }); - * - * @param {Object} params Hook parameters. - * @param {String} params.id ID of the Hook. - * @param {Object} data object containing secrets as key/value pairs + * @param {object} params Hook parameters. + * @param {string} params.id ID of the Hook. + * @param {object} data object containing secrets as key/value pairs * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -HooksManager.prototype.addSecrets = function(params, data, cb) { +HooksManager.prototype.addSecrets = function (params, data, cb) { params = params || {}; data = data || {}; @@ -276,9 +256,8 @@ HooksManager.prototype.addSecrets = function(params, data, cb) { /** * Update secrets in a hook * - * @method updateSecrets - * @memberOf module:management.HooksManager.prototype - * + * @function updateSecrets + * @memberof module:management.HooksManager.prototype * @example * var params = { id :'HOOK_ID'}; * var data = { "DB_USER" : "jdoe", "DB_PASS": "password123!"}; @@ -290,16 +269,14 @@ HooksManager.prototype.addSecrets = function(params, data, cb) { * * // secrets updated. * }); - * - * @param {Object} params Hook parameters. - * @param {String} params.id ID of the Hook. - * @param {Object} data object containing secrets as key/value pairs + * @param {object} params Hook parameters. + * @param {string} params.id ID of the Hook. + * @param {object} data object containing secrets as key/value pairs * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -HooksManager.prototype.updateSecrets = function(params, data, cb) { +HooksManager.prototype.updateSecrets = function (params, data, cb) { params = params || {}; data = data || {}; @@ -322,9 +299,8 @@ HooksManager.prototype.updateSecrets = function(params, data, cb) { /** * Remove secrets from a hook * - * @method removeSecrets - * @memberOf module:management.HooksManager.prototype - * + * @function removeSecrets + * @memberof module:management.HooksManager.prototype * @example * var params = { id :'HOOK_ID'}; * var data =["DB_PASS"]; @@ -336,16 +312,14 @@ HooksManager.prototype.updateSecrets = function(params, data, cb) { * * // secrets added. * }); - * - * @param {Object} params Hook parameters. - * @param {String} params.id ID of the Hook. - * @param {Object} data Array of secret names + * @param {object} params Hook parameters. + * @param {string} params.id ID of the Hook. + * @param {object} data Array of secret names * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -HooksManager.prototype.removeSecrets = function(params, data, cb) { +HooksManager.prototype.removeSecrets = function (params, data, cb) { params = params || {}; data = data || {}; diff --git a/src/management/JobsManager.js b/src/management/JobsManager.js index cca9c74c5..8a8f52d07 100644 --- a/src/management/JobsManager.js +++ b/src/management/JobsManager.js @@ -1,14 +1,14 @@ -var axios = require('axios'); -var extend = require('util')._extend; -var FormData = require('form-data'); -var fs = require('fs'); +const axios = require('axios'); +const FormData = require('form-data'); +const fs = require('fs'); -var ArgumentError = require('rest-facade').ArgumentError; -var Auth0RestClient = require('../Auth0RestClient'); -var RetryRestClient = require('../RetryRestClient'); +const { ArgumentError } = require('rest-facade'); +const Auth0RestClient = require('../Auth0RestClient'); +const RetryRestClient = require('../RetryRestClient'); /** * Simple facade for consuming a REST API endpoint. + * * @external RestClient * @see https://github.com/ngonzalvez/rest-facade */ @@ -16,15 +16,14 @@ var RetryRestClient = require('../RetryRestClient'); /** * @class * Abstract the creation as well as the retrieval of async jobs. - * @constructor - * @memberOf module:management - * - * @param {Object} options The client options. - * @param {String} options.baseUrl The URL of the API. - * @param {Object} [options.headers] Headers to be included in all requests. - * @param {Object} [options.retry] Retry Policy Config + * @class + * @memberof module:management + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config */ -var JobsManager = function(options) { +const JobsManager = function (options) { if (options === null || typeof options !== 'object') { throw new ArgumentError('Must provide client options'); } @@ -37,10 +36,10 @@ var JobsManager = function(options) { throw new ArgumentError('The provided base URL is invalid'); } - var clientOptions = { + const clientOptions = { errorFormatter: { message: 'message', name: 'error' }, headers: options.headers, - query: { repeatParams: false } + query: { repeatParams: false }, }; this.options = options; @@ -51,8 +50,8 @@ var JobsManager = function(options) { * * @type {external:RestClient} */ - var auth0RestClient = new Auth0RestClient( - options.baseUrl + '/jobs/:id', + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/jobs/:id`, clientOptions, options.tokenProvider ); @@ -64,8 +63,8 @@ var JobsManager = function(options) { * * @type {external:RestClient} */ - var jobErrorsRestClient = new Auth0RestClient( - options.baseUrl + '/jobs/:id/errors', + const jobErrorsRestClient = new Auth0RestClient( + `${options.baseUrl}/jobs/:id/errors`, clientOptions, options.tokenProvider ); @@ -78,7 +77,7 @@ var JobsManager = function(options) { * @type {external:RestClient} */ const usersExportsRestClient = new Auth0RestClient( - options.baseUrl + '/jobs/users-exports', + `${options.baseUrl}/jobs/users-exports`, clientOptions, options.tokenProvider ); @@ -88,9 +87,8 @@ var JobsManager = function(options) { /** * Get a job by its ID. * - * @method get - * @memberOf module:management.JobsManager.prototype - * + * @function get + * @memberof module:management.JobsManager.prototype * @example * var params = { * id: '{JOB_ID}' @@ -104,14 +102,12 @@ var JobsManager = function(options) { * // Retrieved job. * console.log(job); * }); - * - * @param {Object} params Job parameters. - * @param {String} params.id Job ID. + * @param {object} params Job parameters. + * @param {string} params.id Job ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -JobsManager.prototype.get = function(params, cb) { +JobsManager.prototype.get = function (params, cb) { if (!params.id || typeof params.id !== 'string') { throw new ArgumentError('The id parameter must be a valid job id'); } @@ -124,39 +120,39 @@ JobsManager.prototype.get = function(params, cb) { return this.jobs.get(params); }; -JobsManager.prototype._importUsers = function(data, cb) { - var options = this.options; - var url = options.baseUrl + '/jobs/users-imports'; - var userData = data.users_json ? Buffer.from(data.users_json) : fs.createReadStream(data.users); - var userFilename = data.users_json ? 'users.json' : data.users; +JobsManager.prototype._importUsers = function (data, cb) { + const { options } = this; + const url = `${options.baseUrl}/jobs/users-imports`; + const userData = data.users_json ? Buffer.from(data.users_json) : fs.createReadStream(data.users); + const userFilename = data.users_json ? 'users.json' : data.users; - var form = new FormData(); + const form = new FormData(); form.append('users', userData, userFilename); form.append('connection_id', data.connection_id); form.append('upsert', data.upsert === true ? 'true' : 'false'); form.append('send_completion_email', data.send_completion_email === false ? 'false' : 'true'); - var headers = { ...options.headers, ...form.getHeaders() }; + const headers = { ...options.headers, ...form.getHeaders() }; headers['Content-Type'] = 'multipart/form-data'; - var promise = options.tokenProvider.getAccessToken().then(function(access_token) { - return axios + const promise = options.tokenProvider.getAccessToken().then((access_token) => + axios .post(url, form, { headers: { ...headers, Authorization: `Bearer ${access_token}` } }) - .catch(function(err) { + .catch((err) => { if (!err.response) { return Promise.reject(err); } - var res = err.response; + const res = err.response; // `superagent` uses the error parameter in callback on http errors. // the following code is intended to keep that behaviour (https://github.com/visionmedia/superagent/blob/master/lib/node/response.js#L170) - var error = new Error('cannot POST' + ' ' + url + ' (' + res.status + ')'); + const error = new Error(`${'cannot POST' + ' '}${url} (${res.status})`); error.status = res.status; error.method = 'POST'; error.text = res.data.message || res.statusText || error.message; return Promise.reject(error); - }); - }); + }) + ); // Don't return a promise if a callback was given. if (cb && cb instanceof Function) { @@ -172,11 +168,10 @@ JobsManager.prototype._importUsers = function(data, cb) { * Given a path to a file and a connection id, create a new job that imports the * users contained in the file or JSON string and associate them with the given * connection. - * @deprecated since version 2.26. It will be deleted in version 3.0. - * - * @method importUsers - * @memberOf module:management.JobsManager.prototype * + * @deprecated since version 2.26. It will be deleted in version 3.0. + * @function importUsers + * @memberof module:management.JobsManager.prototype * @example * var params = { * connection_id: '{CONNECTION_ID}', @@ -188,18 +183,16 @@ JobsManager.prototype._importUsers = function(data, cb) { * // Handle error. * } * }); - * - * @param {Object} data Users import data. - * @param {String} data.connection_id connection_id of the connection to which users will be imported. - * @param {String} [data.users] Path to the users data file. Either users or users_json is mandatory. - * @param {String} [data.users_json] JSON data for the users. - * @param {Boolean} [data.upsert] Whether to update users if they already exist (true) or to ignore them (false). - * @param {Boolean} [data.send_completion_email] Whether to send a completion email to all tenant owners when the job is finished (true) or not (false). + * @param {object} data Users import data. + * @param {string} data.connection_id connection_id of the connection to which users will be imported. + * @param {string} [data.users] Path to the users data file. Either users or users_json is mandatory. + * @param {string} [data.users_json] JSON data for the users. + * @param {boolean} [data.upsert] Whether to update users if they already exist (true) or to ignore them (false). + * @param {boolean} [data.send_completion_email] Whether to send a completion email to all tenant owners when the job is finished (true) or not (false). * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -JobsManager.prototype.importUsers = function(data, cb) { +JobsManager.prototype.importUsers = function (data, cb) { console.warn( '"importUsers" has been deprecated as it was inconsistent with the API. Please, use "importUsersJob" which returns the response data directly.' ); @@ -211,9 +204,8 @@ JobsManager.prototype.importUsers = function(data, cb) { * users contained in the file or JSON string and associate them with the given * connection. * - * @method importUsersJob - * @memberOf module:management.JobsManager.prototype - * + * @function importUsersJob + * @memberof module:management.JobsManager.prototype * @example * var params = { * connection_id: '{CONNECTION_ID}', @@ -225,19 +217,17 @@ JobsManager.prototype.importUsers = function(data, cb) { * // Handle error. * } * }); - * - * @param {Object} data Users import data. - * @param {String} data.connection_id connection_id of the connection to which users will be imported. - * @param {String} [data.users] Path to the users data file. Either users or users_json is mandatory. - * @param {String} [data.users_json] JSON data for the users. - * @param {Boolean} [data.upsert] Whether to update users if they already exist (true) or to ignore them (false). - * @param {Boolean} [data.send_completion_email] Whether to send a completion email to all tenant owners when the job is finished (true) or not (false). + * @param {object} data Users import data. + * @param {string} data.connection_id connection_id of the connection to which users will be imported. + * @param {string} [data.users] Path to the users data file. Either users or users_json is mandatory. + * @param {string} [data.users_json] JSON data for the users. + * @param {boolean} [data.upsert] Whether to update users if they already exist (true) or to ignore them (false). + * @param {boolean} [data.send_completion_email] Whether to send a completion email to all tenant owners when the job is finished (true) or not (false). * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -JobsManager.prototype.importUsersJob = function(data, cb) { - var promise = this._importUsers(data).then(response => response.data); +JobsManager.prototype.importUsersJob = function (data, cb) { + const promise = this._importUsers(data).then((response) => response.data); // Don't return a promise if a callback was given. if (cb && cb instanceof Function) { @@ -252,9 +242,8 @@ JobsManager.prototype.importUsersJob = function(data, cb) { /** * Export all users to a file using a long running job. * - * @method exportUsers - * @memberOf module:management.JobsManager.prototype - * + * @function exportUsers + * @memberof module:management.JobsManager.prototype * @example * var data = { * connection_id: 'con_0000000000000001', @@ -288,17 +277,15 @@ JobsManager.prototype.importUsersJob = function(data, cb) { * // Retrieved job. * console.log(results); * }); - * - * @param {Object} data Users export data. - * @param {String} [data.connection_id] The connection id of the connection from which users will be exported - * @param {String} [data.format] The format of the file. Valid values are: "json" and "csv". - * @param {Number} [data.limit] Limit the number of records. - * @param {Object[]} [data.fields] A list of fields to be included in the CSV. If omitted, a set of predefined fields will be exported. + * @param {object} data Users export data. + * @param {string} [data.connection_id] The connection id of the connection from which users will be exported + * @param {string} [data.format] The format of the file. Valid values are: "json" and "csv". + * @param {number} [data.limit] Limit the number of records. + * @param {object[]} [data.fields] A list of fields to be included in the CSV. If omitted, a set of predefined fields will be exported. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -JobsManager.prototype.exportUsers = function(data, cb) { +JobsManager.prototype.exportUsers = function (data, cb) { if (cb && cb instanceof Function) { return this.usersExports.create(data, cb); } @@ -309,9 +296,8 @@ JobsManager.prototype.exportUsers = function(data, cb) { /** * Given a job ID, retrieve the failed/errored items * - * @method errors - * @memberOf module:management.JobsManager.prototype - * + * @function errors + * @memberof module:management.JobsManager.prototype * @example * var params = { * id: '{JOB_ID}' @@ -325,14 +311,12 @@ JobsManager.prototype.exportUsers = function(data, cb) { * // Retrieved job. * console.log(job); * }); - * - * @param {Object} params Job parameters. - * @param {String} params.id Job ID. + * @param {object} params Job parameters. + * @param {string} params.id Job ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -JobsManager.prototype.errors = function(params, cb) { +JobsManager.prototype.errors = function (params, cb) { if (!params.id || typeof params.id !== 'string') { throw new ArgumentError('The id parameter must be a valid job id'); } @@ -348,9 +332,8 @@ JobsManager.prototype.errors = function(params, cb) { /** * Send a verification email to a user. * - * @method verifyEmail - * @memberOf module:management.JobsManager.prototype - * + * @function verifyEmail + * @memberof module:management.JobsManager.prototype * @example * var params = { * user_id: '{USER_ID}' @@ -361,19 +344,17 @@ JobsManager.prototype.errors = function(params, cb) { * // Handle error. * } * }); - * - * @param {Object} data User data object. - * @param {String} data.user_id ID of the user to be verified. - * @param {String} [data.organization_id] Organization ID - * @param {String} [data.client_id] client_id of the client (application). If no value provided, the global Client ID will be used. - * @param {Object} [data.identity] Used to verify secondary, federated, and passwordless-email identities. - * @param {String} data.identity.user_id user_id of the identity. - * @param {String} data.identity.provider provider of the identity. + * @param {object} data User data object. + * @param {string} data.user_id ID of the user to be verified. + * @param {string} [data.organization_id] Organization ID + * @param {string} [data.client_id] client_id of the client (application). If no value provided, the global Client ID will be used. + * @param {object} [data.identity] Used to verify secondary, federated, and passwordless-email identities. + * @param {string} data.identity.user_id user_id of the identity. + * @param {string} data.identity.provider provider of the identity. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -JobsManager.prototype.verifyEmail = function(data, cb) { +JobsManager.prototype.verifyEmail = function (data, cb) { if (!data.user_id || typeof data.user_id !== 'string') { throw new ArgumentError('Must specify a user ID'); } diff --git a/src/management/LogStreamsManager.js b/src/management/LogStreamsManager.js index 43cae1f4c..c242ec6c4 100644 --- a/src/management/LogStreamsManager.js +++ b/src/management/LogStreamsManager.js @@ -1,21 +1,20 @@ -var ArgumentError = require('rest-facade').ArgumentError; -var utils = require('../utils'); -var Auth0RestClient = require('../Auth0RestClient'); -var RetryRestClient = require('../RetryRestClient'); +const { ArgumentError } = require('rest-facade'); +const utils = require('../utils'); +const Auth0RestClient = require('../Auth0RestClient'); +const RetryRestClient = require('../RetryRestClient'); /** * @class LogStreamsManager * The logStreams class provides a simple abstraction for performing CRUD operations * on Auth0 Log Streams. - * @constructor - * @memberOf module:management - * - * @param {Object} options The client options. - * @param {String} options.baseUrl The URL of the API. - * @param {Object} [options.headers] Headers to be included in all requests. - * @param {Object} [options.retry] Retry Policy Config + * @class + * @memberof module:management + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config */ -var LogStreamsManager = function(options) { +const LogStreamsManager = function (options) { if (options === null || typeof options !== 'object') { throw new ArgumentError('Must provide client options'); } @@ -31,11 +30,11 @@ var LogStreamsManager = function(options) { /** * Options object for the Rest Client instance. * - * @type {Object} + * @type {object} */ - var clientOptions = { + const clientOptions = { headers: options.headers, - query: { repeatParams: false } + query: { repeatParams: false }, }; /** @@ -45,8 +44,8 @@ var LogStreamsManager = function(options) { * * @type {external:RestClient} */ - var auth0RestClient = new Auth0RestClient( - options.baseUrl + '/log-streams/:id ', + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/log-streams/:id `, clientOptions, options.tokenProvider ); @@ -56,27 +55,23 @@ var LogStreamsManager = function(options) { /** * Get all Log Streams. * - * @method getAll - * @memberOf module:management.LogStreamsManager.prototype - * + * @function getAll + * @memberof module:management.LogStreamsManager.prototype * @example * * management.logStreams.getAll(function (err, logStreams) { * console.log(logStreams.length); * }); - * * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(LogStreamsManager, 'getAll', 'resource.getAll'); /** * Get an Auth0 Log Streams. * - * @method get - * @memberOf module:management.LogStreamsManager.prototype - * + * @function get + * @memberof module:management.LogStreamsManager.prototype * @example * management.logStreams.get({ id: LOG_STREAM_ID }, function (err, logStream) { * if (err) { @@ -85,21 +80,18 @@ utils.wrapPropertyMethod(LogStreamsManager, 'getAll', 'resource.getAll'); * * console.log(logStream); * }); - * - * @param {Object} params Log Stream parameters. - * @param {String} params.id Log Stream ID. + * @param {object} params Log Stream parameters. + * @param {string} params.id Log Stream ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(LogStreamsManager, 'get', 'resource.get'); /** * Create an Auth0 Log Stream. * - * @method create - * @memberOf module:management.LogStreamsManager.prototype - * + * @function create + * @memberof module:management.LogStreamsManager.prototype * @example * management.logStreams.create(data, function (err, log) { * if (err) { @@ -108,20 +100,17 @@ utils.wrapPropertyMethod(LogStreamsManager, 'get', 'resource.get'); * * console.log(log); * }); - * - * @param {Object} data Log Stream data. + * @param {object} data Log Stream data. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(LogStreamsManager, 'create', 'resource.create'); /** * Update an Auth0 Log Streams. * - * @method update - * @memberOf module:management.LogStreamsManager.prototype - * + * @function update + * @memberof module:management.LogStreamsManager.prototype * @example * var data = { name: 'New name' }; * var params = { id: LOG_STREAM_ID }; @@ -143,22 +132,19 @@ utils.wrapPropertyMethod(LogStreamsManager, 'create', 'resource.create'); * * console.log(logStream.name); * }); - * - * @param {Object} params Log Stream parameters. - * @param {String} params.id Log Stream ID. - * @param {Object} data Updated Log Stream data. + * @param {object} params Log Stream parameters. + * @param {string} params.id Log Stream ID. + * @param {object} data Updated Log Stream data. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(LogStreamsManager, 'update', 'resource.patch'); /** * Delete an Auth0 Log Streams. * - * @method delete - * @memberOf module:management.LogStreamsManager.prototype - * + * @function delete + * @memberof module:management.LogStreamsManager.prototype * @example * management.logStreams.delete({ id: LOG_STREAM_ID }, function (err, log) { * if (err) { @@ -167,12 +153,10 @@ utils.wrapPropertyMethod(LogStreamsManager, 'update', 'resource.patch'); * * console.log(log); * }); - * - * @param {Object} params Log Stream parameters. - * @param {String} params.id Log Stream ID. + * @param {object} params Log Stream parameters. + * @param {string} params.id Log Stream ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(LogStreamsManager, 'delete', 'resource.delete'); diff --git a/src/management/LogsManager.js b/src/management/LogsManager.js index 85b1e2186..209fbc384 100644 --- a/src/management/LogsManager.js +++ b/src/management/LogsManager.js @@ -1,20 +1,19 @@ -var ArgumentError = require('rest-facade').ArgumentError; -var utils = require('../utils'); -var Auth0RestClient = require('../Auth0RestClient'); -var RetryRestClient = require('../RetryRestClient'); +const { ArgumentError } = require('rest-facade'); +const utils = require('../utils'); +const Auth0RestClient = require('../Auth0RestClient'); +const RetryRestClient = require('../RetryRestClient'); /** * @class LogsManager * Represents the relationship between Auth0 and an Identity provider. - * @constructor - * @memberOf module:management - * - * @param {Object} options The client options. - * @param {String} options.baseUrl The URL of the API. - * @param {Object} [options.headers] Headers to be included in all requests. - * @param {Object} [options.retry] Retry Policy Config + * @class + * @memberof module:management + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config */ -var LogsManager = function(options) { +const LogsManager = function (options) { if (options === null || typeof options !== 'object') { throw new ArgumentError('Must provide client options'); } @@ -30,11 +29,11 @@ var LogsManager = function(options) { /** * Options object for the Rest Client instance. * - * @type {Object} + * @type {object} */ - var clientOptions = { + const clientOptions = { headers: options.headers, - query: { repeatParams: false } + query: { repeatParams: false }, }; /** @@ -44,8 +43,8 @@ var LogsManager = function(options) { * * @type {external:RestClient} */ - var auth0RestClient = new Auth0RestClient( - options.baseUrl + '/logs/:id ', + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/logs/:id `, clientOptions, options.tokenProvider ); @@ -55,9 +54,8 @@ var LogsManager = function(options) { /** * Get all logs. * - * @method getAll - * @memberOf module:management.LogsManager.prototype - * + * @function getAll + * @memberof module:management.LogsManager.prototype * @example * This method takes an optional object as first argument that may be used to * specify pagination settings and the search query. If pagination options are @@ -73,29 +71,26 @@ var LogsManager = function(options) { * management.logs.getAll(params, function (err, logs) { * console.log(logs.length); * }); - * - * @param {Object} [params] Logs params. - * @param {String} [params.q] Search Criteria using Query String Syntax - * @param {Number} [params.page] Page number. Zero based - * @param {Number} [params.per_page] The amount of entries per page - * @param {String} [params.sort] The field to use for sorting. - * @param {String} [params.fields] A comma separated list of fields to include or exclude - * @param {Boolean} [params.include_fields] true if the fields specified are to be included in the result, false otherwise. - * @param {Boolean} [params.include_totals] true if a query summary must be included in the result, false otherwise. Default false - * @param {String} [params.from] For checkpoint pagination, log event Id from which to start selection from. - * @param {Number} [params.take] When using the `from` parameter, the number of entries to retrieve. Default 50, max 100. + * @param {object} [params] Logs params. + * @param {string} [params.q] Search Criteria using Query String Syntax + * @param {number} [params.page] Page number. Zero based + * @param {number} [params.per_page] The amount of entries per page + * @param {string} [params.sort] The field to use for sorting. + * @param {string} [params.fields] A comma separated list of fields to include or exclude + * @param {boolean} [params.include_fields] true if the fields specified are to be included in the result, false otherwise. + * @param {boolean} [params.include_totals] true if a query summary must be included in the result, false otherwise. Default false + * @param {string} [params.from] For checkpoint pagination, log event Id from which to start selection from. + * @param {number} [params.take] When using the `from` parameter, the number of entries to retrieve. Default 50, max 100. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(LogsManager, 'getAll', 'resource.getAll'); /** * Get an Auth0 log. * - * @method get - * @memberOf module:management.LogsManager.prototype - * + * @function get + * @memberof module:management.LogsManager.prototype * @example * management.logs.get({ id: EVENT_ID }, function (err, log) { * if (err) { @@ -104,12 +99,10 @@ utils.wrapPropertyMethod(LogsManager, 'getAll', 'resource.getAll'); * * console.log(log); * }); - * - * @param {Object} params Log parameters. - * @param {String} params.id Log ID. + * @param {object} params Log parameters. + * @param {string} params.id Log ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(LogsManager, 'get', 'resource.get'); diff --git a/src/management/ManagementTokenProvider.js b/src/management/ManagementTokenProvider.js index 85081fcad..e939f5285 100644 --- a/src/management/ManagementTokenProvider.js +++ b/src/management/ManagementTokenProvider.js @@ -1,33 +1,31 @@ -var ArgumentError = require('rest-facade').ArgumentError; -var AuthenticationClient = require('../auth'); -var memoizer = require('lru-memoizer'); -var es6Promisify = require('es6-promisify'); +const { ArgumentError } = require('rest-facade'); +const AuthenticationClient = require('../auth'); +const memoizer = require('lru-memoizer'); +const es6Promisify = require('es6-promisify'); -var DEFAULT_OPTIONS = { enableCache: true }; +const DEFAULT_OPTIONS = { enableCache: true }; /** * @class ManagementTokenProvider * Auth0 Management API Token Provider. - * @constructor - * @memberOf module:management - * - * @param {Object} options Options for the ManagementTokenProvider. - * @param {String} options.domain ManagementClient server domain. - * @param {String} options.clientId Non Interactive Client Id. - * @param {String} options.clientSecret Non Interactive Client Secret. - * @param {String} options.scope Non Interactive Client Scope. - * @param {String} options.audience Audience of the Management API. - * @param {Boolean} [options.enableCache=true] Enabled or Disable Cache - * @param {Number} [options.cacheTTLInSeconds] By default the `expires_in` value will be used to determine the cached time of the token, this can be overridden. - * @param {Object} [options.headers] Additional headers that will be added to the outgoing requests. - * + * @class + * @memberof module:management + * @param {object} options Options for the ManagementTokenProvider. + * @param {string} options.domain ManagementClient server domain. + * @param {string} options.clientId Non Interactive Client Id. + * @param {string} options.clientSecret Non Interactive Client Secret. + * @param {string} options.scope Non Interactive Client Scope. + * @param {string} options.audience Audience of the Management API. + * @param {boolean} [options.enableCache=true] Enabled or Disable Cache + * @param {number} [options.cacheTTLInSeconds] By default the `expires_in` value will be used to determine the cached time of the token, this can be overridden. + * @param {object} [options.headers] Additional headers that will be added to the outgoing requests. */ -var ManagementTokenProvider = function(options) { +const ManagementTokenProvider = function (options) { if (!options || typeof options !== 'object') { throw new ArgumentError('Options must be an object'); } - var params = Object.assign({}, DEFAULT_OPTIONS, options); + const params = Object.assign({}, DEFAULT_OPTIONS, options); if (!params.domain || params.domain.length === 0) { throw new ArgumentError('Must provide a domain'); @@ -64,33 +62,33 @@ var ManagementTokenProvider = function(options) { } this.options = params; - var authenticationClientOptions = { + const authenticationClientOptions = { domain: this.options.domain, clientId: this.options.clientId, clientSecret: this.options.clientSecret, telemetry: this.options.telemetry, clientInfo: this.options.clientInfo, - headers: this.options.headers + headers: this.options.headers, }; this.authenticationClient = new AuthenticationClient(authenticationClientOptions); - var self = this; + const self = this; this.getCachedAccessToken = es6Promisify.promisify( memoizer({ - load: function(options, callback) { + load(options, callback) { self .clientCredentialsGrant(options.domain, options.scope, options.audience) - .then(function(data) { + .then((data) => { callback(null, data); }) - .catch(function(err) { + .catch((err) => { callback(err); }); }, - hash: function(options) { - return options.domain + '-' + options.clientId + '-' + options.scope; + hash(options) { + return `${options.domain}-${options.clientId}-${options.scope}`; }, - itemMaxAge: function(options, data) { + itemMaxAge(options, data) { if (options.cacheTTLInSeconds) { return options.cacheTTLInSeconds * 1000; } @@ -104,7 +102,7 @@ var ManagementTokenProvider = function(options) { } return 60 * 60 * 1000; //1h }, - max: 100 + max: 100, }) ); }; @@ -112,31 +110,26 @@ var ManagementTokenProvider = function(options) { /** * Returns the access_token. * - * @method getAccessToken - * @memberOf module:management.ManagementTokenProvider.prototype - * - * @return {Promise} Promise returning an access_token. + * @function getAccessToken + * @memberof module:management.ManagementTokenProvider.prototype + * @returns {Promise} Promise returning an access_token. */ -ManagementTokenProvider.prototype.getAccessToken = function() { +ManagementTokenProvider.prototype.getAccessToken = function () { if (this.options.enableCache) { - return this.getCachedAccessToken(this.options).then(function(data) { - return data.access_token; - }); + return this.getCachedAccessToken(this.options).then((data) => data.access_token); } else { return this.clientCredentialsGrant( this.options.domain, this.options.scope, this.options.audience - ).then(function(data) { - return data.access_token; - }); + ).then((data) => data.access_token); } }; -ManagementTokenProvider.prototype.clientCredentialsGrant = function(domain, scope, audience) { +ManagementTokenProvider.prototype.clientCredentialsGrant = function (domain, scope, audience) { return this.authenticationClient.clientCredentialsGrant({ - audience: audience, - scope: scope + audience, + scope, }); }; diff --git a/src/management/MigrationsManager.js b/src/management/MigrationsManager.js index b051deecb..55d2d672d 100644 --- a/src/management/MigrationsManager.js +++ b/src/management/MigrationsManager.js @@ -1,19 +1,18 @@ -var ArgumentError = require('rest-facade').ArgumentError; -var Auth0RestClient = require('../Auth0RestClient'); -var RetryRestClient = require('../RetryRestClient'); +const { ArgumentError } = require('rest-facade'); +const Auth0RestClient = require('../Auth0RestClient'); +const RetryRestClient = require('../RetryRestClient'); /** * @class * Abstracts interaction with the migrations endpoint. - * @constructor - * @memberOf module:management - * - * @param {Object} options The client options. - * @param {String} options.baseUrl The URL of the API. - * @param {Object} [options.headers] Headers to be included in all requests. - * @param {Object} [options.retry] Retry Policy Config + * @class + * @memberof module:management + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config */ -var MigrationsManager = function(options) { +const MigrationsManager = function (options) { if (options === null || typeof options !== 'object') { throw new ArgumentError('Must provide manager options'); } @@ -26,10 +25,10 @@ var MigrationsManager = function(options) { throw new ArgumentError('The provided base URL is invalid'); } - var clientOptions = { + const clientOptions = { errorFormatter: { message: 'message', name: 'error' }, headers: options.headers, - query: { repeatParams: false } + query: { repeatParams: false }, }; /** @@ -37,8 +36,8 @@ var MigrationsManager = function(options) { * * @type {external:RestClient} */ - var auth0RestClient = new Auth0RestClient( - options.baseUrl + '/migrations', + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/migrations`, clientOptions, options.tokenProvider ); @@ -48,23 +47,20 @@ var MigrationsManager = function(options) { /** * Update the tenant migrations. * - * @method updateMigrations - * @memberOf module:management.MigrationsManager.prototype - * + * @function updateMigrations + * @memberof module:management.MigrationsManager.prototype * @example * management.migrations.updateMigrations(data, function (err) { * if (err) { * // Handle error. * } * }); - * - * @param {Object} data The tenant migrations to be updated - * @param {Object} data.flags The tenant migrations flags to be updated + * @param {object} data The tenant migrations to be updated + * @param {object} data.flags The tenant migrations flags to be updated * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -MigrationsManager.prototype.updateMigrations = function(data, cb) { +MigrationsManager.prototype.updateMigrations = function (data, cb) { if (cb && cb instanceof Function) { return this.resource.patch({}, data, cb); } @@ -76,9 +72,8 @@ MigrationsManager.prototype.updateMigrations = function(data, cb) { /** * Get the tenant migrations. * - * @method getMigrations - * @memberOf module:management.MigrationsManager.prototype - * + * @function getMigrations + * @memberof module:management.MigrationsManager.prototype * @example * management.migrations.getMigrations(function (err, migrations) { * if (err) { @@ -87,12 +82,11 @@ MigrationsManager.prototype.updateMigrations = function(data, cb) { * * console.log(migrations.flags); * }); - * + * @param data * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -MigrationsManager.prototype.getMigrations = function(data, cb) { +MigrationsManager.prototype.getMigrations = function (data, cb) { if (data instanceof Function && !cb) { cb = data; data = {}; diff --git a/src/management/OrganizationsManager.js b/src/management/OrganizationsManager.js index c54184eda..c18d2b550 100644 --- a/src/management/OrganizationsManager.js +++ b/src/management/OrganizationsManager.js @@ -1,10 +1,11 @@ -var ArgumentError = require('rest-facade').ArgumentError; -var utils = require('../utils'); -var Auth0RestClient = require('../Auth0RestClient'); -var RetryRestClient = require('../RetryRestClient'); +const { ArgumentError } = require('rest-facade'); +const utils = require('../utils'); +const Auth0RestClient = require('../Auth0RestClient'); +const RetryRestClient = require('../RetryRestClient'); /** * Simple facade for consuming a REST API endpoint. + * * @external RestClient * @see https://github.com/ngonzalvez/rest-facade */ @@ -13,15 +14,14 @@ var RetryRestClient = require('../RetryRestClient'); * @class OrganizationsManager * The organizations class provides a simple abstraction for performing CRUD operations * on Auth0 OrganizationsManager. - * @constructor - * @memberOf module:management - * - * @param {Object} options The client options. - * @param {String} options.baseUrl The URL of the API. - * @param {Object} [options.headers] Headers to be included in all requests. - * @param {Object} [options.retry] Retry Policy Config + * @class + * @memberof module:management + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config */ -var OrganizationsManager = function(options) { +const OrganizationsManager = function (options) { if (options === null || typeof options !== 'object') { throw new ArgumentError('Must provide manager options'); } @@ -37,11 +37,11 @@ var OrganizationsManager = function(options) { /** * Options object for the Rest Client instance. * - * @type {Object} + * @type {object} */ - var clientOptions = { + const clientOptions = { headers: options.headers, - query: { repeatParams: false } + query: { repeatParams: false }, }; /** @@ -50,43 +50,43 @@ var OrganizationsManager = function(options) { * * @type {external:RestClient} */ - var auth0RestClient = new Auth0RestClient( - options.baseUrl + '/organizations/:id', + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/organizations/:id`, clientOptions, options.tokenProvider ); this.organizations = new RetryRestClient(auth0RestClient, options.retry); - var connectionsInRoleClient = new Auth0RestClient( - options.baseUrl + '/organizations/:id/enabled_connections/:connection_id', + const connectionsInRoleClient = new Auth0RestClient( + `${options.baseUrl}/organizations/:id/enabled_connections/:connection_id`, clientOptions, options.tokenProvider ); this.connections = new RetryRestClient(connectionsInRoleClient, options.retry); - var membersClient = new Auth0RestClient( - options.baseUrl + '/organizations/:id/members/:user_id', + const membersClient = new Auth0RestClient( + `${options.baseUrl}/organizations/:id/members/:user_id`, clientOptions, options.tokenProvider ); this.members = new RetryRestClient(membersClient, options.retry); - var invitationClient = new Auth0RestClient( - options.baseUrl + '/organizations/:id/invitations/:invitation_id', + const invitationClient = new Auth0RestClient( + `${options.baseUrl}/organizations/:id/invitations/:invitation_id`, clientOptions, options.tokenProvider ); this.invitations = new RetryRestClient(invitationClient, options.retry); - var rolesClient = new Auth0RestClient( - options.baseUrl + '/organizations/:id/members/:user_id/roles', + const rolesClient = new Auth0RestClient( + `${options.baseUrl}/organizations/:id/members/:user_id/roles`, clientOptions, options.tokenProvider ); this.roles = new RetryRestClient(rolesClient, options.retry); - var organizationByNameClient = new Auth0RestClient( - options.baseUrl + '/organizations/name/:name', + const organizationByNameClient = new Auth0RestClient( + `${options.baseUrl}/organizations/name/:name`, clientOptions, options.tokenProvider ); @@ -96,9 +96,8 @@ var OrganizationsManager = function(options) { /** * Create a new organization. * - * @method create - * @memberOf module:management.OrganizationsManager.prototype - * + * @function create + * @memberof module:management.OrganizationsManager.prototype * @example * management.organizations.create(data, function (err) { * if (err) { @@ -107,20 +106,17 @@ var OrganizationsManager = function(options) { * * // Organization created. * }); - * - * @param {Object} data Organization data object. + * @param {object} data Organization data object. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(OrganizationsManager, 'create', 'organizations.create'); /** * Get all organizations. * - * @method getAll - * @memberOf module:management.OrganizationsManager.prototype - * + * @function getAll + * @memberof module:management.OrganizationsManager.prototype * @example * This method takes an optional object as first argument that may be used to * specify pagination settings. If pagination options are not present, @@ -136,24 +132,21 @@ utils.wrapPropertyMethod(OrganizationsManager, 'create', 'organizations.create') * management.organizations.getAll(params, function (err, organizations) { * console.log(organizations.length); * }); - * - * @param {Object} [params] Organizations parameters. - * @param {Number} [params.per_page] Number of results per page. - * @param {Number} [params.page] Page number, zero indexed. - * @param {String} [params.from] For checkpoint pagination, the Id from which to start selection from. - * @param {Number} [params.take] For checkpoint pagination, the number of entries to retrieve. Default 50. + * @param {object} [params] Organizations parameters. + * @param {number} [params.per_page] Number of results per page. + * @param {number} [params.page] Page number, zero indexed. + * @param {string} [params.from] For checkpoint pagination, the Id from which to start selection from. + * @param {number} [params.take] For checkpoint pagination, the number of entries to retrieve. Default 50. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(OrganizationsManager, 'getAll', 'organizations.getAll'); /** * Get an Auth0 organization. * - * @method getByID - * @memberOf module:management.OrganizationsManager.prototype - * + * @function getByID + * @memberof module:management.OrganizationsManager.prototype * @example * management.organizations.getByID({ id: ORGANIZATION_ID }, function (err, role) { * if (err) { @@ -162,21 +155,18 @@ utils.wrapPropertyMethod(OrganizationsManager, 'getAll', 'organizations.getAll') * * console.log(organization); * }); - * - * @param {Object} params Organization parameters. - * @param {String} params.id Organization ID. + * @param {object} params Organization parameters. + * @param {string} params.id Organization ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(OrganizationsManager, 'getByID', 'organizations.get'); /** * Get an Auth0 organization. * - * @method getByName - * @memberOf module:management.OrganizationsManager.prototype - * + * @function getByName + * @memberof module:management.OrganizationsManager.prototype * @example * management.organizations.getByName({ name: ORGANIZATION_NAME}, function (err, role) { * if (err) { @@ -185,21 +175,18 @@ utils.wrapPropertyMethod(OrganizationsManager, 'getByID', 'organizations.get'); * * console.log(organization); * }); - * - * @param {Object} params Organization parameters. - * @param {String} params.name Organization name. + * @param {object} params Organization parameters. + * @param {string} params.name Organization name. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(OrganizationsManager, 'getByName', 'organizationsByName.get'); /** * Update an existing organization. * - * @method update - * @memberOf module:management.OrganizationsManager.prototype - * + * @function update + * @memberof module:management.OrganizationsManager.prototype * @example * var data = { display_name: 'New name' }; * var params = { id: ORGANIZATION_ID }; @@ -211,22 +198,19 @@ utils.wrapPropertyMethod(OrganizationsManager, 'getByName', 'organizationsByName * * console.log(organization.name); // 'New name' * }); - * - * @param {Object} params Organization parameters. - * @param {String} params.id Organization ID. - * @param {Object} data Updated organization data. + * @param {object} params Organization parameters. + * @param {string} params.id Organization ID. + * @param {object} data Updated organization data. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(OrganizationsManager, 'update', 'organizations.patch'); /** * Delete an existing organization. * - * @method delete - * @memberOf module:management.OrganizationsManager.prototype - * + * @function delete + * @memberof module:management.OrganizationsManager.prototype * @example * management.organizations.delete({ id: ORGANIZATION_ID }, function (err) { * if (err) { @@ -235,26 +219,24 @@ utils.wrapPropertyMethod(OrganizationsManager, 'update', 'organizations.patch'); * * // Organization deleted. * }); - * - * @param {Object} params Organization parameters. - * @param {String} params.id Organization ID. + * @param {object} params Organization parameters. + * @param {string} params.id Organization ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(OrganizationsManager, 'delete', 'organizations.delete'); /** - **** Organization Connections + *Organization Connections */ /** * Get Enabled Connections in a Organization * - * @method getEnabledConnections - * @memberOf module:management.OrganizationsManager.prototype - * + * @function getEnabledConnections + * @memberof module:management.OrganizationsManager.prototype * @example + * @param callback * var params = {id : 'ORGANIZATION_ID'} * @example * This method takes an organization ID and returns the enabled connections in an Organization @@ -263,25 +245,23 @@ utils.wrapPropertyMethod(OrganizationsManager, 'delete', 'organizations.delete') * management.organizations.getEnabledConnections( {id : 'ORGANIZATION_ID'}, function (err, enabled_connections) { * console.log(enabled_connections); * }); - * - * @param {Object} params Organization parameters. - * @param {String} params.id Organization ID. + * @param {object} params Organization parameters. + * @param {string} params.id Organization ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -OrganizationsManager.prototype.getEnabledConnections = function(params, callback) { +OrganizationsManager.prototype.getEnabledConnections = function (params, callback) { return this.connections.getAll(params, callback); }; /** * Get Enabled Connection in a Organization * - * @method getEnabledConnection - * @memberOf module:management.OrganizationsManager.prototype - * + * @function getEnabledConnection + * @memberof module:management.OrganizationsManager.prototype * @example * var params = {id : 'ORGANIZATION_ID', connection_id: 'CONNECTION_ID'} + * @param callback * @example * This methods takes the organization ID and connection ID and returns the enabled connection * @@ -289,24 +269,21 @@ OrganizationsManager.prototype.getEnabledConnections = function(params, callback * management.organizations.getEnabledConnections( {id : 'ORGANIZATION_ID', connection_id: 'CONNECTION_ID'}, function (err, enabled_connection) { * console.log(enabled_connection); * }); - * - * @param {Object} params Organization parameters. - * @param {String} params.id Organization ID. - * @param {String} params.connection_id Connection ID. + * @param {object} params Organization parameters. + * @param {string} params.id Organization ID. + * @param {string} params.connection_id Connection ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -OrganizationsManager.prototype.getEnabledConnection = function(params, callback) { +OrganizationsManager.prototype.getEnabledConnection = function (params, callback) { return this.connections.get(params, callback); }; /** * Add an enabled connection for an organization * - * @method addEnabledConnection - * @memberOf module:management.OrganizationsManager.prototype - * + * @function addEnabledConnection + * @memberof module:management.OrganizationsManager.prototype * @example * var params = { id :'ORGANIZATION_ID'}; * var data = { "connection_id" : "CONNECTION_ID", assign_membership_on_login: false }; @@ -316,18 +293,16 @@ OrganizationsManager.prototype.getEnabledConnection = function(params, callback) * // Handle error. * } * }); - * - * @param {Object} params Organization parameters - * @param {String} params.id ID of the Organization. - * @param {Object} data enable connection data - * @param {String} data.connection_id connection ID to enable - * @param {Boolean} data.assign_membership_on_login flag to allow assign membership on login + * @param {object} params Organization parameters + * @param {string} params.id ID of the Organization. + * @param {object} data enable connection data + * @param {string} data.connection_id connection ID to enable + * @param {boolean} data.assign_membership_on_login flag to allow assign membership on login * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -OrganizationsManager.prototype.addEnabledConnection = function(params, data, cb) { +OrganizationsManager.prototype.addEnabledConnection = function (params, data, cb) { data = data || {}; params = params || {}; @@ -348,9 +323,8 @@ OrganizationsManager.prototype.addEnabledConnection = function(params, data, cb) /** * Remove an enabled connection from an organization * - * @method removeEnabledConnection - * @memberOf module:management.OrganizationsManager.prototype - * + * @function removeEnabledConnection + * @memberof module:management.OrganizationsManager.prototype * @example * var params = { id :'ORGANIZATION_ID', connection_id: 'CONNECTION_ID' }; * @@ -359,15 +333,14 @@ OrganizationsManager.prototype.addEnabledConnection = function(params, data, cb) * // Handle error. * } * }); - * @param {Object} params Organization parameters - * @param {String} params.id ID of the Organization. - * @param {String} params.connection_id ID of the Connection. + * @param {object} params Organization parameters + * @param {string} params.id ID of the Organization. + * @param {string} params.connection_id ID of the Connection. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -OrganizationsManager.prototype.removeEnabledConnection = function(params, cb) { +OrganizationsManager.prototype.removeEnabledConnection = function (params, cb) { params = params || {}; if (!params.id) { @@ -394,9 +367,8 @@ OrganizationsManager.prototype.removeEnabledConnection = function(params, cb) { /** * Update an enabled connection from an organization * - * @method updateEnabledConnection - * @memberOf module:management.OrganizationsManager.prototype - * + * @function updateEnabledConnection + * @memberof module:management.OrganizationsManager.prototype * @example * var params = { id :'ORGANIZATION_ID', connection_id: 'CONNECTION_ID' }; * var data = { assign_membership_on_login: true }; @@ -406,17 +378,15 @@ OrganizationsManager.prototype.removeEnabledConnection = function(params, cb) { * // Handle error. * } * }); - * - * @param {Object} params Organization parameters - * @param {String} params.id ID of the Organization. - * @param {String} params.connection_id ID of the Connection. - * @param {Object} data Updated connection. + * @param {object} params Organization parameters + * @param {string} params.id ID of the Organization. + * @param {string} params.connection_id ID of the Connection. + * @param {object} data Updated connection. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -OrganizationsManager.prototype.updateEnabledConnection = function(params, data, cb) { +OrganizationsManager.prototype.updateEnabledConnection = function (params, data, cb) { data = data || {}; params = params || {}; @@ -442,43 +412,40 @@ OrganizationsManager.prototype.updateEnabledConnection = function(params, data, }; /** - **** Organization Members + *Organization Members */ /** * Get Members in a Organization * - * @method getMembers - * @memberOf module:management.OrganizationsManager.prototype - * + * @function getMembers + * @memberof module:management.OrganizationsManager.prototype * @example * var params = {id : 'ORGANIZATION_ID'} * @example + * @param callback * This method takes an organization ID and returns the members in an Organization * * * management.organizations.getMembers( {id : 'ORGANIZATION_ID'}, function (err, members) { * console.log(members); * }); - * - * @param {Object} params Organization parameters - * @param {String} params.id Organization ID - * @param {String} [params.from] For checkpoint pagination, the Id from which to start selection from. - * @param {Number} [params.take] For checkpoint pagination, the number of entries to retrieve. Default 50. + * @param {object} params Organization parameters + * @param {string} params.id Organization ID + * @param {string} [params.from] For checkpoint pagination, the Id from which to start selection from. + * @param {number} [params.take] For checkpoint pagination, the number of entries to retrieve. Default 50. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -OrganizationsManager.prototype.getMembers = function(params, callback) { +OrganizationsManager.prototype.getMembers = function (params, callback) { return this.members.getAll(params, callback); }; /** * Add members in an organization * - * @method addMembers - * @memberOf module:management.OrganizationsManager.prototype - * + * @function addMembers + * @memberof module:management.OrganizationsManager.prototype * @example * var params = { id :'ORGANIZATION_ID'}; * var data = { members: [ 'USER_ID1', 'USER_ID2' ] } @@ -487,16 +454,14 @@ OrganizationsManager.prototype.getMembers = function(params, callback) { * // Handle error. * } * }); - * - * @param {Object} params Organization parameters - * @param {String} params.id ID of the Organization. - * @param {Object} data add members data + * @param {object} params Organization parameters + * @param {string} params.id ID of the Organization. + * @param {object} data add members data * @param {Array} data.members Array of user IDs * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -OrganizationsManager.prototype.addMembers = function(params, data, cb) { +OrganizationsManager.prototype.addMembers = function (params, data, cb) { data = data || {}; params = params || {}; @@ -517,9 +482,8 @@ OrganizationsManager.prototype.addMembers = function(params, data, cb) { /** * Remove members from an organization * - * @method removeMembers - * @memberOf module:management.OrganizationsManager.prototype - * + * @function removeMembers + * @memberof module:management.OrganizationsManager.prototype * @example * var params = { id :'ORGANIZATION_ID' }; * var data = { members: [ 'USER_ID1', 'USER_ID2' ] } @@ -529,16 +493,14 @@ OrganizationsManager.prototype.addMembers = function(params, data, cb) { * // Handle error. * } * }); - * - * @param {Object} params Organization parameters - * @param {String} params.id ID of the Organization. - * @param {Object} data add members data + * @param {object} params Organization parameters + * @param {string} params.id ID of the Organization. + * @param {object} data add members data * @param {Array} data.members Array of user IDs * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -OrganizationsManager.prototype.removeMembers = function(params, data, cb) { +OrganizationsManager.prototype.removeMembers = function (params, data, cb) { data = data || {}; params = params || {}; @@ -557,15 +519,14 @@ OrganizationsManager.prototype.removeMembers = function(params, data, cb) { }; /** - **** Organization Invites + *Organization Invites */ /** * Get Invites in a Organization * - * @method getInvitations - * @memberOf module:management.OrganizationsManager.prototype - * + * @function getInvitations + * @memberof module:management.OrganizationsManager.prototype * @example * var params = {id : 'ORGANIZATION_ID'} * @example @@ -574,33 +535,32 @@ OrganizationsManager.prototype.removeMembers = function(params, data, cb) { * * management.organizations.getInvitations( {id : 'ORGANIZATION_ID'}, function (err, invites) { * console.log(invites); + * @param callback * }); - * - * @param {Object} params Organization parameters - * @param {String} params.id Organization ID - * @param {Number} [params.per_page] Number of results per page. - * @param {Number} [params.page] Page number, zero indexed. - * @param {String} [params.from] For checkpoint pagination, the Id from which to start selection from. - * @param {Number} [params.take] For checkpoint pagination, the number of entries to retrieve. Default 50. - * @param {String} [params.fields] Comma-separated list of fields to include or exclude (based on value provided for include_fields) in the result. Leave empty to retrieve all fields. - * @param {Boolean} [params.include_fields] Whether specified fields are to be included (true) or excluded (false). Defaults to true. - * @param {String} [params.sort] Field to sort by. Use field:order where order is 1 for ascending and -1 for descending Defaults to created_at:-1. + * @param {object} params Organization parameters + * @param {string} params.id Organization ID + * @param {number} [params.per_page] Number of results per page. + * @param {number} [params.page] Page number, zero indexed. + * @param {string} [params.from] For checkpoint pagination, the Id from which to start selection from. + * @param {number} [params.take] For checkpoint pagination, the number of entries to retrieve. Default 50. + * @param {string} [params.fields] Comma-separated list of fields to include or exclude (based on value provided for include_fields) in the result. Leave empty to retrieve all fields. + * @param {boolean} [params.include_fields] Whether specified fields are to be included (true) or excluded (false). Defaults to true. + * @param {string} [params.sort] Field to sort by. Use field:order where order is 1 for ascending and -1 for descending Defaults to created_at:-1. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -OrganizationsManager.prototype.getInvitations = function(params, callback) { +OrganizationsManager.prototype.getInvitations = function (params, callback) { return this.invitations.getAll(params, callback); }; /** * Get an Invitation in a Organization * - * @method getInvitation - * @memberOf module:management.OrganizationsManager.prototype - * + * @function getInvitation + * @memberof module:management.OrganizationsManager.prototype * @example * var params = {id : 'ORGANIZATION_ID', invitation_id: 'INVITATION_ID'} + * @param callback * @example * This methods takes the organization ID and user ID and returns the invitation * @@ -608,15 +568,13 @@ OrganizationsManager.prototype.getInvitations = function(params, callback) { * management.organizations.getInvitation({id : 'ORGANIZATION_ID', invitation_id: 'INVITATION_ID'}, function (err, invite) { * console.log(invite); * }); - * - * @param {Object} params Organization parameters - * @param {String} params.id Organization ID - * @param {String} params.invitation_id Invitation ID + * @param {object} params Organization parameters + * @param {string} params.id Organization ID + * @param {string} params.invitation_id Invitation ID * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -OrganizationsManager.prototype.getInvitation = function(params, callback) { +OrganizationsManager.prototype.getInvitation = function (params, callback) { if (!params.id) { throw new ArgumentError('The organization ID passed in params cannot be null or undefined'); } @@ -637,9 +595,8 @@ OrganizationsManager.prototype.getInvitation = function(params, callback) { /** * Create an invitation in an organization * - * @method createInvitation - * @memberOf module:management.OrganizationsManager.prototype - * + * @function createInvitation + * @memberof module:management.OrganizationsManager.prototype * @example * var params = { id :'ORGANIZATION_ID'}; * var data = { @@ -653,26 +610,24 @@ OrganizationsManager.prototype.getInvitation = function(params, callback) { * // Handle error. * } * }); - * - * @param {Object} params Organization parameters - * @param {String} params.id ID of the Organization. + * @param {object} params Organization parameters + * @param {string} params.id ID of the Organization. * @param {Array} data Invitation data - * @param {Object} data.inviter The person who is sending the invite. - * @param {String} data.inviter.name Name of the person who is sending the invite - * @param {Object} data.invitee Invitee to whom invitation is intended for - * @param {Object} data.invitee.email Email of the invitee to whom invitation is intended for - * @param {String} data.client_id Auth0 client used to resolve the default application login URI. This endpoint must expect &invitation=... and &organization=... parameters (added by API2) to continue the flow with /authorize. If client_id does not have configured login URI, use the tenant level default login route if configured, otherwise return 400 - * @param {String} [data.connection_id] Force user to authenticate against a specific identity provider. - * @param {Object} [data.app_metadata] Application metadata to be assigned to the user after accept the invitation. - * @param {Object} [data.user_metadata] User metadata to be assigned to the user after accept the invitation. + * @param {object} data.inviter The person who is sending the invite. + * @param {string} data.inviter.name Name of the person who is sending the invite + * @param {object} data.invitee Invitee to whom invitation is intended for + * @param {object} data.invitee.email Email of the invitee to whom invitation is intended for + * @param {string} data.client_id Auth0 client used to resolve the default application login URI. This endpoint must expect &invitation=... and &organization=... parameters (added by API2) to continue the flow with /authorize. If client_id does not have configured login URI, use the tenant level default login route if configured, otherwise return 400 + * @param {string} [data.connection_id] Force user to authenticate against a specific identity provider. + * @param {object} [data.app_metadata] Application metadata to be assigned to the user after accept the invitation. + * @param {object} [data.user_metadata] User metadata to be assigned to the user after accept the invitation. * @param {Array} [data.roles] List of roles to be assigned to the user - * @param {Number} [data.ttl_sec] Number of seconds for which the invitation is valid before expiration. If unspecified or set to 0, this value defaults to 604800 seconds (7 days). Upper limit on ttl_sec is 30 days. - * @param {Boolean} [data.send_invitation_email] Whether the user will receive an invitation email (true) or no email (false). Default is true. + * @param {number} [data.ttl_sec] Number of seconds for which the invitation is valid before expiration. If unspecified or set to 0, this value defaults to 604800 seconds (7 days). Upper limit on ttl_sec is 30 days. + * @param {boolean} [data.send_invitation_email] Whether the user will receive an invitation email (true) or no email (false). Default is true. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -OrganizationsManager.prototype.createInvitation = function(params, data, cb) { +OrganizationsManager.prototype.createInvitation = function (params, data, cb) { data = data || []; params = params || {}; @@ -693,9 +648,8 @@ OrganizationsManager.prototype.createInvitation = function(params, data, cb) { /** * Delete an invitation from an organization * - * @method deleteInvitation - * @memberOf module:management.OrganizationsManager.prototype - * + * @function deleteInvitation + * @memberof module:management.OrganizationsManager.prototype * @example * var params = { id :'ORGANIZATION_ID', invitation_id: 'INVITATION_ID }; * @@ -704,15 +658,13 @@ OrganizationsManager.prototype.createInvitation = function(params, data, cb) { * // Handle error. * } * }); - * - * @param {Object} params Organization parameters - * @param {String} params.id ID of the Organization. - * @param {String} params.invitation_id Invitation ID + * @param {object} params Organization parameters + * @param {string} params.id ID of the Organization. + * @param {string} params.invitation_id Invitation ID * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -OrganizationsManager.prototype.deleteInvitation = function(params, cb) { +OrganizationsManager.prototype.deleteInvitation = function (params, cb) { params = params || {}; if (!params.id) { @@ -737,17 +689,17 @@ OrganizationsManager.prototype.deleteInvitation = function(params, cb) { }; /** - **** Organization Roles Membership + *Organization Roles Membership */ /** * Get Roles from a Member in a Organization * - * @method getMemberRoles - * @memberOf module:management.OrganizationsManager.prototype - * + * @function getMemberRoles + * @memberof module:management.OrganizationsManager.prototype * @example * var params = {id : 'ORGANIZATION_ID', user_id: 'user_id'} + * @param callback * @example * This methods takes the organization ID and user ID and returns the roles * @@ -755,24 +707,21 @@ OrganizationsManager.prototype.deleteInvitation = function(params, cb) { * management.organizations.getMemberRoles( {id : 'ORGANIZATION_ID', user_id: 'user_id'}, function (err, roles) { * console.log(roles); * }); - * - * @param {Object} params Organization parameters - * @param {String} params.id ID of the Organization. - * @param {String} params.user_id ID of the user. + * @param {object} params Organization parameters + * @param {string} params.id ID of the Organization. + * @param {string} params.user_id ID of the user. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -OrganizationsManager.prototype.getMemberRoles = function(params, callback) { +OrganizationsManager.prototype.getMemberRoles = function (params, callback) { return this.roles.getAll(params, callback); }; /** * Add a Role to a Member in an organization * - * @method addMemberRoles - * @memberOf module:management.OrganizationsManager.prototype - * + * @function addMemberRoles + * @memberof module:management.OrganizationsManager.prototype * @example * var params = {id : 'ORGANIZATION_ID', user_id: 'user_id'}; * var data = { roles: ["ROLE_ID_1", "ROLE_ID_2"]} @@ -782,17 +731,15 @@ OrganizationsManager.prototype.getMemberRoles = function(params, callback) { * // Handle error. * } * }); - * - * @param {Object} params Organization parameters - * @param {String} params.id ID of the Organization. - * @param {String} params.user_id ID of the user. - * @param {Object} data Add member roles data. + * @param {object} params Organization parameters + * @param {string} params.id ID of the Organization. + * @param {string} params.user_id ID of the user. + * @param {object} data Add member roles data. * @param {Array} data.roles Array of role IDs. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -OrganizationsManager.prototype.addMemberRoles = function(params, data, cb) { +OrganizationsManager.prototype.addMemberRoles = function (params, data, cb) { data = data || {}; params = params || {}; @@ -820,9 +767,8 @@ OrganizationsManager.prototype.addMemberRoles = function(params, data, cb) { /** * Remove Roles from a Member of an organization * - * @method removeMemberRoles - * @memberOf module:management.OrganizationsManager.prototype - * + * @function removeMemberRoles + * @memberof module:management.OrganizationsManager.prototype * @example * var params = { id :'ORGANIZATION_ID', user_id: 'USER_ID }; * var data = { roles: ["ROLE_ID_1", "ROLE_ID_2"]} @@ -832,17 +778,15 @@ OrganizationsManager.prototype.addMemberRoles = function(params, data, cb) { * // Handle error. * } * }); - * - * @param {Object} params Organization parameters - * @param {String} params.id ID of the Organization. - * @param {String} params.user_id Id of the User - * @param {Object} data Remove member roles data. + * @param {object} params Organization parameters + * @param {string} params.id ID of the Organization. + * @param {string} params.user_id Id of the User + * @param {object} data Remove member roles data. * @param {Array} data.roles Array of role IDs. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -OrganizationsManager.prototype.removeMemberRoles = function(params, data, cb) { +OrganizationsManager.prototype.removeMemberRoles = function (params, data, cb) { data = data || {}; params = params || {}; diff --git a/src/management/PromptsManager.js b/src/management/PromptsManager.js index 8065002f6..aff8cad74 100644 --- a/src/management/PromptsManager.js +++ b/src/management/PromptsManager.js @@ -1,10 +1,11 @@ -var ArgumentError = require('rest-facade').ArgumentError; -var utils = require('../utils'); -var Auth0RestClient = require('../Auth0RestClient'); -var RetryRestClient = require('../RetryRestClient'); +const { ArgumentError } = require('rest-facade'); +const utils = require('../utils'); +const Auth0RestClient = require('../Auth0RestClient'); +const RetryRestClient = require('../RetryRestClient'); /** * Simple facade for consuming a REST API endpoint. + * * @external RestClient * @see https://github.com/ngonzalvez/rest-facade */ @@ -12,15 +13,14 @@ var RetryRestClient = require('../RetryRestClient'); /** * @class PromptsManager * Manages settings related to prompts. - * @constructor - * @memberOf module:management - * - * @param {Object} options The client options. - * @param {String} options.baseUrl The URL of the API. - * @param {Object} [options.headers] Headers to be included in all requests. - * @param {Object} [options.retry] Retry Policy Config + * @class + * @memberof module:management + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config */ -var PromptsManager = function(options) { +const PromptsManager = function (options) { if (options === null || typeof options !== 'object') { throw new ArgumentError('Must provide manager options'); } @@ -33,10 +33,10 @@ var PromptsManager = function(options) { throw new ArgumentError('The provided base URL is invalid'); } - var clientOptions = { + const clientOptions = { errorFormatter: { message: 'message', name: 'error' }, headers: options.headers, - query: { repeatParams: false } + query: { repeatParams: false }, }; /** @@ -45,8 +45,8 @@ var PromptsManager = function(options) { * * @type {external:RestClient} */ - var auth0RestClient = new Auth0RestClient( - options.baseUrl + '/prompts', + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/prompts`, clientOptions, options.tokenProvider ); @@ -59,8 +59,8 @@ var PromptsManager = function(options) { * * @type {external:RestClient} */ - var customTextByLanguageAuth0RestClient = new Auth0RestClient( - options.baseUrl + '/prompts/:prompt/custom-text/:language', + const customTextByLanguageAuth0RestClient = new Auth0RestClient( + `${options.baseUrl}/prompts/:prompt/custom-text/:language`, clientOptions, options.tokenProvider ); @@ -73,9 +73,8 @@ var PromptsManager = function(options) { /** * Update the prompts settings. * - * @method updateSettings - * @memberOf module:management.PromptsManager.prototype - * + * @function updateSettings + * @memberof module:management.PromptsManager.prototype * @example * management.prompts.updateSettings(params, data, function (err, prompts) { * if (err) { @@ -85,21 +84,18 @@ var PromptsManager = function(options) { * // Updated prompts * console.log(prompts); * }); - * - * @param {Object} params Prompts parameters. - * @param {Object} data Updated prompts data. + * @param {object} params Prompts parameters. + * @param {object} data Updated prompts data. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(PromptsManager, 'updateSettings', 'resource.patch'); /** * Get the prompts settings.. * - * @method getSettings - * @memberOf module:management.PromptsManager.prototype - * + * @function getSettings + * @memberof module:management.PromptsManager.prototype * @example * management.prompts.getSettings(data, function (err, prompts) { * if (err) { @@ -109,21 +105,18 @@ utils.wrapPropertyMethod(PromptsManager, 'updateSettings', 'resource.patch'); * // Prompts * console.log(prompts); * }); - * - * @param {Object} params Prompts parameters. - * @param {Object} data Prompts data. + * @param {object} params Prompts parameters. + * @param {object} data Prompts data. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(PromptsManager, 'getSettings', 'resource.get'); /** * Retrieve custom text for a specific prompt and language. * - * @method getCustomTextByLanguage - * @memberOf module:management.PromptsManager.prototype - * + * @function getCustomTextByLanguage + * @memberof module:management.PromptsManager.prototype * @example * var params = { prompt: PROMPT_NAME, language: LANGUAGE }; * @@ -134,15 +127,13 @@ utils.wrapPropertyMethod(PromptsManager, 'getSettings', 'resource.get'); * * console.log('CustomText', customText); * }); - * - * @param {Object} params Data object. - * @param {String} params.prompt Name of the prompt. - * @param {String} params.language Language to retrieve. + * @param {object} params Data object. + * @param {string} params.prompt Name of the prompt. + * @param {string} params.language Language to retrieve. * @param {Function} [cb] Callback function - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -PromptsManager.prototype.getCustomTextByLanguage = function(params, cb) { +PromptsManager.prototype.getCustomTextByLanguage = function (params, cb) { params = params || {}; if (!params.prompt || typeof params.prompt !== 'string') { @@ -163,9 +154,8 @@ PromptsManager.prototype.getCustomTextByLanguage = function(params, cb) { /** * Set custom text for a specific prompt. * - * @method updateCustomTextByLanguage - * @memberOf module:management.PromptsManager.prototype - * + * @function updateCustomTextByLanguage + * @memberof module:management.PromptsManager.prototype * @example * var params = { prompt: PROMPT_NAME, language: LANGUAGE, body: BODY_OBJECT }; * @@ -176,18 +166,15 @@ PromptsManager.prototype.getCustomTextByLanguage = function(params, cb) { * * console.log('CustomText', customText); * }); - * - * @param {Object} params Data object. - * @param {String} params.prompt Name of the prompt. - * @param {String} params.language Language to retrieve. - * @param {Object} params.body An object containing custom dictionaries for a group of screens. + * @param {object} params Data object. + * @param {string} params.prompt Name of the prompt. + * @param {string} params.language Language to retrieve. + * @param {object} params.body An object containing custom dictionaries for a group of screens. * @param {Function} [cb] Callback function - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -PromptsManager.prototype.updateCustomTextByLanguage = function(params, cb) { +PromptsManager.prototype.updateCustomTextByLanguage = function (params, cb) { params = params || {}; - options = {}; if (!params.prompt || typeof params.prompt !== 'string') { throw new ArgumentError('The prompt parameter must be a string'); @@ -201,8 +188,10 @@ PromptsManager.prototype.updateCustomTextByLanguage = function(params, cb) { throw new ArgumentError('The body parameter must be an object'); } - options.prompt = params.prompt; - options.language = params.language; + const options = { + prompt: params.prompt, + language: params.language, + }; if (cb && cb instanceof Function) { return this.customTextByLanguage.update(options, params.body, cb); diff --git a/src/management/ResourceServersManager.js b/src/management/ResourceServersManager.js index 480423aed..41e2d89ec 100644 --- a/src/management/ResourceServersManager.js +++ b/src/management/ResourceServersManager.js @@ -1,7 +1,7 @@ -var ArgumentError = require('rest-facade').ArgumentError; -var utils = require('../utils'); -var Auth0RestClient = require('../Auth0RestClient'); -var RetryRestClient = require('../RetryRestClient'); +const { ArgumentError } = require('rest-facade'); +const utils = require('../utils'); +const Auth0RestClient = require('../Auth0RestClient'); +const RetryRestClient = require('../RetryRestClient'); /** * @class ResourceServersManager @@ -12,16 +12,15 @@ var RetryRestClient = require('../RetryRestClient'); * You can learn more about this in the * {@link https://auth0.com/docs/api-auth API Authorization} section of the * documentation. - * @constructor - * @memberOf module:management - * - * @param {Object} options The client options. - * @param {String} options.baseUrl The URL of the API. - * @param {Object} [options.headers] Headers to be included in all requests. - * @param {Object} [options.retry] Retry Policy Config + * @class + * @memberof module:management + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config */ -var ResourceServersManager = function(options) { +const ResourceServersManager = function (options) { if (options === null || typeof options !== 'object') { throw new ArgumentError('Must provide resource server options'); } @@ -37,11 +36,11 @@ var ResourceServersManager = function(options) { /** * Options object for the Rest Client instance. * - * @type {Object} + * @type {object} */ - var clientOptions = { + const clientOptions = { headers: options.headers, - query: { repeatParams: false } + query: { repeatParams: false }, }; /** @@ -50,8 +49,8 @@ var ResourceServersManager = function(options) { * * @type {external:RestClient} */ - var auth0RestClient = new Auth0RestClient( - options.baseUrl + '/resource-servers/:id', + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/resource-servers/:id`, clientOptions, options.tokenProvider ); @@ -61,9 +60,8 @@ var ResourceServersManager = function(options) { /** * Create an API (Resource Server). * - * @method create - * @memberOf module:management.ResourceServersManager.prototype - * + * @function create + * @memberof module:management.ResourceServersManager.prototype * @example * management.resourceServers.create(data, function (err) { * if (err) { @@ -72,20 +70,17 @@ var ResourceServersManager = function(options) { * * // Resource Server created. * }); - * - * @param {Object} data Resource Server data object. + * @param {object} data Resource Server data object. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ResourceServersManager, 'create', 'resource.create'); /** * Get all resource servers. * - * @method getAll - * @memberOf module:management.ResourceServersManager.prototype - * + * @function getAll + * @memberof module:management.ResourceServersManager.prototype * @example * This method takes an optional object as first argument that may be used to * specify pagination settings. If pagination options are not present, @@ -101,22 +96,19 @@ utils.wrapPropertyMethod(ResourceServersManager, 'create', 'resource.create'); * management.resourceServers.getAll(params, function (err, resourceServers) { * console.log(resourceServers.length); * }); - * - * @param {Object} [params] Resource Servers parameters. - * @param {Number} [params.per_page] Number of results per page. - * @param {Number} [params.page] Page number, zero indexed. + * @param {object} [params] Resource Servers parameters. + * @param {number} [params.per_page] Number of results per page. + * @param {number} [params.page] Page number, zero indexed. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ResourceServersManager, 'getAll', 'resource.getAll'); /** * Get a Resource Server. * - * @method get - * @memberOf module:management.ResourceServersManager.prototype - * + * @function get + * @memberof module:management.ResourceServersManager.prototype * @example * management.resourceServers.get({ id: RESOURCE_SERVER_ID }, function (err, resourceServer) { * if (err) { @@ -125,21 +117,18 @@ utils.wrapPropertyMethod(ResourceServersManager, 'getAll', 'resource.getAll'); * * console.log(resourceServer); * }); - * - * @param {Object} params Resource Server parameters. - * @param {String} params.id Resource Server ID. + * @param {object} params Resource Server parameters. + * @param {string} params.id Resource Server ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ResourceServersManager, 'get', 'resource.get'); /** * Update an existing resource server. * - * @method update - * @memberOf module:management.ResourceServersManager.prototype - * + * @function update + * @memberof module:management.ResourceServersManager.prototype * @example * var data = { name: 'newResourceServerName' }; * var params = { id: RESOURCE_SERVER_ID }; @@ -151,22 +140,19 @@ utils.wrapPropertyMethod(ResourceServersManager, 'get', 'resource.get'); * * console.log(resourceServer.name); // 'newResourceServernName' * }); - * - * @param {Object} params Resource Server parameters. - * @param {String} params.id Resource Server ID. - * @param {Object} data Updated Resource Server data. + * @param {object} params Resource Server parameters. + * @param {string} params.id Resource Server ID. + * @param {object} data Updated Resource Server data. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ResourceServersManager, 'update', 'resource.patch'); /** * Delete an existing Resource Server. * - * @method delete - * @memberOf module:management.ResourceServersManager.prototype - * + * @function delete + * @memberof module:management.ResourceServersManager.prototype * @example * management.resourceServers.delete({ id: RESOURCE_SERVER_ID }, function (err) { * if (err) { @@ -175,12 +161,10 @@ utils.wrapPropertyMethod(ResourceServersManager, 'update', 'resource.patch'); * * // Resource Server deleted. * }); - * - * @param {Object} params Resource Server parameters. - * @param {String} params.id Resource Server ID. + * @param {object} params Resource Server parameters. + * @param {string} params.id Resource Server ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ResourceServersManager, 'delete', 'resource.delete'); diff --git a/src/management/RolesManager.js b/src/management/RolesManager.js index 2f49ae865..8a6b1a352 100644 --- a/src/management/RolesManager.js +++ b/src/management/RolesManager.js @@ -1,10 +1,11 @@ -var ArgumentError = require('rest-facade').ArgumentError; -var utils = require('../utils'); -var Auth0RestClient = require('../Auth0RestClient'); -var RetryRestClient = require('../RetryRestClient'); +const { ArgumentError } = require('rest-facade'); +const utils = require('../utils'); +const Auth0RestClient = require('../Auth0RestClient'); +const RetryRestClient = require('../RetryRestClient'); /** * Simple facade for consuming a REST API endpoint. + * * @external RestClient * @see https://github.com/ngonzalvez/rest-facade */ @@ -13,15 +14,14 @@ var RetryRestClient = require('../RetryRestClient'); * @class RolesManager * The role class provides a simple abstraction for performing CRUD operations * on Auth0 RolesManager. - * @constructor - * @memberOf module:management - * - * @param {Object} options The client options. - * @param {String} options.baseUrl The URL of the API. - * @param {Object} [options.headers] Headers to be included in all requests. - * @param {Object} [options.retry] Retry Policy Config + * @class + * @memberof module:management + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config */ -var RolesManager = function(options) { +const RolesManager = function (options) { if (options === null || typeof options !== 'object') { throw new ArgumentError('Must provide manager options'); } @@ -37,11 +37,11 @@ var RolesManager = function(options) { /** * Options object for the Rest Client instance. * - * @type {Object} + * @type {object} */ - var clientOptions = { + const clientOptions = { headers: options.headers, - query: { repeatParams: false } + query: { repeatParams: false }, }; /** @@ -50,22 +50,22 @@ var RolesManager = function(options) { * * @type {external:RestClient} */ - var auth0RestClient = new Auth0RestClient( - options.baseUrl + '/roles/:id', + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/roles/:id`, clientOptions, options.tokenProvider ); this.resource = new RetryRestClient(auth0RestClient, options.retry); - var permissionsInRoleClient = new Auth0RestClient( - options.baseUrl + '/roles/:id/permissions', + const permissionsInRoleClient = new Auth0RestClient( + `${options.baseUrl}/roles/:id/permissions`, clientOptions, options.tokenProvider ); this.permissions = new RetryRestClient(permissionsInRoleClient, options.retry); - var usersInRoleClient = new Auth0RestClient( - options.baseUrl + '/roles/:id/users', + const usersInRoleClient = new Auth0RestClient( + `${options.baseUrl}/roles/:id/users`, clientOptions, options.tokenProvider ); @@ -75,9 +75,8 @@ var RolesManager = function(options) { /** * Create a new role. * - * @method create - * @memberOf module:management.RolesManager.prototype - * + * @function create + * @memberof module:management.RolesManager.prototype * @example * management.roles.create(data, function (err) { * if (err) { @@ -86,20 +85,17 @@ var RolesManager = function(options) { * * // Role created. * }); - * - * @param {Object} data Role data object. + * @param {object} data Role data object. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(RolesManager, 'create', 'resource.create'); /** * Get all roles. * - * @method getAll - * @memberOf module:management.RolesManager.prototype - * + * @function getAll + * @memberof module:management.RolesManager.prototype * @example * This method takes an optional object as first argument that may be used to * specify pagination settings. If pagination options are not present, @@ -115,22 +111,19 @@ utils.wrapPropertyMethod(RolesManager, 'create', 'resource.create'); * management.roles.getAll(params, function (err, roles) { * console.log(roles.length); * }); - * - * @param {Object} [params] Roles parameters. - * @param {Number} [params.per_page] Number of results per page. - * @param {Number} [params.page] Page number, zero indexed. + * @param {object} [params] Roles parameters. + * @param {number} [params.per_page] Number of results per page. + * @param {number} [params.page] Page number, zero indexed. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(RolesManager, 'getAll', 'resource.getAll'); /** * Get an Auth0 role. * - * @method get - * @memberOf module:management.RolesManager.prototype - * + * @function get + * @memberof module:management.RolesManager.prototype * @example * management.roles.get({ id: ROLE_ID }, function (err, role) { * if (err) { @@ -139,21 +132,18 @@ utils.wrapPropertyMethod(RolesManager, 'getAll', 'resource.getAll'); * * console.log(role); * }); - * - * @param {Object} params Role parameters. - * @param {String} params.id Role ID. + * @param {object} params Role parameters. + * @param {string} params.id Role ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(RolesManager, 'get', 'resource.get'); /** * Update an existing role. * - * @method update - * @memberOf module:management.RolesManager.prototype - * + * @function update + * @memberof module:management.RolesManager.prototype * @example * var data = { name: 'New name' }; * var params = { id: ROLE_ID }; @@ -175,22 +165,19 @@ utils.wrapPropertyMethod(RolesManager, 'get', 'resource.get'); * * console.log(role.name); // 'New name' * }); - * - * @param {Object} params Role parameters. - * @param {String} params.id Role ID. - * @param {Object} data Updated role data. + * @param {object} params Role parameters. + * @param {string} params.id Role ID. + * @param {object} data Updated role data. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(RolesManager, 'update', 'resource.patch'); /** * Delete an existing role. * - * @method delete - * @memberOf module:management.RolesManager.prototype - * + * @function delete + * @memberof module:management.RolesManager.prototype * @example * management.roles.delete({ id: ROLE_ID }, function (err) { * if (err) { @@ -199,21 +186,20 @@ utils.wrapPropertyMethod(RolesManager, 'update', 'resource.patch'); * * // Role deleted. * }); - * - * @param {Object} params Role parameters. - * @param {String} params.id Role ID. + * @param {object} params Role parameters. + * @param {string} params.id Role ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(RolesManager, 'delete', 'resource.delete'); /** * Get Permissions in a Role * - * @method getPermissionsInRole - * @memberOf module:management.RolesManager.prototype - * + * @function getPermissionsInRole + * @memberof module:management.RolesManager.prototype + * @param params + * @param callback * @example * var params = {id : 'ROLE_ID'} * @example @@ -223,22 +209,19 @@ utils.wrapPropertyMethod(RolesManager, 'delete', 'resource.delete'); * management.roles.getPermissions( {id : 'ROLE_ID'}, function (err, permissions) { * console.log(permissions); * }); - * - * @param {String} [email] Email address of user(s) to find + * @param {string} [email] Email address of user(s) to find * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -RolesManager.prototype.getPermissions = function(params, callback) { +RolesManager.prototype.getPermissions = function (params, callback) { return this.permissions.getAll(params, callback); }; /** * Add permissions in a role * - * @method addPermissions - * @memberOf module:management.RolesManager.prototype - * + * @function addPermissions + * @memberof module:management.RolesManager.prototype * @example * var params = { id :'ROLE_ID'}; * var data = { "permissions" : [{"permission_name" :"do:something" ,"resource_server_identifier" :"test123" }]}; @@ -250,18 +233,16 @@ RolesManager.prototype.getPermissions = function(params, callback) { * * // permissions added. * }); - * - * @param {String} params.id ID of the Role. - * @param {Object} data permissions data - * @param {String} data.permissions Array of permissions - * @param {String} data.permissions.permission_name Name of a permission - * @param {String} data.permissions.resource_server_identifier Identifier for a resource + * @param {string} params.id ID of the Role. + * @param {object} data permissions data + * @param {string} data.permissions Array of permissions + * @param {string} data.permissions.permission_name Name of a permission + * @param {string} data.permissions.resource_server_identifier Identifier for a resource * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -RolesManager.prototype.addPermissions = function(params, data, cb) { +RolesManager.prototype.addPermissions = function (params, data, cb) { data = data || {}; params = params || {}; @@ -283,9 +264,8 @@ RolesManager.prototype.addPermissions = function(params, data, cb) { /** * Remove permissions from a role * - * @method removePermissions - * @memberOf module:management.RolesManager.prototype - * + * @function removePermissions + * @memberof module:management.RolesManager.prototype * @example * var params = { id :'ROLE_ID'}; * var data = { "permissions" : [{"permission_name" :"do:something" ,"resource_server_identifier" :"test123" }]}; @@ -297,18 +277,16 @@ RolesManager.prototype.addPermissions = function(params, data, cb) { * * // permissions added. * }); - * - * @param {String} params.id ID of the Role. - * @param {Object} data permissions data - * @param {String} data.permissions Array of permissions - * @param {String} data.permissions.permission_name Name of a permission - * @param {String} data.permissions.resource_server_identifier Identifier for a resource + * @param {string} params.id ID of the Role. + * @param {object} data permissions data + * @param {string} data.permissions Array of permissions + * @param {string} data.permissions.permission_name Name of a permission + * @param {string} data.permissions.resource_server_identifier Identifier for a resource * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -RolesManager.prototype.removePermissions = function(params, data, cb) { +RolesManager.prototype.removePermissions = function (params, data, cb) { data = data || {}; params = params || {}; @@ -330,16 +308,16 @@ RolesManager.prototype.removePermissions = function(params, data, cb) { /** * Get Users in a Role * - * @method getUsers - * @memberOf module:management.RolesManager.prototype - * + * @function getUsers + * @memberof module:management.RolesManager.prototype * @example * var params = { * roleId: 'ROLE_ID', * per_page: 50, + * @param params + * @param callback * page: 0 * }; - * * @example * This method takes a roleId and returns all users within that role. Supports offset (page, per_page) and checkpoint pagination (from, take). You must use checkpoint pagination to retrieve beyond the first 1000 records. * @@ -347,26 +325,23 @@ RolesManager.prototype.removePermissions = function(params, data, cb) { * management.roles.getUsers(params, function (err, users) { * console.log(users); * }); - * - * @param {String} [roleId] Id of the role - * @param {Number} [params.per_page] Number of results per page. - * @param {Number} [params.page] Page number, zero indexed. - * @param {String} [params.from] For checkpoint pagination, the Id from which to start selection from. - * @param {Number} [params.take] For checkpoint pagination, the number of entries to retrieve. Default 50. + * @param {string} [roleId] Id of the role + * @param {number} [params.per_page] Number of results per page. + * @param {number} [params.page] Page number, zero indexed. + * @param {string} [params.from] For checkpoint pagination, the Id from which to start selection from. + * @param {number} [params.take] For checkpoint pagination, the number of entries to retrieve. Default 50. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -RolesManager.prototype.getUsers = function(params, callback) { +RolesManager.prototype.getUsers = function (params, callback) { return this.users.getAll(params, callback); }; /** * Assign users to a role * - * @method assignUsers - * @memberOf module:management.RolesManager.prototype - * + * @function assignUsers + * @memberof module:management.RolesManager.prototype * @example * var params = { id :'ROLE_ID'}; * var data = { "users" : ["userId1","userId2"]}; @@ -378,18 +353,16 @@ RolesManager.prototype.getUsers = function(params, callback) { * * // permissions added. * }); - * - * @param {String} params.id ID of the Role. - * @param {Object} data permissions data - * @param {String} data.permissions Array of permissions - * @param {String} data.permissions.permission_name Name of a permission - * @param {String} data.permissions.resource_server_identifier Identifier for a resource + * @param {string} params.id ID of the Role. + * @param {object} data permissions data + * @param {string} data.permissions Array of permissions + * @param {string} data.permissions.permission_name Name of a permission + * @param {string} data.permissions.resource_server_identifier Identifier for a resource * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -RolesManager.prototype.assignUsers = function(params, data, cb) { +RolesManager.prototype.assignUsers = function (params, data, cb) { data = data || {}; params = params || {}; diff --git a/src/management/RulesConfigsManager.js b/src/management/RulesConfigsManager.js index d48ef71b3..24d190bb8 100644 --- a/src/management/RulesConfigsManager.js +++ b/src/management/RulesConfigsManager.js @@ -1,10 +1,11 @@ -var ArgumentError = require('rest-facade').ArgumentError; -var utils = require('../utils'); -var Auth0RestClient = require('../Auth0RestClient'); -var RetryRestClient = require('../RetryRestClient'); +const { ArgumentError } = require('rest-facade'); +const utils = require('../utils'); +const Auth0RestClient = require('../Auth0RestClient'); +const RetryRestClient = require('../RetryRestClient'); /** * Simple facade for consuming a REST API endpoint. + * * @external RestClient * @see https://github.com/ngonzalvez/rest-facade */ @@ -13,15 +14,14 @@ var RetryRestClient = require('../RetryRestClient'); * @class RulesConfigsManager * The rules configs manager class provides a simple abstraction for performing CRUD operations * on Auth0 RulesConfigsManager. - * @constructor - * @memberOf module:management - * - * @param {Object} options The client options. - * @param {String} options.baseUrl The URL of the API. - * @param {Object} [options.headers] Headers to be included in all requests. - * @param {Object} [options.retry] Retry Policy Config + * @class + * @memberof module:management + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config */ -var RulesConfigsManager = function(options) { +const RulesConfigsManager = function (options) { if (options === null || typeof options !== 'object') { throw new ArgumentError('Must provide manager options'); } @@ -37,11 +37,11 @@ var RulesConfigsManager = function(options) { /** * Options object for the Rest Client instance. * - * @type {Object} + * @type {object} */ - var clientOptions = { + const clientOptions = { headers: options.headers, - query: { repeatParams: false } + query: { repeatParams: false }, }; /** @@ -50,8 +50,8 @@ var RulesConfigsManager = function(options) { * * @type {external:RestClient} */ - var auth0RestClient = new Auth0RestClient( - options.baseUrl + '/rules-configs/:key', + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/rules-configs/:key`, clientOptions, options.tokenProvider ); @@ -61,9 +61,8 @@ var RulesConfigsManager = function(options) { /** * Set a new rules config. * - * @method set - * @memberOf module:management.RulesConfigsManager.prototype - * + * @function set + * @memberof module:management.RulesConfigsManager.prototype * @example * var params = { key: RULE_CONFIG_KEY }; * var data = { value: RULES_CONFIG_VALUE }; @@ -75,40 +74,34 @@ var RulesConfigsManager = function(options) { * * // Rules Config set. * }); - * - * @param {Object} params Rule Config parameters. - * @param {String} params.key Rule Config key. - * @param {Object} data Rule Config Data parameters. - * @param {String} data.value Rule Config Data value. + * @param {object} params Rule Config parameters. + * @param {string} params.key Rule Config key. + * @param {object} data Rule Config Data parameters. + * @param {string} data.value Rule Config Data value. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(RulesConfigsManager, 'set', 'resource.update'); /** * Get all rules configs. * - * @method getAll - * @memberOf module:management.RulesConfigsManager.prototype - * + * @function getAll + * @memberof module:management.RulesConfigsManager.prototype * @example * management.rulesConfigs.getAll(function (err, rulesConfig) { * console.log(rulesConfig.length); * }); - * * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(RulesConfigsManager, 'getAll', 'resource.getAll'); /** * Delete an existing rules config. * - * @method delete - * @memberOf module:management.RulesConfigsManager.prototype - * + * @function delete + * @memberof module:management.RulesConfigsManager.prototype * @example * management.rulesConfigs.delete({ key: RULE_CONFIG_KEY }, function (err) { * if (err) { @@ -117,12 +110,10 @@ utils.wrapPropertyMethod(RulesConfigsManager, 'getAll', 'resource.getAll'); * * // Rules Config deleted. * }); - * - * @param {Object} params Rule Configs parameters. - * @param {String} params.key Rule Configs key. + * @param {object} params Rule Configs parameters. + * @param {string} params.key Rule Configs key. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(RulesConfigsManager, 'delete', 'resource.delete'); diff --git a/src/management/RulesManager.js b/src/management/RulesManager.js index 61d578dfa..10e354a47 100644 --- a/src/management/RulesManager.js +++ b/src/management/RulesManager.js @@ -1,10 +1,11 @@ -var ArgumentError = require('rest-facade').ArgumentError; -var utils = require('../utils'); -var Auth0RestClient = require('../Auth0RestClient'); -var RetryRestClient = require('../RetryRestClient'); +const { ArgumentError } = require('rest-facade'); +const utils = require('../utils'); +const Auth0RestClient = require('../Auth0RestClient'); +const RetryRestClient = require('../RetryRestClient'); /** * Simple facade for consuming a REST API endpoint. + * * @external RestClient * @see https://github.com/ngonzalvez/rest-facade */ @@ -13,15 +14,14 @@ var RetryRestClient = require('../RetryRestClient'); * @class RulesManager * The rule class provides a simple abstraction for performing CRUD operations * on Auth0 RulesManagers. - * @constructor - * @memberOf module:management - * - * @param {Object} options The client options. - * @param {String} options.baseUrl The URL of the API. - * @param {Object} [options.headers] Headers to be included in all requests. - * @param {Object} [options.retry] Retry Policy Config + * @class + * @memberof module:management + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config */ -var RulesManager = function(options) { +const RulesManager = function (options) { if (options === null || typeof options !== 'object') { throw new ArgumentError('Must provide manager options'); } @@ -37,11 +37,11 @@ var RulesManager = function(options) { /** * Options object for the Rest Client instance. * - * @type {Object} + * @type {object} */ - var clientOptions = { + const clientOptions = { headers: options.headers, - query: { repeatParams: false } + query: { repeatParams: false }, }; /** @@ -50,8 +50,8 @@ var RulesManager = function(options) { * * @type {external:RestClient} */ - var auth0RestClient = new Auth0RestClient( - options.baseUrl + '/rules/:id', + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/rules/:id`, clientOptions, options.tokenProvider ); @@ -61,9 +61,8 @@ var RulesManager = function(options) { /** * Create a new rule. * - * @method create - * @memberOf module:management.RulesManager.prototype - * + * @function create + * @memberof module:management.RulesManager.prototype * @example * management.rules.create(data, function (err) { * if (err) { @@ -72,20 +71,17 @@ var RulesManager = function(options) { * * // Rule created. * }); - * - * @param {Object} data Rule data object. + * @param {object} data Rule data object. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(RulesManager, 'create', 'resource.create'); /** * Get all rules. * - * @method getAll - * @memberOf module:management.RulesManager.prototype - * + * @function getAll + * @memberof module:management.RulesManager.prototype * @example * This method takes an optional object as first argument that may be used to * specify pagination settings. If pagination options are not present, @@ -101,22 +97,19 @@ utils.wrapPropertyMethod(RulesManager, 'create', 'resource.create'); * management.rules.getAll(params, function (err, rules) { * console.log(rules.length); * }); - * - * @param {Object} [params] Rules parameters. - * @param {Number} [params.per_page] Number of results per page. - * @param {Number} [params.page] Page number, zero indexed. + * @param {object} [params] Rules parameters. + * @param {number} [params.per_page] Number of results per page. + * @param {number} [params.page] Page number, zero indexed. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(RulesManager, 'getAll', 'resource.getAll'); /** * Get an Auth0 rule. * - * @method get - * @memberOf module:management.RulesManager.prototype - * + * @function get + * @memberof module:management.RulesManager.prototype * @example * management.rules.get({ id: RULE_ID }, function (err, rule) { * if (err) { @@ -125,21 +118,18 @@ utils.wrapPropertyMethod(RulesManager, 'getAll', 'resource.getAll'); * * console.log(rule); * }); - * - * @param {Object} params Rule parameters. - * @param {String} params.id Rule ID. + * @param {object} params Rule parameters. + * @param {string} params.id Rule ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(RulesManager, 'get', 'resource.get'); /** * Update an existing rule. * - * @method update - * @memberOf module:management.RulesManager.prototype - * + * @function update + * @memberof module:management.RulesManager.prototype * @example * var data = { name: 'New name' }; * var params = { id: RULE_ID }; @@ -161,22 +151,19 @@ utils.wrapPropertyMethod(RulesManager, 'get', 'resource.get'); * * console.log(rule.name); // 'New name' * }); - * - * @param {Object} params Rule parameters. - * @param {String} params.id Rule ID. - * @param {Object} data Updated rule data. + * @param {object} params Rule parameters. + * @param {string} params.id Rule ID. + * @param {object} data Updated rule data. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(RulesManager, 'update', 'resource.patch'); /** * Delete an existing rule. * - * @method delete - * @memberOf module:management.RulesManager.prototype - * + * @function delete + * @memberof module:management.RulesManager.prototype * @example * management.rules.delete({ id: RULE_ID }, function (err) { * if (err) { @@ -185,12 +172,10 @@ utils.wrapPropertyMethod(RulesManager, 'update', 'resource.patch'); * * // Rule deleted. * }); - * - * @param {Object} params Rule parameters. - * @param {String} params.id Rule ID. + * @param {object} params Rule parameters. + * @param {string} params.id Rule ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(RulesManager, 'delete', 'resource.delete'); diff --git a/src/management/StatsManager.js b/src/management/StatsManager.js index 2254a83be..892ae9496 100644 --- a/src/management/StatsManager.js +++ b/src/management/StatsManager.js @@ -1,9 +1,10 @@ -var ArgumentError = require('rest-facade').ArgumentError; -var Auth0RestClient = require('../Auth0RestClient'); -var RetryRestClient = require('../RetryRestClient'); +const { ArgumentError } = require('rest-facade'); +const Auth0RestClient = require('../Auth0RestClient'); +const RetryRestClient = require('../RetryRestClient'); /** * Simple facade for consuming a REST API endpoint. + * * @external RestClient * @see https://github.com/ngonzalvez/rest-facade */ @@ -11,15 +12,14 @@ var RetryRestClient = require('../RetryRestClient'); /** * @class * Abstracts interaction with the stats endpoint. - * @constructor - * @memberOf module:management - * - * @param {Object} options The client options. - * @param {String} options.baseUrl The URL of the API. - * @param {Object} [options.headers] Headers to be included in all requests. - * @param {Object} [options.retry] Retry Policy Config + * @class + * @memberof module:management + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config */ -var StatsManager = function(options) { +const StatsManager = function (options) { if (options === null || typeof options !== 'object') { throw new ArgumentError('Must provide manager options'); } @@ -32,10 +32,10 @@ var StatsManager = function(options) { throw new ArgumentError('The provided base URL is invalid'); } - var clientOptions = { + const clientOptions = { errorFormatter: { message: 'message', name: 'error' }, headers: options.headers, - query: { repeatParams: false } + query: { repeatParams: false }, }; /** @@ -44,8 +44,8 @@ var StatsManager = function(options) { * * @type {external:RestClient} */ - var auth0RestClient = new Auth0RestClient( - options.baseUrl + '/stats/:type', + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/stats/:type`, clientOptions, options.tokenProvider ); @@ -55,9 +55,8 @@ var StatsManager = function(options) { /** * Get the daily stats. * - * @method getDaily - * @memberOf module:management.StatsManager.prototype - * + * @function getDaily + * @memberof module:management.StatsManager.prototype * @example * var params = { * from: '{YYYYMMDD}', // First day included in the stats. @@ -71,15 +70,13 @@ var StatsManager = function(options) { * * console.log(stats); * }); - * - * @param {Object} params Stats parameters. - * @param {String} params.from The first day in YYYYMMDD format. - * @param {String} params.to The last day in YYYYMMDD format. + * @param {object} params Stats parameters. + * @param {string} params.from The first day in YYYYMMDD format. + * @param {string} params.to The last day in YYYYMMDD format. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -StatsManager.prototype.getDaily = function(params, cb) { +StatsManager.prototype.getDaily = function (params, cb) { params = params || {}; params.type = 'daily'; @@ -93,9 +90,8 @@ StatsManager.prototype.getDaily = function(params, cb) { /** * Get a the active users count. * - * @method getActiveUsersCount - * @memberOf module:management.StatsManager.prototype - * + * @function getActiveUsersCount + * @memberof module:management.StatsManager.prototype * @example * management.stats.getActiveUsersCount(function (err, usersCount) { * if (err) { @@ -104,13 +100,11 @@ StatsManager.prototype.getDaily = function(params, cb) { * * console.log(usersCount); * }); - * * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ -StatsManager.prototype.getActiveUsersCount = function(cb) { - var options = { type: 'active-users' }; +StatsManager.prototype.getActiveUsersCount = function (cb) { + const options = { type: 'active-users' }; if (cb && cb instanceof Function) { return this.resource.get(options, cb); diff --git a/src/management/TenantManager.js b/src/management/TenantManager.js index e8d081633..68cd391ef 100644 --- a/src/management/TenantManager.js +++ b/src/management/TenantManager.js @@ -1,115 +1,103 @@ -var ArgumentError = require('rest-facade').ArgumentError; -var Auth0RestClient = require('../Auth0RestClient'); -var RetryRestClient = require('../RetryRestClient'); +const { ArgumentError } = require('rest-facade'); +const Auth0RestClient = require('../Auth0RestClient'); +const RetryRestClient = require('../RetryRestClient'); /** - * Simple facade for consuming a REST API endpoint. - * @external RestClient - * @see https://github.com/ngonzalvez/rest-facade - */ - -/** - * @class * Abstracts interaction with the tenant endpoint. - * @constructor - * @memberOf module:management - * - * @param {Object} options The client options. - * @param {String} options.baseUrl The URL of the API. - * @param {Object} [options.headers] Headers to be included in all requests. - * @param {Object} [options.retry] Retry Policy Config */ -var TenantManager = function(options) { - if (options === null || typeof options !== 'object') { - throw new ArgumentError('Must provide manager options'); - } +class TenantManager { + /** + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config + */ + constructor(options) { + if (options === null || typeof options !== 'object') { + throw new ArgumentError('Must provide manager options'); + } - if (options.baseUrl === null || options.baseUrl === undefined) { - throw new ArgumentError('Must provide a base URL for the API'); - } + if (options.baseUrl === null || options.baseUrl === undefined) { + throw new ArgumentError('Must provide a base URL for the API'); + } - if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { - throw new ArgumentError('The provided base URL is invalid'); - } + if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { + throw new ArgumentError('The provided base URL is invalid'); + } - var clientOptions = { - errorFormatter: { message: 'message', name: 'error' }, - headers: options.headers, - query: { repeatParams: false } - }; + const clientOptions = { + errorFormatter: { message: 'message', name: 'error' }, + headers: options.headers, + query: { repeatParams: false }, + }; + + /** + * Provides an abstraction layer for consuming the + * {@link https://auth0.com/docs/api/v2#!/Stats Stats endpoint}. + * + * @type {external:RestClient} + */ + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/tenants/settings`, + clientOptions, + options.tokenProvider + ); + this.resource = new RetryRestClient(auth0RestClient, options.retry); + } /** - * Provides an abstraction layer for consuming the - * {@link https://auth0.com/docs/api/v2#!/Stats Stats endpoint}. + * Update the tenant settings. * - * @type {external:RestClient} + * @function updateSettings + * @memberof module:management.TenantManager.prototype + * @example + * management.tenant.updateSettings(data, function (err) { + * if (err) { + * // Handle error. + * } + * }); + * @param {object} data The new tenant settings. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - var auth0RestClient = new Auth0RestClient( - options.baseUrl + '/tenants/settings', - clientOptions, - options.tokenProvider - ); - this.resource = new RetryRestClient(auth0RestClient, options.retry); -}; + updateSettings(data, cb) { + if (cb && cb instanceof Function) { + return this.resource.patch({}, data, cb); + } -/** - * Update the tenant settings. - * - * @method updateSettings - * @memberOf module:management.TenantManager.prototype - * - * @example - * management.tenant.updateSettings(data, function (err) { - * if (err) { - * // Handle error. - * } - * }); - * - * @param {Object} data The new tenant settings. - * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} - */ -TenantManager.prototype.updateSettings = function(data, cb) { - if (cb && cb instanceof Function) { - return this.resource.patch({}, data, cb); + // Return a promise. + return this.resource.patch({}, data); } - // Return a promise. - return this.resource.patch({}, data); -}; + /** + * Get the tenant settings.. + * + * @function getSettings + * @memberof module:management.TenantManager.prototype + * @example + * management.tenant.getSettings({ include_fields: true, fields: 'friendly_name' }, function (err, settings) { + * if (err) { + * // Handle error. + * } + * + * console.log(settings); + * }); + * @param {object} [data] Request parameters + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getSettings(data, cb) { + if (data instanceof Function && !cb) { + cb = data; + data = {}; + } + if (cb && cb instanceof Function) { + return this.resource.get(data, cb); + } -/** - * Get the tenant settings.. - * - * @method getSettings - * @memberOf module:management.TenantManager.prototype - * - * @example - * management.tenant.getSettings({ include_fields: true, fields: 'friendly_name' }, function (err, settings) { - * if (err) { - * // Handle error. - * } - * - * console.log(settings); - * }); - * - * @param {Object} [data] Request parameters - * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} - */ -TenantManager.prototype.getSettings = function(data, cb) { - if (data instanceof Function && !cb) { - cb = data; - data = {}; + // Return a promise. + return this.resource.get(data); } - if (cb && cb instanceof Function) { - return this.resource.get(data, cb); - } - - // Return a promise. - return this.resource.get(data); -}; +} module.exports = TenantManager; diff --git a/src/management/TicketsManager.js b/src/management/TicketsManager.js index 1614a5717..fc50ac419 100644 --- a/src/management/TicketsManager.js +++ b/src/management/TicketsManager.js @@ -1,135 +1,127 @@ -var ArgumentError = require('rest-facade').ArgumentError; -var Auth0RestClient = require('../Auth0RestClient'); -var RetryRestClient = require('../RetryRestClient'); +const { ArgumentError } = require('rest-facade'); +const Auth0RestClient = require('../Auth0RestClient'); +const RetryRestClient = require('../RetryRestClient'); /** - * @class * Abstracts interaction with the tickets endpoint. - * @constructor - * @memberOf module:management - * - * @param {Object} options The client options. - * @param {String} options.baseUrl The URL of the API. - * @param {Object} [options.headers] Headers to be included in all requests. - * @param {Object} [options.retry] Retry Policy Config */ -var TicketsManager = function(options) { - if (options === null || typeof options !== 'object') { - throw new ArgumentError('Must provide manager options'); - } +class TicketsManager { + /** + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config + */ + constructor(options) { + if (options === null || typeof options !== 'object') { + throw new ArgumentError('Must provide manager options'); + } - if (options.baseUrl === null || options.baseUrl === undefined) { - throw new ArgumentError('Must provide a base URL for the API'); - } + if (options.baseUrl === null || options.baseUrl === undefined) { + throw new ArgumentError('Must provide a base URL for the API'); + } - if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { - throw new ArgumentError('The provided base URL is invalid'); - } + if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { + throw new ArgumentError('The provided base URL is invalid'); + } - var clientOptions = { - errorFormatter: { message: 'message', name: 'error' }, - headers: options.headers, - query: { repeatParams: false } - }; + const clientOptions = { + errorFormatter: { message: 'message', name: 'error' }, + headers: options.headers, + query: { repeatParams: false }, + }; + + /** + * Provides an abstraction layer for consuming the + * {@link https://auth0.com/docs/api/v2#!/Tickets Tickets endpoint}. + * + * @type {external:RestClient} + */ + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/tickets/:type`, + clientOptions, + options.tokenProvider + ); + this.resource = new RetryRestClient(auth0RestClient, options.retry); + } /** - * Provides an abstraction layer for consuming the - * {@link https://auth0.com/docs/api/v2#!/Tickets Tickets endpoint}. + * Create a new password change ticket. * - * @type {external:RestClient} + * @example + * var params = { + * result_url: '{REDIRECT_URL}', // Redirect after using the ticket. + * user_id: '{USER_ID}', // Optional. + * email: '{USER_EMAIL}', // Optional. + * new_password: '{PASSWORD}' + * }; + * + * management.tickets.changePassword(params, function (err) { + * if (err) { + * // Handle error. + * } + * }); + * @param {object} data + * @param {string} [data.result_url] URL the user will be redirected to once ticket is used. + * @param {string} [data.user_id] user_id for whom the ticket should be created. (Conflicts with: connection_id, email) + * @param {string} [data.client_id] ID of the client. + * @param {string} [data.organization_id] ID of the organization. + * @param {string} [data.connection_id] ID of the connection. + * @param {Integer} [data.ttl_sec] Number of seconds for which the ticket is valid before expiration. + * @param {string} [data.email] Email of the user. (Requires: connection_id) + * @param {boolean} [data.mark_email_as_verified] Whether to set the email_verified attribute to true (true) or whether it should not be updated (false). + * @param {boolean} [data.includeEmailInRedirect] Whether to include the email address as part of the returnUrl in the reset_email (true), or not (false). + * @param {Function} [cb] Callback function. + * @returns {Promise} */ - var auth0RestClient = new Auth0RestClient( - options.baseUrl + '/tickets/:type', - clientOptions, - options.tokenProvider - ); - this.resource = new RetryRestClient(auth0RestClient, options.retry); -}; + changePassword(data, cb) { + const params = { type: 'password-change' }; -/** - * Create a new password change ticket. - * - * @method changePassword - * @memberOf module:management.TicketsManager.prototype - * - * @example - * var params = { - * result_url: '{REDIRECT_URL}', // Redirect after using the ticket. - * user_id: '{USER_ID}', // Optional. - * email: '{USER_EMAIL}', // Optional. - * new_password: '{PASSWORD}' - * }; - * - * management.tickets.changePassword(params, function (err) { - * if (err) { - * // Handle error. - * } - * }); - * - * @param {Object} data - * @param {String} [data.result_url] URL the user will be redirected to once ticket is used. - * @param {String} [data.user_id] user_id for whom the ticket should be created. (Conflicts with: connection_id, email) - * @param {String} [data.client_id] ID of the client. - * @param {String} [data.organization_id] ID of the organization. - * @param {String} [data.connection_id] ID of the connection. - * @param {Integer} [data.ttl_sec] Number of seconds for which the ticket is valid before expiration. - * @param {String} [data.email] Email of the user. (Requires: connection_id) - * @param {Boolean} [data.mark_email_as_verified] Whether to set the email_verified attribute to true (true) or whether it should not be updated (false). - * @param {Boolean} [data.includeEmailInRedirect] Whether to include the email address as part of the returnUrl in the reset_email (true), or not (false). - * @param {Function} [cb] Callback function. - * @return {Promise} - */ -TicketsManager.prototype.changePassword = function(data, cb) { - var params = { type: 'password-change' }; + if (cb && cb instanceof Function) { + return this.resource.create(params, data, cb); + } - if (cb && cb instanceof Function) { - return this.resource.create(params, data, cb); + // Return a promise. + return this.resource.create(params, data); } - // Return a promise. - return this.resource.create(params, data); -}; + /** + * Create an email verification ticket. + * + * @example + * var data = { + * user_id: '{USER_ID}', + * result_url: '{REDIRECT_URL}' // Optional redirect after the ticket is used. + * }; + * + * management.tickets.verifyEmail(data, function (err) { + * if (err) { + * // Handle error. + * } + * }); + * @param {object} data + * @param {string} [data.result_url] URL the user will be redirected to once ticket is used. + * @param {string} data.user_id user_id for whom the ticket should be created. + * @param {Integer} [data.ttl_sec] Number of seconds for which the ticket is valid before expiration. + * @param {boolean} [data.includeEmailInRedirect] Whether to include the email address as part of the result_url (true), or not (false). + * @param {object} [data.identity] Used to verify secondary, federated, and passwordless-email identities. + * @param {string} data.identity.user_id user_id of the identity. + * @param {string} data.identity.provider provider of the identity. + * @param {string} [data.client_id] client ID. + * @param {string} [data.organization_id] organization ID. + * @param {Function} [cb] Callback function. + * @returns {Promise} + */ + verifyEmail(data, cb) { + const params = { type: 'email-verification' }; -/** - * Create an email verification ticket. - * - * @method verifyEmail - * @memberOf module:management.TicketsManager.prototype - * - * @example - * var data = { - * user_id: '{USER_ID}', - * result_url: '{REDIRECT_URL}' // Optional redirect after the ticket is used. - * }; - * - * management.tickets.verifyEmail(data, function (err) { - * if (err) { - * // Handle error. - * } - * }); - * - * @param {Object} data - * @param {String} [data.result_url] URL the user will be redirected to once ticket is used. - * @param {String} data.user_id user_id for whom the ticket should be created. - * @param {Integer} [data.ttl_sec] Number of seconds for which the ticket is valid before expiration. - * @param {Boolean} [data.includeEmailInRedirect] Whether to include the email address as part of the result_url (true), or not (false). - * @param {Object} [data.identity] Used to verify secondary, federated, and passwordless-email identities. - * @param {String} data.identity.user_id user_id of the identity. - * @param {String} data.identity.provider provider of the identity. - * @param {String} [data.client_id] client ID. - * @param {String} [data.organization_id] organization ID. - * @param {Function} [cb] Callback function. - * @return {Promise} - */ -TicketsManager.prototype.verifyEmail = function(data, cb) { - var params = { type: 'email-verification' }; + if (cb && cb instanceof Function) { + return this.resource.create(params, data, cb); + } - if (cb && cb instanceof Function) { - return this.resource.create(params, data, cb); + // Return a promise. + return this.resource.create(params, data); } - - // Return a promise. - return this.resource.create(params, data); -}; +} module.exports = TicketsManager; diff --git a/src/management/UserBlocksManager.js b/src/management/UserBlocksManager.js index ae338c06f..1636ef3b7 100644 --- a/src/management/UserBlocksManager.js +++ b/src/management/UserBlocksManager.js @@ -1,178 +1,166 @@ -var ArgumentError = require('rest-facade').ArgumentError; -var Auth0RestClient = require('../Auth0RestClient'); -var RetryRestClient = require('../RetryRestClient'); +const { ArgumentError } = require('rest-facade'); +const Auth0RestClient = require('../Auth0RestClient'); +const RetryRestClient = require('../RetryRestClient'); /** * Simple facade for consuming a REST API endpoint. + * * @external RestClient * @see https://github.com/ngonzalvez/rest-facade */ /** - * @class * Abstracts interaction with the user-blocks endpoint. - * @constructor - * @memberOf module:management - * - * @param {Object} options The client options. - * @param {String} options.baseUrl The URL of the API. - * @param {Object} [options.headers] Headers to be included in all requests. - * @param {Object} [options.retry] Retry Policy Config */ -var UserBlocksManager = function(options) { - if (options === null || typeof options !== 'object') { - throw new ArgumentError('Must provide manager options'); - } +class UserBlocksManager { + /** + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config + */ + constructor(options) { + if (options === null || typeof options !== 'object') { + throw new ArgumentError('Must provide manager options'); + } + + if (options.baseUrl === null || options.baseUrl === undefined) { + throw new ArgumentError('Must provide a base URL for the API'); + } + + if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { + throw new ArgumentError('The provided base URL is invalid'); + } + + const clientOptions = { + errorFormatter: { message: 'message', name: 'error' }, + headers: options.headers, + query: { repeatParams: false }, + }; + + const userBlocksByIdResource = new Auth0RestClient( + `${options.baseUrl}/user-blocks/:id`, + clientOptions, + options.tokenProvider + ); + this.userBlocksById = new RetryRestClient(userBlocksByIdResource, options.retry); - if (options.baseUrl === null || options.baseUrl === undefined) { - throw new ArgumentError('Must provide a base URL for the API'); + const userBlocksByIdentifierResource = new Auth0RestClient( + `${options.baseUrl}/user-blocks`, + clientOptions, + options.tokenProvider + ); + this.userBlocksByIdentifier = new RetryRestClient( + userBlocksByIdentifierResource, + options.retry + ); } - if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { - throw new ArgumentError('The provided base URL is invalid'); + /** + * Get user blocks by id. + * + * @function get + * @memberof module:management.UserBlocksManager.prototype + * @example + * management.userBlocks.get({ id: USER_ID }, function (err, blocks) { + * if (err) { + * // Handle error. + * } + * + * console.log(blocks); + * }); + * @param {object} params The user data object.. + * @param {string} params.id The user id. + * @param {Function} [cb] Callback function + * @returns {Promise|undefined} + */ + get(params, ...restOfArgs) { + if (typeof params !== 'object' || typeof params.id !== 'string') { + throw new ArgumentError('You must provide an user id for the get method'); + } + + return this.userBlocksById.get(params, ...restOfArgs); } - var clientOptions = { - errorFormatter: { message: 'message', name: 'error' }, - headers: options.headers, - query: { repeatParams: false } - }; - - var userBlocksByIdResource = new Auth0RestClient( - options.baseUrl + '/user-blocks/:id', - clientOptions, - options.tokenProvider - ); - this.userBlocksById = new RetryRestClient(userBlocksByIdResource, options.retry); - - var userBlocksByIdentifierResource = new Auth0RestClient( - options.baseUrl + '/user-blocks', - clientOptions, - options.tokenProvider - ); - this.userBlocksByIdentifier = new RetryRestClient(userBlocksByIdentifierResource, options.retry); -}; - -/** - * Get user blocks by id. - * - * @method get - * @memberOf module:management.UserBlocksManager.prototype - * - * @example - * management.userBlocks.get({ id: USER_ID }, function (err, blocks) { - * if (err) { - * // Handle error. - * } - * - * console.log(blocks); - * }); - * - * - * @param {Object} params The user data object.. - * @param {String} params.id The user id. - * @param {Function} [cb] Callback function - * - * @return {Promise|undefined} - */ -UserBlocksManager.prototype.get = function(params) { - if (typeof params !== 'object' || typeof params.id !== 'string') { - throw new ArgumentError('You must provide an user id for the get method'); - } - - return this.userBlocksById.get.apply(this.userBlocksById, arguments); -}; - -/** - * Unblock an user by its id. - * - * @method delete - * @memberOf module:management.UserBlocksManager.prototype - * - * @example - * management.userBlocks.delete({ id: USER_ID }, function (err) { - * if (err) { - * // Handle error. - * } - * - * // User unblocked. - * }); - * - * - * @param {Object} params The user data object.. - * @param {String} params.id The user id. - * @param {Function} [cb] Callback function - * - * @return {Promise|undefined} - */ -UserBlocksManager.prototype.delete = function(params) { - if (typeof params !== 'object' || typeof params.id !== 'string') { - throw new ArgumentError('You must provide an user id for the delete method'); + /** + * Unblock an user by its id. + * + * @function delete + * @memberof module:management.UserBlocksManager.prototype + * @example + * management.userBlocks.delete({ id: USER_ID }, function (err) { + * if (err) { + * // Handle error. + * } + * + * // User unblocked. + * }); + * @param {object} params The user data object.. + * @param {string} params.id The user id. + * @param {Function} [cb] Callback function + * @returns {Promise|undefined} + */ + delete(params, ...restOfArgs) { + if (typeof params !== 'object' || typeof params.id !== 'string') { + throw new ArgumentError('You must provide an user id for the delete method'); + } + + return this.userBlocksById.delete(params, ...restOfArgs); } - return this.userBlocksById.delete.apply(this.userBlocksById, arguments); -}; - -/** - * Get user blocks by identifier. - * - * @method getByIdentifier - * @memberOf module:management.UserBlocksManager.prototype - * - * @example - * management.userBlocks.getByIdentifier({ identifier: USER_ID }, function (err, blocks) { - * if (err) { - * // Handle error. - * } - * - * console.log(blocks); - * }); - * - * - * @param {Object} params The user data object.. - * @param {String} params.identifier The user identifier, any of: username, phone_number, email. - * @param {Function} [cb] Callback function - * - * @return {Promise|undefined} - */ -UserBlocksManager.prototype.getByIdentifier = function(params) { - if (typeof params !== 'object' || typeof params.identifier !== 'string') { - throw new ArgumentError('You must provide an user identifier for the getByIdentifier method'); + /** + * Get user blocks by identifier. + * + * @function getByIdentifier + * @memberof module:management.UserBlocksManager.prototype + * @example + * management.userBlocks.getByIdentifier({ identifier: USER_ID }, function (err, blocks) { + * if (err) { + * // Handle error. + * } + * + * console.log(blocks); + * }); + * @param {object} params The user data object.. + * @param {string} params.identifier The user identifier, any of: username, phone_number, email. + * @param {Function} [cb] Callback function + * @returns {Promise|undefined} + */ + getByIdentifier(params, ...restOfArgs) { + if (typeof params !== 'object' || typeof params.identifier !== 'string') { + throw new ArgumentError('You must provide an user identifier for the getByIdentifier method'); + } + + return this.userBlocksByIdentifier.get(params, ...restOfArgs); } - return this.userBlocksByIdentifier.get.apply(this.userBlocksByIdentifier, arguments); -}; - -/** - * Unblock an user by identifier. - * - * @method deleteByIdentifier - * @memberOf module:management.UserBlocksManager.prototype - * - * @example - * management.userBlocks.deleteByIdentifier({ identifier: USER_ID }, function (err) { - * if (err) { - * // Handle error. - * } - * - * // User unblocked. - * }); - * - * - * @param {Object} params The user data object.. - * @param {String} params.identifier The user identifier, any of: username, phone_number, email. - * @param {Function} [cb] Callback function - * - * @return {Promise|undefined} - */ -UserBlocksManager.prototype.deleteByIdentifier = function(params) { - if (typeof params !== 'object' || typeof params.identifier !== 'string') { - throw new ArgumentError( - 'You must provide an user identifier for the deleteByIdentifier method' - ); + /** + * Unblock an user by identifier. + * + * @function deleteByIdentifier + * @memberof module:management.UserBlocksManager.prototype + * @example + * management.userBlocks.deleteByIdentifier({ identifier: USER_ID }, function (err) { + * if (err) { + * // Handle error. + * } + * + * // User unblocked. + * }); + * @param {object} params The user data object.. + * @param {string} params.identifier The user identifier, any of: username, phone_number, email. + * @param {Function} [cb] Callback function + * @returns {Promise|undefined} + */ + deleteByIdentifier(params, ...restOfArgs) { + if (typeof params !== 'object' || typeof params.identifier !== 'string') { + throw new ArgumentError( + 'You must provide an user identifier for the deleteByIdentifier method' + ); + } + + return this.userBlocksByIdentifier.delete(params, ...restOfArgs); } - - return this.userBlocksByIdentifier.delete.apply(this.userBlocksByIdentifier, arguments); -}; +} module.exports = UserBlocksManager; diff --git a/src/management/UsersManager.js b/src/management/UsersManager.js index 967509f42..aee680909 100644 --- a/src/management/UsersManager.js +++ b/src/management/UsersManager.js @@ -1,960 +1,841 @@ -var ArgumentError = require('rest-facade').ArgumentError; -var Auth0RestClient = require('../Auth0RestClient'); -var RetryRestClient = require('../RetryRestClient'); -var sanitizeArguments = require('../utils').sanitizeArguments; +const { ArgumentError } = require('rest-facade'); +const Auth0RestClient = require('../Auth0RestClient'); +const RetryRestClient = require('../RetryRestClient'); +const { sanitizeArguments } = require('../utils'); /** - * Simple facade for consuming a REST API endpoint. - * @external RestClient - * @see https://github.com/ngonzalvez/rest-facade - */ - -/** - * @class * Abstracts interaction with the users endpoint. - * @constructor - * @memberOf module:management - * - * @param {Object} options The client options. - * @param {String} options.baseUrl The URL of the API. - * @param {Object} [options.headers] Headers to be included in all requests. - * @param {Object} [options.retry] Retry Policy Config */ -var UsersManager = function(options) { - if (options === null || typeof options !== 'object') { - throw new ArgumentError('Must provide manager options'); - } - - if (options.baseUrl === null || options.baseUrl === undefined) { - throw new ArgumentError('Must provide a base URL for the API'); - } - - if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { - throw new ArgumentError('The provided base URL is invalid'); - } - - var clientOptions = { - errorFormatter: { message: 'message', name: 'error' }, - headers: options.headers, - query: { repeatParams: false } - }; - - var usersAuth0RestClient = new Auth0RestClient( - options.baseUrl + '/users/:id', - clientOptions, - options.tokenProvider - ); - this.users = new RetryRestClient(usersAuth0RestClient, options.retry); - +class UsersManager { /** - * Provides an abstraction layer for consuming the - * {@link https://auth0.com/docs/api/v2#!/Users/delete_multifactor_by_provider - * Multifactor Provider endpoint}. - * - * @type {external:RestClient} + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config */ - var multifactorAuth0RestClient = new Auth0RestClient( - options.baseUrl + '/users/:id/multifactor/:provider', - clientOptions, - options.tokenProvider - ); - this.multifactor = new RetryRestClient(multifactorAuth0RestClient, options.retry); + constructor(options) { + if (options === null || typeof options !== 'object') { + throw new ArgumentError('Must provide manager options'); + } + + if (options.baseUrl === null || options.baseUrl === undefined) { + throw new ArgumentError('Must provide a base URL for the API'); + } + + if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { + throw new ArgumentError('The provided base URL is invalid'); + } + + const clientOptions = { + errorFormatter: { message: 'message', name: 'error' }, + headers: options.headers, + query: { repeatParams: false }, + }; + + const usersAuth0RestClient = new Auth0RestClient( + `${options.baseUrl}/users/:id`, + clientOptions, + options.tokenProvider + ); + this.users = new RetryRestClient(usersAuth0RestClient, options.retry); + + /** + * Provides an abstraction layer for consuming the + * {@link https://auth0.com/docs/api/v2#!/Users/delete_multifactor_by_provider + * Multifactor Provider endpoint}. + * + * @type {external:RestClient} + */ + const multifactorAuth0RestClient = new Auth0RestClient( + `${options.baseUrl}/users/:id/multifactor/:provider`, + clientOptions, + options.tokenProvider + ); + this.multifactor = new RetryRestClient(multifactorAuth0RestClient, options.retry); + + /** + * Provides a simple abstraction layer for linking user accounts. + * + * @type {external:RestClient} + */ + const identitiesAuth0RestClient = new Auth0RestClient( + `${options.baseUrl}/users/:id/identities/:provider/:user_id`, + clientOptions, + options.tokenProvider + ); + this.identities = new RetryRestClient(identitiesAuth0RestClient, options.retry); + + /** + * Provides a simple abstraction layer for user logs + * + * @type {external:RestClient} + */ + const userLogsAuth0RestClient = new Auth0RestClient( + `${options.baseUrl}/users/:id/logs`, + clientOptions, + options.tokenProvider + ); + this.userLogs = new RetryRestClient(userLogsAuth0RestClient, options.retry); + + /** + * Provides an abstraction layer for retrieving Guardian enrollments. + * + * @type {external:RestClient} + */ + const enrollmentsAuth0RestClient = new Auth0RestClient( + `${options.baseUrl}/users/:id/enrollments`, + clientOptions, + options.tokenProvider + ); + this.enrollments = new RetryRestClient(enrollmentsAuth0RestClient, options.retry); + + /** + * Provides an abstraction layer for the new "users-by-email" API + * + * @type {external:RestClient} + */ + const usersByEmailClient = new Auth0RestClient( + `${options.baseUrl}/users-by-email`, + clientOptions, + options.tokenProvider + ); + this.usersByEmail = new RetryRestClient(usersByEmailClient, options.retry); + + /** + * Provides an abstraction layer for regenerating Guardian recovery codes. + * + * @type {external:RestClient} + */ + const recoveryCodeRegenerationAuth0RestClients = new Auth0RestClient( + `${options.baseUrl}/users/:id/recovery-code-regeneration`, + clientOptions, + options.tokenProvider + ); + this.recoveryCodeRegenerations = new RetryRestClient( + recoveryCodeRegenerationAuth0RestClients, + options.retry + ); + + /** + * Provides an abstraction layer for invalidating all remembered browsers for MFA. + * + * @type {external:RestClient} + */ + const invalidateRememberBrowserAuth0RestClients = new Auth0RestClient( + `${options.baseUrl}/users/:id/multifactor/actions/invalidate-remember-browser`, + clientOptions, + options.tokenProvider + ); + this.invalidateRememberBrowsers = new RetryRestClient( + invalidateRememberBrowserAuth0RestClients, + options.retry + ); + + /** + * Provides an abstraction layer for CRD on roles for a user + * + * @type {external:RestClient} + */ + const userRolesClient = new Auth0RestClient( + `${options.baseUrl}/users/:id/roles`, + clientOptions, + options.tokenProvider + ); + this.roles = new RetryRestClient(userRolesClient, options.retry); + + /** + * Provides an abstraction layer for CRD on permissions directly on a user + * + * @type {external:RestClient} + */ + const userPermissionsClient = new Auth0RestClient( + `${options.baseUrl}/users/:id/permissions`, + clientOptions, + options.tokenProvider + ); + this.permissions = new RetryRestClient(userPermissionsClient, options.retry); + + const organizationsClient = new Auth0RestClient( + `${options.baseUrl}/users/:id/organizations`, + clientOptions, + options.tokenProvider + ); + this.organizations = new RetryRestClient(organizationsClient, options.retry); + } /** - * Provides a simple abstraction layer for linking user accounts. + * Create a new user. * - * @type {external:RestClient} - */ - var identitiesAuth0RestClient = new Auth0RestClient( - options.baseUrl + '/users/:id/identities/:provider/:user_id', - clientOptions, - options.tokenProvider - ); - this.identities = new RetryRestClient(identitiesAuth0RestClient, options.retry); - - /** - * Provides a simple abstraction layer for user logs + * @example + * management.users.create(data, function (err) { + * if (err) { + * // Handle error. + * } * - * @type {external:RestClient} + * // User created. + * }); + * @param {object} data User data. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - var userLogsAuth0RestClient = new Auth0RestClient( - options.baseUrl + '/users/:id/logs', - clientOptions, - options.tokenProvider - ); - this.userLogs = new RetryRestClient(userLogsAuth0RestClient, options.retry); + create(data, cb) { + if (cb && cb instanceof Function) { + return this.users.create(data, cb); + } - /** - * Provides an abstraction layer for retrieving Guardian enrollments. - * - * @type {external:RestClient} - */ - var enrollmentsAuth0RestClient = new Auth0RestClient( - options.baseUrl + '/users/:id/enrollments', - clientOptions, - options.tokenProvider - ); - this.enrollments = new RetryRestClient(enrollmentsAuth0RestClient, options.retry); + return this.users.create(data); + } /** - * Provides an abstraction layer for the new "users-by-email" API + * Get all users. + * + * @example + * This method takes an optional object as first argument that may be used to + * @param {...any} args + * specify pagination settings and the search query. If pagination options are + * not present, the first page of a limited number of results will be returned. + * + * + * // Pagination settings. + * var params = { + * per_page: 10, + * page: 0 + * }; * - * @type {external:RestClient} + * management.users.getAll(params, function (err, users) { + * console.log(users.length); + * }); + * @param {object} [params] Users params. + * @param {number} [params.per_page] Number of results per page. + * @param {number} [params.page] Page number, zero indexed. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - var usersByEmailClient = new Auth0RestClient( - options.baseUrl + '/users-by-email', - clientOptions, - options.tokenProvider - ); - this.usersByEmail = new RetryRestClient(usersByEmailClient, options.retry); + getAll(...args) { + return this.users.getAll(...args); + } /** - * Provides an abstraction layer for regenerating Guardian recovery codes. + * Get Users by an Email Address + * + * @example + * This method takes a first argument as the Email address to look for + * users, and uses the /users-by-email API, not the search API + * * - * @type {external:RestClient} + * management.users.getByEmail('email@address', function (err, users) { + * console.log(users); + * }); + * @param {string} [email] Email address of user(s) to find + * @param {object} [options] Additional options to pass to the endpoint + * @param {string} [options.fields] Comma-separated list of fields to include or exclude in the result + * @param {boolean} [options.include_fields] Whether specified fields are to be included (true) or excluded (false). Defaults to true. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - var recoveryCodeRegenerationAuth0RestClients = new Auth0RestClient( - options.baseUrl + '/users/:id/recovery-code-regeneration', - clientOptions, - options.tokenProvider - ); - this.recoveryCodeRegenerations = new RetryRestClient( - recoveryCodeRegenerationAuth0RestClients, - options.retry - ); + getByEmail(email, options, cb) { + const { options: sanitizedOptions, cb: sanitizedCb } = sanitizeArguments(options, cb); + + return this.usersByEmail.getAll({ email, ...sanitizedOptions }, sanitizedCb); + } /** - * Provides an abstraction layer for invalidating all remembered browsers for MFA. + * Get a user by its id. * - * @type {external:RestClient} + * @example + * @param {...any} args + * management.users.get({ id: USER_ID }, function (err, user) { + * console.log(user); + * }); + * @param {object} data The user data object. + * @param {string} data.id The user id. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - var invalidateRememberBrowserAuth0RestClients = new Auth0RestClient( - options.baseUrl + '/users/:id/multifactor/actions/invalidate-remember-browser', - clientOptions, - options.tokenProvider - ); - this.invalidateRememberBrowsers = new RetryRestClient( - invalidateRememberBrowserAuth0RestClients, - options.retry - ); + get(...args) { + return this.users.get(...args); + } /** - * Provides an abstraction layer for CRD on roles for a user + * Update a user by its id. + * + * @example + * var params = { id: USER_ID }; + * @param {...any} args * - * @type {external:RestClient} + * management.users.update(params, data, function (err, user) { + * if (err) { + * // Handle error. + * } + * + * // Updated user. + * console.log(user); + * }); + * @param {object} params The user parameters. + * @param {string} params.id The user id. + * @param {object} data New user data. + * @param {Function} [cb] Callback function + * @returns {Promise|undefined} */ - var userRolesClient = new Auth0RestClient( - options.baseUrl + '/users/:id/roles', - clientOptions, - options.tokenProvider - ); - this.roles = new RetryRestClient(userRolesClient, options.retry); + update(...args) { + return this.users.patch(...args); + } /** - * Provides an abstraction layer for CRD on permissions directly on a user + * Update the user metadata. + * + * @example + * var params = { id: USER_ID }; + * var metadata = { + * address: '123th Node.js Street' + * }; * - * @type {external:RestClient} + * management.users.updateUserMetadata(params, metadata, function (err, user) { + * if (err) { + * // Handle error. + * } + * + * // Updated user. + * console.log(user); + * }); + * @param {object} params The user data object.. + * @param {string} params.id The user id. + * @param {object} metadata New user metadata. + * @param {Function} [cb] Callback function + * @returns {Promise|undefined} */ - var userPermissionsClient = new Auth0RestClient( - options.baseUrl + '/users/:id/permissions', - clientOptions, - options.tokenProvider - ); - this.permissions = new RetryRestClient(userPermissionsClient, options.retry); - - var organizationsClient = new Auth0RestClient( - options.baseUrl + '/users/:id/organizations', - clientOptions, - options.tokenProvider - ); - this.organizations = new RetryRestClient(organizationsClient, options.retry); -}; - -/** - * Create a new user. - * - * @method create - * @memberOf module:management.UsersManager.prototype - * - * @example - * management.users.create(data, function (err) { - * if (err) { - * // Handle error. - * } - * - * // User created. - * }); - * - * @param {Object} data User data. - * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} - */ -UsersManager.prototype.create = function(data, cb) { - if (cb && cb instanceof Function) { - return this.users.create(data, cb); - } - - return this.users.create(data); -}; - -/** - * Get all users. - * - * @method getAll - * @memberOf module:management.UsersManager.prototype - * - * @example - * This method takes an optional object as first argument that may be used to - * specify pagination settings and the search query. If pagination options are - * not present, the first page of a limited number of results will be returned. - * - * - * // Pagination settings. - * var params = { - * per_page: 10, - * page: 0 - * }; - * - * management.users.getAll(params, function (err, users) { - * console.log(users.length); - * }); - * - * @param {Object} [params] Users params. - * @param {Number} [params.per_page] Number of results per page. - * @param {Number} [params.page] Page number, zero indexed. - * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} - */ -UsersManager.prototype.getAll = function(params) { - return this.users.getAll.apply(this.users, arguments); -}; - -/** - * Get Users by an Email Address - * - * @method getByEmail - * @memberOf module:management.UsersManager.prototype - * - * @example - * This method takes a first argument as the Email address to look for - * users, and uses the /users-by-email API, not the search API - * - * - * management.users.getByEmail('email@address', function (err, users) { - * console.log(users); - * }); - * - * @param {String} [email] Email address of user(s) to find - * @param {Object} [options] Additional options to pass to the endpoint - * @param {String} [options.fields] Comma-separated list of fields to include or exclude in the result - * @param {Boolean} [options.include_fields] Whether specified fields are to be included (true) or excluded (false). Defaults to true. - * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} - */ -UsersManager.prototype.getByEmail = function(email, options, cb) { - var { options, cb } = sanitizeArguments(options, cb); - - return this.usersByEmail.getAll({ email, ...options }, cb); -}; + updateUserMetadata(params, metadata, cb) { + const data = { + user_metadata: metadata, + }; -/** - * Get a user by its id. - * - * @method get - * @memberOf module:management.UsersManager.prototype - * - * @example - * management.users.get({ id: USER_ID }, function (err, user) { - * console.log(user); - * }); - * - * @param {Object} data The user data object. - * @param {String} data.id The user id. - * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} - */ -UsersManager.prototype.get = function() { - return this.users.get.apply(this.users, arguments); -}; - -/** - * Update a user by its id. - * - * @method update - * @memberOf module:management.UsersManager.prototype - * - * @example - * var params = { id: USER_ID }; - * - * management.users.update(params, data, function (err, user) { - * if (err) { - * // Handle error. - * } - * - * // Updated user. - * console.log(user); - * }); - * - * @param {Object} params The user parameters. - * @param {String} params.id The user id. - * @param {Object} data New user data. - * @param {Function} [cb] Callback function - * - * @return {Promise|undefined} - */ -UsersManager.prototype.update = function() { - return this.users.patch.apply(this.users, arguments); -}; + if (cb && cb instanceof Function) { + return this.users.patch(params, data, cb); + } -/** - * Update the user metadata. - * - * @method updateUserMetadata - * @memberOf module:management.UsersManager.prototype - * - * @example - * var params = { id: USER_ID }; - * var metadata = { - * address: '123th Node.js Street' - * }; - * - * management.users.updateUserMetadata(params, metadata, function (err, user) { - * if (err) { - * // Handle error. - * } - * - * // Updated user. - * console.log(user); - * }); - * - * @param {Object} params The user data object.. - * @param {String} params.id The user id. - * @param {Object} metadata New user metadata. - * @param {Function} [cb] Callback function - * - * @return {Promise|undefined} - */ -UsersManager.prototype.updateUserMetadata = function(params, metadata, cb) { - var data = { - user_metadata: metadata - }; - - if (cb && cb instanceof Function) { - return this.users.patch(params, data, cb); + return this.users.patch(params, data); } - return this.users.patch(params, data); -}; + /** + * Update the app metadata. + * + * @example + * var params = { id: USER_ID }; + * var metadata = { + * foo: 'bar' + * }; + * + * management.users.updateAppMetadata(params, metadata, function (err, user) { + * if (err) { + * // Handle error. + * } + * + * // Updated user. + * console.log(user); + * }); + * @param {object} params The user data object.. + * @param {string} params.id The user id. + * @param {object} metadata New app metadata. + * @param {Function} [cb] Callback function + * @returns {Promise|undefined} + */ + updateAppMetadata(params, metadata, cb) { + const data = { + app_metadata: metadata, + }; -/** - * Update the app metadata. - * - * @method updateAppMetadata - * @memberOf module:management.UsersManager.prototype - * - * @example - * var params = { id: USER_ID }; - * var metadata = { - * foo: 'bar' - * }; - * - * management.users.updateAppMetadata(params, metadata, function (err, user) { - * if (err) { - * // Handle error. - * } - * - * // Updated user. - * console.log(user); - * }); - * - * @param {Object} params The user data object.. - * @param {String} params.id The user id. - * @param {Object} metadata New app metadata. - * @param {Function} [cb] Callback function - * - * @return {Promise|undefined} - */ -UsersManager.prototype.updateAppMetadata = function(params, metadata, cb) { - var data = { - app_metadata: metadata - }; + if (cb && cb instanceof Function) { + return this.users.patch(params, data, cb); + } - if (cb && cb instanceof Function) { - return this.users.patch(params, data, cb); + return this.users.patch(params, data); } - return this.users.patch(params, data); -}; + /** + * Delete a user by its id. + * + * @example + * management.users.delete({ id: USER_ID }, function (err) { + * if (err) { + * // Handle error. + * } + * + * // User deleted. + * }); + * @param {object} params The user data object.. + * @param {string} params.id The user id. + * @param {Function} [cb] Callback function + * @returns {Promise|undefined} + */ + delete(params, ...restOfArgs) { + if (typeof params !== 'object' || typeof params.id !== 'string') { + throw new ArgumentError('You must provide an id for the delete method'); + } -/** - * Delete a user by its id. - * - * @method delete - * @memberOf module:management.UsersManager.prototype - * - * @example - * management.users.delete({ id: USER_ID }, function (err) { - * if (err) { - * // Handle error. - * } - * - * // User deleted. - * }); - * - * - * @param {Object} params The user data object.. - * @param {String} params.id The user id. - * @param {Function} [cb] Callback function - * - * @return {Promise|undefined} - */ -UsersManager.prototype.delete = function(params) { - if (typeof params !== 'object' || typeof params.id !== 'string') { - throw new ArgumentError('You must provide an id for the delete method'); + return this.users.delete(params, ...restOfArgs); } - return this.users.delete.apply(this.users, arguments); -}; + /** + * Delete all users. + * + * @example + * management.users.deleteAll(function (err) { + * if (err) { + * // Handle error. + * } + * + * // Users deleted + * }); + * @param {Function} [cb] Callback function + * @returns {Promise|undefined} + * @deprecated This method will be removed in the next major release. + */ + deleteAll(cb, ...restOfArgs) { + if (typeof cb !== 'function') { + const errorMsg = 'The deleteAll method only accepts a callback as argument'; -/** - * Delete all users. - * - * @method deleteAll - * @memberOf module:management.UsersManager.prototype - * - * @example - * management.users.deleteAll(function (err) { - * if (err) { - * // Handle error. - * } - * - * // Users deleted - * }); - * - * @param {Function} [cb] Callback function - * - * @return {Promise|undefined} - * - * @deprecated This method will be removed in the next major release. - */ -UsersManager.prototype.deleteAll = function(cb) { - if (typeof cb !== 'function') { - var errorMsg = 'The deleteAll method only accepts a callback as argument'; + throw new ArgumentError(errorMsg); + } - throw new ArgumentError(errorMsg); + return this.users.delete(cb, ...restOfArgs); } - return this.users.delete.apply(this.users, arguments); -}; + /** + * Delete a multifactor provider. + * + * @example + * var params = { id: USER_ID, provider: MULTIFACTOR_PROVIDER }; + * + * management.users.deleteMultifactorProvider(params, function (err, user) { + * if (err) { + * // Handle error. + * } + * + * // Users accounts unlinked. + * }); + * @param {object} params Data object. + * @param {string} params.id The user id. + * @param {string} params.provider Multifactor provider. + * @param {Function} [cb] Callback function + * @returns {Promise|undefined} + */ + deleteMultifactorProvider(params, cb) { + params = params || {}; -/** - * Delete a multifactor provider. - * - * @method deleteMultifactorProvider - * @memberOf module:management.UsersManager.prototype - * - * @example - * var params = { id: USER_ID, provider: MULTIFACTOR_PROVIDER }; - * - * management.users.deleteMultifactorProvider(params, function (err, user) { - * if (err) { - * // Handle error. - * } - * - * // Users accounts unlinked. - * }); - * - * @param {Object} params Data object. - * @param {String} params.id The user id. - * @param {String} params.provider Multifactor provider. - * @param {Function} [cb] Callback function - * - * @return {Promise|undefined} - */ -UsersManager.prototype.deleteMultifactorProvider = function(params, cb) { - params = params || {}; + if (!params.id || typeof params.id !== 'string') { + throw new ArgumentError('The id parameter must be a valid user id'); + } - if (!params.id || typeof params.id !== 'string') { - throw new ArgumentError('The id parameter must be a valid user id'); - } + if (!params.provider || typeof params.provider !== 'string') { + throw new ArgumentError('Must specify a provider'); + } - if (!params.provider || typeof params.provider !== 'string') { - throw new ArgumentError('Must specify a provider'); - } + if (cb && cb instanceof Function) { + return this.multifactor.delete(params, cb); + } - if (cb && cb instanceof Function) { - return this.multifactor.delete(params, cb); + return this.multifactor.delete(params); } - return this.multifactor.delete(params); -}; + /** + * Link the user with another account. + * + * @example + * var userId = 'USER_ID'; + * var params = { + * user_id: 'OTHER_USER_ID', + * connection_id: 'CONNECTION_ID' + * }; + * + * management.users.link(userId, params, function (err, user) { + * if (err) { + * // Handle error. + * } + * + * // Users linked. + * }); + * @param {string} userId ID of the primary user. + * @param {object} params Secondary user data. + * @param {string} params.user_id ID of the user to be linked. + * @param {string} params.connection_id ID of the connection to be used. + * @param {string} params.provider Identity provider of the secondary user account being linked. + * @param {string} params.link_with JWT for the secondary account being linked. If sending this parameter, provider, user_id, and connection_id must not be sent. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + link(userId, params, cb) { + const query = { id: userId }; + params = params || {}; -/** - * Link the user with another account. - * - * @method link - * @memberOf module:management.UsersManager.prototype - * - * @example - * var userId = 'USER_ID'; - * var params = { - * user_id: 'OTHER_USER_ID', - * connection_id: 'CONNECTION_ID' - * }; - * - * management.users.link(userId, params, function (err, user) { - * if (err) { - * // Handle error. - * } - * - * // Users linked. - * }); - * - * @param {String} userId ID of the primary user. - * @param {Object} params Secondary user data. - * @param {String} params.user_id ID of the user to be linked. - * @param {String} params.connection_id ID of the connection to be used. - * @param {String} params.provider Identity provider of the secondary user account being linked. - * @param {String} params.link_with JWT for the secondary account being linked. If sending this parameter, provider, user_id, and connection_id must not be sent. - * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} - */ -UsersManager.prototype.link = function(userId, params, cb) { - var query = { id: userId }; - params = params || {}; + // Require a user ID. + if (!userId) { + throw new ArgumentError('The userId cannot be null or undefined'); + } + if (typeof userId !== 'string') { + throw new ArgumentError('The userId has to be a string'); + } - // Require a user ID. - if (!userId) { - throw new ArgumentError('The userId cannot be null or undefined'); - } - if (typeof userId !== 'string') { - throw new ArgumentError('The userId has to be a string'); - } + if (cb && cb instanceof Function) { + return this.identities.create(query, params, cb); + } - if (cb && cb instanceof Function) { - return this.identities.create(query, params, cb); + return this.identities.create(query, params); } - return this.identities.create(query, params); -}; + /** + * Unlink the given accounts. + * + * @example + * var params = { id: USER_ID, provider: 'auht0', user_id: OTHER_USER_ID }; + * + * management.users.unlink(params, function (err, user) { + * if (err) { + * // Handle error. + * } + * + * // Users accounts unlinked. + * }); + * @param {object} params Linked users data. + * @param {string} params.id Primary user ID. + * @param {string} params.provider Identity provider in use. + * @param {string} params.user_id Secondary user ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + unlink(params, cb) { + params = params || {}; -/** - * Unlink the given accounts. - * - * @method unlink - * @memberOf module:management.UsersManager.prototype - * - * @example - * var params = { id: USER_ID, provider: 'auht0', user_id: OTHER_USER_ID }; - * - * management.users.unlink(params, function (err, user) { - * if (err) { - * // Handle error. - * } - * - * // Users accounts unlinked. - * }); - * - * @param {Object} params Linked users data. - * @param {String} params.id Primary user ID. - * @param {String} params.provider Identity provider in use. - * @param {String} params.user_id Secondary user ID. - * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} - */ -UsersManager.prototype.unlink = function(params, cb) { - params = params || {}; + if (!params.id || typeof params.id !== 'string') { + throw new ArgumentError('id field is required'); + } - if (!params.id || typeof params.id !== 'string') { - throw new ArgumentError('id field is required'); - } + if (!params.user_id || typeof params.user_id !== 'string') { + throw new ArgumentError('user_id field is required'); + } - if (!params.user_id || typeof params.user_id !== 'string') { - throw new ArgumentError('user_id field is required'); - } + if (!params.provider || typeof params.provider !== 'string') { + throw new ArgumentError('provider field is required'); + } - if (!params.provider || typeof params.provider !== 'string') { - throw new ArgumentError('provider field is required'); - } + if (cb && cb instanceof Function) { + return this.identities.delete(params, cb); + } - if (cb && cb instanceof Function) { - return this.identities.delete(params, cb); + return this.identities.delete(params); } - return this.identities.delete(params); -}; + /** + * Get user's log events. + * + * @example + * var params = { id: USER_ID, page: 0, per_page: 50, sort: 'date:-1', include_totals: true }; + * + * management.users.logs(params, function (err, logs) { + * if (err) { + * // Handle error. + * } + * + * console.log(logs); + * }); + * @param {object} params Get logs data. + * @param {string} params.id User id. + * @param {number} params.per_page Number of results per page. + * @param {number} params.page Page number, zero indexed. + * @param {string} params.sort The field to use for sorting. Use field:order where order is 1 for ascending and -1 for descending. For example date:-1. + * @param {boolean} params.include_totals true if a query summary must be included in the result, false otherwise. Default false; + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + logs(params, cb) { + params = params || {}; -/** - * Get user's log events. - * - * @method logs - * @memberOf module:management.UsersManager.prototype - * - * @example - * var params = { id: USER_ID, page: 0, per_page: 50, sort: 'date:-1', include_totals: true }; - * - * management.users.logs(params, function (err, logs) { - * if (err) { - * // Handle error. - * } - * - * console.log(logs); - * }); - * - * @param {Object} params Get logs data. - * @param {String} params.id User id. - * @param {Number} params.per_page Number of results per page. - * @param {Number} params.page Page number, zero indexed. - * @param {String} params.sort The field to use for sorting. Use field:order where order is 1 for ascending and -1 for descending. For example date:-1. - * @param {Boolean} params.include_totals true if a query summary must be included in the result, false otherwise. Default false; - * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} - */ -UsersManager.prototype.logs = function(params, cb) { - params = params || {}; + if (!params.id || typeof params.id !== 'string') { + throw new ArgumentError('id field is required'); + } + + return this.userLogs.get(params, cb); + } - if (!params.id || typeof params.id !== 'string') { - throw new ArgumentError('id field is required'); + /** + * Get a list of Guardian enrollments. + * + * @example + * management.users.getGuardianEnrollments({ id: USER_ID }, function (err, enrollments) { + * console.log(enrollments); + * }); + * @param {object} data The user data object. + * @param {string} data.id The user id. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getGuardianEnrollments(...args) { + return this.enrollments.get(...args); } - return this.userLogs.get(params, cb); -}; + /** + * Generate new Guardian recovery code. + * + * @example + * management.users.regenerateRecoveryCode("USER_ID", function (err, result) { + * console.log(result.recovery_code); + * }); + * @param {object} params Get logs data. + * @param {string} params.id User id. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + regenerateRecoveryCode(params, cb) { + if (!params || !params.id) { + throw new ArgumentError('The userId cannot be null or undefined'); + } -/** - * Get a list of Guardian enrollments. - * - * @method getGuardianEnrollments - * @memberOf module:management.UsersManager.prototype - * - * @example - * management.users.getGuardianEnrollments({ id: USER_ID }, function (err, enrollments) { - * console.log(enrollments); - * }); - * - * @param {Object} data The user data object. - * @param {String} data.id The user id. - * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} - */ -UsersManager.prototype.getGuardianEnrollments = function() { - return this.enrollments.get.apply(this.enrollments, arguments); -}; + if (cb && cb instanceof Function) { + return this.recoveryCodeRegenerations.create(params, {}, cb); + } -/** - * Generate new Guardian recovery code. - * - * @method regenerateRecoveryCode - * @memberOf module:management.UsersManager.prototype - * - * @example - * management.users.regenerateRecoveryCode("USER_ID", function (err, result) { - * console.log(result.recovery_code); - * }); - * - * @param {Object} params Get logs data. - * @param {String} params.id User id. - * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} - */ -UsersManager.prototype.regenerateRecoveryCode = function(params, cb) { - if (!params || !params.id) { - throw new ArgumentError('The userId cannot be null or undefined'); + return this.recoveryCodeRegenerations.create(params, {}); } - if (cb && cb instanceof Function) { - return this.recoveryCodeRegenerations.create(params, {}, cb); - } + /** + * Invalidate all remembered browsers for MFA. + * + * @example + * management.users.invalidateRememberBrowser({ id: USER_ID }, function (err, result) { + * if (err) { + * // Handle error. + * } + * + * // Invalidated all remembered browsers. + * }); + * @param {object} params The user data object. + * @param {string} params.id The user id. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + invalidateRememberBrowser(params, cb) { + if (!params || !params.id) { + throw new ArgumentError('The userId cannot be null or undefined'); + } - return this.recoveryCodeRegenerations.create(params, {}); -}; + if (cb && cb instanceof Function) { + return this.invalidateRememberBrowsers.create(params, {}, cb); + } -/** - * Invalidate all remembered browsers for MFA. - * - * @method invalidateRememberBrowser - * @memberOf module:management.UsersManager.prototype - * - * @example - * management.users.invalidateRememberBrowser({ id: USER_ID }, function (err, result) { - * if (err) { - * // Handle error. - * } - * - * // Invalidated all remembered browsers. - * }); - * - * @param {Object} params The user data object. - * @param {String} params.id The user id. - * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} - */ -UsersManager.prototype.invalidateRememberBrowser = function(params, cb) { - if (!params || !params.id) { - throw new ArgumentError('The userId cannot be null or undefined'); + return this.invalidateRememberBrowsers.create(params, {}); } - if (cb && cb instanceof Function) { - return this.invalidateRememberBrowsers.create(params, {}, cb); + /** + * Get a list of roles for a user. + * + * @example + * management.users.getRoles({ id: USER_ID }, function (err, roles) { + * console.log(roles); + * }); + * @param {object} data The user data object. + * @param {string} data.id The user id. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getRoles(...args) { + return this.roles.getAll(...args); } - return this.invalidateRememberBrowsers.create(params, {}); -}; + /** + * Assign roles to a user + * + * @example + * var params = { id : 'USER_ID'; + * var data = { "roles" : ["roleId1", "roleID2"]}; + * + * management.users.assignRoles(params, data, function (err, user) { + * if (err) { + * // Handle error. + * } + * + * // roles added. + * }); + * @param {object} params params object + * @param {string} params.id user_id + * @param {string} data data object containing list of role IDs + * @param {string} data.roles Array of role IDs + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ -/** - * Get a list of roles for a user. - * - * @method getUserRoles - * @memberOf module:management.UsersManager.prototype - * - * @example - * management.users.getRoles({ id: USER_ID }, function (err, roles) { - * console.log(roles); - * }); - * - * @param {Object} data The user data object. - * @param {String} data.id The user id. - * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} - */ -UsersManager.prototype.getRoles = function() { - return this.roles.getAll.apply(this.roles, arguments); -}; + assignRoles(params, data, cb) { + const query = params || {}; + data = data || {}; -/** - * Assign roles to a user - * - * @method assignRoles - * @memberOf module:management.RolesManager.prototype - * - * @example - * var params = { id : 'USER_ID'; - * var data = { "roles" : ["roleId1", "roleID2"]}; - * - * management.users.assignRoles(params, data, function (err, user) { - * if (err) { - * // Handle error. - * } - * - * // roles added. - * }); - * - * @param {Object} params params object - * @param {String} params.id user_id - * @param {String} data data object containing list of role IDs - * @param {String} data.roles Array of role IDs - * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} - */ + // Require a user ID. + if (!params.id) { + throw new ArgumentError('The user_id cannot be null or undefined'); + } + if (typeof params.id !== 'string') { + throw new ArgumentError('The user_id has to be a string'); + } -UsersManager.prototype.assignRoles = function(params, data, cb) { - var query = params || {}; - data = data || {}; + if (cb && cb instanceof Function) { + return this.roles.create(query, data, cb); + } - // Require a user ID. - if (!params.id) { - throw new ArgumentError('The user_id cannot be null or undefined'); - } - if (typeof params.id !== 'string') { - throw new ArgumentError('The user_id has to be a string'); + return this.roles.create(query, data); } - if (cb && cb instanceof Function) { - return this.roles.create(query, data, cb); - } + /** + * Remove roles from a user + * + * @example + * var params = { id : 'USER_ID'; + * var data = { "roles" : ["roleId1", "roleID2"]}; + * + * management.users.removeRoles(params, data, function (err, user) { + * if (err) { + * // Handle error. + * } + * + * // roles removed. + * }); + * @param {object} params params object + * @param {string} params.id user_id + * @param {string} data data object containing list of role IDs + * @param {string} data.roles Array of role IDs + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ - return this.roles.create(query, data); -}; + removeRoles(params, data, cb) { + const query = params || {}; + data = data || {}; -/** - * Remove roles from a user - * - * @method removeRoles - * @memberOf module:management.RolesManager.prototype - * - * @example - * var params = { id : 'USER_ID'; - * var data = { "roles" : ["roleId1", "roleID2"]}; - * - * management.users.removeRoles(params, data, function (err, user) { - * if (err) { - * // Handle error. - * } - * - * // roles removed. - * }); - * - * @param {Object} params params object - * @param {String} params.id user_id - * @param {String} data data object containing list of role IDs - * @param {String} data.roles Array of role IDs - * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} - */ + // Require a user ID. + if (!params.id) { + throw new ArgumentError('The user_id cannot be null or undefined'); + } + if (typeof params.id !== 'string') { + throw new ArgumentError('The user_id has to be a string'); + } -UsersManager.prototype.removeRoles = function(params, data, cb) { - var query = params || {}; - data = data || {}; + if (cb && cb instanceof Function) { + return this.roles.delete(query, data, cb); + } - // Require a user ID. - if (!params.id) { - throw new ArgumentError('The user_id cannot be null or undefined'); - } - if (typeof params.id !== 'string') { - throw new ArgumentError('The user_id has to be a string'); + return this.roles.delete(query, data); } - if (cb && cb instanceof Function) { - return this.roles.delete(query, data, cb); + /** + * Get a list of permissions for a user. + * + * @example + * management.users.getPermissions({ id: USER_ID }, function (err, permissions) { + * console.log(permissions); + * }); + * @param {object} data The user data object. + * @param {string} data.id The user id. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getPermissions(...args) { + return this.permissions.getAll(...args); } - return this.roles.delete(query, data); -}; + /** + * Assign permissions to a user + * + * @example + * var params = { id : 'USER_ID'; + * var data = { "permissions" : [{"permission_name" :"do:something" ,"resource_server_identifier" :"test123" }]}; + * + * management.users.assignPermissions(params, data, function (err, user) { + * if (err) { + * // Handle error. + * } + * + * // permissions added. + * }); + * @param {object} params params object + * @param {string} params.id user_id + * @param {string} data data object containing list of permissions + * @param {string} data.permissions Array of permission IDs + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ -/** - * Get a list of permissions for a user. - * - * @method getPermissions - * @memberOf module:management.UsersManager.prototype - * - * @example - * management.users.getPermissions({ id: USER_ID }, function (err, permissions) { - * console.log(permissions); - * }); - * - * @param {Object} data The user data object. - * @param {String} data.id The user id. - * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} - */ -UsersManager.prototype.getPermissions = function() { - return this.permissions.getAll.apply(this.permissions, arguments); -}; + assignPermissions(params, data, cb) { + const query = params || {}; + data = data || {}; -/** - * Assign permissions to a user - * - * @method assignPermissions - * @memberOf module:management.permissionsManager.prototype - * - * @example - * var params = { id : 'USER_ID'; - * var data = { "permissions" : [{"permission_name" :"do:something" ,"resource_server_identifier" :"test123" }]}; - * - * management.users.assignPermissions(params, data, function (err, user) { - * if (err) { - * // Handle error. - * } - * - * // permissions added. - * }); - * - * @param {Object} params params object - * @param {String} params.id user_id - * @param {String} data data object containing list of permissions - * @param {String} data.permissions Array of permission IDs - * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} - */ + // Require a user ID. + if (!params.id) { + throw new ArgumentError('The user_id cannot be null or undefined'); + } + if (typeof params.id !== 'string') { + throw new ArgumentError('The user_id has to be a string'); + } -UsersManager.prototype.assignPermissions = function(params, data, cb) { - var query = params || {}; - data = data || {}; + if (cb && cb instanceof Function) { + return this.permissions.create(query, data, cb); + } - // Require a user ID. - if (!params.id) { - throw new ArgumentError('The user_id cannot be null or undefined'); - } - if (typeof params.id !== 'string') { - throw new ArgumentError('The user_id has to be a string'); + return this.permissions.create(query, data); } - if (cb && cb instanceof Function) { - return this.permissions.create(query, data, cb); - } + /** + * Remove permissions from a user + * + * @example + * var params = { id : 'USER_ID'; + * var data = { "permissions" : [{"permission_name" :"do:something" ,"resource_server_identifier" :"test123" }]}; + * + * management.users.removePermissions(params, data, function (err, user) { + * if (err) { + * // Handle error. + * } + * + * // permissions removed. + * }); + * @param {object} params params object + * @param {string} params.id user_id + * @param {string} data data object containing list of permission IDs + * @param {string} data.permissions Array of permission IDs + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ - return this.permissions.create(query, data); -}; + removePermissions(params, data, cb) { + const query = params || {}; + data = data || {}; -/** - * Remove permissions from a user - * - * @method removePermissions - * @memberOf module:management.permissionsManager.prototype - * - * @example - * var params = { id : 'USER_ID'; - * var data = { "permissions" : [{"permission_name" :"do:something" ,"resource_server_identifier" :"test123" }]}; - * - * management.users.removePermissions(params, data, function (err, user) { - * if (err) { - * // Handle error. - * } - * - * // permissions removed. - * }); - * - * @param {Object} params params object - * @param {String} params.id user_id - * @param {String} data data object containing list of permission IDs - * @param {String} data.permissions Array of permission IDs - * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} - */ + // Require a user ID. + if (!params.id) { + throw new ArgumentError('The user_id cannot be null or undefined'); + } + if (typeof params.id !== 'string') { + throw new ArgumentError('The user_id has to be a string'); + } -UsersManager.prototype.removePermissions = function(params, data, cb) { - var query = params || {}; - data = data || {}; + if (cb && cb instanceof Function) { + return this.permissions.delete(query, data, cb); + } - // Require a user ID. - if (!params.id) { - throw new ArgumentError('The user_id cannot be null or undefined'); - } - if (typeof params.id !== 'string') { - throw new ArgumentError('The user_id has to be a string'); + return this.permissions.delete(query, data); } - if (cb && cb instanceof Function) { - return this.permissions.delete(query, data, cb); + /** + * Get a list of organizations for a user. + * + * @example + * @param {...any} args + * management.users.getUserOrganizations({ id: USER_ID }, function (err, orgs) { + * console.log(orgs); + * }); + * @param {object} data The user data object. + * @param {string} data.id The user id. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getUserOrganizations(...args) { + return this.organizations.getAll(...args); } - - return this.permissions.delete(query, data); -}; - -/** - * Get a list of organizations for a user. - * - * @method getUserOrganizations - * @memberOf module:management.UsersManager.prototype - * - * @example - * management.users.getUserOrganizations({ id: USER_ID }, function (err, orgs) { - * console.log(orgs); - * }); - * - * @param {Object} data The user data object. - * @param {String} data.id The user id. - * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} - */ -UsersManager.prototype.getUserOrganizations = function() { - return this.organizations.getAll.apply(this.organizations, arguments); -}; +} module.exports = UsersManager; diff --git a/src/management/index.js b/src/management/index.js index 1955118fe..2ad6d0800 100644 --- a/src/management/index.js +++ b/src/management/index.js @@ -1,44 +1,42 @@ -/** @module management */ - -var util = require('util'); -var utils = require('../utils'); -var jsonToBase64 = utils.jsonToBase64; -var generateClientInfo = utils.generateClientInfo; -var ArgumentError = require('rest-facade').ArgumentError; +const util = require('util'); +const utils = require('../utils'); +const { jsonToBase64 } = utils; +const { generateClientInfo } = utils; +const { ArgumentError } = require('rest-facade'); // Managers. -var ClientsManager = require('./ClientsManager'); -var ClientGrantsManager = require('./ClientGrantsManager'); -var GrantsManager = require('./GrantsManager'); -var UsersManager = require('./UsersManager'); -var UserBlocksManager = require('./UserBlocksManager'); -var ConnectionsManager = require('./ConnectionsManager'); -var BlacklistedTokensManager = require('./BlacklistedTokensManager'); -var RulesManager = require('./RulesManager'); -var DeviceCredentialsManager = require('./DeviceCredentialsManager'); -var EmailProviderManager = require('./EmailProviderManager'); -var StatsManager = require('./StatsManager'); -var TenantManager = require('./TenantManager'); -var JobsManager = require('./JobsManager'); -var TicketsManager = require('./TicketsManager'); -var LogsManager = require('./LogsManager'); -var LogStreamsManager = require('./LogStreamsManager'); -var ResourceServersManager = require('./ResourceServersManager'); -var ManagementTokenProvider = require('./ManagementTokenProvider'); -var RulesConfigsManager = require('./RulesConfigsManager'); -var EmailTemplatesManager = require('./EmailTemplatesManager'); -var GuardianManager = require('./GuardianManager'); -var CustomDomainsManager = require('./CustomDomainsManager'); -var RolesManager = require('./RolesManager'); -var HooksManager = require('./HooksManager'); -var BrandingManager = require('./BrandingManager'); -var MigrationsManager = require('./MigrationsManager'); -var PromptsManager = require('./PromptsManager'); -var ActionsManager = require('./ActionsManager'); -var OrganizationsManager = require('./OrganizationsManager'); - -var BASE_URL_FORMAT = 'https://%s/api/v2'; -var MANAGEMENT_API_AUD_FORMAT = 'https://%s/api/v2/'; +const ClientsManager = require('./ClientsManager'); +const ClientGrantsManager = require('./ClientGrantsManager'); +const GrantsManager = require('./GrantsManager'); +const UsersManager = require('./UsersManager'); +const UserBlocksManager = require('./UserBlocksManager'); +const ConnectionsManager = require('./ConnectionsManager'); +const BlacklistedTokensManager = require('./BlacklistedTokensManager'); +const RulesManager = require('./RulesManager'); +const DeviceCredentialsManager = require('./DeviceCredentialsManager'); +const EmailProviderManager = require('./EmailProviderManager'); +const StatsManager = require('./StatsManager'); +const TenantManager = require('./TenantManager'); +const JobsManager = require('./JobsManager'); +const TicketsManager = require('./TicketsManager'); +const LogsManager = require('./LogsManager'); +const LogStreamsManager = require('./LogStreamsManager'); +const ResourceServersManager = require('./ResourceServersManager'); +const ManagementTokenProvider = require('./ManagementTokenProvider'); +const RulesConfigsManager = require('./RulesConfigsManager'); +const EmailTemplatesManager = require('./EmailTemplatesManager'); +const GuardianManager = require('./GuardianManager'); +const CustomDomainsManager = require('./CustomDomainsManager'); +const RolesManager = require('./RolesManager'); +const HooksManager = require('./HooksManager'); +const BrandingManager = require('./BrandingManager'); +const MigrationsManager = require('./MigrationsManager'); +const PromptsManager = require('./PromptsManager'); +const ActionsManager = require('./ActionsManager'); +const OrganizationsManager = require('./OrganizationsManager'); + +const BASE_URL_FORMAT = 'https://%s/api/v2'; +const MANAGEMENT_API_AUD_FORMAT = 'https://%s/api/v2/'; /** * @class ManagementClient @@ -48,9 +46,8 @@ var MANAGEMENT_API_AUD_FORMAT = 'https://%s/api/v2/'; * parties performing administrative tasks. Generally speaking, anything that * can be done through the Auth0 dashboard (and more) can also be done through * this API. - * @constructor - * @memberOf module:management - * + * @class + * @memberof module:management * @example * Initialize your client class with an API v2 token (you can generate one * here) and a domain. @@ -61,8 +58,6 @@ var MANAGEMENT_API_AUD_FORMAT = 'https://%s/api/v2/'; * domain: '{YOUR_ACCOUNT}.auth0.com', * token: '{YOUR_API_V2_TOKEN}' * }); - * - * * @example * Initialize your client class, by using a Non Interactive Client to fetch an access_token * via the Client Credentials Grant. @@ -80,24 +75,22 @@ var MANAGEMENT_API_AUD_FORMAT = 'https://%s/api/v2/'; * cacheTTLInSeconds: 10 * } * }); - * - * @param {Object} options Options for the ManagementClient SDK. + * @param {object} options Options for the ManagementClient SDK. * If a token is provided only the domain is required, other parameters are ignored. * If no token is provided domain, clientId, clientSecret and scopes are required - * @param {String} options.domain ManagementClient server domain. - * @param {String} [options.token] API access token. - * @param {String} [options.clientId] Management API Non Interactive Client Id. - * @param {String} [options.clientSecret] Management API Non Interactive Client Secret. - * @param {String} [options.audience] Management API Audience. By default is your domain's, e.g. the domain is `tenant.auth0.com` and the audience is `http://tenant.auth0.com/api/v2/` - * @param {String} [options.scope] Management API Scopes. - * @param {Boolean} [options.tokenProvider.enableCache=true] Enabled or Disable Cache. - * @param {Number} [options.tokenProvider.cacheTTLInSeconds] By default the `expires_in` value will be used to determine the cached time of the token, this can be overridden. - * @param {Boolean} [options.retry.enabled=true] Enabled or Disable Retry Policy functionality. - * @param {Number} [options.retry.maxRetries=10] Retry failed requests X times. - * @param {Object} [options.headers] Additional headers that will be added to the outgoing requests. - * - */ -var ManagementClient = function(options) { + * @param {string} options.domain ManagementClient server domain. + * @param {string} [options.token] API access token. + * @param {string} [options.clientId] Management API Non Interactive Client Id. + * @param {string} [options.clientSecret] Management API Non Interactive Client Secret. + * @param {string} [options.audience] Management API Audience. By default is your domain's, e.g. the domain is `tenant.auth0.com` and the audience is `http://tenant.auth0.com/api/v2/` + * @param {string} [options.scope] Management API Scopes. + * @param {boolean} [options.tokenProvider.enableCache=true] Enabled or Disable Cache. + * @param {number} [options.tokenProvider.cacheTTLInSeconds] By default the `expires_in` value will be used to determine the cached time of the token, this can be overridden. + * @param {boolean} [options.retry.enabled=true] Enabled or Disable Retry Policy functionality. + * @param {number} [options.retry.maxRetries=10] Retry failed requests X times. + * @param {object} [options.headers] Additional headers that will be added to the outgoing requests. + */ +const ManagementClient = function (options) { if (!options || typeof options !== 'object') { throw new ArgumentError('Management API SDK options must be an object'); } @@ -106,21 +99,20 @@ var ManagementClient = function(options) { throw new ArgumentError('Must provide a domain'); } - var baseUrl = util.format(BASE_URL_FORMAT, options.domain); - var userAgent = options.userAgent || 'node.js/' + process.version.replace('v', ''); + const baseUrl = util.format(BASE_URL_FORMAT, options.domain); - var defaultHeaders = { - 'User-Agent': 'node.js/' + process.version.replace('v', ''), - 'Content-Type': 'application/json' + const defaultHeaders = { + 'User-Agent': `node.js/${process.version.replace('v', '')}`, + 'Content-Type': 'application/json', }; - var managerOptions = { + const managerOptions = { headers: Object.assign(defaultHeaders, options.headers || {}), - baseUrl: baseUrl + baseUrl, }; if (options.token === undefined) { - var config = Object.assign( + const config = Object.assign( { audience: util.format(MANAGEMENT_API_AUD_FORMAT, options.domain) }, options ); @@ -136,19 +128,19 @@ var ManagementClient = function(options) { throw new ArgumentError('Must provide a token'); } else { this.tokenProvider = { - getAccessToken: function() { + getAccessToken() { return Promise.resolve(options.token); - } + }, }; - managerOptions.headers['Authorization'] = 'Bearer ' + options.token; + managerOptions.headers['Authorization'] = `Bearer ${options.token}`; } managerOptions.tokenProvider = this.tokenProvider; if (options.telemetry !== false) { - var clientInfo = options.clientInfo || generateClientInfo(); + const clientInfo = options.clientInfo || generateClientInfo(); if ('string' === typeof clientInfo.name && clientInfo.name.length > 0) { - var telemetry = jsonToBase64(clientInfo); + const telemetry = jsonToBase64(clientInfo); managerOptions.headers['Auth0-Client'] = telemetry; } } @@ -373,9 +365,8 @@ var ManagementClient = function(options) { /** * Get all connections. * - * @method getConnections - * @memberOf module:management.ManagementClient.prototype - * + * @function getConnections + * @memberof module:management.ManagementClient.prototype * @example * This method takes an optional object as first argument that may be used to * specify pagination settings. If pagination options are not present, @@ -391,22 +382,19 @@ var ManagementClient = function(options) { * management.getConnections(params, function (err, connections) { * console.log(connections.length); * }); - * - * @param {Object} [params] Connections params. - * @param {Number} [params.per_page] Number of results per page. - * @param {Number} [params.page] Page number, zero indexed. + * @param {object} [params] Connections params. + * @param {number} [params.per_page] Number of results per page. + * @param {number} [params.page] Page number, zero indexed. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getConnections', 'connections.getAll'); /** * Create a new connection. * - * @method createConnection - * @memberOf module:management.ManagementClient.prototype - * + * @function createConnection + * @memberof module:management.ManagementClient.prototype * @example * management.createConnection(data, function (err) { * if (err) { @@ -415,20 +403,17 @@ utils.wrapPropertyMethod(ManagementClient, 'getConnections', 'connections.getAll * * // Connection created. * }); - * - * @param {Object} data Connection data object. + * @param {object} data Connection data object. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'createConnection', 'connections.create'); /** * Get an Auth0 connection. * - * @method getConnection - * @memberOf module:management.ManagementClient.prototype - * + * @function getConnection + * @memberof module:management.ManagementClient.prototype * @example * management.getConnection({ id: CONNECTION_ID }, function (err, connection) { * if (err) { @@ -437,21 +422,18 @@ utils.wrapPropertyMethod(ManagementClient, 'createConnection', 'connections.crea * * console.log(connection); * }); - * - * @param {Object} params Connection parameters. - * @param {String} params.id Connection ID. + * @param {object} params Connection parameters. + * @param {string} params.id Connection ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getConnection', 'connections.get'); /** * Delete an existing connection. * - * @method deleteConnection - * @memberOf module:management.ManagementClient.prototype - * + * @function deleteConnection + * @memberof module:management.ManagementClient.prototype * @example * management.deleteConnection({ id: CONNECTION_ID }, function (err) { * if (err) { @@ -460,21 +442,18 @@ utils.wrapPropertyMethod(ManagementClient, 'getConnection', 'connections.get'); * * // Connection deleted. * }); - * - * @param {Object} params Connection parameters. - * @param {String} params.id Connection ID. + * @param {object} params Connection parameters. + * @param {string} params.id Connection ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'deleteConnection', 'connections.delete'); /** * Update an existing connection. * - * @method updateConnection - * @memberOf module:management.ManagementClient.prototype - * + * @function updateConnection + * @memberof module:management.ManagementClient.prototype * @example * var data = { name: 'newConnectionName' }; * var params = { id: CONNECTION_ID }; @@ -486,22 +465,19 @@ utils.wrapPropertyMethod(ManagementClient, 'deleteConnection', 'connections.dele * * console.log(connection.name); // 'newConnectionName' * }); - * - * @param {Object} params Connection parameters. - * @param {String} params.id Connection ID. - * @param {Object} data Updated connection data. + * @param {object} params Connection parameters. + * @param {string} params.id Connection ID. + * @param {object} data Updated connection data. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'updateConnection', 'connections.update'); /** * Get all Auth0 clients. * - * @method getClients - * @memberOf module:management.ManagementClient.prototype - * + * @function getClients + * @memberof module:management.ManagementClient.prototype * @example * This method takes an optional object as first argument that may be used to * specify pagination settings. If pagination options are not present, @@ -517,22 +493,19 @@ utils.wrapPropertyMethod(ManagementClient, 'updateConnection', 'connections.upda * management.getClients(params, function (err, clients) { * console.log(clients.length); * }); - * - * @param {Object} [params] Clients parameters. - * @param {Number} [params.per_page] Number of results per page. - * @param {Number} [params.page] Page number, zero indexed. + * @param {object} [params] Clients parameters. + * @param {number} [params.per_page] Number of results per page. + * @param {number} [params.page] Page number, zero indexed. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getClients', 'clients.getAll'); /** * Get an Auth0 client. * - * @method getClient - * @memberOf module:management.ManagementClient.prototype - * + * @function getClient + * @memberof module:management.ManagementClient.prototype * @example * management.getClient({ client_id: CLIENT_ID }, function (err, client) { * if (err) { @@ -541,21 +514,18 @@ utils.wrapPropertyMethod(ManagementClient, 'getClients', 'clients.getAll'); * * console.log(client); * }); - * - * @param {Object} params Client parameters. - * @param {String} params.client_id Application client ID. + * @param {object} params Client parameters. + * @param {string} params.client_id Application client ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getClient', 'clients.get'); /** * Create an Auth0 client. * - * @method createClient - * @memberOf module:management.ManagementClient.prototype - * + * @function createClient + * @memberof module:management.ManagementClient.prototype * @example * management.createClient(data, function (err) { * if (err) { @@ -564,20 +534,17 @@ utils.wrapPropertyMethod(ManagementClient, 'getClient', 'clients.get'); * * // Client created. * }); - * - * @param {Object} data The client data object. + * @param {object} data The client data object. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'createClient', 'clients.create'); /** * Update an Auth0 client. * - * @method updateClient - * @memberOf module:management.ManagementClient.prototype - * + * @function updateClient + * @memberof module:management.ManagementClient.prototype * @example * var data = { name: 'newClientName' }; * var params = { client_id: CLIENT_ID }; @@ -589,22 +556,19 @@ utils.wrapPropertyMethod(ManagementClient, 'createClient', 'clients.create'); * * console.log(client.name); // 'newClientName' * }); - * - * @param {Object} params Client parameters. - * @param {String} params.client_id Application client ID. - * @param {Object} data Updated client data. + * @param {object} params Client parameters. + * @param {string} params.client_id Application client ID. + * @param {object} data Updated client data. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'updateClient', 'clients.update'); /** * Delete an Auth0 client. * - * @method deleteClient - * @memberOf module:management.ManagementClient.prototype - * + * @function deleteClient + * @memberof module:management.ManagementClient.prototype * @example * management.deleteClient({ client_id: CLIENT_ID }, function (err) { * if (err) { @@ -613,21 +577,18 @@ utils.wrapPropertyMethod(ManagementClient, 'updateClient', 'clients.update'); * * // Client deleted. * }); - * - * @param {Object} params Client parameters. - * @param {String} params.client_id Application client ID. + * @param {object} params Client parameters. + * @param {string} params.client_id Application client ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'deleteClient', 'clients.delete'); /** * Get all Auth0 Client Grants. * - * @method getClientGrants - * @memberOf module:management.ManagementClient.prototype - * + * @function getClientGrants + * @memberof module:management.ManagementClient.prototype * @example * This method takes an optional object as first argument that may be used to * specify pagination settings. If pagination options are not present, @@ -643,22 +604,19 @@ utils.wrapPropertyMethod(ManagementClient, 'deleteClient', 'clients.delete'); * management.getClientGrants(params, function (err, grants) { * console.log(grants.length); * }); - * - * @param {Object} [params] Client Grants parameters. - * @param {Number} [params.per_page] Number of results per page. - * @param {Number} [params.page] Page number, zero indexed. + * @param {object} [params] Client Grants parameters. + * @param {number} [params.per_page] Number of results per page. + * @param {number} [params.page] Page number, zero indexed. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getClientGrants', 'clientGrants.getAll'); /** * Create an Auth0 client grant. * - * @method createClientGrant - * @memberOf module:management.ManagementClient.prototype - * + * @function createClientGrant + * @memberof module:management.ManagementClient.prototype * @example * management.clientGrants.create(data, function (err) { * if (err) { @@ -667,20 +625,17 @@ utils.wrapPropertyMethod(ManagementClient, 'getClientGrants', 'clientGrants.getA * * // Client grant created. * }); - * - * @param {Object} data The client data object. + * @param {object} data The client data object. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'createClientGrant', 'clientGrants.create'); /** * Update an Auth0 client grant. * - * @method updateClientGrant - * @memberOf module:management.ManagementClient.prototype - * + * @function updateClientGrant + * @memberof module:management.ManagementClient.prototype * @example * var data = { * client_id: CLIENT_ID, @@ -696,22 +651,19 @@ utils.wrapPropertyMethod(ManagementClient, 'createClientGrant', 'clientGrants.cr * * console.log(grant.id); * }); - * - * @param {Object} params Client parameters. - * @param {String} params.id Client grant ID. - * @param {Object} data Updated client data. + * @param {object} params Client parameters. + * @param {string} params.id Client grant ID. + * @param {object} data Updated client data. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'updateClientGrant', 'clientGrants.update'); /** * Delete an Auth0 client grant. * - * @method deleteClientGrant - * @memberOf module:management.ManagementClient.prototype - * + * @function deleteClientGrant + * @memberof module:management.ManagementClient.prototype * @example * management.clientGrants.delete({ id: GRANT_ID }, function (err) { * if (err) { @@ -720,21 +672,18 @@ utils.wrapPropertyMethod(ManagementClient, 'updateClientGrant', 'clientGrants.up * * // Grant deleted. * }); - * - * @param {Object} params Client parameters. - * @param {String} params.id Client grant ID. + * @param {object} params Client parameters. + * @param {string} params.id Client grant ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'deleteClientGrant', 'clientGrants.delete'); /** * Get all Auth0 Grants. * - * @method getGrants - * @memberOf module:management.ManagementClient.prototype - * + * @function getGrants + * @memberof module:management.ManagementClient.prototype * @example * var params = { * per_page: 10, @@ -748,26 +697,23 @@ utils.wrapPropertyMethod(ManagementClient, 'deleteClientGrant', 'clientGrants.de * management.getGrants(params, function (err, grants) { * console.log(grants.length); * }); - * - * @param {Object} params Grants parameters. - * @param {Number} params.per_page Number of results per page. - * @param {Number} params.page Page number, zero indexed. - * @param {Boolean} params.include_totals true if a query summary must be included in the result, false otherwise. Default false; - * @param {String} params.user_id The user_id of the grants to retrieve. - * @param {String} params.client_id The client_id of the grants to retrieve. - * @param {String} params.audience The audience of the grants to retrieve. + * @param {object} params Grants parameters. + * @param {number} params.per_page Number of results per page. + * @param {number} params.page Page number, zero indexed. + * @param {boolean} params.include_totals true if a query summary must be included in the result, false otherwise. Default false; + * @param {string} params.user_id The user_id of the grants to retrieve. + * @param {string} params.client_id The client_id of the grants to retrieve. + * @param {string} params.audience The audience of the grants to retrieve. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getGrants', 'grants.getAll'); /** * Delete an Auth0 grant. * - * @method deleteGrant - * @memberOf module:management.GrantsManager.prototype - * + * @function deleteGrant + * @memberof module:management.GrantsManager.prototype * @example * var params = { * id: GRANT_ID, @@ -781,22 +727,19 @@ utils.wrapPropertyMethod(ManagementClient, 'getGrants', 'grants.getAll'); * * // Grant deleted. * }); - * - * @param {Object} params Grant parameters. - * @param {String} params.id Grant ID. - * @param {String} params.user_id The user_id of the grants to delete. + * @param {object} params Grant parameters. + * @param {string} params.id Grant ID. + * @param {string} params.user_id The user_id of the grants to delete. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'deleteGrant', 'grants.delete'); /** * Create an Auth0 credential. * - * @method createDevicePublicKey - * @memberOf module:management.ManagementClient.prototype - * + * @function createDevicePublicKey + * @memberof module:management.ManagementClient.prototype * @example * management.createConnection(data, function (err) { * if (err) { @@ -805,11 +748,9 @@ utils.wrapPropertyMethod(ManagementClient, 'deleteGrant', 'grants.delete'); * * // Credential created. * }); - * - * @param {Object} data The device credential data object. + * @param {object} data The device credential data object. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod( ManagementClient, @@ -820,29 +761,25 @@ utils.wrapPropertyMethod( /** * Get all Auth0 credentials. * - * @method getDeviceCredentials - * @memberOf module:management.ManagementClient.prototype - * + * @function getDeviceCredentials + * @memberof module:management.ManagementClient.prototype * @example * var params = {user_id: "USER_ID"}; * * management.getDeviceCredentials(params, function (err, credentials) { * console.log(credentials.length); * }); - * - * @param {Object} params Credential parameters. + * @param {object} params Credential parameters. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getDeviceCredentials', 'deviceCredentials.getAll'); /** * Delete an Auth0 device credential. * - * @method deleteDeviceCredential - * @memberOf module:management.ManagementClient.prototype - * + * @function deleteDeviceCredential + * @memberof module:management.ManagementClient.prototype * @example * var params = { id: CREDENTIAL_ID }; * @@ -853,21 +790,18 @@ utils.wrapPropertyMethod(ManagementClient, 'getDeviceCredentials', 'deviceCreden * * // Credential deleted. * }); - * - * @param {Object} params Credential parameters. - * @param {String} params.id Device credential ID. + * @param {object} params Credential parameters. + * @param {string} params.id Device credential ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'deleteDeviceCredential', 'deviceCredentials.delete'); /** * Get all rules. * - * @method getRules - * @memberOf module:management.ManagementClient.prototype - * + * @function getRules + * @memberof module:management.ManagementClient.prototype * @example * This method takes an optional object as first argument that may be used to * specify pagination settings. If pagination options are not present, @@ -883,22 +817,19 @@ utils.wrapPropertyMethod(ManagementClient, 'deleteDeviceCredential', 'deviceCred * management.getRules(params, function (err, rules) { * console.log(rules.length); * }); - * - * @param {Object} [params] Rules parameters. - * @param {Number} [params.per_page] Number of results per page. - * @param {Number} [params.page] Page number, zero indexed. + * @param {object} [params] Rules parameters. + * @param {number} [params.per_page] Number of results per page. + * @param {number} [params.page] Page number, zero indexed. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getRules', 'rules.getAll'); /** * Create a new rule. * - * @method createRule - * @memberOf module:management.ManagementClient.prototype - * + * @function createRule + * @memberof module:management.ManagementClient.prototype * @example * management.createRule(data, function (err) { * if (err) { @@ -907,20 +838,17 @@ utils.wrapPropertyMethod(ManagementClient, 'getRules', 'rules.getAll'); * * // Rule created. * }); - * - * @param {Object} data Rule data object. + * @param {object} data Rule data object. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'createRule', 'rules.create'); /** * Get an Auth0 rule. * - * @method getRule - * @memberOf module:management.ManagementClient.prototype - * + * @function getRule + * @memberof module:management.ManagementClient.prototype * @example * management.getRule({ id: RULE_ID }, function (err, rule) { * if (err) { @@ -929,21 +857,18 @@ utils.wrapPropertyMethod(ManagementClient, 'createRule', 'rules.create'); * * console.log(rule); * }); - * - * @param {Object} params Rule parameters. - * @param {String} params.id Rule ID. + * @param {object} params Rule parameters. + * @param {string} params.id Rule ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getRule', 'rules.get'); /** * Delete an existing rule. * - * @method deleteRule - * @memberOf module:management.ManagementClient.prototype - * + * @function deleteRule + * @memberof module:management.ManagementClient.prototype * @example * auth0.deleteRule({ id: RULE_ID }, function (err) { * if (err) { @@ -952,21 +877,18 @@ utils.wrapPropertyMethod(ManagementClient, 'getRule', 'rules.get'); * * // Rule deleted. * }); - * - * @param {Object} params Rule parameters. - * @param {String} params.id Rule ID. + * @param {object} params Rule parameters. + * @param {string} params.id Rule ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'deleteRule', 'rules.delete'); /** * Update an existing rule. * - * @method updateRule - * @memberOf module:management.ManagementClient.prototype - * + * @function updateRule + * @memberof module:management.ManagementClient.prototype * @example * var params = { id: RULE_ID }; * var data = { name: 'my-rule'}; @@ -977,22 +899,19 @@ utils.wrapPropertyMethod(ManagementClient, 'deleteRule', 'rules.delete'); * * console.log(rule.name); // 'my-rule'. * }); - * - * @param {Object} params Rule parameters. - * @param {String} params.id Rule ID. - * @param {Object} data Updated rule data. + * @param {object} params Rule parameters. + * @param {string} params.id Rule ID. + * @param {object} data Updated rule data. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'updateRule', 'rules.update'); /** * Get all users. * - * @method getUsers - * @memberOf module:management.ManagementClient.prototype - * + * @function getUsers + * @memberof module:management.ManagementClient.prototype * @example * This method takes an optional object as first argument that may be used to * specify pagination settings. If pagination options are not present, @@ -1010,24 +929,21 @@ utils.wrapPropertyMethod(ManagementClient, 'updateRule', 'rules.update'); * auth0.getUsers(params, function (err, users) { * console.log(users.length); * }); - * - * @param {Object} [params] Users params. - * @param {Number} [params.search_engine] The version of the search engine to use. - * @param {String} [params.q] User Search string to filter which users are returned. Follows Lucene query string syntax as documented at https://auth0.com/docs/api/management/v2#!/Users/get_users. - * @param {Number} [params.per_page] Number of results per page. - * @param {Number} [params.page] Page number, zero indexed. + * @param {object} [params] Users params. + * @param {number} [params.search_engine] The version of the search engine to use. + * @param {string} [params.q] User Search string to filter which users are returned. Follows Lucene query string syntax as documented at https://auth0.com/docs/api/management/v2#!/Users/get_users. + * @param {number} [params.per_page] Number of results per page. + * @param {number} [params.page] Page number, zero indexed. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getUsers', 'users.getAll'); /** * Get users for a given email address * - * @method getUsersByEmail - * @memberOf module:management.ManagementClient.prototype - * + * @function getUsersByEmail + * @memberof module:management.ManagementClient.prototype * @example * This method takes an email address as the first argument, * and returns all users with that email address @@ -1036,42 +952,36 @@ utils.wrapPropertyMethod(ManagementClient, 'getUsers', 'users.getAll'); * auth0.getUsersByEmail(email, function (err, users) { * console.log(users); * }); - * - * @param {String} [email] Email address of user(s) to find - * @param {Object} [options] Additional options to pass to the endpoint - * @param {String} [options.fields] Comma-separated list of fields to include or exclude in the result - * @param {Boolean} [options.include_fields] Whether specified fields are to be included (true) or excluded (false). Defaults to true. + * @param {string} [email] Email address of user(s) to find + * @param {object} [options] Additional options to pass to the endpoint + * @param {string} [options.fields] Comma-separated list of fields to include or exclude in the result + * @param {boolean} [options.include_fields] Whether specified fields are to be included (true) or excluded (false). Defaults to true. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getUsersByEmail', 'users.getByEmail'); /** * Get a user by its id. * - * @method getUser - * @memberOf module:management.ManagementClient.prototype - * + * @function getUser + * @memberof module:management.ManagementClient.prototype * @example * management.getUser({ id: USER_ID }, function (err, user) { * console.log(user); * }); - * - * @param {Object} data The user data object. - * @param {String} data.id The user id. + * @param {object} data The user data object. + * @param {string} data.id The user id. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getUser', 'users.get'); /** * Delete all users. * - * @method deleteAllUsers - * @memberOf module:management.ManagementClient.prototype - * + * @function deleteAllUsers + * @memberof module:management.ManagementClient.prototype * @example * management.deleteAllUsers(function (err) { * if (err) { @@ -1080,11 +990,8 @@ utils.wrapPropertyMethod(ManagementClient, 'getUser', 'users.get'); * * // Users deleted * }); - * * @param {Function} [cb] Callback function - * - * @return {Promise|undefined} - * + * @returns {Promise|undefined} * @deprecated This method will be removed in the next major release. */ utils.wrapPropertyMethod(ManagementClient, 'deleteAllUsers', 'users.deleteAll'); @@ -1092,9 +999,8 @@ utils.wrapPropertyMethod(ManagementClient, 'deleteAllUsers', 'users.deleteAll'); /** * Delete a user by its id. * - * @method deleteUser - * @memberOf module:management.ManagementClient.prototype - * + * @function deleteUser + * @memberof module:management.ManagementClient.prototype * @example * management.deleteUser({ id: USER_ID }, function (err) { * if (err) { @@ -1103,21 +1009,18 @@ utils.wrapPropertyMethod(ManagementClient, 'deleteAllUsers', 'users.deleteAll'); * * // User deleted. * }); - * - * @param {Object} params The user data object.. - * @param {String} params.id The user id. + * @param {object} params The user data object.. + * @param {string} params.id The user id. * @param {Function} [cb] Callback function - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'deleteUser', 'users.delete'); /** * Create a new user. * - * @method createUser - * @memberOf module:management.ManagementClient.prototype - * + * @function createUser + * @memberof module:management.ManagementClient.prototype * @example * management.createUser(data, function (err) { * if (err) { @@ -1126,20 +1029,17 @@ utils.wrapPropertyMethod(ManagementClient, 'deleteUser', 'users.delete'); * * // User created. * }); - * - * @param {Object} data User data. + * @param {object} data User data. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'createUser', 'users.create'); /** * Update a user by its id. * - * @method updateUser - * @memberOf module:management.ManagementClient.prototype - * + * @function updateUser + * @memberof module:management.ManagementClient.prototype * @example * var params = { id: USER_ID }; * @@ -1151,22 +1051,19 @@ utils.wrapPropertyMethod(ManagementClient, 'createUser', 'users.create'); * // Updated user. * console.log(user); * }); - * - * @param {Object} params The user parameters. - * @param {String} params.id The user id. - * @param {Object} data New user data. + * @param {object} params The user parameters. + * @param {string} params.id The user id. + * @param {object} data New user data. * @param {Function} [cb] Callback function - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'updateUser', 'users.update'); /** * Update the user metadata for a user. * - * @method updateUserMetadata - * @memberOf module:management.ManagementClient.prototype - * + * @function updateUserMetadata + * @memberof module:management.ManagementClient.prototype * @example * var params = { id: USER_ID }; * var metadata = { @@ -1181,22 +1078,19 @@ utils.wrapPropertyMethod(ManagementClient, 'updateUser', 'users.update'); * // Updated user. * console.log(user); * }); - * - * @param {Object} params The user data object.. - * @param {String} params.id The user id. - * @param {Object} metadata New user metadata. + * @param {object} params The user data object.. + * @param {string} params.id The user id. + * @param {object} metadata New user metadata. * @param {Function} [cb] Callback function - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'updateUserMetadata', 'users.updateUserMetadata'); /** * Update the app metadata for a user. * - * @method updateAppMetadata - * @memberOf module:management.ManagementClient.prototype - * + * @function updateAppMetadata + * @memberof module:management.ManagementClient.prototype * @example * var params = { id: USER_ID }; * var metadata = { @@ -1211,22 +1105,19 @@ utils.wrapPropertyMethod(ManagementClient, 'updateUserMetadata', 'users.updateUs * // Updated user. * console.log(user); * }); - * - * @param {Object} params The user data object.. - * @param {String} params.id The user id. - * @param {Object} metadata New app metadata. + * @param {object} params The user data object.. + * @param {string} params.id The user id. + * @param {object} metadata New app metadata. * @param {Function} [cb] Callback function - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'updateAppMetadata', 'users.updateAppMetadata'); /** * Delete a multifactor provider for a user. * - * @method deleteUserMultifactor - * @memberOf module:management.ManagementClient.prototype - * + * @function deleteUserMultifactor + * @memberof module:management.ManagementClient.prototype * @example * var params = { id: USER_ID, provider: MULTIFACTOR_PROVIDER }; * @@ -1237,13 +1128,11 @@ utils.wrapPropertyMethod(ManagementClient, 'updateAppMetadata', 'users.updateApp * * // Users accounts unlinked. * }); - * - * @param {Object} params Data object. - * @param {String} params.id The user id. - * @param {String} params.provider Multifactor provider. + * @param {object} params Data object. + * @param {string} params.id The user id. + * @param {string} params.provider Multifactor provider. * @param {Function} [cb] Callback function - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod( ManagementClient, @@ -1254,9 +1143,8 @@ utils.wrapPropertyMethod( /** * Delete a multifactor provider for a user. * - * @method deleteUserMultifcator - * @memberOf module:management.ManagementClient.prototype - * + * @function deleteUserMultifcator + * @memberof module:management.ManagementClient.prototype * @example * var params = { id: USER_ID, provider: MULTIFACTOR_PROVIDER }; * @@ -1267,14 +1155,11 @@ utils.wrapPropertyMethod( * * // Users accounts unlinked. * }); - * - * @param {Object} params Data object. - * @param {String} params.id The user id. - * @param {String} params.provider Multifactor provider. + * @param {object} params Data object. + * @param {string} params.id The user id. + * @param {string} params.provider Multifactor provider. * @param {Function} [cb] Callback function - * - * @return {Promise|undefined} - * + * @returns {Promise|undefined} * @deprecated The function name has a typo. * We're shipping this so it doesn't break compatibility. * Use {@link deleteUserMultifactor} instead. @@ -1288,9 +1173,8 @@ utils.wrapPropertyMethod( /** * Unlink the given accounts. * - * @method unlinkUsers - * @memberOf module:management.ManagementClient.prototype - * + * @function unlinkUsers + * @memberof module:management.ManagementClient.prototype * @example * var params = { id: USER_ID, provider: 'auht0', user_id: OTHER_USER_ID }; * @@ -1301,23 +1185,20 @@ utils.wrapPropertyMethod( * * // Users accounts unlinked. * }); - * - * @param {Object} params Linked users data. - * @param {String} params.id Primary user ID. - * @param {String} params.provider Identity provider in use. - * @param {String} params.user_id Secondary user ID. + * @param {object} params Linked users data. + * @param {string} params.id Primary user ID. + * @param {string} params.provider Identity provider in use. + * @param {string} params.user_id Secondary user ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'unlinkUsers', 'users.unlink'); /** * Link the user with another account. * - * @method linkUsers - * @memberOf module:management.ManagementClient.prototype - * + * @function linkUsers + * @memberof module:management.ManagementClient.prototype * @example * var userId = 'USER_ID'; * var params = { @@ -1332,25 +1213,22 @@ utils.wrapPropertyMethod(ManagementClient, 'unlinkUsers', 'users.unlink'); * * // Users linked. * }); - * - * @param {String} userId ID of the primary user. - * @param {Object} params Secondary user data. - * @param {String} params.user_id ID of the user to be linked. - * @param {String} params.connection_id ID of the connection to be used. - * @param {String} params.provider Identity provider of the secondary user account being linked. - * @param {String} params.link_with JWT for the secondary account being linked. If sending this parameter, provider, user_id, and connection_id must not be sent. + * @param {string} userId ID of the primary user. + * @param {object} params Secondary user data. + * @param {string} params.user_id ID of the user to be linked. + * @param {string} params.connection_id ID of the connection to be used. + * @param {string} params.provider Identity provider of the secondary user account being linked. + * @param {string} params.link_with JWT for the secondary account being linked. If sending this parameter, provider, user_id, and connection_id must not be sent. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'linkUsers', 'users.link'); /** * Get user's log events. * - * @method getUserLogs - * @memberOf module:management.ManagementClient.prototype - * + * @function getUserLogs + * @memberof module:management.ManagementClient.prototype * @example * var params = { id: USER_ID, page: 0, per_page: 50, sort: 'date:-1', include_totals: true }; * @@ -1361,25 +1239,22 @@ utils.wrapPropertyMethod(ManagementClient, 'linkUsers', 'users.link'); * * console.log(logs); * }); - * - * @param {Object} params Get logs data. - * @param {String} params.id User id. - * @param {Number} params.per_page Number of results per page. - * @param {Number} params.page Page number, zero indexed. - * @param {String} params.sort The field to use for sorting. Use field:order where order is 1 for ascending and -1 for descending. For example date:-1. - * @param {Boolean} params.include_totals true if a query summary must be included in the result, false otherwise. Default false; + * @param {object} params Get logs data. + * @param {string} params.id User id. + * @param {number} params.per_page Number of results per page. + * @param {number} params.page Page number, zero indexed. + * @param {string} params.sort The field to use for sorting. Use field:order where order is 1 for ascending and -1 for descending. For example date:-1. + * @param {boolean} params.include_totals true if a query summary must be included in the result, false otherwise. Default false; * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getUserLogs', 'users.logs'); /** * Get user's roles * - * @method getUserRoles - * @memberOf module:management.ManagementClient.prototype - * + * @function getUserRoles + * @memberof module:management.ManagementClient.prototype * @example * var params = { id: USER_ID, page: 0, per_page: 50, sort: 'date:-1', include_totals: true }; * @@ -1390,25 +1265,22 @@ utils.wrapPropertyMethod(ManagementClient, 'getUserLogs', 'users.logs'); * * console.log(logs); * }); - * - * @param {Object} params Get roles data. - * @param {String} params.id User id. - * @param {Number} params.per_page Number of results per page. - * @param {Number} params.page Page number, zero indexed. - * @param {String} params.sort The field to use for sorting. Use field:order where order is 1 for ascending and -1 for descending. For example date:-1. - * @param {Boolean} params.include_totals true if a query summary must be included in the result, false otherwise. Default false; + * @param {object} params Get roles data. + * @param {string} params.id User id. + * @param {number} params.per_page Number of results per page. + * @param {number} params.page Page number, zero indexed. + * @param {string} params.sort The field to use for sorting. Use field:order where order is 1 for ascending and -1 for descending. For example date:-1. + * @param {boolean} params.include_totals true if a query summary must be included in the result, false otherwise. Default false; * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getUserRoles', 'users.getRoles'); /** * Assign roles to a user * - * @method assignRolestoUser - * @memberOf module:management.ManagementClient.prototype - * + * @function assignRolestoUser + * @memberof module:management.ManagementClient.prototype * @example * var parms = { id : 'USER_ID'}; * var data = { "roles" :["role1"]}; @@ -1420,23 +1292,20 @@ utils.wrapPropertyMethod(ManagementClient, 'getUserRoles', 'users.getRoles'); * * // User assigned roles. * }); - * - * @param {Object} params params object - * @param {String} params.id user_id - * @param {Object} data data object containing list of role IDs - * @param {String} data.roles Array of role IDs + * @param {object} params params object + * @param {string} params.id user_id + * @param {object} data data object containing list of role IDs + * @param {string} data.roles Array of role IDs * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'assignRolestoUser', 'users.assignRoles'); /** * Assign users to a role * - * @method assignUsersToRole - * @memberOf module:management.ManagementClient.prototype - * + * @function assignUsersToRole + * @memberof module:management.ManagementClient.prototype * @example * var params = { id :'ROLE_ID'}; * var data = { "users" : ["userId1","userId2"]}; @@ -1448,24 +1317,21 @@ utils.wrapPropertyMethod(ManagementClient, 'assignRolestoUser', 'users.assignRol * * // permissions added. * }); - * - * @param {String} params.id ID of the Role. - * @param {Object} data permissions data - * @param {String} data.permissions Array of permissions - * @param {String} data.permissions.permission_name Name of a permission - * @param {String} data.permissions.resource_server_identifier Identifier for a resource + * @param {string} params.id ID of the Role. + * @param {object} data permissions data + * @param {string} data.permissions Array of permissions + * @param {string} data.permissions.permission_name Name of a permission + * @param {string} data.permissions.resource_server_identifier Identifier for a resource * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'assignUsersToRole', 'roles.assignUsers'); /** * Remove roles from a user * - * @method removeRolesFromUser - * @memberOf module:management.ManagementClient.prototype - * + * @function removeRolesFromUser + * @memberof module:management.ManagementClient.prototype * @example * var parms = { id : 'USER_ID'}; * var data = { "roles" :["role1"]}; @@ -1477,23 +1343,20 @@ utils.wrapPropertyMethod(ManagementClient, 'assignUsersToRole', 'roles.assignUse * * // User assigned roles. * }); - * - * @param {Object} params params object - * @param {String} params.id user_id - * @param {String} data data object containing list of role IDs - * @param {String} data.roles Array of role IDs + * @param {object} params params object + * @param {string} params.id user_id + * @param {string} data data object containing list of role IDs + * @param {string} data.roles Array of role IDs * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'removeRolesFromUser', 'users.removeRoles'); /** * Get user's permissions * - * @method getUserPermissions - * @memberOf module:management.ManagementClient.prototype - * + * @function getUserPermissions + * @memberof module:management.ManagementClient.prototype * @example * var params = { id: USER_ID, page: 0, per_page: 50, sort: 'date:-1', include_totals: true }; * @@ -1504,25 +1367,22 @@ utils.wrapPropertyMethod(ManagementClient, 'removeRolesFromUser', 'users.removeR * * console.log(logs); * }); - * - * @param {Object} params Get permissions data. - * @param {String} params.id User id. - * @param {Number} params.per_page Number of results per page. - * @param {Number} params.page Page number, zero indexed. - * @param {String} params.sort The field to use for sorting. Use field:order where order is 1 for ascending and -1 for descending. For example date:-1. - * @param {Boolean} params.include_totals true if a query summary must be included in the result, false otherwise. Default false; + * @param {object} params Get permissions data. + * @param {string} params.id User id. + * @param {number} params.per_page Number of results per page. + * @param {number} params.page Page number, zero indexed. + * @param {string} params.sort The field to use for sorting. Use field:order where order is 1 for ascending and -1 for descending. For example date:-1. + * @param {boolean} params.include_totals true if a query summary must be included in the result, false otherwise. Default false; * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getUserPermissions', 'users.getPermissions'); /** * Assign permissions to a user * - * @method assignPermissionsToUser - * @memberOf module:management.ManagementClient.prototype - * + * @function assignPermissionsToUser + * @memberof module:management.ManagementClient.prototype * @example * var parms = { id : 'USER_ID'}; * var data = { "permissions" : [{"permission_name" :"do:something" ,"resource_server_identifier" :"test123" }]}; @@ -1534,23 +1394,20 @@ utils.wrapPropertyMethod(ManagementClient, 'getUserPermissions', 'users.getPermi * * // User assigned permissions. * }); - * - * @param {Object} params params object - * @param {String} params.id user_id - * @param {String} data data object containing list of permissions - * @param {String} data.permissions Array of permission IDs + * @param {object} params params object + * @param {string} params.id user_id + * @param {string} data data object containing list of permissions + * @param {string} data.permissions Array of permission IDs * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'assignPermissionsToUser', 'users.assignPermissions'); /** * Remove permissions from a user * - * @method removePermissionsFromUser - * @memberOf module:management.ManagementClient.prototype - * + * @function removePermissionsFromUser + * @memberof module:management.ManagementClient.prototype * @example * var parms = { id : 'USER_ID'}; * var data = { "permissions" : [{"permission_name" :"do:something" ,"resource_server_identifier" :"test123" }]}; @@ -1562,33 +1419,28 @@ utils.wrapPropertyMethod(ManagementClient, 'assignPermissionsToUser', 'users.ass * * // User assigned permissions. * }); - * - * @param {Object} params params object - * @param {String} params.id user_id - * @param {String} data data object containing list of permission IDs - * @param {String} data.permissions Array of permission IDs + * @param {object} params params object + * @param {string} params.id user_id + * @param {string} data data object containing list of permission IDs + * @param {string} data.permissions Array of permission IDs * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'removePermissionsFromUser', 'users.removePermissions'); /** * Get a list of a user's Guardian enrollments. * - * @method getGuardianEnrollments - * @memberOf module:management.ManagementClient.prototype - * + * @function getGuardianEnrollments + * @memberof module:management.ManagementClient.prototype * @example * management.getGuardianEnrollments({ id: USER_ID }, function (err, enrollments) { * console.log(enrollments); * }); - * - * @param {Object} data The user data object. - * @param {String} data.id The user id. + * @param {object} data The user data object. + * @param {string} data.id The user id. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod( ManagementClient, @@ -1599,19 +1451,16 @@ utils.wrapPropertyMethod( /** * Generate new Guardian recovery code. * - * @method regenerateRecoveryCode - * @memberOf module:management.ManagementClient.prototype - * + * @function regenerateRecoveryCode + * @memberof module:management.ManagementClient.prototype * @example * management.regenerateRecoveryCode({ id: USER_ID }, function (err, newRecoveryCode) { * console.log(newRecoveryCode); * }); - * - * @param {Object} data The user data object. - * @param {String} data.id The user id. + * @param {object} data The user data object. + * @param {string} data.id The user id. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod( ManagementClient, @@ -1622,9 +1471,8 @@ utils.wrapPropertyMethod( /** * Invalidate all remembered browsers for MFA. * - * @method invalidateRememberBrowser - * @memberOf module:management.ManagementClient.prototype - * + * @function invalidateRememberBrowser + * @memberof module:management.ManagementClient.prototype * @example * management.invalidateRememberBrowser({ id: USER_ID }, function (err) { * if (err) { @@ -1633,12 +1481,10 @@ utils.wrapPropertyMethod( * * // Invalidated all remembered browsers. * }); - * - * @param {Object} data The user data object. - * @param {String} data.id The user id. + * @param {object} data The user data object. + * @param {string} data.id The user id. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod( ManagementClient, @@ -1649,9 +1495,8 @@ utils.wrapPropertyMethod( /** * Get user blocks by its id. * - * @method getUserBlocks - * @memberOf module:management.ManagementClient.prototype - * + * @function getUserBlocks + * @memberof module:management.ManagementClient.prototype * @example * management.getUserBlocks({ id: USER_ID }, function (err, blocks) { * if (err) { @@ -1660,21 +1505,18 @@ utils.wrapPropertyMethod( * * console.log(blocks); * }); - * - * @param {Object} params The user data object.. - * @param {String} params.id The user id. + * @param {object} params The user data object.. + * @param {string} params.id The user id. * @param {Function} [cb] Callback function - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getUserBlocks', 'userBlocks.get'); /** * Unblock an user by its id. * - * @method unblockUser - * @memberOf module:management.ManagementClient.prototype - * + * @function unblockUser + * @memberof module:management.ManagementClient.prototype * @example * management.unblockUser({ id: USER_ID }, function (err) { * if (err) { @@ -1683,21 +1525,18 @@ utils.wrapPropertyMethod(ManagementClient, 'getUserBlocks', 'userBlocks.get'); * * // User unblocked. * }); - * - * @param {Object} params The user data object.. - * @param {String} params.id The user id. + * @param {object} params The user data object.. + * @param {string} params.id The user id. * @param {Function} [cb] Callback function - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'unblockUser', 'userBlocks.delete'); /** * Get user blocks by its identifier. * - * @method getUserBlocksByIdentifier - * @memberOf module:management.ManagementClient.prototype - * + * @function getUserBlocksByIdentifier + * @memberof module:management.ManagementClient.prototype * @example * management.getUserBlocksByIdentifier({ identifier: USER_ID }, function (err, blocks) { * if (err) { @@ -1706,12 +1545,10 @@ utils.wrapPropertyMethod(ManagementClient, 'unblockUser', 'userBlocks.delete'); * * console.log(blocks); * }); - * - * @param {Object} params The user data object.. - * @param {String} params.identifier The user identifier, any of: username, phone_number, email. + * @param {object} params The user data object.. + * @param {string} params.identifier The user identifier, any of: username, phone_number, email. * @param {Function} [cb] Callback function - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod( ManagementClient, @@ -1722,9 +1559,8 @@ utils.wrapPropertyMethod( /** * Unblock an user by its id. * - * @method unblockUser - * @memberOf module:management.ManagementClient.prototype - * + * @function unblockUser + * @memberof module:management.ManagementClient.prototype * @example * management.unblockUserByIdentifier({ identifier: USER_ID }, function (err) { * if (err) { @@ -1733,12 +1569,10 @@ utils.wrapPropertyMethod( * * // User unblocked. * }); - * - * @param {Object} params The user data object.. - * @param {String} params.identifier The user identifier, any of: username, phone_number, email. + * @param {object} params The user data object.. + * @param {string} params.identifier The user identifier, any of: username, phone_number, email. * @param {Function} [cb] Callback function - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod( ManagementClient, @@ -1749,19 +1583,16 @@ utils.wrapPropertyMethod( /** * Get a single Guardian enrollment. * - * @method getGuardianEnrollment - * @memberOf module:management.ManagementClient.prototype - * + * @function getGuardianEnrollment + * @memberof module:management.ManagementClient.prototype * @example * management.getGuardianEnrollment({ id: ENROLLMENT_ID }, function (err, enrollment) { * console.log(enrollment); * }); - * - * @param {Object} data The Guardian enrollment data object. - * @param {String} data.id The Guardian enrollment id. + * @param {object} data The Guardian enrollment data object. + * @param {string} data.id The Guardian enrollment id. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod( ManagementClient, @@ -1772,9 +1603,8 @@ utils.wrapPropertyMethod( /** * Delete a user's Guardian enrollment. * - * @method deleteGuardianEnrollment - * @memberOf module:management.ManagementClient.prototype - * + * @function deleteGuardianEnrollment + * @memberof module:management.ManagementClient.prototype * @example * management.deleteGuardianEnrollment({ id: ENROLLMENT_ID }, function (err) { * if (err) { @@ -1783,12 +1613,10 @@ utils.wrapPropertyMethod( * * // Email provider deleted. * }); - * - * @param {Object} data The Guardian enrollment data object. - * @param {String} data.id The Guardian enrollment id. + * @param {object} data The Guardian enrollment data object. + * @param {string} data.id The Guardian enrollment id. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod( ManagementClient, @@ -1799,26 +1627,22 @@ utils.wrapPropertyMethod( /** * Get all blacklisted tokens. * - * @method getBlacklistedTokens - * @memberOf module:management.ManagementClient.prototype - * + * @function getBlacklistedTokens + * @memberof module:management.ManagementClient.prototype * @example * management.getBlacklistedTokens(function (err, tokens) { * console.log(tokens.length); * }); - * * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getBlacklistedTokens', 'blacklistedTokens.getAll'); /** * Blacklist a new token. * - * @method blacklistToken - * @memberOf module:management.ManagementClient.prototype - * + * @function blacklistToken + * @memberof module:management.ManagementClient.prototype * @example * var token = { * aud: 'aud', @@ -1832,42 +1656,36 @@ utils.wrapPropertyMethod(ManagementClient, 'getBlacklistedTokens', 'blacklistedT * * // Token blacklisted. * }); - * - * @param {Object} token Token data. - * @param {String} token.aud Audience (your app client ID). - * @param {String} token.jti The JWT ID claim. + * @param {object} token Token data. + * @param {string} token.aud Audience (your app client ID). + * @param {string} token.jti The JWT ID claim. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'blacklistToken', 'blacklistedTokens.add'); /** * Create a new Email Template. * - * @method createEmailTemplate - * @memberOf module:management.ManagementClient.prototype - * + * @function createEmailTemplate + * @memberof module:management.ManagementClient.prototype * @example * management.createEmailTemplate(data, function (err) { * if (err) { * // Handle error. * // Email Template created. * }); - * - * @param {Object} data Email Template data object. + * @param {object} data Email Template data object. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'createEmailTemplate', 'emailTemplates.create'); /** * Get an Auth0 Email Template. * - * @method getEmailTemplate - * @memberOf module:management.ManagementClient.prototype - * + * @function getEmailTemplate + * @memberof module:management.ManagementClient.prototype * @example * management.getEmailTemplate({ name: EMAIL_TEMPLATE_NAME }, function (err, emailTemplate) { * if (err) { @@ -1876,21 +1694,18 @@ utils.wrapPropertyMethod(ManagementClient, 'createEmailTemplate', 'emailTemplate * * console.log(emailTemplate); * }); - * - * @param {Object} params Email Template parameters. - * @param {String} params.name Template Name + * @param {object} params Email Template parameters. + * @param {string} params.name Template Name * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getEmailTemplate', 'emailTemplates.get'); /** * Update an existing Email Template. * - * @method updateEmailTemplates - * @memberOf module:management.ManagementClient.prototype - * + * @function updateEmailTemplates + * @memberof module:management.ManagementClient.prototype * @example * var data = { from: 'new@email.com' }; * var params = { name: EMAIL_TEMPLATE_NAME }; @@ -1902,42 +1717,36 @@ utils.wrapPropertyMethod(ManagementClient, 'getEmailTemplate', 'emailTemplates.g * * console.log(emailTemplate.from); // 'new@email.com' * }); - * - * @param {Object} params Email Template parameters. - * @param {String} params.name Template Name - * @param {Object} data Updated Email Template data. + * @param {object} params Email Template parameters. + * @param {string} params.name Template Name + * @param {object} data Updated Email Template data. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'updateEmailTemplate', 'emailTemplates.update'); /** * Get the email provider. * - * @method getEmailProvider - * @memberOf module:management.ManagementClient.prototype - * + * @function getEmailProvider + * @memberof module:management.ManagementClient.prototype * @example * management.getEmailProvider(function (err, provider) { * console.log(provider.length); * }); - * * @param {Function} [cb] Callback function. - * @param {Object} [params] Clients parameters. - * @param {Number} [params.fields] A comma separated list of fields to include or exclude (depending on include_fields) from the result, empty to retrieve: name, enabled, settings fields. - * @param {Number} [params.include_fields] true if the fields specified are to be excluded from the result, false otherwise (defaults to true) - - * @return {Promise|undefined} + * @param {object} [params] Clients parameters. + * @param {number} [params.fields] A comma separated list of fields to include or exclude (depending on include_fields) from the result, empty to retrieve: name, enabled, settings fields. + * @param {number} [params.include_fields] true if the fields specified are to be excluded from the result, false otherwise (defaults to true) + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getEmailProvider', 'emailProvider.get'); /** * Configure the email provider. * - * @method configureEmailProvider - * @memberOf module:management.ManagementClient.prototype - * + * @function configureEmailProvider + * @memberof module:management.ManagementClient.prototype * @example * management.configureEmailProvider(data, function (err) { * if (err) { @@ -1946,20 +1755,17 @@ utils.wrapPropertyMethod(ManagementClient, 'getEmailProvider', 'emailProvider.ge * * // Email provider configured. * }); - * - * @param {Object} data The email provider data object. + * @param {object} data The email provider data object. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'configureEmailProvider', 'emailProvider.configure'); /** * Delete email provider. * - * @method deleteEmailProvider - * @memberOf module:management.ManagementClient.prototype - * + * @function deleteEmailProvider + * @memberof module:management.ManagementClient.prototype * @example * management.deleteEmailProvider(function (err) { * if (err) { @@ -1968,19 +1774,16 @@ utils.wrapPropertyMethod(ManagementClient, 'configureEmailProvider', 'emailProvi * * // Email provider deleted. * }); - * * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'deleteEmailProvider', 'emailProvider.delete'); /** * Update the email provider. * - * @method updateEmailProvider - * @memberOf module:management.ManagementClient.prototype - * + * @function updateEmailProvider + * @memberof module:management.ManagementClient.prototype * @example * management.updateEmailProvider(params, data, function (err, provider) { * if (err) { @@ -1990,21 +1793,18 @@ utils.wrapPropertyMethod(ManagementClient, 'deleteEmailProvider', 'emailProvider * // Updated email provider. * console.log(provider); * }); - * - * @param {Object} params Email provider parameters. - * @param {Object} data Updated email provider data. + * @param {object} params Email provider parameters. + * @param {object} data Updated email provider data. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'updateEmailProvider', 'emailProvider.update'); /** * Get a the active users count. * - * @method getActiveUsersCount - * @memberOf module:management.ManagementClient.prototype - * + * @function getActiveUsersCount + * @memberof module:management.ManagementClient.prototype * @example * management.getActiveUsersCount(function (err, usersCount) { * if (err) { @@ -2013,19 +1813,16 @@ utils.wrapPropertyMethod(ManagementClient, 'updateEmailProvider', 'emailProvider * * console.log(usersCount); * }); - * * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getActiveUsersCount', 'stats.getActiveUsersCount'); /** * Get the daily stats. * - * @method getDailyStats - * @memberOf module:management.ManagementClient.prototype - * + * @function getDailyStats + * @memberof module:management.ManagementClient.prototype * @example * var params = { * from: '{YYYYMMDD}', // First day included in the stats. @@ -2039,22 +1836,19 @@ utils.wrapPropertyMethod(ManagementClient, 'getActiveUsersCount', 'stats.getActi * * console.log(stats); * }); - * - * @param {Object} params Stats parameters. - * @param {String} params.from The first day in YYYYMMDD format. - * @param {String} params.to The last day in YYYYMMDD format. + * @param {object} params Stats parameters. + * @param {string} params.from The first day in YYYYMMDD format. + * @param {string} params.to The last day in YYYYMMDD format. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getDailyStats', 'stats.getDaily'); /** * Get the tenant settings.. * - * @method getTenantSettings - * @memberOf module:management.ManagementClient.prototype - * + * @function getTenantSettings + * @memberof module:management.ManagementClient.prototype * @example * management.getSettings(function (err, settings) { * if (err) { @@ -2063,39 +1857,33 @@ utils.wrapPropertyMethod(ManagementClient, 'getDailyStats', 'stats.getDaily'); * * console.log(settings); * }); - * * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getTenantSettings', 'tenant.getSettings'); /** * Update the tenant settings. * - * @method updateTenantSettings - * @memberOf module:management.ManagementClient.prototype - * + * @function updateTenantSettings + * @memberof module:management.ManagementClient.prototype * @example * management.updateTenantSettings(data, function (err) { * if (err) { * // Handle error. * } * }); - * - * @param {Object} data The new tenant settings. + * @param {object} data The new tenant settings. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'updateTenantSettings', 'tenant.updateSettings'); /** * Get a job by its ID. * - * @method getJob - * @memberOf module:management.ManagementClient.prototype - * + * @function getJob + * @memberof module:management.ManagementClient.prototype * @example * var params = { * id: '{JOB_ID}' @@ -2109,12 +1897,10 @@ utils.wrapPropertyMethod(ManagementClient, 'updateTenantSettings', 'tenant.updat * // Retrieved job. * console.log(job); * }); - * - * @param {Object} params Job parameters. - * @param {String} params.id Job ID. + * @param {object} params Job parameters. + * @param {string} params.id Job ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getJob', 'jobs.get'); @@ -2123,9 +1909,8 @@ utils.wrapPropertyMethod(ManagementClient, 'getJob', 'jobs.get'); * users contained in the file or JSON string and associate them with the given * connection. * - * @method importUsers - * @memberOf module:management.ManagementClient.prototype - * + * @function importUsers + * @memberof module:management.ManagementClient.prototype * @example * var params = { * connection_id: '{CONNECTION_ID}', @@ -2137,16 +1922,14 @@ utils.wrapPropertyMethod(ManagementClient, 'getJob', 'jobs.get'); * // Handle error. * } * }); - * - * @param {Object} data Users import data. - * @param {String} data.connection_id connection_id of the connection to which users will be imported. - * @param {String} [data.users] Path to the users data file. Either users or users_json is mandatory. - * @param {String} [data.users_json] JSON data for the users. - * @param {Boolean} [data.upsert] Whether to update users if they already exist (true) or to ignore them (false). - * @param {Boolean} [data.send_completion_email] Whether to send a completion email to all tenant owners when the job is finished (true) or not (false). + * @param {object} data Users import data. + * @param {string} data.connection_id connection_id of the connection to which users will be imported. + * @param {string} [data.users] Path to the users data file. Either users or users_json is mandatory. + * @param {string} [data.users_json] JSON data for the users. + * @param {boolean} [data.upsert] Whether to update users if they already exist (true) or to ignore them (false). + * @param {boolean} [data.send_completion_email] Whether to send a completion email to all tenant owners when the job is finished (true) or not (false). * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'importUsers', 'jobs.importUsers'); @@ -2155,9 +1938,8 @@ utils.wrapPropertyMethod(ManagementClient, 'importUsers', 'jobs.importUsers'); * users contained in the file or JSON string and associate them with the given * connection. * - * @method importUsersJob - * @memberOf module:management.ManagementClient.prototype - * + * @function importUsersJob + * @memberof module:management.ManagementClient.prototype * @example * var params = { * connection_id: '{CONNECTION_ID}', @@ -2169,25 +1951,22 @@ utils.wrapPropertyMethod(ManagementClient, 'importUsers', 'jobs.importUsers'); * // Handle error. * } * }); - * - * @param {Object} data Users import data. - * @param {String} data.connection_id connection_id of the connection to which users will be imported. - * @param {String} [data.users] Path to the users data file. Either users or users_json is mandatory. - * @param {String} [data.users_json] JSON data for the users. - * @param {Boolean} [data.upsert] Whether to update users if they already exist (true) or to ignore them (false). - * @param {Boolean} [data.send_completion_email] Whether to send a completion email to all tenant owners when the job is finished (true) or not (false). + * @param {object} data Users import data. + * @param {string} data.connection_id connection_id of the connection to which users will be imported. + * @param {string} [data.users] Path to the users data file. Either users or users_json is mandatory. + * @param {string} [data.users_json] JSON data for the users. + * @param {boolean} [data.upsert] Whether to update users if they already exist (true) or to ignore them (false). + * @param {boolean} [data.send_completion_email] Whether to send a completion email to all tenant owners when the job is finished (true) or not (false). * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'importUsersJob', 'jobs.importUsersJob'); /** * Export all users to a file using a long running job. * - * @method exportUsers - * @memberOf module:management.ManagementClient.prototype - * + * @function exportUsers + * @memberof module:management.ManagementClient.prototype * @example * var data = { * connection_id: 'con_0000000000000001', @@ -2221,24 +2000,21 @@ utils.wrapPropertyMethod(ManagementClient, 'importUsersJob', 'jobs.importUsersJo * // Retrieved job. * console.log(results); * }); - * - * @param {Object} data Users export data. - * @param {String} [data.connection_id] The connection id of the connection from which users will be exported - * @param {String} [data.format] The format of the file. Valid values are: "json" and "csv". - * @param {Number} [data.limit] Limit the number of records. - * @param {Object[]} [data.fields] A list of fields to be included in the CSV. If omitted, a set of predefined fields will be exported. + * @param {object} data Users export data. + * @param {string} [data.connection_id] The connection id of the connection from which users will be exported + * @param {string} [data.format] The format of the file. Valid values are: "json" and "csv". + * @param {number} [data.limit] Limit the number of records. + * @param {object[]} [data.fields] A list of fields to be included in the CSV. If omitted, a set of predefined fields will be exported. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'exportUsers', 'jobs.exportUsers'); /** * Given a job ID, retrieve the failed/errored items * - * @method errors - * @memberOf module:management.JobsManager.prototype - * + * @function errors + * @memberof module:management.JobsManager.prototype * @example * var params = { * id: '{JOB_ID}' @@ -2252,21 +2028,18 @@ utils.wrapPropertyMethod(ManagementClient, 'exportUsers', 'jobs.exportUsers'); * // Retrieved job. * console.log(job); * }); - * - * @param {Object} params Job parameters. - * @param {String} params.id Job ID. + * @param {object} params Job parameters. + * @param {string} params.id Job ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getJobErrors', 'jobs.errors'); /** * Send a verification email to a user. * - * @method sendEmailVerification - * @memberOf module:management.ManagementClient.prototype - * + * @function sendEmailVerification + * @memberof module:management.ManagementClient.prototype * @example * var params = { * user_id: '{USER_ID}' @@ -2277,26 +2050,23 @@ utils.wrapPropertyMethod(ManagementClient, 'getJobErrors', 'jobs.errors'); * // Handle error. * } * }); - * - * @param {Object} data User data object. - * @param {String} data.user_id ID of the user to be verified. - * @param {String} [data.organization_id] Organization ID - * @param {String} [data.client_id] client_id of the client (application). If no value provided, the global Client ID will be used. - * @param {Object} [data.identity] Used to verify secondary, federated, and passwordless-email identities. - * @param {String} data.identity.user_id user_id of the identity. - * @param {String} data.identity.provider provider of the identity. + * @param {object} data User data object. + * @param {string} data.user_id ID of the user to be verified. + * @param {string} [data.organization_id] Organization ID + * @param {string} [data.client_id] client_id of the client (application). If no value provided, the global Client ID will be used. + * @param {object} [data.identity] Used to verify secondary, federated, and passwordless-email identities. + * @param {string} data.identity.user_id user_id of the identity. + * @param {string} data.identity.provider provider of the identity. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'sendEmailVerification', 'jobs.verifyEmail'); /** * Create a new password change ticket. * - * @method createPasswordChangeTicket - * @memberOf module:management.ManagementClient.prototype - * + * @function createPasswordChangeTicket + * @memberof module:management.ManagementClient.prototype * @example * * var params = { @@ -2317,18 +2087,16 @@ utils.wrapPropertyMethod(ManagementClient, 'sendEmailVerification', 'jobs.verify * // Handle error. * } * }); - * * @param {Function} [cb] Callback function. - * @return {Promise} + * @returns {Promise} */ utils.wrapPropertyMethod(ManagementClient, 'createPasswordChangeTicket', 'tickets.changePassword'); /** * Create an email verification ticket. * - * @method createEmailVerificationTicket - * @memberOf module:management.ManagementClient.prototype - * + * @function createEmailVerificationTicket + * @memberof module:management.ManagementClient.prototype * @example * var data = { * user_id: '{USER_ID}', @@ -2340,18 +2108,16 @@ utils.wrapPropertyMethod(ManagementClient, 'createPasswordChangeTicket', 'ticket * // Handle error. * } * }); - * * @param {Function} [cb] Callback function. - * @return {Promise} + * @returns {Promise} */ utils.wrapPropertyMethod(ManagementClient, 'createEmailVerificationTicket', 'tickets.verifyEmail'); /** * Get an Auth0 log. * - * @method getLog - * @memberOf module:management.ManagementClient.prototype - * + * @function getLog + * @memberof module:management.ManagementClient.prototype * @example * management.getLog({ id: EVENT_ID }, function (err, log) { * if (err) { @@ -2360,21 +2126,18 @@ utils.wrapPropertyMethod(ManagementClient, 'createEmailVerificationTicket', 'tic * * console.log(log); * }); - * - * @param {Object} params Log parameters. - * @param {String} params.id Event ID. + * @param {object} params Log parameters. + * @param {string} params.id Event ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getLog', 'logs.get'); /** * Get all logs. * - * @method getLogs - * @memberOf module:management.ManagementClient.prototype - * + * @function getLogs + * @memberof module:management.ManagementClient.prototype * @example * This method takes an optional object as first argument that may be used to * specify pagination settings and the search query. If pagination options are @@ -2390,45 +2153,40 @@ utils.wrapPropertyMethod(ManagementClient, 'getLog', 'logs.get'); * management.getLogs(params, function (err, logs) { * console.log(logs.length); * }); - * - * @param {Object} [params] Logs params. - * @param {String} [params.q] Search Criteria using Query String Syntax - * @param {Number} [params.page] Page number. Zero based - * @param {Number} [params.per_page] The amount of entries per page - * @param {String} [params.sort] The field to use for sorting. - * @param {String} [params.fields] A comma separated list of fields to include or exclude - * @param {Boolean} [params.include_fields] true if the fields specified are to be included in the result, false otherwise. - * @param {Boolean} [params.include_totals] true if a query summary must be included in the result, false otherwise. Default false + * @param {object} [params] Logs params. + * @param {string} [params.q] Search Criteria using Query String Syntax + * @param {number} [params.page] Page number. Zero based + * @param {number} [params.per_page] The amount of entries per page + * @param {string} [params.sort] The field to use for sorting. + * @param {string} [params.fields] A comma separated list of fields to include or exclude + * @param {boolean} [params.include_fields] true if the fields specified are to be included in the result, false otherwise. + * @param {boolean} [params.include_totals] true if a query summary must be included in the result, false otherwise. Default false * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getLogs', 'logs.getAll'); /** * Get all Log Streams. * - * @method getLogStreams - * @memberOf module:management.ManagementClient.prototype + * @function getLogStreams + * @memberof module:management.ManagementClient.prototype * * * * management.getLogStreams( function (err, logStreams) { * console.log(logStreams.length); * }); - * * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getLogStreams', 'logStreams.getAll'); /** * Create a new Log Stream. * - * @method createLogStream - * @memberOf module:management.ManagementClient.prototype - * + * @function createLogStream + * @memberof module:management.ManagementClient.prototype * @example * management.createLogStream(data, function (err) { * if (err) { @@ -2437,20 +2195,17 @@ utils.wrapPropertyMethod(ManagementClient, 'getLogStreams', 'logStreams.getAll') * * // Log Stream created. * }); - * - * @param {Object} data Log Stream data. + * @param {object} data Log Stream data. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'createLogStream', 'logStreams.create'); /** * Get an Auth0 Log Stream. * - * @method getLogStream - * @memberOf module:management.ManagementClient.prototype - * + * @function getLogStream + * @memberof module:management.ManagementClient.prototype * @example * management.getLogStream({ id: LOG_STREAM_ID }, function (err, logStream) { * if (err) { @@ -2459,21 +2214,18 @@ utils.wrapPropertyMethod(ManagementClient, 'createLogStream', 'logStreams.create * * console.log(logStream); * }); - * - * @param {Object} params Log Stream parameters. - * @param {String} params.id Log Stream ID. + * @param {object} params Log Stream parameters. + * @param {string} params.id Log Stream ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getLogStream', 'logStreams.get'); /** * Delete an existing Log Stream. * - * @method deleteLogStream - * @memberOf module:management.ManagementClient.prototype - * + * @function deleteLogStream + * @memberof module:management.ManagementClient.prototype * @example * management.deleteLogStream({ id: LOG_STREAM_ID }, function (err) { * if (err) { @@ -2482,21 +2234,18 @@ utils.wrapPropertyMethod(ManagementClient, 'getLogStream', 'logStreams.get'); * * // Log Stream deleted. * }); - * - * @param {Object} params Log Stream parameters. - * @param {String} params.id Log Stream ID. + * @param {object} params Log Stream parameters. + * @param {string} params.id Log Stream ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'deleteLogStream', 'logStreams.delete'); /** * Update an existing Log Stream. * - * @method updateLogStream - * @memberOf module:management.ManagementClient.prototype - * + * @function updateLogStream + * @memberof module:management.ManagementClient.prototype * @example * var params = { id: LOG_STREAM_ID }; * var data = { name: 'my-log-stream'}; @@ -2507,22 +2256,19 @@ utils.wrapPropertyMethod(ManagementClient, 'deleteLogStream', 'logStreams.delete * * console.log(logStream.name); // 'my-log-stream'. * }); - * - * @param {Object} params Rule parameters. - * @param {String} params.id Rule ID. - * @param {Object} data Updated rule data. + * @param {object} params Rule parameters. + * @param {string} params.id Rule ID. + * @param {object} data Updated rule data. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'updateLogStream', 'logStreams.update'); /** * Create a new resource server. * - * @method createResourceServer - * @memberOf module:management.ManagementClient.prototype - * + * @function createResourceServer + * @memberof module:management.ManagementClient.prototype * @example * management.createResourceServer(data, function (err) { * if (err) { @@ -2531,20 +2277,17 @@ utils.wrapPropertyMethod(ManagementClient, 'updateLogStream', 'logStreams.update * * // Resource Server created. * }); - * - * @param {Object} data Resource Server data object. + * @param {object} data Resource Server data object. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'createResourceServer', 'resourceServers.create'); /** * Get all resource servers. * - * @method getResourceServers - * @memberOf module:management.ManagementClient.prototype - * + * @function getResourceServers + * @memberof module:management.ManagementClient.prototype * @example * This method takes an optional object as first argument that may be used to * specify pagination settings. If pagination options are not present, @@ -2560,22 +2303,19 @@ utils.wrapPropertyMethod(ManagementClient, 'createResourceServer', 'resourceServ * management.getResourceServers(params, function (err, resourceServers) { * console.log(resourceServers.length); * }); - * - * @param {Object} [params] Resource Servers parameters. - * @param {Number} [params.per_page] Number of results per page. - * @param {Number} [params.page] Page number, zero indexed. + * @param {object} [params] Resource Servers parameters. + * @param {number} [params.per_page] Number of results per page. + * @param {number} [params.page] Page number, zero indexed. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getResourceServers', 'resourceServers.getAll'); /** * Get a Resource Server. * - * @method getResourceServer - * @memberOf module:management.ManagementClient.prototype - * + * @function getResourceServer + * @memberof module:management.ManagementClient.prototype * @example * management.getResourceServer({ id: RESOURCE_SERVER_ID }, function (err, resourceServer) { * if (err) { @@ -2584,21 +2324,18 @@ utils.wrapPropertyMethod(ManagementClient, 'getResourceServers', 'resourceServer * * console.log(resourceServer); * }); - * - * @param {Object} params Resource Server parameters. - * @param {String} params.id Resource Server ID. + * @param {object} params Resource Server parameters. + * @param {string} params.id Resource Server ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getResourceServer', 'resourceServers.get'); /** * Delete an existing resource server. * - * @method deleteResourceServer - * @memberOf module:management.ManagementClient.prototype - * + * @function deleteResourceServer + * @memberof module:management.ManagementClient.prototype * @example * management.deleteResourceServer({ id: RESOURCE_SERVER_ID }, function (err) { * if (err) { @@ -2607,21 +2344,18 @@ utils.wrapPropertyMethod(ManagementClient, 'getResourceServer', 'resourceServers * * // Resource Server deleted. * }); - * - * @param {Object} params Resource Server parameters. - * @param {String} params.id Resource Server ID. + * @param {object} params Resource Server parameters. + * @param {string} params.id Resource Server ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'deleteResourceServer', 'resourceServers.delete'); /** * Update an existing resource server. * - * @method updateResourceServer - * @memberOf module:management.ManagementClient.prototype - * + * @function updateResourceServer + * @memberof module:management.ManagementClient.prototype * @example * var data = { name: 'newResourceServerName' }; * var params = { id: RESOURCE_SERVER_ID }; @@ -2633,22 +2367,19 @@ utils.wrapPropertyMethod(ManagementClient, 'deleteResourceServer', 'resourceServ * * console.log(resourceServer.name); // 'newResourceServerName' * }); - * - * @param {Object} params Resource Server parameters. - * @param {String} params.id Resource Server ID. - * @param {Object} data Updated Resource Server data. + * @param {object} params Resource Server parameters. + * @param {string} params.id Resource Server ID. + * @param {object} data Updated Resource Server data. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'updateResourceServer', 'resourceServers.update'); /** * Set a new rules config. * - * @method setRulesConfig - * @memberOf module:management.ManagementClient.prototype - * + * @function setRulesConfig + * @memberof module:management.ManagementClient.prototype * @example * var params = { key: RULE_CONFIG_KEY }; * var data = { value: RULES_CONFIG_VALUE }; @@ -2660,24 +2391,21 @@ utils.wrapPropertyMethod(ManagementClient, 'updateResourceServer', 'resourceServ * * // Rules Config set. * }); - * - * @param {Object} params Rule Config parameters. - * @param {String} params.key Rule Config key. - * @param {Object} data Rule Config Data parameters. - * @param {String} data.value Rule Config Data value. + * @param {object} params Rule Config parameters. + * @param {string} params.key Rule Config key. + * @param {object} data Rule Config Data parameters. + * @param {string} data.value Rule Config Data value. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'setRulesConfig', 'rulesConfigs.set'); /** * Get rules config. * - * @method getRulesConfigs - * @memberOf module:management.ManagementClient.prototype + * @function getRulesConfigs + * @memberof module:management.ManagementClient.prototype * @param {Function} [cb] Callback function. - * * @example * * management.getRulesConfigs(function (err, rulesConfigs) { @@ -2687,17 +2415,15 @@ utils.wrapPropertyMethod(ManagementClient, 'setRulesConfig', 'rulesConfigs.set') * * // Get Rules Configs. * }); - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getRulesConfigs', 'rulesConfigs.getAll'); /** * Delete rules config. * - * @method deleteRulesConfig - * @memberOf module:management.ManagementClient.prototype - * + * @function deleteRulesConfig + * @memberof module:management.ManagementClient.prototype * @example * * management.deleteRulesConfig({ key: RULE_CONFIG_KEY }, function (err) { @@ -2707,21 +2433,18 @@ utils.wrapPropertyMethod(ManagementClient, 'getRulesConfigs', 'rulesConfigs.getA * * // Rules Config deleted. * }); - * - * @param {Object} params Rule Configs parameters. - * @param {String} params.key Rule Configs key. + * @param {object} params Rule Configs parameters. + * @param {string} params.key Rule Configs key. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'deleteRulesConfig', 'rulesConfigs.delete'); /** * Create an Auth0 Custom Domain. * - * @method createCustomDomain - * @memberOf module:management.ManagementClient.prototype - * + * @function createCustomDomain + * @memberof module:management.ManagementClient.prototype * @example * management.createCustomDomain(data, function (err) { * if (err) { @@ -2730,35 +2453,30 @@ utils.wrapPropertyMethod(ManagementClient, 'deleteRulesConfig', 'rulesConfigs.de * * // CustomDomain created. * }); - * - * @param {Object} data The custom domain data object. + * @param {object} data The custom domain data object. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'createCustomDomain', 'customDomains.create'); /** * Get all Auth0 CustomDomains. * - * @method getCustomDomains - * @memberOf module:management.ManagementClient.prototype - * + * @function getCustomDomains + * @memberof module:management.ManagementClient.prototype * @example * management.getCustomDomains(function (err, customDomains) { * console.log(customDomains.length); * }); - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getCustomDomains', 'customDomains.getAll'); /** * Get a Custom Domain. * - * @method getCustomDomain - * @memberOf module:management.ManagementClient.prototype - * + * @function getCustomDomain + * @memberof module:management.ManagementClient.prototype * @example * management.getCustomDomain({ id: CUSTOM_DOMAIN_ID }, function (err, customDomain) { * if (err) { @@ -2767,21 +2485,18 @@ utils.wrapPropertyMethod(ManagementClient, 'getCustomDomains', 'customDomains.ge * * console.log(customDomain); * }); - * - * @param {Object} params Custom Domain parameters. - * @param {String} params.id Custom Domain ID. + * @param {object} params Custom Domain parameters. + * @param {string} params.id Custom Domain ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getCustomDomain', 'customDomains.get'); /** * Verify a Custom Domain. * - * @method verifyCustomDomain - * @memberOf module:management.ManagementClient.prototype - * + * @function verifyCustomDomain + * @memberof module:management.ManagementClient.prototype * @example * management.verifyCustomDomain({ id: CUSTOM_DOMAIN_ID }, function (err, customDomain) { * if (err) { @@ -2790,21 +2505,18 @@ utils.wrapPropertyMethod(ManagementClient, 'getCustomDomain', 'customDomains.get * * console.log(customDomain); * }); - * - * @param {Object} params Custom Domain parameters. - * @param {String} params.id Custom Domain ID. + * @param {object} params Custom Domain parameters. + * @param {string} params.id Custom Domain ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'verifyCustomDomain', 'customDomains.verify'); /** * Delete a Custom Domain. * - * @method deleteCustomDomain - * @memberOf module:management.ManagementClient.prototype - * + * @function deleteCustomDomain + * @memberof module:management.ManagementClient.prototype * @example * management.deleteCustomDomain({ id: CUSTOM_DOMAIN_ID }, function (err) { * if (err) { @@ -2813,29 +2525,24 @@ utils.wrapPropertyMethod(ManagementClient, 'verifyCustomDomain', 'customDomains. * * // CustomDomain deleted. * }); - * - * @param {Object} params Custom Domain parameters. - * @param {String} params.id Custom Domain ID. + * @param {object} params Custom Domain parameters. + * @param {string} params.id Custom Domain ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'deleteCustomDomain', 'customDomains.delete'); /** * Create a Guardian enrollment ticket. * - * @method createGuardianEnrollmentTicket - * @memberOf module:management.ManagementClient.prototype - * + * @function createGuardianEnrollmentTicket + * @memberof module:management.ManagementClient.prototype * @example * management.createGuardianEnrollmentTicket(function (err, ticket) { * console.log(ticket); * }); - * * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod( ManagementClient, @@ -2846,35 +2553,29 @@ utils.wrapPropertyMethod( /** * Get a list of Guardian factors and statuses. * - * @method getGuardianFactors - * @memberOf module:management.ManagementClient.prototype - * + * @function getGuardianFactors + * @memberof module:management.ManagementClient.prototype * @example * management.getGuardianFactors(function (err, factors) { * console.log(factors.length); * }); - * * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getGuardianFactors', 'guardian.getFactors'); /** * Get the settings of a Guardian factor. * - * @method getGuardianFactorSettings - * @memberOf module:management.ManagementClient.prototype - * + * @function getGuardianFactorSettings + * @memberof module:management.ManagementClient.prototype * @example * management.getGuardianFactorSettings({ name: 'duo' }, function (err, settings) { * console.log(settings); * }); - * - * @param {Object} params Factor parameters. + * @param {object} params Factor parameters. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod( ManagementClient, @@ -2885,18 +2586,15 @@ utils.wrapPropertyMethod( /** * Get Guardian factor provider configuration * - * @method getGuardianFactorProvider - * @memberOf module:management.ManagementClient.prototype - * + * @function getGuardianFactorProvider + * @memberof module:management.ManagementClient.prototype * @example * management.getFactorProvider({ name: 'sms', provider: 'twilio'}, function (err, provider) { * console.log(provider); * }); - * - * @param {Object} params Factor provider parameters. + * @param {object} params Factor provider parameters. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod( ManagementClient, @@ -2907,9 +2605,8 @@ utils.wrapPropertyMethod( /** * Update Guardian's factor provider * - * @method updateFactorProvider - * @memberOf module:management.ManagementClient.prototype - * + * @function updateFactorProvider + * @memberof module:management.ManagementClient.prototype * @example * management.updateGuardianFactorProvider({ name: 'sms', provider: 'twilio' }, { * messaging_service_sid: 'XXXXXXXXXXXXXX', @@ -2918,12 +2615,10 @@ utils.wrapPropertyMethod( * }, function (err, provider) { * console.log(provider); * }); - * - * @param {Object} params Factor provider parameters. - * @param {Object} data Updated Factor provider data. + * @param {object} params Factor provider parameters. + * @param {object} data Updated Factor provider data. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod( ManagementClient, @@ -2934,9 +2629,8 @@ utils.wrapPropertyMethod( /** * Update a Guardian's factor settings * - * @method updateGuardianFactorSettings - * @memberOf module:management.ManagementClient.prototype - * + * @function updateGuardianFactorSettings + * @memberof module:management.ManagementClient.prototype * @example * management.updateGuardianFactorSettings( * { name: 'webauthn-roaming' }, @@ -2944,12 +2638,10 @@ utils.wrapPropertyMethod( * function (err, settings) { * console.log(settings); * }) - * - * @param {Object} params Factor parameters. - * @param {Object} data Updated Factor settings data. + * @param {object} params Factor parameters. + * @param {object} data Updated Factor settings data. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod( ManagementClient, @@ -2960,18 +2652,15 @@ utils.wrapPropertyMethod( /** * Get Guardian enrollment and verification factor templates * - * @method getGuardianFactorTemplates - * @memberOf module:management.ManagementClient.prototype - * + * @function getGuardianFactorTemplates + * @memberof module:management.ManagementClient.prototype * @example * management.getGuardianFactorTemplates({ name: 'sms' }, function (err, templates) { * console.log(templates); * }); - * - * @param {Object} params Factor parameters. + * @param {object} params Factor parameters. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod( ManagementClient, @@ -2982,9 +2671,8 @@ utils.wrapPropertyMethod( /** * Update Guardian enrollment and verification factor templates * - * @method updateGuardianFactorTemplates - * @memberOf module:management.ManagementClient.prototype - * + * @function updateGuardianFactorTemplates + * @memberof module:management.ManagementClient.prototype * @example * management.updateGuardianFactorTemplates({ name: 'sms' }, { * enrollment_message: "{{code}} is your verification code for {{tenant.friendly_name}}. Please enter this code to verify your enrollment.", @@ -2992,12 +2680,10 @@ utils.wrapPropertyMethod( * }, function (err, templates) { * console.log(templates); * }); - * - * @param {Object} params Factor parameters. - * @param {Object} data Updated factor templates data. + * @param {object} params Factor parameters. + * @param {object} data Updated factor templates data. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod( ManagementClient, @@ -3008,76 +2694,64 @@ utils.wrapPropertyMethod( /** * Update Guardian Factor * - * @method updateGuardianFactor - * @memberOf module:management.ManagementClient.prototype - * + * @function updateGuardianFactor + * @memberof module:management.ManagementClient.prototype * @example * management.updateGuardianFactor({ name: 'sms' }, { * enabled: true * }, function (err, factor) { * console.log(factor); * }); - * - * @param {Object} params Factor parameters. - * @param {Object} data Updated factor data. + * @param {object} params Factor parameters. + * @param {object} data Updated factor data. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'updateGuardianFactor', 'guardian.updateFactor'); /** * Get enabled Guardian policies * - * @method getGuardianPolicies - * @memberOf module:management.ManagementClient.prototype - * + * @function getGuardianPolicies + * @memberof module:management.ManagementClient.prototype * @example * management.getGuardianPolicies(function (err, policies) { * console.log(policies); * }); - * * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getGuardianPolicies', 'guardian.getPolicies'); /** * Update enabled Guardian policies * - * @method updateGuardianPolicies - * @memberOf module:management.ManagementClient.prototype - * + * @function updateGuardianPolicies + * @memberof module:management.ManagementClient.prototype * @example * management.updateGuardianPolicies({}, [ * 'all-applications' * ], function (err, policies) { * console.log(policies); * }); - * - * @param {Object} params Parameters. - * @param {String[]} data Policies to enable. Empty array disables all policies. + * @param {object} params Parameters. + * @param {string[]} data Policies to enable. Empty array disables all policies. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'updateGuardianPolicies', 'guardian.updatePolicies'); /** * Get the Guardian phone factor's selected provider * - * @method getGuardianPhoneFactorSelectedProvider - * @memberOf module:management.ManagementClient.prototype - * + * @function getGuardianPhoneFactorSelectedProvider + * @memberof module:management.ManagementClient.prototype * @example * management.getGuardianPhoneFactorSelectedProvider(function (err, selectedProvider) { * console.log(selectedProvider); * }); - * * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod( ManagementClient, @@ -3088,22 +2762,19 @@ utils.wrapPropertyMethod( /** * Update the Guardian phone factor's selected provider * - * @method updateGuardianPhoneFactorSelectedProvider - * @memberOf module:management.ManagementClient.prototype - * + * @function updateGuardianPhoneFactorSelectedProvider + * @memberof module:management.ManagementClient.prototype * @example * management.updateGuardianPhoneFactorSelectedProvider({}, { * provider: 'twilio' * }, function (err, factor) { * console.log(factor); * }); - * - * @param {Object} params Parameters. - * @param {Object} data Updated selected provider data. - * @param {String} data.provider Name of the selected provider + * @param {object} params Parameters. + * @param {object} data Updated selected provider data. + * @param {string} data.provider Name of the selected provider * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod( ManagementClient, @@ -3114,17 +2785,14 @@ utils.wrapPropertyMethod( /** * Get the Guardian phone factor's message types * - * @method getGuardianPhoneFactorMessageTypes - * @memberOf module:management.ManagementClient.prototype - * + * @function getGuardianPhoneFactorMessageTypes + * @memberof module:management.ManagementClient.prototype * @example * management.getGuardianPhoneFactorMessageTypes(function (err, messageTypes) { * console.log(messageTypes); * }); - * * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod( ManagementClient, @@ -3135,22 +2803,19 @@ utils.wrapPropertyMethod( /** * Update the Guardian phone factor's message types * - * @method updateGuardianPhoneFactorMessageTypes - * @memberOf module:management.ManagementClient.prototype - * + * @function updateGuardianPhoneFactorMessageTypes + * @memberof module:management.ManagementClient.prototype * @example * management.updateGuardianPhoneFactorMessageTypes({}, { * message_types: ['sms', 'voice'] * }, function (err, factor) { * console.log(factor); * }); - * - * @param {Object} params Parameters. - * @param {Object} data Updated selected provider data. - * @param {String[]} data.message_types Message types (only `"sms"` and `"voice"` are supported). + * @param {object} params Parameters. + * @param {object} data Updated selected provider data. + * @param {string[]} data.message_types Message types (only `"sms"` and `"voice"` are supported). * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod( ManagementClient, @@ -3161,9 +2826,8 @@ utils.wrapPropertyMethod( /** * Get all roles. * - * @method getRoles - * @memberOf module:management.ManagementClient.prototype - * + * @function getRoles + * @memberof module:management.ManagementClient.prototype * @example * This method takes an optional object as first argument that may be used to * specify pagination settings. If pagination options are not present, @@ -3179,22 +2843,19 @@ utils.wrapPropertyMethod( * management.getRoles(params, function (err, roles) { * console.log(roles.length); * }); - * - * @param {Object} [params] Roles parameters. - * @param {Number} [params.per_page] Number of results per page. - * @param {Number} [params.page] Page number, zero indexed. + * @param {object} [params] Roles parameters. + * @param {number} [params.per_page] Number of results per page. + * @param {number} [params.page] Page number, zero indexed. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getRoles', 'roles.getAll'); /** * Create a new role. * - * @method createRole - * @memberOf module:management.ManagementClient.prototype - * + * @function createRole + * @memberof module:management.ManagementClient.prototype * @example * data = {"name": "test1","description": "123"} * management.createRole(data, function (err) { @@ -3204,20 +2865,17 @@ utils.wrapPropertyMethod(ManagementClient, 'getRoles', 'roles.getAll'); * * // Role created. * }); - * - * @param {Object} data Role data object. + * @param {object} data Role data object. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'createRole', 'roles.create'); /** * Get an Auth0 role. * - * @method getRole - * @memberOf module:management.ManagementClient.prototype - * + * @function getRole + * @memberof module:management.ManagementClient.prototype * @example * management.getRole({ id: ROLE_ID }, function (err, role) { * if (err) { @@ -3226,21 +2884,18 @@ utils.wrapPropertyMethod(ManagementClient, 'createRole', 'roles.create'); * * console.log(role); * }); - * - * @param {Object} params Role parameters. - * @param {String} params.id Role ID. + * @param {object} params Role parameters. + * @param {string} params.id Role ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getRole', 'roles.get'); /** * Delete an existing role. * - * @method deleteRole - * @memberOf module:management.ManagementClient.prototype - * + * @function deleteRole + * @memberof module:management.ManagementClient.prototype * @example * management.deleteRole({ id: ROLE_ID }, function (err) { * if (err) { @@ -3249,21 +2904,18 @@ utils.wrapPropertyMethod(ManagementClient, 'getRole', 'roles.get'); * * // Role deleted. * }); - * - * @param {Object} params Role parameters. - * @param {String} params.id Role ID. + * @param {object} params Role parameters. + * @param {string} params.id Role ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'deleteRole', 'roles.delete'); /** * Update an existing role. * - * @method updateRole - * @memberOf module:management.ManagementClient.prototype - * + * @function updateRole + * @memberof module:management.ManagementClient.prototype * @example * var params = { id: ROLE_ID }; * var data = { name: 'my-role'}; @@ -3274,22 +2926,19 @@ utils.wrapPropertyMethod(ManagementClient, 'deleteRole', 'roles.delete'); * * console.log(role.name); // 'my-role'. * }); - * - * @param {Object} params Role parameters. - * @param {String} params.id Role ID. - * @param {Object} data Updated role data. + * @param {object} params Role parameters. + * @param {string} params.id Role ID. + * @param {object} data Updated role data. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'updateRole', 'roles.update'); /** * Get permissions for a given role * - * @method getPermissionsInRole - * @memberOf module:management.ManagementClient.prototype - * + * @function getPermissionsInRole + * @memberof module:management.ManagementClient.prototype * @example * var params = { id :'ROLE_ID'}; * @example @@ -3301,20 +2950,17 @@ utils.wrapPropertyMethod(ManagementClient, 'updateRole', 'roles.update'); * management.getPermissionsInRole(params, function (err, permissions) { * console.log(permissions); * }); - * - * @param {String} [roleId] Id of the role + * @param {string} [roleId] Id of the role * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getPermissionsInRole', 'roles.getPermissions'); /** * Add permissions in a role * - * @method addPermissionsInRole - * @memberOf module:management.ManagementClient.prototype - * + * @function addPermissionsInRole + * @memberof module:management.ManagementClient.prototype * @example * var params = { id :'ROLE_ID'}; * var data = { "permissions" : [{"permission_name" :"do:something" ,"resource_server_identifier" :"test123" }]}; @@ -3322,24 +2968,21 @@ utils.wrapPropertyMethod(ManagementClient, 'getPermissionsInRole', 'roles.getPer * management.addPermissionsInRole(params, data, function (err, permissions) { * console.log(permissions); * }); - * - * @param {String} params.id ID of the Role. - * @param {Object} data permissions data - * @param {String} data.permissions Array of permissions - * @param {String} data.permissions.permission_name Name of a permission - * @param {String} data.permissions.resource_server_identifier Identifier for a resource + * @param {string} params.id ID of the Role. + * @param {object} data permissions data + * @param {string} data.permissions Array of permissions + * @param {string} data.permissions.permission_name Name of a permission + * @param {string} data.permissions.resource_server_identifier Identifier for a resource * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'addPermissionsInRole', 'roles.addPermissions'); /** * Remove permissions from a role * - * @method removePermissionsFromRole - * @memberOf module:management.ManagementClient.prototype - * + * @function removePermissionsFromRole + * @memberof module:management.ManagementClient.prototype * @example * var params = { id :'ROLE_ID'}; * var data = { "permissions" : [{"permission_name" :"do:something" ,"resource_server_identifier" :"test123" }]}; @@ -3347,31 +2990,27 @@ utils.wrapPropertyMethod(ManagementClient, 'addPermissionsInRole', 'roles.addPer * management.removePermissionsFromRole(params, data, function (err, permissions) { * console.log(permissions); * }); - * - * @param {String} params.id ID of the Role. - * @param {Object} data permissions data - * @param {String} data.permissions Array of permissions - * @param {String} data.permissions.permission_name Name of a permission - * @param {String} data.permissions.resource_server_identifier Identifier for a resource + * @param {string} params.id ID of the Role. + * @param {object} data permissions data + * @param {string} data.permissions Array of permissions + * @param {string} data.permissions.permission_name Name of a permission + * @param {string} data.permissions.resource_server_identifier Identifier for a resource * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'removePermissionsFromRole', 'roles.removePermissions'); /** * Get users in a given role * - * @method getUsersInRole - * @memberOf module:management.ManagementClient.prototype - * + * @function getUsersInRole + * @memberof module:management.ManagementClient.prototype * @example * var params = { * id: 'ROLE_ID', * per_page: 50, * page: 0 * }; - * * @example * This method takes a roleId and returns all users within that role. Supports offset (page, per_page) and checkpoint pagination (from, take). You must use checkpoint pagination to retrieve beyond the first 1000 records. * @@ -3379,24 +3018,21 @@ utils.wrapPropertyMethod(ManagementClient, 'removePermissionsFromRole', 'roles.r * management.getUsersInRole(params, function (err, users) { * console.log(users); * }); - * - * @param {String} [id] Id of the role - * @param {Number} [params.per_page] Number of results per page. - * @param {Number} [params.page] Page number, zero indexed. - * @param {String} [params.from] Optional id from which to start selection. - * @param {Number} [params.take] The total amount of entries to retrieve when using the from parameter. Defaults to 50. + * @param {string} [id] Id of the role + * @param {number} [params.per_page] Number of results per page. + * @param {number} [params.page] Page number, zero indexed. + * @param {string} [params.from] Optional id from which to start selection. + * @param {number} [params.take] The total amount of entries to retrieve when using the from parameter. Defaults to 50. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getUsersInRole', 'roles.getUsers'); /** * Get all hooks. * - * @method getHooks - * @memberOf module:management.ManagementClient.prototype - * + * @function getHooks + * @memberof module:management.ManagementClient.prototype * @example * This method takes an optional object as first argument that may be used to * specify pagination settings. If pagination options are not present, @@ -3412,22 +3048,19 @@ utils.wrapPropertyMethod(ManagementClient, 'getUsersInRole', 'roles.getUsers'); * management.getHooks(params, function (err, hooks) { * console.log(hooks.length); * }); - * - * @param {Object} [params] Hooks parameters. - * @param {Number} [params.per_page] Number of results per page. - * @param {Number} [params.page] Page number, zero indexed. + * @param {object} [params] Hooks parameters. + * @param {number} [params.per_page] Number of results per page. + * @param {number} [params.page] Page number, zero indexed. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getHooks', 'hooks.getAll'); /** * Get an Auth0 hook. * - * @method getHook - * @memberOf module:management.ManagementClient.prototype - * + * @function getHook + * @memberof module:management.ManagementClient.prototype * @example * management.getHook({ id: HOOK_ID }, function (err, hook) { * if (err) { @@ -3436,21 +3069,18 @@ utils.wrapPropertyMethod(ManagementClient, 'getHooks', 'hooks.getAll'); * * console.log(hook); * }); - * - * @param {Object} params Hook parameters. - * @param {String} params.id Hook ID. + * @param {object} params Hook parameters. + * @param {string} params.id Hook ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getHook', 'hooks.get'); /** * Create a new hook. * - * @method createHook - * @memberOf module:management.ManagementClient.prototype - * + * @function createHook + * @memberof module:management.ManagementClient.prototype * @example * management.createHook(data, function (err) { * if (err) { @@ -3459,20 +3089,17 @@ utils.wrapPropertyMethod(ManagementClient, 'getHook', 'hooks.get'); * * // Hook created. * }); - * - * @param {Object} data Hook data object. + * @param {object} data Hook data object. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'createHook', 'hooks.create'); /** * Update an existing hook. * - * @method updateHook - * @memberOf module:management.ManagementClient.prototype - * + * @function updateHook + * @memberof module:management.ManagementClient.prototype * @example * var params = { id: HOOK_ID }; * var data = { name: 'my-hook'}; @@ -3483,22 +3110,19 @@ utils.wrapPropertyMethod(ManagementClient, 'createHook', 'hooks.create'); * * console.log(hook.name); // 'my-hook'. * }); - * - * @param {Object} params Hook parameters. - * @param {String} params.id Hook ID. - * @param {Object} data Updated hook data. + * @param {object} params Hook parameters. + * @param {string} params.id Hook ID. + * @param {object} data Updated hook data. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'updateHook', 'hooks.update'); /** * Delete an existing hook. * - * @method deleteHook - * @memberOf module:management.ManagementClient.prototype - * + * @function deleteHook + * @memberof module:management.ManagementClient.prototype * @example * auth0.deleteHook({ id: HOOK_ID }, function (err) { * if (err) { @@ -3507,21 +3131,18 @@ utils.wrapPropertyMethod(ManagementClient, 'updateHook', 'hooks.update'); * * // Hook deleted. * }); - * - * @param {Object} params Hook parameters. - * @param {String} params.id Hook ID. + * @param {object} params Hook parameters. + * @param {string} params.id Hook ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'deleteHook', 'hooks.delete'); /** * Get an Auth0 hook's secrets. * - * @method getHookSecrets - * @memberOf module:management.ManagementClient.prototype - * + * @function getHookSecrets + * @memberof module:management.ManagementClient.prototype * @example * var params = { id: HOOK_ID } * management.getHookSecrets(params, function (err, secrets) { @@ -3531,21 +3152,18 @@ utils.wrapPropertyMethod(ManagementClient, 'deleteHook', 'hooks.delete'); * * console.log(secrets); * }); - * - * @param {Object} params Hook parameters. - * @param {String} params.id Hook ID. + * @param {object} params Hook parameters. + * @param {string} params.id Hook ID. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getHookSecrets', 'hooks.getSecrets'); /** * Add hook screts. * - * @method addHookScrets - * @memberOf module:management.ManagementClient.prototype - * + * @function addHookScrets + * @memberof module:management.ManagementClient.prototype * @example * var params = { id: 'HOOK_ID' } * var data = { DB_PASSWORD: 'password1', API_TOKEN: 'secret' } @@ -3556,22 +3174,19 @@ utils.wrapPropertyMethod(ManagementClient, 'getHookSecrets', 'hooks.getSecrets') * * // Hook secrets created. * }); - * - * @param {Object} params Hook parameters. - * @param {String} params.id Hook ID. - * @param {Object} data Secrets key/value pairs + * @param {object} params Hook parameters. + * @param {string} params.id Hook ID. + * @param {object} data Secrets key/value pairs * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'addHookSecrets', 'hooks.addSecrets'); /** * Update an existing hook. * - * @method updateHookSecrets - * @memberOf module:management.ManagementClient.prototype - * + * @function updateHookSecrets + * @memberof module:management.ManagementClient.prototype * @example * var params = { id: HOOK_ID }; * var data = { API_TOKEN: 'updated-secret'}; @@ -3582,22 +3197,19 @@ utils.wrapPropertyMethod(ManagementClient, 'addHookSecrets', 'hooks.addSecrets') * * console.log(secrets) * }); - * - * @param {Object} params Hook parameters. - * @param {String} params.id Hook ID. - * @param {Object} data Secrets key/value pairs + * @param {object} params Hook parameters. + * @param {string} params.id Hook ID. + * @param {object} data Secrets key/value pairs * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'updateHookSecrets', 'hooks.updateSecrets'); /** * Delete an existing hook. * - * @method removeHookSecrets - * @memberOf module:management.ManagementClient.prototype - * + * @function removeHookSecrets + * @memberof module:management.ManagementClient.prototype * @example * var params = { id: HOOK_ID } * var data = ['API_TOKEN', 'DB_PASSWORD'] @@ -3608,32 +3220,28 @@ utils.wrapPropertyMethod(ManagementClient, 'updateHookSecrets', 'hooks.updateSec * * // Hook deleted. * }); - * - * @param {Object} params Hook parameters. - * @param {String} params.id Hook ID. - * @param {Object} data Secrets key/value pairs + * @param {object} params Hook parameters. + * @param {string} params.id Hook ID. + * @param {object} data Secrets key/value pairs * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'removeHookSecrets', 'hooks.removeSecrets'); /** * Returns the access_token. * - * @method getAccessToken - * @memberOf module:management.ManagementClient.prototype - * - * @return {Promise} Promise returning an access_token. + * @function getAccessToken + * @memberof module:management.ManagementClient.prototype + * @returns {Promise} Promise returning an access_token. */ utils.wrapPropertyMethod(ManagementClient, 'getAccessToken', 'tokenProvider.getAccessToken'); /** * Update the branding settings. * - * @method updateBrandingSettings - * @memberOf module:management.ManagementClient.prototype - * + * @function updateBrandingSettings + * @memberof module:management.ManagementClient.prototype * @example * management.updateBrandingSettings(data, function (err, branding) { * if (err) { @@ -3643,21 +3251,18 @@ utils.wrapPropertyMethod(ManagementClient, 'getAccessToken', 'tokenProvider.getA * // Updated branding * console.log(branding); * }); - * - * @param {Object} params Branding parameters. - * @param {Object} data Updated branding data. + * @param {object} params Branding parameters. + * @param {object} data Updated branding data. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'updateBrandingSettings', 'branding.updateSettings'); /** * Get the branding settings.. * - * @method getBrandingSettings - * @memberOf module:management.ManagementClient.prototype - * + * @function getBrandingSettings + * @memberof module:management.ManagementClient.prototype * @example * management.getBrandingSettings(data, function (err, branding) { * if (err) { @@ -3667,21 +3272,18 @@ utils.wrapPropertyMethod(ManagementClient, 'updateBrandingSettings', 'branding.u * // Branding * console.log(branding); * }); - * - * @param {Object} params Branding parameters. - * @param {Object} data Branding data. + * @param {object} params Branding parameters. + * @param {object} data Branding data. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getBrandingSettings', 'branding.getSettings'); /** * Get the new universal login template. * - * @method getBrandingUniversalLoginTemplate - * @memberOf module:management.ManagementClient.prototype - * + * @function getBrandingUniversalLoginTemplate + * @memberof module:management.ManagementClient.prototype * @example * management.getBrandingUniversalLoginTemplate(data, function (err, template) { * if (err) { @@ -3691,12 +3293,10 @@ utils.wrapPropertyMethod(ManagementClient, 'getBrandingSettings', 'branding.getS * // Branding * console.log(template); * }); - * - * @param {Object} params Branding parameters (leave empty). - * @param {Object} data Branding data (leave empty). + * @param {object} params Branding parameters (leave empty). + * @param {object} data Branding data (leave empty). * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod( ManagementClient, @@ -3707,21 +3307,18 @@ utils.wrapPropertyMethod( /** * Get the new universal login template. * - * @method setBrandingUniversalLoginTemplate - * @memberOf module:management.ManagementClient.prototype - * + * @function setBrandingUniversalLoginTemplate + * @memberof module:management.ManagementClient.prototype * @example * management.setBrandingUniversalLoginTemplate({ template: "a template" }, function (err, template) { * if (err) { * // Handle error. * } * }); - * - * @param {Object} params Branding parameters (leave empty). - * @param {Object} template Branding data (object with template field). + * @param {object} params Branding parameters (leave empty). + * @param {object} template Branding data (object with template field). * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod( ManagementClient, @@ -3732,21 +3329,18 @@ utils.wrapPropertyMethod( /** * Delete the new universal login template. * - * @method deleteBrandingUniversalLoginTemplate - * @memberOf module:management.ManagementClient.prototype - * + * @function deleteBrandingUniversalLoginTemplate + * @memberof module:management.ManagementClient.prototype * @example * management.deleteBrandingUniversalLoginTemplate(template, function (err) { * if (err) { * // Handle error. * } * }); - * - * @param {Object} params Branding parameters (leave empty). - * @param {Object} data Branding data (leave empty). + * @param {object} params Branding parameters (leave empty). + * @param {object} data Branding data (leave empty). * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod( ManagementClient, @@ -3757,9 +3351,8 @@ utils.wrapPropertyMethod( /** * Update the tenant migrations. * - * @method updateMigrations - * @memberOf module:management.ManagementClient.prototype - * + * @function updateMigrations + * @memberof module:management.ManagementClient.prototype * @example * data = { flags: { migration: true } }; * management.updateMigrations(data, function (err, migrations) { @@ -3770,20 +3363,17 @@ utils.wrapPropertyMethod( * // Updated migrations flags * console.log(migrations.flags); * }); - * - * @param {Object} data Updated migrations data. + * @param {object} data Updated migrations data. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'updateMigrations', 'migrations.updateMigrations'); /** * Get migrations flags * - * @method getMigrations - * @memberOf module:management.ManagementClient.prototype - * + * @function getMigrations + * @memberof module:management.ManagementClient.prototype * @example * management.getMigrations(function (err, migrations) { * if (err) { @@ -3793,27 +3383,22 @@ utils.wrapPropertyMethod(ManagementClient, 'updateMigrations', 'migrations.updat * // Migration flags * console.log(migrations.flags); * }); - * * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getMigrations', 'migrations.getMigrations'); /** * Get prompts settings.. * - * @method getPromptsSettings - * @memberOf module:management.ManagementClient.prototype - * + * @function getPromptsSettings + * @memberof module:management.ManagementClient.prototype * @example * management.getPromptsSettings(function (err, settings) { - * * console.log(settings); + * console.log(settings); * }); - * * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'getPromptsSettings', 'prompts.getSettings'); @@ -3821,20 +3406,17 @@ utils.wrapPropertyMethod(ManagementClient, 'getPromptsSettings', 'prompts.getSet /** * Update prompts settings. * - * @method updatePromptsSettings - * @memberOf module:management.ManagementClient.prototype - * + * @function updatePromptsSettings + * @memberof module:management.ManagementClient.prototype * @example * management.updatePromptsSettings(data, function (err) { * if (err) { * // Handle error. * } * }); - * - * @param {Object} data The new prompts settings. + * @param {object} data The new prompts settings. * @param {Function} [cb] Callback function. - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod(ManagementClient, 'updatePromptsSettings', 'prompts.updateSettings'); @@ -3842,22 +3424,19 @@ utils.wrapPropertyMethod(ManagementClient, 'updatePromptsSettings', 'prompts.upd /** * Retrieve custom text for a specific prompt and language. * - * @method getCustomTextByLanguage - * @memberOf module:management.PromptsManager.prototype - * + * @function getCustomTextByLanguage + * @memberof module:management.PromptsManager.prototype * @example * var params = { prompt: PROMPT_NAME, language: LANGUAGE }; * * management.prompts.getCustomTextByLanguage(params, function (err, customText) { - * * console.log('CustomText', customText); + * console.log('CustomText', customText); * }); - * - * @param {Object} params Data object. - * @param {String} params.prompt Name of the prompt. - * @param {String} params.language Language to retrieve. + * @param {object} params Data object. + * @param {string} params.prompt Name of the prompt. + * @param {string} params.language Language to retrieve. * @param {Function} [cb] Callback function - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod( @@ -3869,23 +3448,20 @@ utils.wrapPropertyMethod( /** * Set custom text for a specific prompt. * - * @method updateCustomTextByLanguage - * @memberOf module:management.PromptsManager.prototype - * + * @function updateCustomTextByLanguage + * @memberof module:management.PromptsManager.prototype * @example * var params = { prompt: PROMPT_NAME, language: LANGUAGE, body: BODY_OBJECT }; * * management.prompts.updateCustomTextByLanguage(params, function (err, customText) { - * * console.log('CustomText', customText); + * console.log('CustomText', customText); * }); - * - * @param {Object} params Data object. - * @param {String} params.prompt Name of the prompt. - * @param {String} params.language Language to retrieve. - * @param {Object} params.body An object containing custom dictionaries for a group of screens. + * @param {object} params Data object. + * @param {string} params.prompt Name of the prompt. + * @param {string} params.language Language to retrieve. + * @param {object} params.body An object containing custom dictionaries for a group of screens. * @param {Function} [cb] Callback function - * - * @return {Promise|undefined} + * @returns {Promise|undefined} */ utils.wrapPropertyMethod( diff --git a/src/utils.js b/src/utils.js index fe545b9df..8285540ba 100644 --- a/src/utils.js +++ b/src/utils.js @@ -1,89 +1,83 @@ -var pkg = require('../package.json'); - -/** - * @module utils - */ -var utils = (module.exports = {}); +const pkg = require('../package.json'); /** * Given a JSON string, convert it to its base64 representation. * - * @method jsonToBase64 - * @memberOf module:utils + * @param {object} json Json data + * @returns {string} */ -utils.jsonToBase64 = function(json) { - var bytes = Buffer.from(JSON.stringify(json)); +const jsonToBase64 = (json) => { + const bytes = Buffer.from(JSON.stringify(json)); - return bytes - .toString('base64') - .replace(/\+/g, '-') - .replace(/\//g, '_') - .replace(/=+$/, ''); + return bytes.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); }; /** * Return an object with information about the current client. * - * @method generateClientInfo - * @memberOf module:utils - * - * @return {Object} Object containing client information. + * @function generateClientInfo + * @returns {object} Object containing client information. */ -utils.generateClientInfo = function() { - return { - name: 'node-auth0', - version: pkg.version, - env: { - node: process.version.replace('v', '') - } - }; -}; +const generateClientInfo = () => ({ + name: 'node-auth0', + version: pkg.version, + env: { + node: process.version.replace('v', ''), + }, +}); /** * Simple wrapper that, given a class, a property name and a method name, * creates a new method in the class that is a wrapper for the given * property method. - * - * @method wrapPropertyMethod - * @memberOf module:utils */ -utils.wrapPropertyMethod = function(Parent, name, propertyMethod) { - var path = propertyMethod.split('.'); + +const wrapPropertyMethod = (Parent, name, propertyMethod) => { + const path = propertyMethod.split('.'); if (path.length > 2) { throw new Error('wrapPropertyMethod() only supports one level of nesting for propertyMethod'); } - var property = path.shift(); - var method = path.pop(); + const property = path.shift(); + const method = path.pop(); Object.defineProperty(Parent.prototype, name, { enumerable: false, - get: function() { + get() { return this[property][method].bind(this[property]); - } + }, }); }; -utils.containsUnsafeChars = s => { +const containsUnsafeChars = (s) => { const safeChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$-_.+!*'(),%"; - return !!s.split('').find(c => !safeChars.includes(c)); + return !!s.split('').find((c) => !safeChars.includes(c)); }; -utils.maybeDecode = url => { - if (utils.containsUnsafeChars(url)) { +const maybeDecode = (url) => { + if (containsUnsafeChars(url)) { return encodeURIComponent(url); } return url; }; -utils.sanitizeArguments = function(optionsCandidate, cbCandidate) { +const sanitizeArguments = function (optionsCandidate, cbCandidate) { if (optionsCandidate instanceof Function) { return { cb: optionsCandidate, - options: undefined + options: undefined, }; } return { cb: cbCandidate, - options: optionsCandidate + options: optionsCandidate, }; }; + +module.exports = { + jsonToBase64, + generateClientInfo, + wrapPropertyMethod, + containsUnsafeChars, + maybeDecode, + sanitizeArguments, +}; diff --git a/test/auth/authentication-client.tests.js b/test/auth/authentication-client.tests.js index 4f0a744e9..6af54558d 100644 --- a/test/auth/authentication-client.tests.js +++ b/test/auth/authentication-client.tests.js @@ -1,90 +1,88 @@ -var expect = require('chai').expect; -var sinon = require('sinon'); -var proxyquire = require('proxyquire'); +const { expect } = require('chai'); +const sinon = require('sinon'); +const proxyquire = require('proxyquire'); -var ArgumentError = require('rest-facade').ArgumentError; +const { ArgumentError } = require('rest-facade'); -var AuthenticationClient = require('../../src/auth'); -var OAuthAuthenticator = require('../../src/auth/OAuthAuthenticator'); -var DatabaseAuthenticator = require('../../src/auth/DatabaseAuthenticator'); -var PasswordlessAuthenticator = require('../../src/auth/PasswordlessAuthenticator'); -var UsersManager = require('../../src/auth/UsersManager'); -var TokensManager = require('../../src/auth/TokensManager'); +const AuthenticationClient = require('../../src/auth'); +const OAuthAuthenticator = require('../../src/auth/OAuthAuthenticator'); +const DatabaseAuthenticator = require('../../src/auth/DatabaseAuthenticator'); +const PasswordlessAuthenticator = require('../../src/auth/PasswordlessAuthenticator'); +const UsersManager = require('../../src/auth/UsersManager'); +const TokensManager = require('../../src/auth/TokensManager'); -var ensureProperty = require('../utils').ensureProperty; +const { ensureProperty } = require('../utils'); -describe('AuthenticationClient', function() { - describe('#constructor', function() { - it('should raise an error when no options object is provided', function() { +describe('AuthenticationClient', () => { + describe('#constructor', () => { + it('should raise an error when no options object is provided', () => { expect(AuthenticationClient).to.throw( ArgumentError, 'Authentication Client SDK options must be an object' ); }); - it('should raise an error when the domain is not valid', function() { - var client = AuthenticationClient.bind(null, { token: 'token', domain: '' }); + it('should raise an error when the domain is not valid', () => { + const client = AuthenticationClient.bind(null, { token: 'token', domain: '' }); expect(client).to.throw(ArgumentError, 'Must provide a domain'); }); }); - describe('instance properties', function() { - var properties = { + describe('instance properties', () => { + const properties = { OAuthAuthenticator: { name: 'oauth', - cls: OAuthAuthenticator + cls: OAuthAuthenticator, }, DatabaseAuthenticator: { name: 'database', - cls: DatabaseAuthenticator + cls: DatabaseAuthenticator, }, PasswordlessAuthenticator: { name: 'passwordless', - cls: PasswordlessAuthenticator + cls: PasswordlessAuthenticator, }, UsersManager: { name: 'users', - cls: UsersManager + cls: UsersManager, }, TokensManager: { name: 'tokens', - cls: TokensManager - } + cls: TokensManager, + }, }; - var options = { + const options = { clientId: 'CLIENT_ID', - domain: 'tenant.auth0.com' + domain: 'tenant.auth0.com', }; - var client = new AuthenticationClient(options); + const client = new AuthenticationClient(options); // Tests common to all properties. - for (var name in properties) { - var property = properties[name]; + for (const name in properties) { + const property = properties[name]; it( - 'should expose an instance of ' + name, + `should expose an instance of ${name}`, ensureProperty(client, property.name, property.cls) ); } }); - describe('client info', function() { - it('should configure instances with default telemetry header', function() { - var utilsStub = { - generateClientInfo: sinon.spy(function() { - return { name: 'test-sdk', version: 'ver-123' }; - }) + describe('client info', () => { + it('should configure instances with default telemetry header', () => { + const utilsStub = { + generateClientInfo: sinon.spy(() => ({ name: 'test-sdk', version: 'ver-123' })), }; - var AuthenticationClientProxy = proxyquire('../../src/auth/', { - '../utils': utilsStub + const AuthenticationClientProxy = proxyquire('../../src/auth/', { + '../utils': utilsStub, }); - var client = new AuthenticationClientProxy({ token: 'token', domain: 'auth0.com' }); + const client = new AuthenticationClientProxy({ token: 'token', domain: 'auth0.com' }); - var requestHeaders = { + const requestHeaders = { 'Auth0-Client': 'eyJuYW1lIjoidGVzdC1zZGsiLCJ2ZXJzaW9uIjoidmVyLTEyMyJ9', - 'Content-Type': 'application/json' + 'Content-Type': 'application/json', }; expect(client.oauth.oauth.options.headers).to.contain(requestHeaders); expect(client.database.dbConnections.options.headers).to.contain(requestHeaders); @@ -93,18 +91,18 @@ describe('AuthenticationClient', function() { expect(client.tokens.headers).to.contain(requestHeaders); }); - it('should configure instances with custom telemetry header', function() { - var customTelemetry = { name: 'custom', version: 'beta-01', env: { node: 'v10' } }; - var client = new AuthenticationClient({ + it('should configure instances with custom telemetry header', () => { + const customTelemetry = { name: 'custom', version: 'beta-01', env: { node: 'v10' } }; + const client = new AuthenticationClient({ token: 'token', domain: 'auth0.com', - clientInfo: customTelemetry + clientInfo: customTelemetry, }); - var requestHeaders = { + const requestHeaders = { 'Auth0-Client': 'eyJuYW1lIjoiY3VzdG9tIiwidmVyc2lvbiI6ImJldGEtMDEiLCJlbnYiOnsibm9kZSI6InYxMCJ9fQ', - 'Content-Type': 'application/json' + 'Content-Type': 'application/json', }; expect(client.oauth.oauth.options.headers).to.contain(requestHeaders); expect(client.database.dbConnections.options.headers).to.contain(requestHeaders); @@ -113,12 +111,12 @@ describe('AuthenticationClient', function() { expect(client.tokens.headers).to.contain(requestHeaders); }); - it('should configure instances without telemetry when "name" property is empty', function() { - var customTelemetry = { name: '', version: 'beta-01', env: { node: 'v10' } }; - var client = new AuthenticationClient({ + it('should configure instances without telemetry when "name" property is empty', () => { + const customTelemetry = { name: '', version: 'beta-01', env: { node: 'v10' } }; + const client = new AuthenticationClient({ token: 'token', domain: 'auth0.com', - clientInfo: customTelemetry + clientInfo: customTelemetry, }); expect(client.oauth.oauth.options.headers).to.not.have.property('Auth0-Client'); @@ -128,11 +126,11 @@ describe('AuthenticationClient', function() { expect(client.tokens.headers).to.not.have.property('Auth0-Client'); }); - it('should configure instances without telemetry header when disabled', function() { - var client = new AuthenticationClient({ + it('should configure instances without telemetry header when disabled', () => { + const client = new AuthenticationClient({ token: 'token', domain: 'auth0.com', - telemetry: false + telemetry: false, }); expect(client.oauth.oauth.options.headers).to.not.have.property('Auth0-Client'); @@ -143,14 +141,14 @@ describe('AuthenticationClient', function() { }); }); - describe('user agent', function() { - it('should use the node version when the user agent option is not provided', function() { - var client = new AuthenticationClient({ + describe('user agent', () => { + it('should use the node version when the user agent option is not provided', () => { + const client = new AuthenticationClient({ token: 'token', - domain: 'auth0.com' + domain: 'auth0.com', }); - var expected = { 'User-Agent': 'node.js/' + process.version.replace('v', '') }; + const expected = { 'User-Agent': `node.js/${process.version.replace('v', '')}` }; expect(client.oauth.oauth.options.headers).to.contain(expected); expect(client.database.dbConnections.options.headers).to.contain(expected); @@ -159,16 +157,16 @@ describe('AuthenticationClient', function() { expect(client.tokens.headers).to.contain(expected); }); - it('should include additional headers when provided', function() { - var customHeaders = { + it('should include additional headers when provided', () => { + const customHeaders = { 'User-Agent': 'my-user-agent', - 'Another-header': 'test-header' + 'Another-header': 'test-header', }; - var client = new AuthenticationClient({ + const client = new AuthenticationClient({ token: 'token', domain: 'auth0.com', - headers: customHeaders + headers: customHeaders, }); expect(client.oauth.oauth.options.headers).to.contain(customHeaders); @@ -179,67 +177,49 @@ describe('AuthenticationClient', function() { }); }); - describe('instance methods', function() { - var methods = []; - var client = new AuthenticationClient({ token: 'token', domain: 'auth0.com' }); - - methods.forEach(function(method) { - ensureMethod(client, method); - }); - }); - describe(`verifySMSCode`, () => { - before(function() { + before(function () { this.client = new AuthenticationClient({ token: 'token', domain: 'auth0.com' }); this.passwordlessMock = sinon.mock(this.client.passwordless); - this.callback = function() {}; + this.callback = function () {}; }); - it('should call signIn with otp if provided', function() { - this.passwordlessMock - .expects('signIn') - .once() - .withExactArgs( - { - username: '123', - otp: 'code' - }, - this.callback - ); + it('should call signIn with otp if provided', function () { + this.passwordlessMock.expects('signIn').once().withExactArgs( + { + username: '123', + otp: 'code', + }, + this.callback + ); this.client.verifySMSCode({ phone_number: '123', otp: 'code' }, this.callback); }); - it('should call signIn with password if provided', function() { - this.passwordlessMock - .expects('signIn') - .once() - .withExactArgs( - { - username: '123', - password: 'code' - }, - this.callback - ); + it('should call signIn with password if provided', function () { + this.passwordlessMock.expects('signIn').once().withExactArgs( + { + username: '123', + password: 'code', + }, + this.callback + ); this.client.verifySMSCode({ phone_number: '123', password: 'code' }, this.callback); }); }); describe(`verifyEmailCode`, () => { - before(function() { + before(function () { this.client = new AuthenticationClient({ token: 'token', domain: 'auth0.com' }); this.passwordlessMock = sinon.mock(this.client.passwordless); - this.callback = function() {}; + this.callback = function () {}; }); - it('should call signIn with otp if provided', function() { - this.passwordlessMock - .expects('signIn') - .once() - .withExactArgs( - { - username: '123', - realm: 'email', - otp: 'code' - }, - this.callback - ); + it('should call signIn with otp if provided', function () { + this.passwordlessMock.expects('signIn').once().withExactArgs( + { + username: '123', + realm: 'email', + otp: 'code', + }, + this.callback + ); this.client.verifyEmailCode({ email: '123', otp: 'code' }, this.callback); }); }); diff --git a/test/auth/database-auth.tests.js b/test/auth/database-auth.tests.js index d54b07167..9ecfcc8a8 100644 --- a/test/auth/database-auth.tests.js +++ b/test/auth/database-auth.tests.js @@ -1,104 +1,99 @@ -var expect = require('chai').expect; -var extend = require('util')._extend; -var nock = require('nock'); +const { expect } = require('chai'); +const nock = require('nock'); -// Constants. -var SRC_DIR = '../../src'; -var DOMAIN = 'tenant.auth0.com'; -var API_URL = 'https://' + DOMAIN; -var CLIENT_ID = 'TEST_CLIENT_ID'; +const DOMAIN = 'tenant.auth0.com'; +const API_URL = `https://${DOMAIN}`; +const CLIENT_ID = 'TEST_CLIENT_ID'; -var ArgumentError = require('rest-facade').ArgumentError; -var Authenticator = require(SRC_DIR + '/auth/DatabaseAuthenticator'); -var OAuth = require(SRC_DIR + '/auth/OAuthAuthenticator'); +const { ArgumentError } = require('rest-facade'); +const DatabaseAuthenticator = require(`../../src/auth/DatabaseAuthenticator`); +const OAuth = require(`../../src/auth/OAuthAuthenticator`); -var validOptions = { +const validOptions = { baseUrl: API_URL, - clientId: CLIENT_ID + clientId: CLIENT_ID, }; -describe('DatabaseAuthenticator', function() { - afterEach(function() { +describe('DatabaseAuthenticator', () => { + afterEach(() => { nock.cleanAll(); }); - describe('#constructor', function() { - it('should require an options object', function() { - expect(Authenticator).to.throw(ArgumentError, 'Missing authenticator options'); + describe('#constructor', () => { + it('should require an options object', () => { + expect(() => { + new DatabaseAuthenticator(); + }).to.throw(ArgumentError, 'Missing authenticator options'); - expect(Authenticator.bind(null, 1)).to.throw( - ArgumentError, - 'The authenticator options must be an object' - ); + expect(() => { + new DatabaseAuthenticator(1); + }).to.throw(ArgumentError, 'The authenticator options must be an object'); - expect(Authenticator.bind(null, validOptions)).to.not.throw(ArgumentError); + expect(() => { + new DatabaseAuthenticator(validOptions); + }).to.not.throw(ArgumentError); }); }); - describe('instance', function() { - var methods = ['signIn', 'signUp', 'changePassword', 'requestChangePasswordEmail']; - var oauth = new OAuth(validOptions); - var authenticator = new Authenticator(validOptions, oauth); + describe('instance', () => { + const methods = ['signIn', 'signUp', 'changePassword', 'requestChangePasswordEmail']; + const oauth = new OAuth(validOptions); + const authenticator = new DatabaseAuthenticator(validOptions, oauth); - methods.forEach(function(method) { - it('should have a ' + method + ' method', function() { + methods.forEach((method) => { + it(`should have a ${method} method`, () => { expect(authenticator[method]).to.exist.to.be.an.instanceOf(Function); }); }); }); - describe('#signIn', function() { - var path = '/oauth/ro'; - var userData = { + describe('#signIn', () => { + const path = '/oauth/ro'; + const userData = { username: 'username', - password: 'pwd' + password: 'pwd', }; - beforeEach(function() { - var oauth = new OAuth(validOptions); - this.authenticator = new Authenticator(validOptions, oauth); - this.request = nock(API_URL) - .post(path) - .reply(200); + beforeEach(function () { + const oauth = new OAuth(validOptions); + this.authenticator = new DatabaseAuthenticator(validOptions, oauth); + this.request = nock(API_URL).post(path).reply(200); }); - it('should require an object as first argument', function() { + it('should require an object as first argument', function () { expect(this.authenticator.signIn).to.throw(ArgumentError, 'Missing user data object'); }); - it('should require a username', function() { - var auth = this.authenticator; - var userData = { password: 'password' }; - var signIn = auth.signIn.bind(auth, userData); + it('should require a username', function () { + const auth = this.authenticator; + const userData = { password: 'password' }; + const signIn = auth.signIn.bind(auth, userData); expect(signIn).to.throw(ArgumentError, 'username field is required'); }); - it('should require a password', function() { - var auth = this.authenticator; - var userData = { username: 'username' }; - var signIn = auth.signIn.bind(auth, userData); + it('should require a password', function () { + const auth = this.authenticator; + const userData = { username: 'username' }; + const signIn = auth.signIn.bind(auth, userData); expect(signIn).to.throw(ArgumentError, 'password field is required'); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.authenticator.signIn(userData, done.bind(null, null)); }); - it('should return a promise when no callback is provided', function(done) { - this.authenticator - .signIn(userData) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise when no callback is provided', function (done) { + this.authenticator.signIn(userData).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should perform a POST request to ' + path, function(done) { - var request = this.request; + it(`should perform a POST request to ${path}`, function (done) { + const { request } = this; this.authenticator .signIn(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -106,12 +101,12 @@ describe('DatabaseAuthenticator', function() { .catch(done); }); - it('should include the user data in the request', function(done) { + it('should include the user data in the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - for (var property in userData) { + const request = nock(API_URL) + .post(path, (body) => { + for (const property in userData) { if (userData[property] !== body[property]) { return false; } @@ -123,7 +118,7 @@ describe('DatabaseAuthenticator', function() { this.authenticator .signIn(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -131,18 +126,16 @@ describe('DatabaseAuthenticator', function() { .catch(done); }); - it('should include the Auth0 client ID in the request', function(done) { + it('should include the Auth0 client ID in the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - return body.client_id === CLIENT_ID; - }) + const request = nock(API_URL) + .post(path, (body) => body.client_id === CLIENT_ID) .reply(200); this.authenticator .signIn(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -150,18 +143,16 @@ describe('DatabaseAuthenticator', function() { .catch(done); }); - it('should use Username-Password-Authentication by default', function(done) { + it('should use Username-Password-Authentication by default', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - return body.connection === 'Username-Password-Authentication'; - }) + const request = nock(API_URL) + .post(path, (body) => body.connection === 'Username-Password-Authentication') .reply(200); this.authenticator .signIn(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -169,19 +160,17 @@ describe('DatabaseAuthenticator', function() { .catch(done); }); - it('should allow the user to specify the connection', function(done) { + it('should allow the user to specify the connection', function (done) { nock.cleanAll(); - var data = extend({ connection: 'TEST_CONNECTION' }, userData); - var request = nock(API_URL) - .post(path, function(body) { - return body.connection === 'TEST_CONNECTION'; - }) + const data = { connection: 'TEST_CONNECTION', ...userData }; + const request = nock(API_URL) + .post(path, (body) => body.connection === 'TEST_CONNECTION') .reply(200); this.authenticator .signIn(data) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -189,18 +178,16 @@ describe('DatabaseAuthenticator', function() { .catch(done); }); - it('should use password as default grant type', function(done) { + it('should use password as default grant type', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - return body.grant_type === 'password'; - }) + const request = nock(API_URL) + .post(path, (body) => body.grant_type === 'password') .reply(200); this.authenticator .signIn(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -208,19 +195,17 @@ describe('DatabaseAuthenticator', function() { .catch(done); }); - it('should allow the user to specify the grant type', function(done) { + it('should allow the user to specify the grant type', function (done) { nock.cleanAll(); - var data = extend({ grant_type: 'TEST_GRANT' }, userData); - var request = nock(API_URL) - .post(path, function(body) { - return body.grant_type === 'TEST_GRANT'; - }) + const data = { grant_type: 'TEST_GRANT', ...userData }; + const request = nock(API_URL) + .post(path, (body) => body.grant_type === 'TEST_GRANT') .reply(200); this.authenticator .signIn(data) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -228,18 +213,16 @@ describe('DatabaseAuthenticator', function() { .catch(done); }); - it('should use the openid scope by default', function(done) { + it('should use the openid scope by default', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - return body.scope === 'openid'; - }) + const request = nock(API_URL) + .post(path, (body) => body.scope === 'openid') .reply(200); this.authenticator .signIn(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -248,66 +231,66 @@ describe('DatabaseAuthenticator', function() { }); }); - describe('#signUp', function() { - var path = '/dbconnections/signup'; - var userData = { + describe('#signUp', () => { + const path = '/dbconnections/signup'; + const userData = { email: 'test@domain.com', password: 'pwd', - connection: 'TEST_CONNECTION' + connection: 'TEST_CONNECTION', }; - beforeEach(function() { - this.authenticator = new Authenticator(validOptions); - this.request = nock(API_URL) - .post(path) - .reply(200); + beforeEach(function () { + this.authenticator = new DatabaseAuthenticator(validOptions); + this.request = nock(API_URL).post(path).reply(200); }); - it('should require an object as first argument', function() { - expect(this.authenticator.signUp).to.throw(ArgumentError, 'Missing user data object'); + it('should require an object as first argument', function () { + expect(() => { + this.authenticator.signUp(); + }).to.throw(ArgumentError, 'Missing user data object'); }); - it('should require an email', function() { - var auth = this.authenticator; - var userData = { password: 'password' }; - var signUp = auth.signUp.bind(auth, userData); + it('should require an email', function () { + const auth = this.authenticator; + const userData = { password: 'password' }; + const signUp = auth.signUp.bind(auth, userData); - expect(signUp).to.throw(ArgumentError, 'email field is required'); + expect(() => { + signUp(); + }).to.throw(ArgumentError, 'email field is required'); }); - it('should require a password', function() { - var auth = this.authenticator; - var userData = { email: 'email@domain.com' }; - var signUp = auth.signUp.bind(auth, userData); + it('should require a password', function () { + const auth = this.authenticator; + const userData = { email: 'email@domain.com' }; + const signUp = auth.signUp.bind(auth, userData); expect(signUp).to.throw(ArgumentError, 'password field is required'); }); - it('should require a connection', function() { - var auth = this.authenticator; - var userData = { email: 'email@domain.com', password: 'test' }; - var signUp = auth.signUp.bind(auth, userData); + it('should require a connection', function () { + const auth = this.authenticator; + const userData = { email: 'email@domain.com', password: 'test' }; - expect(signUp).to.throw(ArgumentError, 'connection field is required'); + expect(() => { + auth.signUp(userData); + }).to.throw(ArgumentError, 'connection field is required'); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.authenticator.signUp(userData, done.bind(null, null)); }); - it('should return a promise when no callback is provided', function(done) { - this.authenticator - .signUp(userData) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise when no callback is provided', function (done) { + this.authenticator.signUp(userData).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should perform a POST request to ' + path, function(done) { - var request = this.request; + it(`should perform a POST request to ${path}`, function (done) { + const { request } = this; this.authenticator .signUp(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -315,12 +298,12 @@ describe('DatabaseAuthenticator', function() { .catch(done); }); - it('should include the user data in the request', function(done) { + it('should include the user data in the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - for (var property in userData) { + const request = nock(API_URL) + .post(path, (body) => { + for (const property in userData) { if (userData[property] !== body[property]) { return false; } @@ -332,7 +315,7 @@ describe('DatabaseAuthenticator', function() { this.authenticator .signUp(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -340,18 +323,16 @@ describe('DatabaseAuthenticator', function() { .catch(done); }); - it('should include the Auth0 client ID in the request', function(done) { + it('should include the Auth0 client ID in the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - return body.client_id === CLIENT_ID; - }) + const request = nock(API_URL) + .post(path, (body) => body.client_id === CLIENT_ID) .reply(200); this.authenticator .signUp(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -360,66 +341,69 @@ describe('DatabaseAuthenticator', function() { }); }); - describe('#changePassword', function() { - var path = '/dbconnections/change_password'; - var userData = { + describe('#changePassword', () => { + const path = '/dbconnections/change_password'; + const userData = { email: 'test@domain.com', password: 'newPwd', - connection: 'TEST_CONNECTION' + connection: 'TEST_CONNECTION', }; - beforeEach(function() { - this.authenticator = new Authenticator(validOptions); - this.request = nock(API_URL) - .post(path) - .reply(200); + beforeEach(function () { + this.authenticator = new DatabaseAuthenticator(validOptions); + this.request = nock(API_URL).post(path).reply(200); }); - it('should require an object as first argument', function() { - expect(this.authenticator.changePassword).to.throw(ArgumentError, 'Missing user data object'); + it('should require an object as first argument', function () { + expect(() => { + this.authenticator.changePassword(); + }).to.throw(ArgumentError, 'Missing user data object'); }); - it('should require an email', function() { - var auth = this.authenticator; - var userData = { password: 'password' }; - var changePassword = auth.changePassword.bind(auth, userData); + it('should require an email', function () { + const auth = this.authenticator; + const userData = { password: 'password' }; - expect(changePassword).to.throw(ArgumentError, 'email field is required'); + expect(() => { + auth.changePassword(userData); + }).to.throw(ArgumentError, 'email field is required'); }); - it('should require a password', function() { - var auth = this.authenticator; - var userData = { email: 'email@domain.com' }; - var changePassword = auth.changePassword.bind(auth, userData); + it('should require a password', function () { + const auth = this.authenticator; + const userData = { email: 'email@domain.com' }; - expect(changePassword).to.throw(ArgumentError, 'password field is required'); + expect(() => { + auth.changePassword(userData); + }).to.throw(ArgumentError, 'password field is required'); }); - it('should require a connection', function() { - var auth = this.authenticator; - var userData = { email: 'email@domain.com', password: 'test' }; - var changePassword = auth.changePassword.bind(auth, userData); + it('should require a connection', function () { + const auth = this.authenticator; + const userData = { email: 'email@domain.com', password: 'test' }; - expect(changePassword).to.throw(ArgumentError, 'connection field is required'); + expect(() => { + auth.changePassword(userData); + }).to.throw(ArgumentError, 'connection field is required'); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.authenticator.changePassword(userData, done.bind(null, null)); }); - it('should return a promise when no callback is provided', function(done) { + it('should return a promise when no callback is provided', function (done) { this.authenticator .changePassword(userData) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should perform a POST request to ' + path, function(done) { - var request = this.request; + it(`should perform a POST request to ${path}`, function (done) { + const { request } = this; this.authenticator .changePassword(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -427,12 +411,12 @@ describe('DatabaseAuthenticator', function() { .catch(done); }); - it('should include the user data in the request', function(done) { + it('should include the user data in the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - for (var property in userData) { + const request = nock(API_URL) + .post(path, (body) => { + for (const property in userData) { if (userData[property] !== body[property]) { return false; } @@ -444,7 +428,7 @@ describe('DatabaseAuthenticator', function() { this.authenticator .changePassword(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -452,18 +436,16 @@ describe('DatabaseAuthenticator', function() { .catch(done); }); - it('should include the Auth0 client ID in the request', function(done) { + it('should include the Auth0 client ID in the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - return body.client_id === CLIENT_ID; - }) + const request = nock(API_URL) + .post(path, (body) => body.client_id === CLIENT_ID) .reply(200); this.authenticator .changePassword(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -472,60 +454,56 @@ describe('DatabaseAuthenticator', function() { }); }); - describe('#requestChangePasswordEmail', function() { - var path = '/dbconnections/change_password'; - var userData = { + describe('#requestChangePasswordEmail', () => { + const path = '/dbconnections/change_password'; + const userData = { email: 'test@domain.com', - connection: 'TEST_CONNECTION' + connection: 'TEST_CONNECTION', }; - beforeEach(function() { - this.authenticator = new Authenticator(validOptions); - this.request = nock(API_URL) - .post(path) - .reply(200); + beforeEach(function () { + this.authenticator = new DatabaseAuthenticator(validOptions); + this.request = nock(API_URL).post(path).reply(200); }); - it('should require an object as first argument', function() { - expect(this.authenticator.requestChangePasswordEmail).to.throw( - ArgumentError, - 'Missing user data object' - ); + it('should require an object as first argument', function () { + expect(() => { + this.authenticator.requestChangePasswordEmail(); + }).to.throw(ArgumentError, 'Missing user data object'); }); - it('should require an email', function() { - var auth = this.authenticator; - var userData = {}; - var requestChangePasswordEmail = auth.requestChangePasswordEmail.bind(auth, userData); - - expect(requestChangePasswordEmail).to.throw(ArgumentError, 'email field is required'); + it('should require an email', function () { + expect(() => { + this.authenticator.requestChangePasswordEmail({}); + }).to.throw(ArgumentError, 'email field is required'); }); - it('should require a connection', function() { - var auth = this.authenticator; - var userData = { email: 'email@domain.com' }; - var requestChangePasswordEmail = auth.requestChangePasswordEmail.bind(auth, userData); + it('should require a connection', function () { + const auth = this.authenticator; + const userData = { email: 'email@domain.com' }; - expect(requestChangePasswordEmail).to.throw(ArgumentError, 'connection field is required'); + expect(() => { + auth.requestChangePasswordEmail(userData); + }).to.throw(ArgumentError, 'connection field is required'); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.authenticator.requestChangePasswordEmail(userData, done.bind(null, null)); }); - it('should return a promise when no callback is provided', function(done) { + it('should return a promise when no callback is provided', function (done) { this.authenticator .requestChangePasswordEmail(userData) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should perform a POST request to ' + path, function(done) { - var request = this.request; + it(`should perform a POST request to ${path}`, function (done) { + const { request } = this; this.authenticator .requestChangePasswordEmail(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -533,12 +511,12 @@ describe('DatabaseAuthenticator', function() { .catch(done); }); - it('should include the user data in the request', function(done) { + it('should include the user data in the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - for (var property in userData) { + const request = nock(API_URL) + .post(path, (body) => { + for (const property in userData) { if (userData[property] !== body[property]) { return false; } @@ -550,7 +528,7 @@ describe('DatabaseAuthenticator', function() { this.authenticator .requestChangePasswordEmail(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -558,18 +536,16 @@ describe('DatabaseAuthenticator', function() { .catch(done); }); - it('should include the Auth0 client ID in the request', function(done) { + it('should include the Auth0 client ID in the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - return body.client_id === CLIENT_ID; - }) + const request = nock(API_URL) + .post(path, (body) => body.client_id === CLIENT_ID) .reply(200); this.authenticator .requestChangePasswordEmail(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); diff --git a/test/auth/oauth-with-idtoken-validation.tests.js b/test/auth/oauth-with-idtoken-validation.tests.js index f43b4202d..6e265391a 100644 --- a/test/auth/oauth-with-idtoken-validation.tests.js +++ b/test/auth/oauth-with-idtoken-validation.tests.js @@ -1,26 +1,26 @@ -var expect = require('chai').expect; -var sinon = require('sinon'); -var proxyquire = require('proxyquire'); +const { expect } = require('chai'); +const sinon = require('sinon'); +const proxyquire = require('proxyquire'); -var jwt = require('jsonwebtoken'); -var jwksClient = require('jwks-rsa'); -var pem = require('pem'); +const jwt = require('jsonwebtoken'); +const jwksClient = require('jwks-rsa'); +const pem = require('pem'); // Constants. -var DOMAIN = 'tenant.auth0.com'; -var CLIENT_ID = 'TEST_CLIENT_ID'; -var CLIENT_SECRET = Buffer.from('TEST_CLIENT_SECRET', 'base64'); +const DOMAIN = 'tenant.auth0.com'; +const CLIENT_ID = 'TEST_CLIENT_ID'; +const CLIENT_SECRET = Buffer.from('TEST_CLIENT_SECRET', 'base64'); -var OAUthWithIDTokenValidation = require('../../src/auth/OAUthWithIDTokenValidation'); -var PARAMS = { params: true }; -var DATA = { data: true }; +const OAUthWithIDTokenValidation = require('../../src/auth/OAUthWithIDTokenValidation'); +const PARAMS = { params: true }; +const DATA = { data: true }; -var createCertificate = function(cb) { - pem.createCertificate({ days: 1, selfSigned: true }, function(err, keys) { +const createCertificate = function (cb) { + pem.createCertificate({ days: 1, selfSigned: true }, (err, keys) => { if (err) { throw err; } - pem.getPublicKey(keys.certificate, function(e, p) { + pem.getPublicKey(keys.certificate, (e, p) => { if (e) { throw e; } @@ -29,26 +29,26 @@ var createCertificate = function(cb) { }); }; -describe('OAUthWithIDTokenValidation', function() { - describe('constructor', function() { - it('validates `oauth` is required', function() { - expect(function() { +describe('OAUthWithIDTokenValidation', () => { + describe('constructor', () => { + it('validates `oauth` is required', () => { + expect(() => { new OAUthWithIDTokenValidation(); }).to.throw('Missing OAuthAuthenticator param'); }); - it('validates `options` is required', function() { - expect(function() { + it('validates `options` is required', () => { + expect(() => { new OAUthWithIDTokenValidation({}); }).to.throw('Missing authenticator options'); }); - it('validates `oauth` is required', function() { - expect(function() { + it('validates `oauth` is required', () => { + expect(() => { new OAUthWithIDTokenValidation({}, 'asd'); }).to.throw('The authenticator options must be an object'); }); }); - describe('#create', function() { - this.afterEach(function() { + describe('#create', function () { + this.afterEach(() => { if (jwt.verify.restore) { jwt.verify.restore(); } @@ -56,469 +56,430 @@ describe('OAUthWithIDTokenValidation', function() { jwksClient.restore(); } }); - it('Calls `oauth.create` with correct params', function(done) { - var oauth = { - create: function(params, data) { + it('Calls `oauth.create` with correct params', (done) => { + const oauth = { + create(params, data) { expect(params).to.be.equal(PARAMS); expect(data).to.be.equal(DATA); - return new Promise(res => res({})); - } + return new Promise((res) => res({})); + }, }; - var oauthWithValidation = new OAUthWithIDTokenValidation(oauth, {}); + const oauthWithValidation = new OAUthWithIDTokenValidation(oauth, {}); oauthWithValidation.create(PARAMS, DATA, done); }); - it('Does nothing when there is no id_token', function(done) { - var oauth = { - create: function() { - return new Promise(res => res({})); - } + it('Does nothing when there is no id_token', (done) => { + const oauth = { + create() { + return new Promise((res) => res({})); + }, }; - var oauthWithValidation = new OAUthWithIDTokenValidation(oauth, {}); + const oauthWithValidation = new OAUthWithIDTokenValidation(oauth, {}); oauthWithValidation.create(PARAMS, DATA, done); }); - it('Bypasses validation when options.__bypassIdTokenValidation is true', function(done) { - var oauth = { - create: function() { - return new Promise(res => res({ id_token: 'foobar' })); - } + it('Bypasses validation when options.__bypassIdTokenValidation is true', (done) => { + const oauth = { + create() { + return new Promise((res) => res({ id_token: 'foobar' })); + }, }; - var oauthWithValidation = new OAUthWithIDTokenValidation(oauth, { - __bypassIdTokenValidation: true + const oauthWithValidation = new OAUthWithIDTokenValidation(oauth, { + __bypassIdTokenValidation: true, }); oauthWithValidation.create(PARAMS, DATA, done); }); - it('Calls jwt.verify with token and algs', function(done) { - var oauth = { - create: function() { - return new Promise(res => res({ id_token: 'foobar' })); - } + it('Calls jwt.verify with token and algs', (done) => { + const oauth = { + create() { + return new Promise((res) => res({ id_token: 'foobar' })); + }, }; - sinon.stub(jwt, 'verify').callsFake(function(idtoken, getKey, options, callback) { + sinon.stub(jwt, 'verify').callsFake((idtoken, getKey, options) => { expect(idtoken).to.be.equal('foobar'); expect(options).to.be.eql({ audience: CLIENT_ID, algorithms: ['HS256', 'RS256'], - issuer: 'https://' + DOMAIN + '/' + issuer: `https://${DOMAIN}/`, }); done(); }); - var oauthWithValidation = new OAUthWithIDTokenValidation(oauth, { + const oauthWithValidation = new OAUthWithIDTokenValidation(oauth, { clientId: CLIENT_ID, - domain: DOMAIN + domain: DOMAIN, }); oauthWithValidation.create(PARAMS, DATA); }); - it('Returns auth result when verify response is successful', function(done) { - var oauth = { - create: function() { - return new Promise(res => res({ id_token: 'foobar' })); - } + it('Returns auth result when verify response is successful', (done) => { + const oauth = { + create() { + return new Promise((res) => res({ id_token: 'foobar' })); + }, }; - sinon.stub(jwt, 'verify').callsFake(function(idtoken, getKey, options, callback) { + sinon.stub(jwt, 'verify').callsFake((idtoken, getKey, options, callback) => { callback(null, { verification: 'result' }); }); - OAUthWithIDTokenValidationProxy = proxyquire('../../src/auth/OAUthWithIDTokenValidation', { - './idToken': { validate: token => token } - }); + const OAUthWithIDTokenValidationProxy = proxyquire( + '../../src/auth/OAUthWithIDTokenValidation', + { + './idToken': { validate: (token) => token }, + } + ); - var oauthWithValidation = new OAUthWithIDTokenValidationProxy(oauth, {}); - oauthWithValidation.create(PARAMS, DATA).then(function(r) { + const oauthWithValidation = new OAUthWithIDTokenValidationProxy(oauth, {}); + oauthWithValidation.create(PARAMS, DATA).then((r) => { expect(r).to.be.eql({ id_token: 'foobar' }); done(); }); }); - it('Returns error when verify response is an error', function(done) { - var oauth = { - create: function() { - return new Promise(res => res({ id_token: 'foobar' })); - } + it('Returns error when verify response is an error', (done) => { + const oauth = { + create() { + return new Promise((res) => res({ id_token: 'foobar' })); + }, }; - sinon.stub(jwt, 'verify').callsFake(function(idtoken, getKey, options, callback) { + sinon.stub(jwt, 'verify').callsFake((idtoken, getKey, options, callback) => { callback({ the: 'error' }); }); - var oauthWithValidation = new OAUthWithIDTokenValidation(oauth, {}); - oauthWithValidation.create(PARAMS, DATA).catch(function(r) { + const oauthWithValidation = new OAUthWithIDTokenValidation(oauth, {}); + oauthWithValidation.create(PARAMS, DATA).catch((r) => { expect(r).to.be.eql({ the: 'error' }); done(); }); }); - it('Uses `clientSecret` as key when header.alg === HS256 and there is a user secret', function(done) { - var oauth = { - create: function() { - return new Promise(res => res({ id_token: 'foobar' })); - } + it('Uses `clientSecret` as key when header.alg === HS256 and there is a user secret', (done) => { + const oauth = { + create() { + return new Promise((res) => res({ id_token: 'foobar' })); + }, }; - sinon.stub(jwt, 'verify').callsFake(function(idtoken, getKey, options, callback) { - getKey({ alg: 'HS256' }, function(err, key) { + sinon.stub(jwt, 'verify').callsFake((idtoken, getKey) => { + getKey({ alg: 'HS256' }, (err, key) => { expect(key).to.be.eql(Buffer.from(CLIENT_SECRET, 'base64')); done(); }); }); - var oauthWithValidation = new OAUthWithIDTokenValidation(oauth, { - clientSecret: CLIENT_SECRET + const oauthWithValidation = new OAUthWithIDTokenValidation(oauth, { + clientSecret: CLIENT_SECRET, }); oauthWithValidation.create(PARAMS, DATA); }); - it('Returns unvalidated response when header.alg === HS256 and there is no user secret', function(done) { - var oauth = { - create: function() { - return new Promise(res => res({ id_token: 'foobar' })); - } + it('Returns unvalidated response when header.alg === HS256 and there is no user secret', (done) => { + const oauth = { + create() { + return new Promise((res) => res({ id_token: 'foobar' })); + }, }; - OAUthWithIDTokenValidationProxy = proxyquire('../../src/auth/OAUthWithIDTokenValidation', { - './idToken': { validate: token => token } - }); + const OAUthWithIDTokenValidationProxy = proxyquire( + '../../src/auth/OAUthWithIDTokenValidation', + { + './idToken': { validate: (token) => token }, + } + ); - sinon.stub(jwt, 'verify').callsFake(function(idtoken, getKey, options, callback) { - getKey({ alg: 'HS256' }, function(err, key) { + sinon.stub(jwt, 'verify').callsFake((idtoken, getKey, options, callback) => { + getKey({ alg: 'HS256' }, (err, key) => { expect(err.message).to.contain( 'Validation of `id_token` requires a `clientSecret` when using the HS256 algorithm. To ensure tokens are validated, please switch the signing algorithm to RS256 or provide a `clientSecret` in the constructor.' ); callback(err, key); }); }); - var oauthWithValidation = new OAUthWithIDTokenValidationProxy(oauth, {}); - oauthWithValidation.create(PARAMS, DATA, function(err, response) { + const oauthWithValidation = new OAUthWithIDTokenValidationProxy(oauth, {}); + oauthWithValidation.create(PARAMS, DATA, (err, response) => { expect(err).to.be.null; expect(response).to.be.eql({ id_token: 'foobar' }); done(); }); }); - describe('when header.alg !== HS256', function() { - it('creates a jwksClient with the correct jwksUri', function(done) { - var oauth = { - create: function() { - return new Promise(res => res({ id_token: 'foobar' })); - } + describe('when header.alg !== HS256', () => { + it('creates a jwksClient with the correct jwksUri', (done) => { + const oauth = { + create: () => new Promise((res) => res({ id_token: 'foobar' })), }; - var jwksClientStub = sinon.spy(function() { - return { - getSigningKey: function(kid, cb) { - cb(null, { publicKey: 'publicKey' }); - } - }; - }); - OAUthWithIDTokenValidationProxy = proxyquire('../../src/auth/OAUthWithIDTokenValidation', { - 'jwks-rsa': jwksClientStub - }); - sinon.stub(jwt, 'verify').callsFake(function(idtoken, getKey, options, callback) { - getKey({ alg: 'RS256' }, function(err, key) { + const jwksClientStub = sinon.spy(() => ({ + getSigningKey(kid, cb) { + cb(null, { publicKey: 'publicKey' }); + }, + })); + + sinon.stub(jwt, 'verify').callsFake((idtoken, getKey) => { + getKey({ alg: 'RS256' }, () => { expect(jwksClientStub.getCall(0).args[0].jwksUri).to.be.equal( 'https://tenant.auth0.com/.well-known/jwks.json' ); done(); }); }); - var oauthWithValidation = new OAUthWithIDTokenValidationProxy(oauth, { + const oauthWithValidation = new OAUthWithIDTokenValidation(oauth, { domain: DOMAIN, - clientSecret: CLIENT_SECRET + clientSecret: CLIENT_SECRET, + jwksClient: jwksClientStub, }); oauthWithValidation.create(PARAMS, DATA); }); - it('returns the error when available', function(done) { - var oauth = { - create: function() { - return new Promise(res => res({ id_token: 'foobar' })); - } + it('returns the error when available', (done) => { + const oauth = { + create() { + return new Promise((res) => res({ id_token: 'foobar' })); + }, }; - var jwksClientStub = sinon.spy(function() { - return { - getSigningKey: function(kid, cb) { - cb({ the: 'error' }); - } - }; - }); - OAUthWithIDTokenValidationProxy = proxyquire('../../src/auth/OAUthWithIDTokenValidation', { - 'jwks-rsa': jwksClientStub - }); + const jwksClientStub = sinon.spy(() => ({ + getSigningKey(kid, cb) { + cb({ the: 'error' }); + }, + })); - sinon.stub(jwt, 'verify').callsFake(function(idtoken, getKey, options, callback) { - getKey({ kid: 'kid', alg: 'RS256' }, function(err, key) { + sinon.stub(jwt, 'verify').callsFake((idtoken, getKey) => { + getKey({ kid: 'kid', alg: 'RS256' }, (err) => { expect(err).to.be.eql({ the: 'error' }); done(); }); }); - var oauthWithValidation = new OAUthWithIDTokenValidationProxy(oauth, { + const oauthWithValidation = new OAUthWithIDTokenValidation(oauth, { domain: DOMAIN, - clientSecret: CLIENT_SECRET + clientSecret: CLIENT_SECRET, + jwksClient: jwksClientStub, }); oauthWithValidation.create(PARAMS, DATA); }); - it('uses the publicKey when available', function(done) { - var oauth = { - create: function() { - return new Promise(res => res({ id_token: 'foobar' })); - } + it('uses the publicKey when available', (done) => { + const oauth = { + create() { + return new Promise((res) => res({ id_token: 'foobar' })); + }, }; - var jwksClientStub = sinon.spy(function() { - return { - getSigningKey: function(kid, cb) { - expect(kid).to.be.equal('kid'); - cb(null, { publicKey: 'publicKey' }); - } - }; - }); - OAUthWithIDTokenValidationProxy = proxyquire('../../src/auth/OAUthWithIDTokenValidation', { - 'jwks-rsa': jwksClientStub - }); + const jwksClientStub = sinon.spy(() => ({ + getSigningKey(kid, cb) { + expect(kid).to.be.equal('kid'); + cb(null, { publicKey: 'publicKey' }); + }, + })); - sinon.stub(jwt, 'verify').callsFake(function(idtoken, getKey, options, callback) { - getKey({ kid: 'kid', alg: 'RS256' }, function(err, key) { + sinon.stub(jwt, 'verify').callsFake((idtoken, getKey) => { + getKey({ kid: 'kid', alg: 'RS256' }, (err, key) => { expect(key).to.be.equal('publicKey'); done(); }); }); - var oauthWithValidation = new OAUthWithIDTokenValidationProxy(oauth, { + const oauthWithValidation = new OAUthWithIDTokenValidation(oauth, { domain: DOMAIN, - clientSecret: CLIENT_SECRET + clientSecret: CLIENT_SECRET, + jwksClient: jwksClientStub, }); oauthWithValidation.create(PARAMS, DATA); }); - it('uses the publicKey when both keys (publicKey and rsaPublicKey) available', function(done) { - var oauth = { - create: function() { - return new Promise(res => res({ id_token: 'foobar' })); - } + it('uses the publicKey when both keys (publicKey and rsaPublicKey) available', (done) => { + const oauth = { + create() { + return new Promise((res) => res({ id_token: 'foobar' })); + }, }; - var jwksClientStub = sinon.spy(function() { - return { - getSigningKey: function(kid, cb) { - expect(kid).to.be.equal('kid'); - cb(null, { publicKey: 'publicKey', rsaPublicKey: 'rsaPublicKey' }); - } - }; - }); - OAUthWithIDTokenValidationProxy = proxyquire('../../src/auth/OAUthWithIDTokenValidation', { - 'jwks-rsa': jwksClientStub - }); + const jwksClientStub = sinon.spy(() => ({ + getSigningKey(kid, cb) { + expect(kid).to.be.equal('kid'); + cb(null, { publicKey: 'publicKey', rsaPublicKey: 'rsaPublicKey' }); + }, + })); - sinon.stub(jwt, 'verify').callsFake(function(idtoken, getKey, options, callback) { - getKey({ kid: 'kid', alg: 'RS256' }, function(err, key) { + sinon.stub(jwt, 'verify').callsFake((idtoken, getKey) => { + getKey({ kid: 'kid', alg: 'RS256' }, (err, key) => { expect(key).to.be.equal('publicKey'); done(); }); }); - var oauthWithValidation = new OAUthWithIDTokenValidationProxy(oauth, { + const oauthWithValidation = new OAUthWithIDTokenValidation(oauth, { domain: DOMAIN, - clientSecret: CLIENT_SECRET + clientSecret: CLIENT_SECRET, + jwksClient: jwksClientStub, }); oauthWithValidation.create(PARAMS, DATA); }); - it('uses the rsaPublicKey when there is no publicKey available', function(done) { - var oauth = { - create: function() { - return new Promise(res => res({ id_token: 'foobar' })); - } + it('uses the rsaPublicKey when there is no publicKey available', (done) => { + const oauth = { + create() { + return new Promise((res) => res({ id_token: 'foobar' })); + }, }; - var jwksClientStub = sinon.spy(function() { - return { - getSigningKey: function(kid, cb) { - expect(kid).to.be.equal('kid'); - cb(null, { rsaPublicKey: 'rsaPublicKey' }); - } - }; - }); - OAUthWithIDTokenValidationProxy = proxyquire('../../src/auth/OAUthWithIDTokenValidation', { - 'jwks-rsa': jwksClientStub - }); + const jwksClientStub = sinon.spy(() => ({ + getSigningKey(kid, cb) { + expect(kid).to.be.equal('kid'); + cb(null, { rsaPublicKey: 'rsaPublicKey' }); + }, + })); - sinon.stub(jwt, 'verify').callsFake(function(idtoken, getKey, options, callback) { - getKey({ kid: 'kid', alg: 'RS256' }, function(err, key) { + sinon.stub(jwt, 'verify').callsFake((idtoken, getKey) => { + getKey({ kid: 'kid', alg: 'RS256' }, (err, key) => { expect(key).to.be.equal('rsaPublicKey'); done(); }); }); - var oauthWithValidation = new OAUthWithIDTokenValidationProxy(oauth, { + const oauthWithValidation = new OAUthWithIDTokenValidation(oauth, { domain: DOMAIN, - clientSecret: CLIENT_SECRET + clientSecret: CLIENT_SECRET, + jwksClient: jwksClientStub, }); oauthWithValidation.create(PARAMS, DATA); }); }); - describe('#integration', function() { - it('fails with a HS256 id_token and `options.supportedAlgorithms===RS256`', done => { - var oauth = { - create: function() { - return new Promise(res => + describe('#integration', () => { + it('fails with a HS256 id_token and `options.supportedAlgorithms===RS256`', (done) => { + const oauth = { + create() { + return new Promise((res) => res({ id_token: - 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuaWNrbmFtZSI6ImpvaG5mb28iLCJuYW1lIjoiam9obmZvb0BnbWFpbC5jb20iLCJwaWN0dXJlIjoiaHR0cHM6Ly9zLmdyYXZhdGFyLmNvbS9hdmF0YXIvMzhmYTAwMjQyM2JkOGM5NDFjNmVkMDU4OGI2MGZmZWQ_cz00ODAmcj1wZyZkPWh0dHBzJTNBJTJGJTJGY2RuLmF1dGgwLmNvbSUyRmF2YXRhcnMlMkZqby5wbmciLCJ1cGRhdGVkX2F0IjoiMjAxOC0wOS0xMlQyMDo1MjoxMS4zMDZaIiwiZW1haWwiOiJqb2huZm9vQGdtYWlsLmNvbSIsImVtYWlsX3ZlcmlmaWVkIjpmYWxzZSwiaXNzIjoiaHR0cHM6Ly9hdXRoLmJydWNrZS5jbHViLyIsInN1YiI6ImF1dGgwfDVhMjA1NGZmNDUxNTc3MTFiZTgxODJmNCIsImF1ZCI6IkVxbjdHTUV3VzhDbmN1S2FhcFRuNWs5VEJ0MzRQdldmIiwiaWF0IjoxNTM2Nzg1NTMxLCJleHAiOjE1MzY4MjE1MzF9.mZGsJyJYyp_mkINcnV0JRJ6QPsTXUE8FrpRTruAIqhE' + 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuaWNrbmFtZSI6ImpvaG5mb28iLCJuYW1lIjoiam9obmZvb0BnbWFpbC5jb20iLCJwaWN0dXJlIjoiaHR0cHM6Ly9zLmdyYXZhdGFyLmNvbS9hdmF0YXIvMzhmYTAwMjQyM2JkOGM5NDFjNmVkMDU4OGI2MGZmZWQ_cz00ODAmcj1wZyZkPWh0dHBzJTNBJTJGJTJGY2RuLmF1dGgwLmNvbSUyRmF2YXRhcnMlMkZqby5wbmciLCJ1cGRhdGVkX2F0IjoiMjAxOC0wOS0xMlQyMDo1MjoxMS4zMDZaIiwiZW1haWwiOiJqb2huZm9vQGdtYWlsLmNvbSIsImVtYWlsX3ZlcmlmaWVkIjpmYWxzZSwiaXNzIjoiaHR0cHM6Ly9hdXRoLmJydWNrZS5jbHViLyIsInN1YiI6ImF1dGgwfDVhMjA1NGZmNDUxNTc3MTFiZTgxODJmNCIsImF1ZCI6IkVxbjdHTUV3VzhDbmN1S2FhcFRuNWs5VEJ0MzRQdldmIiwiaWF0IjoxNTM2Nzg1NTMxLCJleHAiOjE1MzY4MjE1MzF9.mZGsJyJYyp_mkINcnV0JRJ6QPsTXUE8FrpRTruAIqhE', }) ); - } + }, }; - var oauthWithValidation = new OAUthWithIDTokenValidation(oauth, { + const oauthWithValidation = new OAUthWithIDTokenValidation(oauth, { clientSecret: CLIENT_SECRET, - supportedAlgorithms: ['RS256'] + supportedAlgorithms: ['RS256'], }); - oauthWithValidation.create(PARAMS, DATA, function(e) { + oauthWithValidation.create(PARAMS, DATA, (e) => { expect(e.message).to.eq('invalid algorithm'); done(); }); }); - it('fails with a RS256 id_token and `options.supportedAlgorithms===HS256`', done => { - createCertificate(function(c) { - var idtoken = jwt.sign({ foo: 'bar' }, c.serviceKey, { + it('fails with a RS256 id_token and `options.supportedAlgorithms===HS256`', (done) => { + createCertificate((c) => { + const idtoken = jwt.sign({ foo: 'bar' }, c.serviceKey, { algorithm: 'RS256', issuer: 'https://auth.brucke.club', audience: 'foobar', - expiresIn: '1d' + expiresIn: '1d', }); - var oauth = { - create: function() { - return new Promise(res => + const oauth = { + create() { + return new Promise((res) => res({ - id_token: idtoken + id_token: idtoken, }) ); - } + }, }; - var jwksClientStub = sinon.spy(function() { - return { - getSigningKey: function(kid, cb) { - cb(null, { publicKey: c.publicKey }); - } - }; - }); - OAUthWithIDTokenValidationProxy = proxyquire( - '../../src/auth/OAUthWithIDTokenValidation', - { - 'jwks-rsa': jwksClientStub - } - ); - var oauthWithValidation = new OAUthWithIDTokenValidationProxy(oauth, { + const jwksClientStub = sinon.spy(() => ({ + getSigningKey(kid, cb) { + cb(null, { publicKey: c.publicKey }); + }, + })); + + const oauthWithValidation = new OAUthWithIDTokenValidation(oauth, { clientSecret: CLIENT_SECRET, domain: 'auth.brucke.club', - supportedAlgorithms: ['HS256'] + supportedAlgorithms: ['HS256'], + jwksClient: jwksClientStub, }); - oauthWithValidation.create(PARAMS, DATA, function(e, d) { + oauthWithValidation.create(PARAMS, DATA, (e) => { expect(e.message).to.eq('invalid algorithm'); done(); }); }); }); - it('fails when `token.exp` is expired', done => { - createCertificate(function(c) { - var idtoken = jwt.sign({ foo: 'bar' }, c.serviceKey, { + it('fails when `token.exp` is expired', (done) => { + createCertificate((c) => { + const idtoken = jwt.sign({ foo: 'bar' }, c.serviceKey, { algorithm: 'RS256', issuer: 'https://auth.brucke.club', audience: 'foobar', - expiresIn: '-1h' + expiresIn: '-1h', }); - var oauth = { - create: function() { - return new Promise(res => + const oauth = { + create() { + return new Promise((res) => res({ - id_token: idtoken + id_token: idtoken, }) ); - } + }, }; - var jwksClientStub = sinon.spy(function() { - return { - getSigningKey: function(kid, cb) { - cb(null, { publicKey: c.publicKey }); - } - }; - }); - OAUthWithIDTokenValidationProxy = proxyquire( - '../../src/auth/OAUthWithIDTokenValidation', - { - 'jwks-rsa': jwksClientStub - } - ); - var oauthWithValidation = new OAUthWithIDTokenValidationProxy(oauth, { + const jwksClientStub = sinon.spy(() => ({ + getSigningKey(kid, cb) { + cb(null, { publicKey: c.publicKey }); + }, + })); + + const oauthWithValidation = new OAUthWithIDTokenValidation(oauth, { clientSecret: CLIENT_SECRET, domain: 'auth.brucke.club', - supportedAlgorithms: ['RS256'] + supportedAlgorithms: ['RS256'], + jwksClient: jwksClientStub, }); - oauthWithValidation.create(PARAMS, DATA, function(e, d) { + oauthWithValidation.create(PARAMS, DATA, (e) => { expect(e.message).to.eq('jwt expired'); done(); }); }); }); - describe('when using a valid certificate to generate an invalid id_token', function() { - it('fails when `token.aud` is invalid', done => { - createCertificate(function(c) { - var idtoken = jwt.sign({ foo: 'bar' }, c.serviceKey, { + describe('when using a valid certificate to generate an invalid id_token', () => { + it('fails when `token.aud` is invalid', (done) => { + createCertificate((c) => { + const idtoken = jwt.sign({ foo: 'bar' }, c.serviceKey, { algorithm: 'RS256', audience: 'wrong_audience', - expiresIn: '1h' + expiresIn: '1h', }); - var oauth = { - create: function() { - return new Promise(res => + const oauth = { + create() { + return new Promise((res) => res({ - id_token: idtoken + id_token: idtoken, }) ); - } + }, }; - var jwksClientStub = sinon.spy(function() { - return { - getSigningKey: function(kid, cb) { - cb(null, { publicKey: c.publicKey }); - } - }; - }); - OAUthWithIDTokenValidationProxy = proxyquire( - '../../src/auth/OAUthWithIDTokenValidation', - { - 'jwks-rsa': jwksClientStub - } - ); - var oauthWithValidation = new OAUthWithIDTokenValidationProxy(oauth, { + const jwksClientStub = sinon.spy(() => ({ + getSigningKey(kid, cb) { + cb(null, { publicKey: c.publicKey }); + }, + })); + + const oauthWithValidation = new OAUthWithIDTokenValidation(oauth, { clientId: 'foobar', clientSecret: CLIENT_SECRET, domain: 'brucke.auth0.com', - supportedAlgorithms: ['RS256'] + supportedAlgorithms: ['RS256'], + jwksClient: jwksClientStub, }); - oauthWithValidation.create(PARAMS, DATA, function(e) { + oauthWithValidation.create(PARAMS, DATA, (e) => { expect(e.message).to.eq('jwt audience invalid. expected: foobar'); done(); }); }); }); - it('fails when `token.iss` is invalid', done => { + it('fails when `token.iss` is invalid', (done) => { const TEST_AUDIENCE = 'foobar'; - createCertificate(function(c) { - var idtoken = jwt.sign({ foo: 'bar' }, c.serviceKey, { + createCertificate((c) => { + const idtoken = jwt.sign({ foo: 'bar' }, c.serviceKey, { algorithm: 'RS256', issuer: 'wrong_issuer', audience: TEST_AUDIENCE, - expiresIn: '1h' + expiresIn: '1h', }); - var oauth = { - create: function() { - return new Promise(res => + const oauth = { + create() { + return new Promise((res) => res({ - id_token: idtoken + id_token: idtoken, }) ); - } + }, }; - var jwksClientStub = sinon.spy(function() { - return { - getSigningKey: function(kid, cb) { - cb(null, { publicKey: c.publicKey }); - } - }; - }); - OAUthWithIDTokenValidationProxy = proxyquire( - '../../src/auth/OAUthWithIDTokenValidation', - { - 'jwks-rsa': jwksClientStub - } - ); - var oauthWithValidation = new OAUthWithIDTokenValidationProxy(oauth, { + const jwksClientStub = sinon.spy(() => ({ + getSigningKey(kid, cb) { + cb(null, { publicKey: c.publicKey }); + }, + })); + + const oauthWithValidation = new OAUthWithIDTokenValidation(oauth, { clientId: 'foobar', clientSecret: CLIENT_SECRET, domain: 'brucke.auth0.com', - supportedAlgorithms: ['RS256'] + supportedAlgorithms: ['RS256'], + jwksClient: jwksClientStub, }); - oauthWithValidation.create(PARAMS, DATA, function(e) { + oauthWithValidation.create(PARAMS, DATA, (e) => { expect(e.message).to.eq('jwt issuer invalid. expected: https://brucke.auth0.com/'); done(); }); diff --git a/test/auth/oauth.tests.js b/test/auth/oauth.tests.js index 6219d59d6..f84235c7a 100644 --- a/test/auth/oauth.tests.js +++ b/test/auth/oauth.tests.js @@ -1,110 +1,105 @@ -var expect = require('chai').expect; -var extend = require('util')._extend; -var nock = require('nock'); -var sinon = require('sinon'); - -// Constants. -var SRC_DIR = '../../src'; -var DOMAIN = 'tenant.auth0.com'; -var API_URL = 'https://' + DOMAIN; -var CLIENT_ID = 'TEST_CLIENT_ID'; -var CLIENT_SECRET = 'TEST_CLIENT_SECRET'; - -var ArgumentError = require('rest-facade').ArgumentError; -var Authenticator = require(SRC_DIR + '/auth/OAuthAuthenticator'); -var OAUthWithIDTokenValidation = require('../../src/auth/OAUthWithIDTokenValidation'); - -var validOptions = { +const { expect } = require('chai'); +const nock = require('nock'); +const sinon = require('sinon'); + +const DOMAIN = 'tenant.auth0.com'; +const API_URL = `https://${DOMAIN}`; +const CLIENT_ID = 'TEST_CLIENT_ID'; +const CLIENT_SECRET = 'TEST_CLIENT_SECRET'; + +const { ArgumentError } = require('rest-facade'); +const Authenticator = require(`../../src/auth/OAuthAuthenticator`); +const OAUthWithIDTokenValidation = require('../../src/auth/OAUthWithIDTokenValidation'); + +const validOptions = { baseUrl: API_URL, clientId: CLIENT_ID, - clientSecret: CLIENT_SECRET + clientSecret: CLIENT_SECRET, }; -describe('OAuthAuthenticator', function() { - beforeEach(function() { +describe('OAuthAuthenticator', () => { + beforeEach(() => { sinon.spy(OAUthWithIDTokenValidation.prototype, 'create'); }); - afterEach(function() { + afterEach(() => { OAUthWithIDTokenValidation.prototype.create.restore(); nock.cleanAll(); }); - describe('#constructor', function() { - it('should require an options object', function() { - expect(Authenticator).to.throw(ArgumentError, 'Missing authenticator options'); + describe('#constructor', () => { + it('should require an options object', () => { + expect(() => { + new Authenticator(); + }).to.throw(ArgumentError, 'Missing authenticator options'); - expect(Authenticator.bind(null, 1)).to.throw( - ArgumentError, - 'The authenticator options must be an object' - ); + expect(() => { + new Authenticator(1); + }).to.throw(ArgumentError, 'The authenticator options must be an object'); - expect(Authenticator.bind(null, validOptions)).to.not.throw(ArgumentError); + expect(() => { + new Authenticator(validOptions); + }).to.not.throw(ArgumentError); }); }); - describe('instance', function() { - var methods = [ + describe('instance', () => { + const methods = [ 'signIn', 'socialSignIn', 'passwordGrant', 'authorizationCodeGrant', - 'refreshToken' + 'refreshToken', ]; - var authenticator = new Authenticator(validOptions); + const authenticator = new Authenticator(validOptions); - methods.forEach(function(method) { - it('should have a ' + method + ' method', function() { + methods.forEach((method) => { + it(`should have a ${method} method`, () => { expect(authenticator[method]).to.exist.to.be.an.instanceOf(Function); }); }); }); - describe('#signIn', function() { - var path = '/oauth/ro'; - var userData = { + describe('#signIn', () => { + const path = '/oauth/ro'; + const userData = { username: 'username', password: 'pwd', - connection: 'Username-Password-Authentication' + connection: 'Username-Password-Authentication', }; - var options = { - forwardedFor: '0.0.0.0' + const options = { + forwardedFor: '0.0.0.0', }; - beforeEach(function() { + beforeEach(function () { this.authenticator = new Authenticator(validOptions); - this.request = nock(API_URL) - .post(path) - .reply(200); + this.request = nock(API_URL).post(path).reply(200); }); - it('should require an object as first argument', function() { + it('should require an object as first argument', function () { expect(this.authenticator.signIn).to.throw(ArgumentError, 'Missing user data object'); }); - it('should require a connection', function() { - var auth = this.authenticator; - var signIn = auth.signIn.bind(auth, {}); + it('should require a connection', function () { + const auth = this.authenticator; + const signIn = auth.signIn.bind(auth, {}); expect(signIn).to.throw(ArgumentError, 'connection field is required'); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.authenticator.signIn(userData, done.bind(null, null)); }); - it('should return a promise when no callback is provided', function(done) { - this.authenticator - .signIn(userData) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise when no callback is provided', function (done) { + this.authenticator.signIn(userData).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should perform a POST request to ' + path, function(done) { - var request = this.request; + it(`should perform a POST request to ${path}`, function (done) { + const { request } = this; this.authenticator .signIn(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -112,12 +107,12 @@ describe('OAuthAuthenticator', function() { .catch(done); }); - it('should include the user data un the request', function(done) { + it('should include the user data un the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - for (var property in userData) { + const request = nock(API_URL) + .post(path, (body) => { + for (const property in userData) { if (userData[property] !== body[property]) { return false; } @@ -129,7 +124,7 @@ describe('OAuthAuthenticator', function() { this.authenticator .signIn(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -137,18 +132,16 @@ describe('OAuthAuthenticator', function() { .catch(done); }); - it('should include the Auth0 client ID in the request', function(done) { + it('should include the Auth0 client ID in the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - return body.client_id === CLIENT_ID; - }) + const request = nock(API_URL) + .post(path, (body) => body.client_id === CLIENT_ID) .reply(200); this.authenticator .signIn(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -156,18 +149,16 @@ describe('OAuthAuthenticator', function() { .catch(done); }); - it('should allow the user to specify the connection', function(done) { + it('should allow the user to specify the connection', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - return body.connection === 'Username-Password-Authentication'; - }) + const request = nock(API_URL) + .post(path, (body) => body.connection === 'Username-Password-Authentication') .reply(200); this.authenticator .signIn(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -175,18 +166,16 @@ describe('OAuthAuthenticator', function() { .catch(done); }); - it('should use password as default grant type', function(done) { + it('should use password as default grant type', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - return body.grant_type === 'password'; - }) + const request = nock(API_URL) + .post(path, (body) => body.grant_type === 'password') .reply(200); this.authenticator .signIn(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -194,19 +183,17 @@ describe('OAuthAuthenticator', function() { .catch(done); }); - it('should allow the user to specify the grant type', function(done) { + it('should allow the user to specify the grant type', function (done) { nock.cleanAll(); - var data = extend({ grant_type: 'TEST_GRANT' }, userData); - var request = nock(API_URL) - .post(path, function(body) { - return body.grant_type === 'TEST_GRANT'; - }) + const data = { grant_type: 'TEST_GRANT', ...userData }; + const request = nock(API_URL) + .post(path, (body) => body.grant_type === 'TEST_GRANT') .reply(200); this.authenticator .signIn(data) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -214,18 +201,16 @@ describe('OAuthAuthenticator', function() { .catch(done); }); - it('should use the openid scope by default', function(done) { + it('should use the openid scope by default', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - return body.scope === 'openid'; - }) + const request = nock(API_URL) + .post(path, (body) => body.scope === 'openid') .reply(200); this.authenticator .signIn(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -233,18 +218,18 @@ describe('OAuthAuthenticator', function() { .catch(done); }); - it('should make it possible to pass auth0-forwarded-for header', function(done) { + it('should make it possible to pass auth0-forwarded-for header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function() { + const request = nock(API_URL) + .post(path, function () { return this.getHeader('auth0-forwarded-for') === options.forwardedFor; }) .reply(200); this.authenticator .signIn(userData, options) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -252,10 +237,10 @@ describe('OAuthAuthenticator', function() { .catch(done); }); - it('should use OAUthWithIDTokenValidation', function(done) { + it('should use OAUthWithIDTokenValidation', function (done) { this.authenticator .signIn(userData) - .then(function() { + .then(() => { expect(OAUthWithIDTokenValidation.prototype.create.calledOnce).to.be.true; done(); }) @@ -263,58 +248,56 @@ describe('OAuthAuthenticator', function() { }); }); - describe('#passwordGrant', function() { - var path = '/oauth/token'; - var userData = { + describe('#passwordGrant', () => { + const path = '/oauth/token'; + const userData = { username: 'username', - password: 'pwd' + password: 'pwd', }; - var options = { - forwardedFor: '0.0.0.0' + const options = { + forwardedFor: '0.0.0.0', }; - beforeEach(function() { + beforeEach(function () { this.authenticator = new Authenticator(validOptions); - this.request = nock(API_URL) - .post(path) - .reply(200); + this.request = nock(API_URL).post(path).reply(200); }); - it('should require an object as first argument', function() { + it('should require an object as first argument', function () { expect(this.authenticator.passwordGrant).to.throw(ArgumentError, 'Missing user data object'); }); - it('should require a username', function() { - var auth = this.authenticator; - var signIn = auth.passwordGrant.bind(auth, { password: 'pwd' }); + it('should require a username', function () { + const auth = this.authenticator; + const signIn = auth.passwordGrant.bind(auth, { password: 'pwd' }); expect(signIn).to.throw(ArgumentError, 'username field is required'); }); - it('should require a password', function() { - var auth = this.authenticator; - var signIn = auth.passwordGrant.bind(auth, { username: 'samples@auth0.com' }); + it('should require a password', function () { + const auth = this.authenticator; + const signIn = auth.passwordGrant.bind(auth, { username: 'samples@auth0.com' }); expect(signIn).to.throw(ArgumentError, 'password field is required'); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.authenticator.passwordGrant(userData, done.bind(null, null)); }); - it('should return a promise when no callback is provided', function(done) { + it('should return a promise when no callback is provided', function (done) { this.authenticator .passwordGrant(userData) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should perform a POST request to ' + path, function(done) { - var request = this.request; + it(`should perform a POST request to ${path}`, function (done) { + const { request } = this; this.authenticator .passwordGrant(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -322,12 +305,12 @@ describe('OAuthAuthenticator', function() { .catch(done); }); - it('should include the user data in the request', function(done) { + it('should include the user data in the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - for (var property in userData) { + const request = nock(API_URL) + .post(path, (body) => { + for (const property in userData) { if (userData[property] !== body[property]) { return false; } @@ -339,7 +322,7 @@ describe('OAuthAuthenticator', function() { this.authenticator .passwordGrant(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -347,18 +330,16 @@ describe('OAuthAuthenticator', function() { .catch(done); }); - it('should include the Auth0 client ID in the request', function(done) { + it('should include the Auth0 client ID in the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - return body.client_id === CLIENT_ID; - }) + const request = nock(API_URL) + .post(path, (body) => body.client_id === CLIENT_ID) .reply(200); this.authenticator .passwordGrant(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -366,18 +347,16 @@ describe('OAuthAuthenticator', function() { .catch(done); }); - it('should include the Auth0 client secret in the request', function(done) { + it('should include the Auth0 client secret in the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - return body.client_secret === CLIENT_SECRET; - }) + const request = nock(API_URL) + .post(path, (body) => body.client_secret === CLIENT_SECRET) .reply(200); this.authenticator .passwordGrant(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -385,21 +364,21 @@ describe('OAuthAuthenticator', function() { .catch(done); }); - it('should allow the user to specify the realm', function(done) { + it('should allow the user to specify the realm', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - return ( + const request = nock(API_URL) + .post( + path, + (body) => body.realm === 'Username-Password-Authentication' && body.grant_type === 'http://auth0.com/oauth/grant-type/password-realm' - ); - }) + ) .reply(200); this.authenticator .passwordGrant(Object.assign({ realm: 'Username-Password-Authentication' }, userData)) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -407,18 +386,16 @@ describe('OAuthAuthenticator', function() { .catch(done); }); - it('should use password as default grant type', function(done) { + it('should use password as default grant type', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - return body.grant_type === 'password'; - }) + const request = nock(API_URL) + .post(path, (body) => body.grant_type === 'password') .reply(200); this.authenticator .passwordGrant(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -426,18 +403,18 @@ describe('OAuthAuthenticator', function() { .catch(done); }); - it('should make it possible to pass auth0-forwarded-for header', function(done) { + it('should make it possible to pass auth0-forwarded-for header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function() { + const request = nock(API_URL) + .post(path, function () { return this.getHeader('auth0-forwarded-for') === options.forwardedFor; }) .reply(200); this.authenticator .passwordGrant(userData, options) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -445,10 +422,10 @@ describe('OAuthAuthenticator', function() { .catch(done); }); - it('should use OAUthWithIDTokenValidation', function(done) { + it('should use OAUthWithIDTokenValidation', function (done) { this.authenticator .passwordGrant(userData) - .then(function() { + .then(() => { expect(OAUthWithIDTokenValidation.prototype.create.calledOnce).to.be.true; done(); }) @@ -456,50 +433,48 @@ describe('OAuthAuthenticator', function() { }); }); - describe('#refreshToken', function() { - var path = '/oauth/token'; - var userData = { - refresh_token: 'refresh_token' + describe('#refreshToken', () => { + const path = '/oauth/token'; + const userData = { + refresh_token: 'refresh_token', }; - beforeEach(function() { + beforeEach(function () { this.authenticator = new Authenticator(validOptions); - this.request = nock(API_URL) - .post(path) - .reply(200); + this.request = nock(API_URL).post(path).reply(200); }); - it('should require an object as first argument', function() { + it('should require an object as first argument', function () { expect(this.authenticator.refreshToken).to.throw(ArgumentError, 'Missing data object'); }); - it('should require a refreshToken', function() { - var auth = this.authenticator; - var refresh = auth.refreshToken.bind(auth, {}); + it('should require a refreshToken', function () { + const auth = this.authenticator; + const refresh = auth.refreshToken.bind(auth, {}); expect(refresh).to.throw(ArgumentError, 'refresh_token is required'); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.authenticator.refreshToken(userData, done.bind(null, null)); }); - it('should return a promise when no callback is provided', function(done) { + it('should return a promise when no callback is provided', function (done) { this.authenticator .refreshToken(userData) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should perform a POST request to ' + path, function(done) { - var request = this.request; + it(`should perform a POST request to ${path}`, function (done) { + const { request } = this; this.authenticator .refreshToken(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); }) .catch(done); }); - it('should include the user data in the request', function(done) { + it('should include the user data in the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - for (var property in userData) { + const request = nock(API_URL) + .post(path, (body) => { + for (const property in userData) { if (userData[property] !== body[property]) { return false; } @@ -509,52 +484,46 @@ describe('OAuthAuthenticator', function() { .reply(200); this.authenticator .refreshToken(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); }) .catch(done); }); - it('should include the Auth0 client ID in the request', function(done) { + it('should include the Auth0 client ID in the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - return body.client_id === CLIENT_ID; - }) + const request = nock(API_URL) + .post(path, (body) => body.client_id === CLIENT_ID) .reply(200); this.authenticator .refreshToken(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); }) .catch(done); }); - it('should include the Auth0 client secret in the request', function(done) { + it('should include the Auth0 client secret in the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - return body.client_secret === CLIENT_SECRET; - }) + const request = nock(API_URL) + .post(path, (body) => body.client_secret === CLIENT_SECRET) .reply(200); this.authenticator .refreshToken(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); }) .catch(done); }); - it('should use refresh_token as default grant type', function(done) { + it('should use refresh_token as default grant type', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - return body.grant_type === 'refresh_token'; - }) + const request = nock(API_URL) + .post(path, (body) => body.grant_type === 'refresh_token') .reply(200); this.authenticator .refreshToken(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); }) @@ -562,129 +531,123 @@ describe('OAuthAuthenticator', function() { }); }); - describe('#socialSignIn', function() { - var path = '/oauth/access_token'; - var userData = { + describe('#socialSignIn', () => { + const path = '/oauth/access_token'; + const userData = { access_token: 'TEST_ACCESS_TOKEN', - connection: 'facebook' + connection: 'facebook', }; - beforeEach(function() { + beforeEach(function () { this.authenticator = new Authenticator(validOptions); - this.request = nock(API_URL) - .post(path) - .reply(200); + this.request = nock(API_URL).post(path).reply(200); }); - it('should require an object as first argument', function() { - var auth = this.authenticator; - var socialSignIn = auth.socialSignIn.bind(auth); - var message = 'Missing user credential objects'; + it('should require an object as first argument', function () { + const auth = this.authenticator; + const socialSignIn = auth.socialSignIn.bind(auth); + const message = 'Missing user credential objects'; expect(socialSignIn).to.throw(ArgumentError, message); expect(socialSignIn.bind(auth, userData)).to.not.throw(ArgumentError, message); }); - it('should require an access token', function() { - var auth = this.authenticator; - var socialSignIn = auth.socialSignIn.bind(auth, {}); - var message = 'access_token field is required'; + it('should require an access token', function () { + const auth = this.authenticator; + const socialSignIn = auth.socialSignIn.bind(auth, {}); + const message = 'access_token field is required'; expect(socialSignIn).to.throw(ArgumentError, message); }); - it('should require a connection', function() { - var auth = this.authenticator; - var data = { - access_token: userData.access_token + it('should require a connection', function () { + const auth = this.authenticator; + const data = { + access_token: userData.access_token, }; - var socialSignIn = auth.socialSignIn.bind(auth, data); - var message = 'connection field is required'; + const socialSignIn = auth.socialSignIn.bind(auth, data); + const message = 'connection field is required'; expect(socialSignIn).to.throw(ArgumentError, message); }); - it('should require a connection', function() { - var auth = this.authenticator; - var data = { - access_token: userData.access_token + it('should require a connection', function () { + const auth = this.authenticator; + const data = { + access_token: userData.access_token, }; - var socialSignIn = auth.socialSignIn.bind(auth, data); - var message = 'connection field is required'; + const socialSignIn = auth.socialSignIn.bind(auth, data); + const message = 'connection field is required'; expect(socialSignIn).to.throw(ArgumentError, message); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.authenticator.socialSignIn(userData, done.bind(null, null)); }); - it('should return a promise when no callback is given', function(done) { + it('should return a promise when no callback is given', function (done) { this.authenticator .socialSignIn(userData) .then(() => done()) .catch(() => done()); }); - it('should not return a promise when a callback is given', function() { - var cb = function() {}; - var returnValue = this.authenticator.socialSignIn(userData, cb); + it('should not return a promise when a callback is given', function () { + const cb = function () {}; + const returnValue = this.authenticator.socialSignIn(userData, cb); expect(returnValue).to.be.undefined; }); - it('should perform a POST request to ' + path, function(done) { - var request = this.request; + it(`should perform a POST request to ${path}`, function (done) { + const { request } = this; - this.authenticator.socialSignIn(userData).then(function() { + this.authenticator.socialSignIn(userData).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should allow the user to specify a custom client ID', function(done) { + it('should allow the user to specify a custom client ID', function (done) { nock.cleanAll(); - var data = extend({}, userData); + const data = { ...userData }; data.client_id = 'OVERRIDEN_ID'; - var request = nock(API_URL) - .post(path, data) - .reply(200); + const request = nock(API_URL).post(path, data).reply(200); - this.authenticator.socialSignIn(data).then(function() { + this.authenticator.socialSignIn(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should allow the user to specify the scope', function(done) { + it('should allow the user to specify the scope', function (done) { nock.cleanAll(); - var data = extend({}, userData); + const data = { ...userData }; data.scope = 'openid name email'; - var request = nock(API_URL) - .post(path, data) - .reply(200); + const request = nock(API_URL).post(path, data).reply(200); - this.authenticator.socialSignIn(data).then(function() { + this.authenticator.socialSignIn(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should use application/json as Content-Type', function(done) { + it('should use application/json as Content-Type', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .post(path) .matchHeader('Content-Type', 'application/json') .reply(200); - this.authenticator.socialSignIn(userData).then(function() { + this.authenticator.socialSignIn(userData).then(() => { expect(request.isDone()).to.be.true; done(); @@ -692,65 +655,63 @@ describe('OAuthAuthenticator', function() { }); }); - describe('#clientCredentials', function() { - var path = '/oauth/token'; - var options = { + describe('#clientCredentials', () => { + const path = '/oauth/token'; + const options = { audience: 'audience', - scope: 'scope' + scope: 'scope', }; - beforeEach(function() { + beforeEach(function () { this.authenticator = new Authenticator(validOptions); - this.request = nock(API_URL) - .post(path) - .reply(200); + this.request = nock(API_URL).post(path).reply(200); }); - it('should require an object as first argument', function() { + it('should require an object as first argument', function () { expect(this.authenticator.clientCredentialsGrant).to.throw( ArgumentError, 'Missing options object' ); }); - it('should require the client_id', function() { - var authenticator = new Authenticator({}); - expect(function() { + it('should require the client_id', () => { + const authenticator = new Authenticator({}); + expect(() => { authenticator.clientCredentialsGrant({}); }).to.throw(ArgumentError, 'client_id field is required'); }); - it('should require the client_secret', function() { - var authenticator = new Authenticator({ - clientId: CLIENT_ID + it('should require the client_secret', () => { + const authenticator = new Authenticator({ + clientId: CLIENT_ID, }); - expect(function() { + expect(() => { authenticator.clientCredentialsGrant({}); }).to.throw(ArgumentError, 'client_secret field is required'); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.authenticator.clientCredentialsGrant(options, done.bind(null, null)); }); - it('should return a promise when no callback is provided', function() { + it('should return a promise when no callback is provided', function () { return this.authenticator.clientCredentialsGrant(options); }); - it('should perform a POST request to ' + path, function() { - var request = this.request; + it(`should perform a POST request to ${path}`, function () { + const { request } = this; - return this.authenticator.clientCredentialsGrant(options).then(function() { + return this.authenticator.clientCredentialsGrant(options).then(() => { expect(request.isDone()).to.be.true; }); }); - it('should include the options in the request', function() { + it('should include the options in the request', function () { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - for (var property in options) { + const request = nock(API_URL) + .post(path, (body) => { + for (const property in options) { if (options[property] !== body[property]) { return false; } @@ -760,134 +721,122 @@ describe('OAuthAuthenticator', function() { }) .reply(200); - return this.authenticator.clientCredentialsGrant(options).then(function() { + return this.authenticator.clientCredentialsGrant(options).then(() => { expect(request.isDone()).to.be.true; }); }); - it('should include the Auth0 client ID and secret in the request', function() { + it('should include the Auth0 client ID and secret in the request', function () { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - return body.client_id === CLIENT_ID && body.client_secret === CLIENT_SECRET; - }) + const request = nock(API_URL) + .post(path, (body) => body.client_id === CLIENT_ID && body.client_secret === CLIENT_SECRET) .reply(200); - return this.authenticator.clientCredentialsGrant(options).then(function() { + return this.authenticator.clientCredentialsGrant(options).then(() => { expect(request.isDone()).to.be.true; }); }); - it('should allow the user to specify the audience and scope', function() { + it('should allow the user to specify the audience and scope', function () { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - return body.audience === 'audience' && body.scope === 'scope'; - }) + const request = nock(API_URL) + .post(path, (body) => body.audience === 'audience' && body.scope === 'scope') .reply(200); - return this.authenticator.clientCredentialsGrant(options).then(function() { + return this.authenticator.clientCredentialsGrant(options).then(() => { expect(request.isDone()).to.be.true; }); }); - it('should use client_credentials as default grant type', function() { + it('should use client_credentials as default grant type', function () { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - return body.grant_type === 'client_credentials'; - }) + const request = nock(API_URL) + .post(path, (body) => body.grant_type === 'client_credentials') .reply(200); - return this.authenticator.clientCredentialsGrant(options).then(function() { + return this.authenticator.clientCredentialsGrant(options).then(() => { expect(request.isDone()).to.be.true; }); }); - it('should allow the user to specify the grant type', function() { + it('should allow the user to specify the grant type', function () { nock.cleanAll(); - var data = extend({ grant_type: 'TEST_GRANT' }, options); - var request = nock(API_URL) - .post(path, function(body) { - return body.grant_type === 'TEST_GRANT'; - }) + const data = { grant_type: 'TEST_GRANT', ...options }; + const request = nock(API_URL) + .post(path, (body) => body.grant_type === 'TEST_GRANT') .reply(200); - return this.authenticator.clientCredentialsGrant(data).then(function() { + return this.authenticator.clientCredentialsGrant(data).then(() => { expect(request.isDone()).to.be.true; }); }); - it('should sanitize sensitive request data from errors', function() { + it('should sanitize sensitive request data from errors', function () { nock.cleanAll(); - var request = nock(API_URL) - .post(path) - .reply(401); + nock(API_URL).post(path).reply(401); - return this.authenticator.clientCredentialsGrant(options).catch(function(err) { + return this.authenticator.clientCredentialsGrant(options).catch((err) => { const originalRequestData = err.originalError.response.request._data; expect(originalRequestData.client_secret).to.not.equal(CLIENT_SECRET); }); }); }); - describe('#authorizationCodeGrant', function() { - var path = '/oauth/token'; - var data = { + describe('#authorizationCodeGrant', () => { + const path = '/oauth/token'; + const data = { code: 'auth_code', - redirect_uri: API_URL + redirect_uri: API_URL, }; - beforeEach(function() { + beforeEach(function () { this.authenticator = new Authenticator(validOptions); - this.request = nock(API_URL) - .post(path) - .reply(200); + this.request = nock(API_URL).post(path).reply(200); }); - it('should require an object as first argument', function() { + it('should require an object as first argument', function () { expect(this.authenticator.authorizationCodeGrant).to.throw( ArgumentError, 'Missing options object' ); }); - it('should require a code', function() { - var auth = this.authenticator; - var signIn = auth.authorizationCodeGrant.bind(auth, { redirect: API_URL }); + it('should require a code', function () { + const auth = this.authenticator; + const signIn = auth.authorizationCodeGrant.bind(auth, { redirect: API_URL }); expect(signIn).to.throw(ArgumentError, 'code field is required'); }); - it('should require a redirect_uri', function() { - var auth = this.authenticator; - var signIn = auth.authorizationCodeGrant.bind(auth, { code: 'auth_code' }); + it('should require a redirect_uri', function () { + const auth = this.authenticator; + const signIn = auth.authorizationCodeGrant.bind(auth, { code: 'auth_code' }); expect(signIn).to.throw(ArgumentError, 'redirect_uri field is required'); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.authenticator.authorizationCodeGrant(data, done.bind(null, null)); }); - it('should return a promise when no callback is provided', function(done) { + it('should return a promise when no callback is provided', function (done) { this.authenticator .authorizationCodeGrant(data) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should perform a POST request to ' + path, function(done) { - var request = this.request; + it(`should perform a POST request to ${path}`, function (done) { + const { request } = this; this.authenticator .authorizationCodeGrant(data) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -895,12 +844,12 @@ describe('OAuthAuthenticator', function() { .catch(done); }); - it('should include the data in the request', function(done) { + it('should include the data in the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - for (var property in data) { + const request = nock(API_URL) + .post(path, (body) => { + for (const property in data) { if (data[property] !== body[property]) { return false; } @@ -912,7 +861,7 @@ describe('OAuthAuthenticator', function() { this.authenticator .authorizationCodeGrant(data) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -920,18 +869,16 @@ describe('OAuthAuthenticator', function() { .catch(done); }); - it('should include the Auth0 client ID in the request', function(done) { + it('should include the Auth0 client ID in the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - return body.client_id === CLIENT_ID; - }) + const request = nock(API_URL) + .post(path, (body) => body.client_id === CLIENT_ID) .reply(200); this.authenticator .authorizationCodeGrant(data) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -939,18 +886,16 @@ describe('OAuthAuthenticator', function() { .catch(done); }); - it('should include the Auth0 client secret in the request', function(done) { + it('should include the Auth0 client secret in the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - return body.client_secret === CLIENT_SECRET; - }) + const request = nock(API_URL) + .post(path, (body) => body.client_secret === CLIENT_SECRET) .reply(200); this.authenticator .authorizationCodeGrant(data) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -958,18 +903,16 @@ describe('OAuthAuthenticator', function() { .catch(done); }); - it('should use authorization_code as default grant type', function(done) { + it('should use authorization_code as default grant type', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - return body.grant_type === 'authorization_code'; - }) + const request = nock(API_URL) + .post(path, (body) => body.grant_type === 'authorization_code') .reply(200); this.authenticator .authorizationCodeGrant(data) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -977,10 +920,10 @@ describe('OAuthAuthenticator', function() { .catch(done); }); - it('should use OAUthWithIDTokenValidation', function(done) { + it('should use OAUthWithIDTokenValidation', function (done) { this.authenticator .authorizationCodeGrant(data) - .then(function() { + .then(() => { expect(OAUthWithIDTokenValidation.prototype.create.calledOnce).to.be.true; done(); }) diff --git a/test/auth/passwordless.tests.js b/test/auth/passwordless.tests.js index 4a4a1fb3f..935fe0e3d 100644 --- a/test/auth/passwordless.tests.js +++ b/test/auth/passwordless.tests.js @@ -1,108 +1,106 @@ -var expect = require('chai').expect; -var extend = require('util')._extend; -var nock = require('nock'); +const { expect } = require('chai'); +const nock = require('nock'); -// Constants. -var SRC_DIR = '../../src'; -var DOMAIN = 'tenant.auth0.com'; -var API_URL = 'https://' + DOMAIN; -var CLIENT_ID = 'TEST_CLIENT_ID'; +const DOMAIN = 'tenant.auth0.com'; +const API_URL = `https://${DOMAIN}`; +const CLIENT_ID = 'TEST_CLIENT_ID'; -var ArgumentError = require('rest-facade').ArgumentError; -var Authenticator = require(SRC_DIR + '/auth/PasswordlessAuthenticator'); -var OAuth = require(SRC_DIR + '/auth/OAuthAuthenticator'); +const { ArgumentError } = require('rest-facade'); +const Authenticator = require(`../../src/auth/PasswordlessAuthenticator`); +const OAuth = require(`../../src/auth/OAuthAuthenticator`); -var validOptions = { +const validOptions = { baseUrl: API_URL, - clientId: CLIENT_ID + clientId: CLIENT_ID, }; -describe('PasswordlessAuthenticator', function() { - afterEach(function() { +describe('PasswordlessAuthenticator', () => { + afterEach(() => { nock.cleanAll(); }); - describe('#constructor', function() { - it('should require an options object', function() { - expect(Authenticator).to.throw(ArgumentError, 'Missing authenticator options'); + describe('#constructor', () => { + it('should require an options object', () => { + expect(() => { + new Authenticator(); + }).to.throw(ArgumentError, 'Missing authenticator options'); - expect(Authenticator.bind(null, 1)).to.throw( - ArgumentError, - 'The authenticator options must be an object' - ); + expect(() => { + new Authenticator(1); + }).to.throw(ArgumentError, 'The authenticator options must be an object'); - expect(Authenticator.bind(null, validOptions)).to.not.throw(ArgumentError); + expect(() => { + new Authenticator(validOptions); + }).to.not.throw(ArgumentError); }); }); - describe('instance', function() { - var methods = ['signIn', 'sendEmail', 'sendSMS']; - var oauth = new OAuth(validOptions); - var authenticator = new Authenticator(validOptions, oauth); + describe('instance', () => { + const methods = ['signIn', 'sendEmail', 'sendSMS']; + const oauth = new OAuth(validOptions); + const authenticator = new Authenticator(validOptions, oauth); - methods.forEach(function(method) { - it('should have a ' + method + ' method', function() { + methods.forEach((method) => { + it(`should have a ${method} method`, () => { expect(authenticator[method]).to.exist.to.be.an.instanceOf(Function); }); }); }); - describe('#signIn', function() { - describe('/oauth/ro', function() { - var path = '/oauth/ro'; - var userData = { + describe('#signIn', () => { + describe('/oauth/ro', () => { + const path = '/oauth/ro'; + const userData = { username: 'username', - password: 'pwd' + password: 'pwd', }; - var options = { - forwardedFor: '0.0.0.0' + const options = { + forwardedFor: '0.0.0.0', }; - beforeEach(function() { - var oauth = new OAuth(validOptions); + beforeEach(function () { + const oauth = new OAuth(validOptions); this.authenticator = new Authenticator(validOptions, oauth); - this.request = nock(API_URL) - .post(path) - .reply(200); + this.request = nock(API_URL).post(path).reply(200); }); - it('should require an object as first argument', function() { + it('should require an object as first argument', function () { expect(this.authenticator.signIn).to.throw(ArgumentError, 'Missing user data object'); }); - it('should require a phone number', function() { - var auth = this.authenticator; - var userData = { password: 'password' }; - var signIn = auth.signIn.bind(auth, userData); + it('should require a phone number', function () { + const auth = this.authenticator; + const userData = { password: 'password' }; + const signIn = auth.signIn.bind(auth, userData); expect(signIn).to.throw(ArgumentError, 'username field (phone number) is required'); }); - it('should require a verification code', function() { - var auth = this.authenticator; - var userData = { username: 'username' }; - var signIn = auth.signIn.bind(auth, userData); + it('should require a verification code', function () { + const auth = this.authenticator; + const userData = { username: 'username' }; + const signIn = auth.signIn.bind(auth, userData); expect(signIn).to.throw(ArgumentError, 'password field (verification code) is required'); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.authenticator.signIn(userData, done.bind(null, null)); }); - it('should return a promise when no callback is provided', function(done) { + it('should return a promise when no callback is provided', function (done) { this.authenticator .signIn(userData) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should perform a POST request to ' + path, function(done) { - var request = this.request; + it(`should perform a POST request to ${path}`, function (done) { + const { request } = this; this.authenticator .signIn(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -110,12 +108,12 @@ describe('PasswordlessAuthenticator', function() { .catch(done); }); - it('should include the user data in the request', function(done) { + it('should include the user data in the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - for (var property in userData) { + const request = nock(API_URL) + .post(path, (body) => { + for (const property in userData) { if (userData[property] !== body[property]) { return false; } @@ -127,7 +125,7 @@ describe('PasswordlessAuthenticator', function() { this.authenticator .signIn(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -135,18 +133,16 @@ describe('PasswordlessAuthenticator', function() { .catch(done); }); - it('should include the Auth0 client ID in the request', function(done) { + it('should include the Auth0 client ID in the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - return body.client_id === CLIENT_ID; - }) + const request = nock(API_URL) + .post(path, (body) => body.client_id === CLIENT_ID) .reply(200); this.authenticator .signIn(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -154,18 +150,16 @@ describe('PasswordlessAuthenticator', function() { .catch(done); }); - it('should use SMS connection', function(done) { + it('should use SMS connection', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - return body.connection === 'sms'; - }) + const request = nock(API_URL) + .post(path, (body) => body.connection === 'sms') .reply(200); this.authenticator .signIn(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -173,18 +167,16 @@ describe('PasswordlessAuthenticator', function() { .catch(done); }); - it('should use email connection', function(done) { + it('should use email connection', function (done) { nock.cleanAll(); - var data = extend({ connection: 'email' }, userData); - var request = nock(API_URL) - .post(path, function(body) { - return body.connection === 'email'; - }) + const data = { connection: 'email', ...userData }; + const request = nock(API_URL) + .post(path, (body) => body.connection === 'email') .reply(200); this.authenticator .signIn(data) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -192,19 +184,17 @@ describe('PasswordlessAuthenticator', function() { .catch(done); }); - it('should allow the user to specify the connection as sms or email', function(done) { + it('should allow the user to specify the connection as sms or email', function (done) { nock.cleanAll(); - var data = extend({ connection: 'TEST_CONNECTION' }, userData); - var request = nock(API_URL) - .post(path, function(body) { - return body.connection === 'sms' || body.connection === 'email'; - }) + const data = { connection: 'TEST_CONNECTION', ...userData }; + const request = nock(API_URL) + .post(path, (body) => body.connection === 'sms' || body.connection === 'email') .reply(200); this.authenticator .signIn(data) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -212,18 +202,16 @@ describe('PasswordlessAuthenticator', function() { .catch(done); }); - it('should use password as grant type', function(done) { + it('should use password as grant type', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - return body.grant_type === 'password'; - }) + const request = nock(API_URL) + .post(path, (body) => body.grant_type === 'password') .reply(200); this.authenticator .signIn(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -231,18 +219,16 @@ describe('PasswordlessAuthenticator', function() { .catch(done); }); - it('should use the openid scope', function(done) { + it('should use the openid scope', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - return body.scope === 'openid'; - }) + const request = nock(API_URL) + .post(path, (body) => body.scope === 'openid') .reply(200); this.authenticator .signIn(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -250,18 +236,18 @@ describe('PasswordlessAuthenticator', function() { .catch(done); }); - it('should make it possible to pass auth0-forwarded-for header', function(done) { + it('should make it possible to pass auth0-forwarded-for header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function() { + const request = nock(API_URL) + .post(path, function () { return this.getHeader('auth0-forwarded-for') === options.forwardedFor; }) .reply(200); this.authenticator .signIn(userData, options) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -270,61 +256,59 @@ describe('PasswordlessAuthenticator', function() { }); }); - describe('/oauth/token', function() { - var path = '/oauth/token'; - var userData = { + describe('/oauth/token', () => { + const path = '/oauth/token'; + const userData = { username: 'username', - otp: '000000' + otp: '000000', }; - var options = { - forwardedFor: '0.0.0.0' + const options = { + forwardedFor: '0.0.0.0', }; - beforeEach(function() { - var oauth = new OAuth(validOptions); + beforeEach(function () { + const oauth = new OAuth(validOptions); this.authenticator = new Authenticator(validOptions, oauth); - this.request = nock(API_URL) - .post(path) - .reply(200); + this.request = nock(API_URL).post(path).reply(200); }); - it('should require an object as first argument', function() { + it('should require an object as first argument', function () { expect(this.authenticator.signIn).to.throw(ArgumentError, 'Missing user data object'); }); - it('should require a phone number', function() { - var auth = this.authenticator; - var userData = { otp: '000000' }; - var signIn = auth.signIn.bind(auth, userData); + it('should require a phone number', function () { + const auth = this.authenticator; + const userData = { otp: '000000' }; + const signIn = auth.signIn.bind(auth, userData); expect(signIn).to.throw(ArgumentError, 'username field (phone number) is required'); }); - it('should require a verification code', function() { - var auth = this.authenticator; - var userData = { username: 'username' }; - var signIn = auth.signIn.bind(auth, userData); + it('should require a verification code', function () { + const auth = this.authenticator; + const userData = { username: 'username' }; + const signIn = auth.signIn.bind(auth, userData); expect(signIn).to.throw(ArgumentError, 'password field (verification code) is required'); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.authenticator.signIn(userData, done.bind(null, null)); }); - it('should return a promise when no callback is provided', function(done) { + it('should return a promise when no callback is provided', function (done) { this.authenticator .signIn(userData) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should perform a POST request to ' + path, function(done) { - var request = this.request; + it(`should perform a POST request to ${path}`, function (done) { + const { request } = this; this.authenticator .signIn(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -332,12 +316,12 @@ describe('PasswordlessAuthenticator', function() { .catch(done); }); - it('should include the user data in the request', function(done) { + it('should include the user data in the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - for (var property in userData) { + const request = nock(API_URL) + .post(path, (body) => { + for (const property in userData) { if (userData[property] !== body[property]) { return false; } @@ -349,7 +333,7 @@ describe('PasswordlessAuthenticator', function() { this.authenticator .signIn(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -357,18 +341,16 @@ describe('PasswordlessAuthenticator', function() { .catch(done); }); - it('should include the Auth0 client ID in the request', function(done) { + it('should include the Auth0 client ID in the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - return body.client_id === CLIENT_ID; - }) + const request = nock(API_URL) + .post(path, (body) => body.client_id === CLIENT_ID) .reply(200); this.authenticator .signIn(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -376,18 +358,16 @@ describe('PasswordlessAuthenticator', function() { .catch(done); }); - it('should use SMS realm', function(done) { + it('should use SMS realm', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - return body.realm === 'sms'; - }) + const request = nock(API_URL) + .post(path, (body) => body.realm === 'sms') .reply(200); this.authenticator .signIn(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -395,18 +375,16 @@ describe('PasswordlessAuthenticator', function() { .catch(done); }); - it('should use email realm', function(done) { + it('should use email realm', function (done) { nock.cleanAll(); - var data = extend({ realm: 'email' }, userData); - var request = nock(API_URL) - .post(path, function(body) { - return body.realm === 'email'; - }) + const data = { realm: 'email', ...userData }; + const request = nock(API_URL) + .post(path, (body) => body.realm === 'email') .reply(200); this.authenticator .signIn(data) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -414,19 +392,17 @@ describe('PasswordlessAuthenticator', function() { .catch(done); }); - it('should allow the user to specify the realm as sms or email', function(done) { + it('should allow the user to specify the realm as sms or email', function (done) { nock.cleanAll(); - var data = extend({ realm: 'TEST_CONNECTION' }, userData); - var request = nock(API_URL) - .post(path, function(body) { - return body.realm === 'sms' || body.realm === 'email'; - }) + const data = { realm: 'TEST_CONNECTION', ...userData }; + const request = nock(API_URL) + .post(path, (body) => body.realm === 'sms' || body.realm === 'email') .reply(200); this.authenticator .signIn(data) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -434,18 +410,19 @@ describe('PasswordlessAuthenticator', function() { .catch(done); }); - it('should use otp as grant type', function(done) { + it('should use otp as grant type', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - return body.grant_type === 'http://auth0.com/oauth/grant-type/passwordless/otp'; - }) + const request = nock(API_URL) + .post( + path, + (body) => body.grant_type === 'http://auth0.com/oauth/grant-type/passwordless/otp' + ) .reply(200); this.authenticator .signIn(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -453,18 +430,16 @@ describe('PasswordlessAuthenticator', function() { .catch(done); }); - it('should use the openid scope', function(done) { + it('should use the openid scope', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - return body.scope === 'openid'; - }) + const request = nock(API_URL) + .post(path, (body) => body.scope === 'openid') .reply(200); this.authenticator .signIn(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -472,18 +447,18 @@ describe('PasswordlessAuthenticator', function() { .catch(done); }); - it('should make it possible to pass auth0-forwarded-for header', function(done) { + it('should make it possible to pass auth0-forwarded-for header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function() { + const request = nock(API_URL) + .post(path, function () { return this.getHeader('auth0-forwarded-for') === options.forwardedFor; }) .reply(200); this.authenticator .signIn(userData, options) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -493,61 +468,61 @@ describe('PasswordlessAuthenticator', function() { }); }); - describe('#sendEmail', function() { - var path = '/passwordless/start'; - var userData = { + describe('#sendEmail', () => { + const path = '/passwordless/start'; + const userData = { email: 'email@domain.com', - send: 'link' + send: 'link', }; - var options = { - forwardedFor: '0.0.0.0' + const options = { + forwardedFor: '0.0.0.0', }; - beforeEach(function() { - var oauth = new OAuth(validOptions); + beforeEach(function () { + const oauth = new OAuth(validOptions); this.authenticator = new Authenticator(validOptions, oauth); - this.request = nock(API_URL) - .post(path) - .reply(200); + this.request = nock(API_URL).post(path).reply(200); }); - it('should require an object as first argument', function() { - expect(this.authenticator.sendEmail).to.throw(ArgumentError, 'Missing user data object'); + it('should require an object as first argument', function () { + expect(() => { + this.authenticator.sendEmail(); + }).to.throw(ArgumentError, 'Missing user data object'); }); - it('should require an email', function() { - var auth = this.authenticator; - var userData = {}; - var sendEmail = auth.sendEmail.bind(auth, userData); + it('should require an email', function () { + const auth = this.authenticator; + const userData = {}; + const sendEmail = auth.sendEmail.bind(auth, userData); expect(sendEmail).to.throw(ArgumentError, 'email field is required'); }); - it('should require the send field', function() { - var auth = this.authenticator; - var userData = { email: 'email@domain.com' }; - var sendEmail = auth.sendEmail.bind(auth, userData); + it('should require the send field', function () { + const auth = this.authenticator; + const userData = { email: 'email@domain.com' }; + const sendEmail = auth.sendEmail.bind(auth, userData); expect(sendEmail).to.throw(ArgumentError, 'send field is required'); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.authenticator.sendEmail(userData, done.bind(null, null)); }); - it('should return a promise when no callback is provided', function(done) { + it('should return a promise when no callback is provided', function (done) { this.authenticator .sendEmail(userData) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should perform a POST request to ' + path, function(done) { - var request = this.request; + it(`should perform a POST request to ${path}`, function (done) { + const { request } = this; this.authenticator .sendEmail(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -555,12 +530,12 @@ describe('PasswordlessAuthenticator', function() { .catch(done); }); - it('should include the user data in the request', function(done) { + it('should include the user data in the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - for (var property in userData) { + const request = nock(API_URL) + .post(path, (body) => { + for (const property in userData) { if (userData[property] !== body[property]) { return false; } @@ -572,7 +547,7 @@ describe('PasswordlessAuthenticator', function() { this.authenticator .sendEmail(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -580,18 +555,16 @@ describe('PasswordlessAuthenticator', function() { .catch(done); }); - it('should include the Auth0 client ID in the request', function(done) { + it('should include the Auth0 client ID in the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - return body.client_id === CLIENT_ID; - }) + const request = nock(API_URL) + .post(path, (body) => body.client_id === CLIENT_ID) .reply(200); this.authenticator .sendEmail(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -599,18 +572,16 @@ describe('PasswordlessAuthenticator', function() { .catch(done); }); - it('should use the email connection', function(done) { + it('should use the email connection', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - return body.connection === 'email'; - }) + const request = nock(API_URL) + .post(path, (body) => body.connection === 'email') .reply(200); this.authenticator .sendEmail(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -618,21 +589,19 @@ describe('PasswordlessAuthenticator', function() { .catch(done); }); - it('should use the specified send type', function(done) { + it('should use the specified send type', function (done) { nock.cleanAll(); - var data = extend({}, userData); - var request = nock(API_URL) - .post(path, function(body) { - return body.send === 'code'; - }) + const data = { ...userData }; + const request = nock(API_URL) + .post(path, (body) => body.send === 'code') .reply(200); data.send = 'code'; this.authenticator .sendEmail(data) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -640,19 +609,17 @@ describe('PasswordlessAuthenticator', function() { .catch(done); }); - it("shouldn't allow the user to specify the connection", function(done) { + it("shouldn't allow the user to specify the connection", function (done) { nock.cleanAll(); - var data = extend({ connection: 'TEST_CONNECTION' }, userData); - var request = nock(API_URL) - .post(path, function(body) { - return body.connection === 'email'; - }) + const data = { connection: 'TEST_CONNECTION', ...userData }; + const request = nock(API_URL) + .post(path, (body) => body.connection === 'email') .reply(200); this.authenticator .sendEmail(data) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -660,18 +627,18 @@ describe('PasswordlessAuthenticator', function() { .catch(done); }); - it('should make it possible to pass auth0-forwarded-for header', function(done) { + it('should make it possible to pass auth0-forwarded-for header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function() { + const request = nock(API_URL) + .post(path, function () { return this.getHeader('auth0-forwarded-for') === options.forwardedFor; }) .reply(200); this.authenticator .sendEmail(userData, options) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -680,52 +647,50 @@ describe('PasswordlessAuthenticator', function() { }); }); - describe('#sendSMS', function() { - var path = '/passwordless/start'; - var userData = { - phone_number: '12345678' + describe('#sendSMS', () => { + const path = '/passwordless/start'; + const userData = { + phone_number: '12345678', }; - var options = { - forwardedFor: '0.0.0.0' + const options = { + forwardedFor: '0.0.0.0', }; - beforeEach(function() { - var oauth = new OAuth(validOptions); + beforeEach(function () { + const oauth = new OAuth(validOptions); this.authenticator = new Authenticator(validOptions, oauth); - this.request = nock(API_URL) - .post(path) - .reply(200); + this.request = nock(API_URL).post(path).reply(200); }); - it('should require an object as first argument', function() { - expect(this.authenticator.sendSMS).to.throw(ArgumentError, 'Missing user data object'); + it('should require an object as first argument', function () { + expect(() => { + this.authenticator.sendSMS(); + }).to.throw(ArgumentError, 'Missing user data object'); }); - it('should require a phone number', function() { - var auth = this.authenticator; - var userData = {}; - var sendSMS = auth.sendSMS.bind(auth, userData); + it('should require a phone number', function () { + const auth = this.authenticator; + const userData = {}; - expect(sendSMS).to.throw(ArgumentError, 'phone_number field is required'); + expect(() => { + auth.sendSMS(userData); + }).to.throw(ArgumentError, 'phone_number field is required'); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.authenticator.sendSMS(userData, done.bind(null, null)); }); - it('should return a promise when no callback is provided', function(done) { - this.authenticator - .sendSMS(userData) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise when no callback is provided', function (done) { + this.authenticator.sendSMS(userData).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should perform a POST request to ' + path, function(done) { - var request = this.request; + it(`should perform a POST request to ${path}`, function (done) { + const { request } = this; this.authenticator .sendSMS(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -733,12 +698,12 @@ describe('PasswordlessAuthenticator', function() { .catch(done); }); - it('should include the user data in the request', function(done) { + it('should include the user data in the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - for (var property in userData) { + const request = nock(API_URL) + .post(path, (body) => { + for (const property in userData) { if (userData[property] !== body[property]) { return false; } @@ -750,7 +715,7 @@ describe('PasswordlessAuthenticator', function() { this.authenticator .sendSMS(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -758,18 +723,16 @@ describe('PasswordlessAuthenticator', function() { .catch(done); }); - it('should include the Auth0 client ID in the request', function(done) { + it('should include the Auth0 client ID in the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - return body.client_id === CLIENT_ID; - }) + const request = nock(API_URL) + .post(path, (body) => body.client_id === CLIENT_ID) .reply(200); this.authenticator .sendSMS(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -777,18 +740,16 @@ describe('PasswordlessAuthenticator', function() { .catch(done); }); - it('should use the sms connection', function(done) { + it('should use the sms connection', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function(body) { - return body.connection === 'sms'; - }) + const request = nock(API_URL) + .post(path, (body) => body.connection === 'sms') .reply(200); this.authenticator .sendSMS(userData) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -796,19 +757,17 @@ describe('PasswordlessAuthenticator', function() { .catch(done); }); - it("shouldn't allow the user to specify the connection", function(done) { + it("shouldn't allow the user to specify the connection", function (done) { nock.cleanAll(); - var data = extend({ connection: 'TEST_CONNECTION' }, userData); - var request = nock(API_URL) - .post(path, function(body) { - return body.connection === 'sms'; - }) + const data = { connection: 'TEST_CONNECTION', ...userData }; + const request = nock(API_URL) + .post(path, (body) => body.connection === 'sms') .reply(200); this.authenticator .sendSMS(data) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -816,18 +775,18 @@ describe('PasswordlessAuthenticator', function() { .catch(done); }); - it('should make it possible to pass auth0-forwarded-for header', function(done) { + it('should make it possible to pass auth0-forwarded-for header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post(path, function() { + const request = nock(API_URL) + .post(path, function () { return this.getHeader('auth0-forwarded-for') === options.forwardedFor; }) .reply(200); this.authenticator .sendSMS(userData, options) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); diff --git a/test/auth/tokens-manager.tests.js b/test/auth/tokens-manager.tests.js index f77838a51..4ffdb270f 100644 --- a/test/auth/tokens-manager.tests.js +++ b/test/auth/tokens-manager.tests.js @@ -1,128 +1,126 @@ -var expect = require('chai').expect; -var nock = require('nock'); -var utilTypes = require('util').types; +const { expect } = require('chai'); +const nock = require('nock'); +const utilTypes = require('util').types; -var BASE_URL = 'https://tenant.auth0.com'; +const BASE_URL = 'https://tenant.auth0.com'; -var ArgumentError = require('rest-facade').ArgumentError; -var TokensManager = require('../../src/auth/TokensManager'); +const { ArgumentError } = require('rest-facade'); +const TokensManager = require('../../src/auth/TokensManager'); -describe('TokensManager', function() { - var validOptions = { +describe('TokensManager', () => { + const validOptions = { baseUrl: BASE_URL, headers: { 'Content-Type': 'application/json', - 'Test-Header': 'TEST' + 'Test-Header': 'TEST', }, clientId: 'CLIENT_ID', - clientSecret: 'CLIENT_SECRET' + clientSecret: 'CLIENT_SECRET', }; - afterEach(function() { + afterEach(() => { nock.cleanAll(); }); - describe('#constructor', function() { - it('should require an options object', function() { - expect(TokensManager).to.throw(ArgumentError, 'Missing tokens manager options'); + describe('#constructor', () => { + it('should require an options object', () => { + expect(() => { + new TokensManager(); + }).to.throw(ArgumentError, 'Missing tokens manager options'); }); - it('should require a base URL', function() { - var manager = TokensManager.bind(null, {}); - - expect(manager).to.throw(ArgumentError, 'baseUrl field is required'); + it('should require a base URL', () => { + expect(() => { + new TokensManager({}); + }).to.throw(ArgumentError, 'baseUrl field is required'); }); }); - describe('instance', function() { - var methods = ['getInfo', 'getDelegationToken', 'revokeRefreshToken']; - var manager = new TokensManager(validOptions); + describe('instance', () => { + const methods = ['getInfo', 'getDelegationToken', 'revokeRefreshToken']; + const manager = new TokensManager(validOptions); - methods.forEach(function(methodName) { - it('should have a ' + methodName + ' method', function() { + methods.forEach((methodName) => { + it(`should have a ${methodName} method`, () => { expect(manager[methodName]).to.exist.to.be.an.instanceOf(Function); }); }); }); - describe('#getInfo', function() { - var manager = new TokensManager(validOptions); - var path = '/tokeninfo'; + describe('#getInfo', () => { + const manager = new TokensManager(validOptions); + const path = '/tokeninfo'; - beforeEach(function() { - this.request = nock(BASE_URL) - .post(path) - .reply(200); + beforeEach(function () { + this.request = nock(BASE_URL).post(path).reply(200); }); - it('should require an ID token', function() { - var getInfo = manager.getInfo.bind(manager); + it('should require an ID token', () => { + const getInfo = manager.getInfo.bind(manager); expect(getInfo).to.throw(ArgumentError, 'An ID token is required'); }); - it('should throw an error when the token is invalid', function() { - var getInfo = manager.getInfo.bind(manager, ''); + it('should throw an error when the token is invalid', () => { + const getInfo = manager.getInfo.bind(manager, ''); expect(getInfo).to.throw(ArgumentError, 'The ID token is not valid'); }); - it('should not throw errors when the token is valid', function() { - var getInfo = manager.getInfo.bind(manager, 'VALID_TOKEN'); + it('should not throw errors when the token is valid', () => { + const getInfo = manager.getInfo.bind(manager, 'VALID_TOKEN'); expect(getInfo).to.not.throw(ArgumentError); }); - it('should accept a callback', function(done) { + it('should accept a callback', (done) => { manager.getInfo('VALID_TOKEN', done.bind(null, null)); }); - it('should return a promise when no callback is provided', function() { - var returnValue = manager.getInfo('VALID_TOKEN'); + it('should return a promise when no callback is provided', () => { + const returnValue = manager.getInfo('VALID_TOKEN'); expect(utilTypes.isPromise(returnValue)).ok; }); - it('should not return a promise when a callback is provided', function() { - var returnValue = manager.getInfo('VALID_TOKEN', function() {}); + it('should not return a promise when a callback is provided', () => { + const returnValue = manager.getInfo('VALID_TOKEN', () => {}); expect(returnValue).to.be.undefined; }); - it('should perform a POST request to ' + path, function(done) { - var request = this.request; + it(`should perform a POST request to ${path}`, function (done) { + const { request } = this; - manager.getInfo('VALID_TOKEN').then(function() { + manager.getInfo('VALID_TOKEN').then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the headers specified in the instance options', function(done) { + it('should include the headers specified in the instance options', (done) => { nock.cleanAll(); - var request = nock(BASE_URL) + const request = nock(BASE_URL) .post(path) .matchHeader('Content-Type', validOptions.headers['Content-Type']) .reply(200); - manager.getInfo('VALID_TOKEN').then(function() { + manager.getInfo('VALID_TOKEN').then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should send the ID token in the body of the request', function(done) { + it('should send the ID token in the body of the request', (done) => { nock.cleanAll(); - var request = nock(BASE_URL) - .post(path, function(body) { - return body.id_token === 'VALID_TOKEN'; - }) + const request = nock(BASE_URL) + .post(path, (body) => body.id_token === 'VALID_TOKEN') .reply(200); - manager.getInfo('VALID_TOKEN').then(function() { + manager.getInfo('VALID_TOKEN').then(() => { expect(request.isDone()).to.be.true; done(); @@ -130,25 +128,23 @@ describe('TokensManager', function() { }); }); - describe('#getDelegationToken', function() { - var path = '/delegation'; - var manager = new TokensManager(validOptions); + describe('#getDelegationToken', () => { + const path = '/delegation'; + const manager = new TokensManager(validOptions); - beforeEach(function() { - this.request = nock(BASE_URL) - .post(path) - .reply(200); + beforeEach(function () { + this.request = nock(BASE_URL).post(path).reply(200); }); - it('should require a data object', function() { - var getDelegationToken = manager.getDelegationToken.bind(manager); + it('should require a data object', () => { + const getDelegationToken = manager.getDelegationToken.bind(manager); expect(getDelegationToken).to.throw(ArgumentError, 'Missing token data object'); }); - it('should require an ID token or refresh token', function() { - var data = {}; - var getDelegationToken = manager.getDelegationToken.bind(manager, data); + it('should require an ID token or refresh token', () => { + const data = {}; + const getDelegationToken = manager.getDelegationToken.bind(manager, data); expect(getDelegationToken).to.throw( ArgumentError, @@ -156,9 +152,9 @@ describe('TokensManager', function() { ); }); - it('should not accept an ID token and a refresh token simulatenously', function() { - var data = { id_token: 'foo', refresh_token: 'bar' }; - var getDelegationToken = manager.getDelegationToken.bind(manager, data); + it('should not accept an ID token and a refresh token simulatenously', () => { + const data = { id_token: 'foo', refresh_token: 'bar' }; + const getDelegationToken = manager.getDelegationToken.bind(manager, data); expect(getDelegationToken).to.throw( ArgumentError, @@ -166,83 +162,83 @@ describe('TokensManager', function() { ); }); - it('should require a target client', function() { - var data = { id_token: 'TEST_ID_TOKEN' }; - var getDelegationToken = manager.getDelegationToken.bind(manager, data); + it('should require a target client', () => { + const data = { id_token: 'TEST_ID_TOKEN' }; + const getDelegationToken = manager.getDelegationToken.bind(manager, data); expect(getDelegationToken).to.throw(ArgumentError, 'target field is required'); }); - it('should require an API type', function() { - var data = { + it('should require an API type', () => { + const data = { id_token: 'TEST_ID_TOKEN', - target: 'TEST_TARGET' + target: 'TEST_TARGET', }; - var getDelegationToken = manager.getDelegationToken.bind(manager, data); + const getDelegationToken = manager.getDelegationToken.bind(manager, data); expect(getDelegationToken).to.throw(ArgumentError, 'api_type field is required'); }); - it('should require an grant type', function() { - var data = { + it('should require an grant type', () => { + const data = { id_token: 'TEST_ID_TOKEN', target: 'TEST_TARGET', - api_type: 'aws' + api_type: 'aws', }; - var getDelegationToken = manager.getDelegationToken.bind(manager, data); + const getDelegationToken = manager.getDelegationToken.bind(manager, data); expect(getDelegationToken).to.throw(ArgumentError, 'grant_type field is required'); }); - it('should accept a callback', function(done) { - var data = { + it('should accept a callback', (done) => { + const data = { id_token: 'TEST_ID_TOKEN', target: 'TEST_TARGET', api_type: 'aws', - grant_type: 'SAMPLE_GRANT_TYPE' + grant_type: 'SAMPLE_GRANT_TYPE', }; manager.getDelegationToken(data, done.bind(null, null)); }); - it('should return a promise when no callback is given', function() { - var data = { + it('should return a promise when no callback is given', () => { + const data = { id_token: 'TEST_ID_TOKEN', target: 'TEST_TARGET', api_type: 'aws', - grant_type: 'SAMPLE_GRANT_TYPE' + grant_type: 'SAMPLE_GRANT_TYPE', }; - var returnValue = manager.getDelegationToken(data); + const returnValue = manager.getDelegationToken(data); expect(utilTypes.isPromise(returnValue)).ok; }); - it('should not return a promise when a callback is given', function() { - var data = { + it('should not return a promise when a callback is given', () => { + const data = { id_token: 'TEST_ID_TOKEN', target: 'TEST_TARGET', api_type: 'aws', - grant_type: 'SAMPLE_GRANT_TYPE' + grant_type: 'SAMPLE_GRANT_TYPE', }; - var returnValue = manager.getDelegationToken(data, function() {}); + const returnValue = manager.getDelegationToken(data, () => {}); expect(returnValue).to.equal(undefined); }); - it('should perform a POST request to ' + path, function() {}); + it(`should perform a POST request to ${path}`, () => {}); - it('should include the data in the body of the request', function(done) { + it('should include the data in the body of the request', (done) => { nock.cleanAll(); - var data = { + const data = { id_token: 'TEST_ID_TOKEN', target: 'TEST_TARGET', api_type: 'aws', - grant_type: 'SAMPLE_GRANT_TYPE' + grant_type: 'SAMPLE_GRANT_TYPE', }; - var request = nock(BASE_URL) - .post(path, function(body) { - for (var property in data) { + const request = nock(BASE_URL) + .post(path, (body) => { + for (const property in data) { if (body[property] !== data[property]) { return false; } @@ -252,76 +248,72 @@ describe('TokensManager', function() { }) .reply(); - manager.getDelegationToken(data).then(function() { + manager.getDelegationToken(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should use the instance client ID if none specified', function(done) { + it('should use the instance client ID if none specified', (done) => { nock.cleanAll(); - var data = { + const data = { id_token: 'TEST_ID_TOKEN', target: 'TEST_TARGET', api_type: 'aws', - grant_type: 'SAMPLE_GRANT_TYPE' + grant_type: 'SAMPLE_GRANT_TYPE', }; - var request = nock(BASE_URL) - .post(path, function(body) { - return body.client_id === validOptions.clientId; - }) + const request = nock(BASE_URL) + .post(path, (body) => body.client_id === validOptions.clientId) .reply(); - manager.getDelegationToken(data).then(function() { + manager.getDelegationToken(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should let the user override the default client ID', function(done) { + it('should let the user override the default client ID', (done) => { nock.cleanAll(); - var data = { + const data = { id_token: 'TEST_ID_TOKEN', target: 'TEST_TARGET', api_type: 'aws', grant_type: 'SAMPLE_GRANT_TYPE', - client_id: 'OVERRIDEN_CLIENT_ID' + client_id: 'OVERRIDEN_CLIENT_ID', }; - var request = nock(BASE_URL) - .post(path, function(body) { - return body.client_id === data.client_id; - }) + const request = nock(BASE_URL) + .post(path, (body) => body.client_id === data.client_id) .reply(); - manager.getDelegationToken(data).then(function() { + manager.getDelegationToken(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the headers specified in the instance options', function(done) { + it('should include the headers specified in the instance options', (done) => { nock.cleanAll(); - var data = { + const data = { id_token: 'TEST_ID_TOKEN', target: 'TEST_TARGET', api_type: 'aws', - grant_type: 'SAMPLE_GRANT_TYPE' + grant_type: 'SAMPLE_GRANT_TYPE', }; - var request = nock(BASE_URL) + const request = nock(BASE_URL) .post(path) .matchHeader('Test-Header', validOptions.headers['Test-Header']) .reply(200); - manager.getDelegationToken(data).then(function() { + manager.getDelegationToken(data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -329,43 +321,41 @@ describe('TokensManager', function() { }); }); - describe('#revokeRefreshToken', function() { - var path = '/oauth/revoke'; - var manager = new TokensManager(validOptions); + describe('#revokeRefreshToken', () => { + const path = '/oauth/revoke'; + const manager = new TokensManager(validOptions); - beforeEach(function() { - this.request = nock(BASE_URL) - .post(path) - .reply(200); + beforeEach(function () { + this.request = nock(BASE_URL).post(path).reply(200); }); - it('should require a token data object', function() { - var revokeRefreshToken = manager.revokeRefreshToken.bind(manager); + it('should require a token data object', () => { + const revokeRefreshToken = manager.revokeRefreshToken.bind(manager); expect(revokeRefreshToken).to.throw(ArgumentError, 'Missing token data object'); }); - it('should require a token property in the token data object', function() { - var data = {}; - var revokeRefreshToken = manager.revokeRefreshToken.bind(manager, data); + it('should require a token property in the token data object', () => { + const data = {}; + const revokeRefreshToken = manager.revokeRefreshToken.bind(manager, data); expect(revokeRefreshToken).to.throw(ArgumentError, 'token property is required'); }); - it('should require at least a target client ID', function() { - var manager = new TokensManager({ + it('should require at least a target client ID', () => { + const manager = new TokensManager({ baseUrl: BASE_URL, headers: { 'Content-Type': 'application/json', - 'Test-Header': 'TEST' - } + 'Test-Header': 'TEST', + }, }); - var data = { - token: 'TEST_REFRESH_TOKEN' + const data = { + token: 'TEST_REFRESH_TOKEN', }; - var revokeRefreshToken = manager.revokeRefreshToken.bind(manager, data); + const revokeRefreshToken = manager.revokeRefreshToken.bind(manager, data); expect(revokeRefreshToken).to.throw( ArgumentError, @@ -373,43 +363,43 @@ describe('TokensManager', function() { ); }); - it('should accept a callback', function(done) { - var data = { - token: 'TEST_REFRESH_TOKEN' + it('should accept a callback', (done) => { + const data = { + token: 'TEST_REFRESH_TOKEN', }; manager.revokeRefreshToken(data, done.bind(null, null)); }); - it('should return a promise when no callback is given', function() { - var data = { - token: 'TEST_REFRESH_TOKEN' + it('should return a promise when no callback is given', () => { + const data = { + token: 'TEST_REFRESH_TOKEN', }; - var returnValue = manager.revokeRefreshToken(data); + const returnValue = manager.revokeRefreshToken(data); expect(utilTypes.isPromise(returnValue)).ok; }); - it('should not return a promise when a callback is given', function() { - var data = { - token: 'TEST_REFRESH_TOKEN' + it('should not return a promise when a callback is given', () => { + const data = { + token: 'TEST_REFRESH_TOKEN', }; - var returnValue = manager.revokeRefreshToken(data, function() {}); + const returnValue = manager.revokeRefreshToken(data, () => {}); expect(returnValue).to.equal(undefined); }); - it('should perform a POST request to ' + path, function() {}); + it(`should perform a POST request to ${path}`, () => {}); - it('should include the data in the body of the request', function(done) { + it('should include the data in the body of the request', (done) => { nock.cleanAll(); - var data = { - token: 'TEST_REFRESH_TOKEN' + const data = { + token: 'TEST_REFRESH_TOKEN', }; - var request = nock(BASE_URL) - .post(path, function(body) { - for (var property in data) { + const request = nock(BASE_URL) + .post(path, (body) => { + for (const property in data) { if (body[property] !== data[property]) { return false; } @@ -419,108 +409,100 @@ describe('TokensManager', function() { }) .reply(); - manager.revokeRefreshToken(data).then(function() { + manager.revokeRefreshToken(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should use the TokensManager instance client ID if none specified', function(done) { + it('should use the TokensManager instance client ID if none specified', (done) => { nock.cleanAll(); - var data = { - token: 'TEST_REFRESH_TOKEN' + const data = { + token: 'TEST_REFRESH_TOKEN', }; - var request = nock(BASE_URL) - .post(path, function(body) { - return body.client_id === validOptions.clientId; - }) + const request = nock(BASE_URL) + .post(path, (body) => body.client_id === validOptions.clientId) .reply(); - manager.revokeRefreshToken(data).then(function() { + manager.revokeRefreshToken(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should let the user override the default client ID', function(done) { + it('should let the user override the default client ID', (done) => { nock.cleanAll(); - var data = { + const data = { token: 'TEST_REFRESH_TOKEN', - client_id: 'OVERRIDEN_CLIENT_ID' + client_id: 'OVERRIDEN_CLIENT_ID', }; - var request = nock(BASE_URL) - .post(path, function(body) { - return body.client_id === data.client_id; - }) + const request = nock(BASE_URL) + .post(path, (body) => body.client_id === data.client_id) .reply(); - manager.revokeRefreshToken(data).then(function() { + manager.revokeRefreshToken(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should use the TokensManager instance client secret if none specified', function(done) { + it('should use the TokensManager instance client secret if none specified', (done) => { nock.cleanAll(); - var data = { - token: 'TEST_REFRESH_TOKEN' + const data = { + token: 'TEST_REFRESH_TOKEN', }; - var request = nock(BASE_URL) - .post(path, function(body) { - return body.client_secret === validOptions.clientSecret; - }) + const request = nock(BASE_URL) + .post(path, (body) => body.client_secret === validOptions.clientSecret) .reply(); - manager.revokeRefreshToken(data).then(function() { + manager.revokeRefreshToken(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should let the user override the default client secret', function(done) { + it('should let the user override the default client secret', (done) => { nock.cleanAll(); - var data = { + const data = { token: 'TEST_REFRESH_TOKEN', - client_secret: 'OVERRIDEN_CLIENT_SECRET' + client_secret: 'OVERRIDEN_CLIENT_SECRET', }; - var request = nock(BASE_URL) - .post(path, function(body) { - return body.client_secret === data.client_secret; - }) + const request = nock(BASE_URL) + .post(path, (body) => body.client_secret === data.client_secret) .reply(); - manager.revokeRefreshToken(data).then(function() { + manager.revokeRefreshToken(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the headers specified in the instance options', function(done) { + it('should include the headers specified in the instance options', (done) => { nock.cleanAll(); - var data = { - token: 'TEST_REFRESH_TOKEN' + const data = { + token: 'TEST_REFRESH_TOKEN', }; - var request = nock(BASE_URL) + const request = nock(BASE_URL) .post(path) .matchHeader('Test-Header', validOptions.headers['Test-Header']) .reply(200); - manager.revokeRefreshToken(data).then(function() { + manager.revokeRefreshToken(data).then(() => { expect(request.isDone()).to.be.true; done(); diff --git a/test/auth/user-profile.tests.js b/test/auth/user-profile.tests.js deleted file mode 100644 index 5f8fd5610..000000000 --- a/test/auth/user-profile.tests.js +++ /dev/null @@ -1,19 +0,0 @@ -var expect = require('chai').expect; -var extend = require('util')._extend; -var nock = require('nock'); - -// Constants. -var SRC_DIR = '../../src'; -var DOMAIN = 'tenant.auth0.com'; -var API_URL = 'https://' + DOMAIN; -var CLIENT_ID = 'TEST_CLIENT_ID'; - -var ArgumentError = require('rest-facade').ArgumentError; -var Authenticator = require(SRC_DIR + '/auth/OAuthAuthenticator'); - -var validOptions = { - domain: DOMAIN, - clientId: CLIENT_ID -}; - -describe('UserProfile', function() {}); diff --git a/test/auth/users-manager.tests.js b/test/auth/users-manager.tests.js index fe032bbbe..b3c119052 100644 --- a/test/auth/users-manager.tests.js +++ b/test/auth/users-manager.tests.js @@ -1,97 +1,99 @@ -var expect = require('chai').expect; -var nock = require('nock'); -var utilTypes = require('util').types; +const { expect } = require('chai'); +const nock = require('nock'); +const utilTypes = require('util').types; -var BASE_URL = 'https://tenant.auth0.com'; -var CLIENT_ID = 'TEST_CLIENT_ID'; +const BASE_URL = 'https://tenant.auth0.com'; +const CLIENT_ID = 'TEST_CLIENT_ID'; -var ArgumentError = require('rest-facade').ArgumentError; -var UsersManager = require('../../src/auth/UsersManager'); +const { ArgumentError } = require('rest-facade'); +const UsersManager = require('../../src/auth/UsersManager'); -describe('UsersManager', function() { - var options = { +describe('UsersManager', () => { + const options = { baseUrl: BASE_URL, clientId: CLIENT_ID, headers: { - 'Content-Type': 'application/json' - } + 'Content-Type': 'application/json', + }, }; - afterEach(function() { + afterEach(() => { nock.cleanAll(); }); - describe('#constructor', function() { - it('should require an options object', function() { - expect(UsersManager).to.throw(ArgumentError, 'Missing users manager options'); + describe('#constructor', () => { + it('should require an options object', () => { + expect(() => { + new UsersManager(); + }).to.throw(ArgumentError, 'Missing users manager options'); }); - it('should require a base URL', function() { - expect(UsersManager.bind(null, {})).to.throw(ArgumentError, 'baseUrl field is required'); + it('should require a base URL', () => { + expect(() => { + new UsersManager({}); + }).to.throw(ArgumentError, 'baseUrl field is required'); }); }); - describe('instance', function() { - var manager = new UsersManager(options); - var methods = ['getInfo', 'impersonate']; + describe('instance', () => { + const manager = new UsersManager(options); + const methods = ['getInfo', 'impersonate']; - methods.forEach(function(methodName) { - it('should have a ' + methodName + ' method', function() { + methods.forEach((methodName) => { + it(`should have a ${methodName} method`, () => { expect(manager[methodName]).to.exist.to.be.an.instanceOf(Function); }); }); }); - describe('#getInfo', function() { - var manager = new UsersManager(options); - var path = '/userinfo'; + describe('#getInfo', () => { + const manager = new UsersManager(options); + const path = '/userinfo'; - beforeEach(function() { - this.request = nock(BASE_URL) - .get(path) - .reply(200); + beforeEach(function () { + this.request = nock(BASE_URL).get(path).reply(200); }); - it('should require an access token', function() { - var getInfo = manager.getInfo.bind(manager); + it('should require an access token', () => { + const getInfo = manager.getInfo.bind(manager); expect(getInfo).to.throw(ArgumentError, 'An access token is required'); }); - it('should throw an error when the token is invalid', function() { - var getInfo = manager.getInfo.bind(manager, ''); + it('should throw an error when the token is invalid', () => { + const getInfo = manager.getInfo.bind(manager, ''); expect(getInfo).to.throw(ArgumentError, 'Invalid access token'); }); - it('should not throw errors when the token is valid', function() { - var getInfo = manager.getInfo.bind(manager, 'VALID_TOKEN'); + it('should not throw errors when the token is valid', () => { + const getInfo = manager.getInfo.bind(manager, 'VALID_TOKEN'); expect(getInfo).to.not.throw(ArgumentError); }); - it('should accept a callback', function(done) { + it('should accept a callback', (done) => { manager.getInfo('ACCESS_TOKEN', done.bind(null, null)); }); - it('should not return a promise when a callback is provided', function() { - var returnValue = manager.getInfo('ACCESS_TOKEN', function() {}); + it('should not return a promise when a callback is provided', () => { + const returnValue = manager.getInfo('ACCESS_TOKEN', () => {}); expect(returnValue).to.equal(undefined); }); - it('should return a promise when no callback is provided', function() { - var returnValue = manager.getInfo('ACCESS_TOKEN'); + it('should return a promise when no callback is provided', () => { + const returnValue = manager.getInfo('ACCESS_TOKEN'); expect(utilTypes.isPromise(returnValue)).ok; }); - it('should perform a GET request to ' + path, function(done) { - var request = this.request; + it(`should perform a GET request to ${path}`, function (done) { + const { request } = this; manager .getInfo('ACCESS_TOKEN') - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -99,17 +101,17 @@ describe('UsersManager', function() { .catch(done); }); - it('should include the headers specified in the UsersManager options', function(done) { + it('should include the headers specified in the UsersManager options', (done) => { nock.cleanAll(); - var request = nock(BASE_URL) + const request = nock(BASE_URL) .get('/userinfo') .matchHeader('Content-Type', options.headers['Content-Type']) .reply(200); manager .getInfo('ACCESS_TOKEN') - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -117,17 +119,17 @@ describe('UsersManager', function() { .catch(done); }); - it('should send the access token in the Authorization header', function(done) { + it('should send the access token in the Authorization header', (done) => { nock.cleanAll(); - var request = nock(BASE_URL) + const request = nock(BASE_URL) .get('/userinfo') .matchHeader('Authorization', 'Bearer ACCESS_TOKEN') .reply(200); manager .getInfo('ACCESS_TOKEN') - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -136,104 +138,102 @@ describe('UsersManager', function() { }); }); - describe('#impersonate', function() { - var USER_ID = encodeURIComponent('github|12345'); - var token = 'API V1 TOKEN'; - var manager = new UsersManager(options); - var path = '/users/' + USER_ID + '/impersonate'; + describe('#impersonate', () => { + const USER_ID = encodeURIComponent('github|12345'); + const token = 'API V1 TOKEN'; + const manager = new UsersManager(options); + const path = `/users/${USER_ID}/impersonate`; - beforeEach(function() { - this.request = nock(BASE_URL) - .post(path) - .reply(200); + beforeEach(function () { + this.request = nock(BASE_URL).post(path).reply(200); }); - it('should require a user ID', function() { - var impersonate = manager.impersonate.bind(manager); + it('should require a user ID', () => { + const impersonate = manager.impersonate.bind(manager); expect(impersonate).to.throw(ArgumentError, 'You must specify a user ID'); }); - it('should throw an error when the user ID is not valid', function() { - var impersonate = manager.impersonate.bind(manager, ''); + it('should throw an error when the user ID is not valid', () => { + const impersonate = manager.impersonate.bind(manager, ''); expect(impersonate).to.throw(ArgumentError, 'The user ID is not valid'); }); - it('should require the impersonation settings object', function() { - var impersonate = manager.impersonate.bind(manager, USER_ID); + it('should require the impersonation settings object', () => { + const impersonate = manager.impersonate.bind(manager, USER_ID); expect(impersonate).to.throw(ArgumentError, 'Missing impersonation settings object'); }); - it('should require an impersonator ID', function() { - var impersonate = manager.impersonate.bind(manager, USER_ID, {}); + it('should require an impersonator ID', () => { + const impersonate = manager.impersonate.bind(manager, USER_ID, {}); expect(impersonate).to.throw(ArgumentError, 'impersonator_id field is required'); }); - it('should require a token', function() { - var settings = { + it('should require a token', () => { + const settings = { impersonator_id: 'auth0|12345', - protocol: 'oauth2' + protocol: 'oauth2', }; - var impersonate = manager.impersonate.bind(manager, USER_ID, settings); + const impersonate = manager.impersonate.bind(manager, USER_ID, settings); expect(impersonate).to.throw(ArgumentError, 'token field is required'); }); - it('should require a protocol', function() { - var settings = { - impersonator_id: 'auth0|12345' + it('should require a protocol', () => { + const settings = { + impersonator_id: 'auth0|12345', }; - var impersonate = manager.impersonate.bind(manager, USER_ID, settings); + const impersonate = manager.impersonate.bind(manager, USER_ID, settings); expect(impersonate).to.throw(ArgumentError, 'protocol field is required'); }); - it('should accept a callback', function(done) { - var settings = { + it('should accept a callback', (done) => { + const settings = { impersonator_id: 'auth0|12345', protocol: 'oauth2', - token: token + token, }; manager.impersonate(USER_ID, settings, done.bind(null, null)); }); - it('should not return a promise when a callback is provided', function() { - var settings = { + it('should not return a promise when a callback is provided', () => { + const settings = { impersonator_id: 'auth0|12345', protocol: 'oauth2', - token: token + token, }; - var returnValue = manager.impersonate(USER_ID, settings, function() {}); + const returnValue = manager.impersonate(USER_ID, settings, () => {}); expect(returnValue).to.equal(undefined); }); - it('should return a promise when no callback is provided', function() { - var settings = { + it('should return a promise when no callback is provided', () => { + const settings = { impersonator_id: 'auth0|12345', protocol: 'oauth2', - token: token + token, }; - var returnValue = manager.impersonate(USER_ID, settings); + const returnValue = manager.impersonate(USER_ID, settings); expect(utilTypes.isPromise(returnValue)).ok; }); - it('should perform a POST request to ' + path, function(done) { - var request = this.request; - var settings = { + it(`should perform a POST request to ${path}`, function (done) { + const { request } = this; + const settings = { impersonator_id: 'auth0|12345', protocol: 'oauth2', - token: token + token, }; manager .impersonate(USER_ID, settings) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -241,107 +241,101 @@ describe('UsersManager', function() { .catch(done); }); - it('should use the default client ID', function(done) { + it('should use the default client ID', (done) => { nock.cleanAll(); - var settings = { + const settings = { impersonator_id: 'auth0|12345', protocol: 'oauth2', - token: token + token, }; - var request = nock(BASE_URL) - .post(path, function(body) { - return body.client_id === CLIENT_ID; - }) + const request = nock(BASE_URL) + .post(path, (body) => body.client_id === CLIENT_ID) .reply(200); - manager.impersonate(USER_ID, settings).then(function() { + manager.impersonate(USER_ID, settings).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should allow the user to override the client ID', function(done) { + it('should allow the user to override the client ID', (done) => { nock.cleanAll(); - var settings = { + const settings = { impersonator_id: 'auth0|12345', protocol: 'oauth2', clientId: 'OVERRIDEN_CLIENT_ID', - token: token + token, }; - var request = nock(BASE_URL) - .post(path, function(body) { - return body.client_id === 'OVERRIDEN_CLIENT_ID'; - }) + const request = nock(BASE_URL) + .post(path, (body) => body.client_id === 'OVERRIDEN_CLIENT_ID') .reply(200); - manager.impersonate(USER_ID, settings).then(function() { + manager.impersonate(USER_ID, settings).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should use the default headers', function(done) { + it('should use the default headers', (done) => { nock.cleanAll(); - var settings = { + const settings = { impersonator_id: 'auth0|12345', protocol: 'oauth2', - token: token + token, }; - var request = nock(BASE_URL) + const request = nock(BASE_URL) .post(path) .matchHeader('Content-Type', options.headers['Content-Type']) .reply(200); - manager.impersonate(USER_ID, settings).then(function() { + manager.impersonate(USER_ID, settings).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should use the authorization header', function(done) { + it('should use the authorization header', (done) => { nock.cleanAll(); - var settings = { + const settings = { impersonator_id: 'auth0|12345', protocol: 'oauth2', - token: token + token, }; - var request = nock(BASE_URL) + const request = nock(BASE_URL) .post(path) .matchHeader('Authorization', `Bearer ${token}`) .reply(200); - manager.impersonate(USER_ID, settings).then(function() { + manager.impersonate(USER_ID, settings).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should allow the user to add additional parameters', function(done) { + it('should allow the user to add additional parameters', (done) => { nock.cleanAll(); - var settings = { + const settings = { impersonator_id: 'auth0|12345', protocol: 'oauth2', additionalParameters: { - response_type: 'code' + response_type: 'code', }, - token: token + token, }; - var request = nock(BASE_URL) - .post(path, function(body) { - return body.additionalParameters.response_type === 'code'; - }) + const request = nock(BASE_URL) + .post(path, (body) => body.additionalParameters.response_type === 'code') .reply(200); - manager.impersonate(USER_ID, settings).then(function() { + manager.impersonate(USER_ID, settings).then(() => { expect(request.isDone()).to.be.true; done(); diff --git a/test/auth0-rest-client.tests.js b/test/auth0-rest-client.tests.js index 7e2c2bc9f..3f6a1a6a1 100644 --- a/test/auth0-rest-client.tests.js +++ b/test/auth0-rest-client.tests.js @@ -1,92 +1,97 @@ -var expect = require('chai').expect; -var nock = require('nock'); +const { expect } = require('chai'); +const nock = require('nock'); -var ArgumentError = require('rest-facade').ArgumentError; -var ManagementTokenProvider = require('../src/management/ManagementTokenProvider'); -var Auth0RestClient = require('../src/Auth0RestClient'); +const { ArgumentError } = require('rest-facade'); +const Auth0RestClient = require('../src/Auth0RestClient'); -var API_URL = 'https://tenant.auth0.com'; +const API_URL = 'https://tenant.auth0.com'; -describe('Auth0RestClient', function() { - before(function() { +describe('Auth0RestClient', () => { + before(function () { this.providerMock = { - getAccessToken: function() { + getAccessToken() { return Promise.resolve('access_token'); - } + }, }; }); - it('should raise an error when no resource Url is provided', function() { - expect(Auth0RestClient).to.throw(ArgumentError, 'Must provide a Resource Url'); + it('should raise an error when no resource Url is provided', () => { + expect(() => { + new Auth0RestClient(); + }).to.throw(ArgumentError, 'Must provide a Resource Url'); }); - it('should raise an error when resource Url is invalid', function() { - var client = Auth0RestClient.bind(null, ''); - expect(client).to.throw(ArgumentError, 'The provided Resource Url is invalid'); + it('should raise an error when resource Url is invalid', () => { + expect(() => { + new Auth0RestClient(''); + }).to.throw(ArgumentError, 'The provided Resource Url is invalid'); }); - it('should raise an error when no options is provided', function() { - var client = Auth0RestClient.bind(null, '/some-resource'); - expect(client).to.throw(ArgumentError, 'Must provide options'); + it('should raise an error when no options is provided', () => { + expect(() => { + new Auth0RestClient('/some-resource'); + }).to.throw(ArgumentError, 'Must provide options'); }); describe('`get`', () => { - it('should encode params.id on `get` requests', function(done) { - nock(API_URL) - .get('/some-resource/auth0%7C1234') - .reply(200, { data: 'value' }); + it('should encode params.id on `get` requests', function (done) { + nock(API_URL).get('/some-resource/auth0%7C1234').reply(200, { data: 'value' }); - var options = { - headers: {} + const options = { + headers: {}, }; - var client = new Auth0RestClient(API_URL + '/some-resource/:id', options, this.providerMock); - client.get({ id: 'auth0|1234' }, function(err, data) { + const client = new Auth0RestClient( + `${API_URL}/some-resource/:id`, + options, + this.providerMock + ); + client.get({ id: 'auth0|1234' }, (err, data) => { expect(data).to.deep.equal({ data: 'value' }); done(); nock.cleanAll(); }); }); - it('should not encode other params on `get` requests', function(done) { + it('should not encode other params on `get` requests', function (done) { nock(API_URL) .get('/some-resource/1234?otherEncoded=auth0%7C6789&other=foobar') .reply(200, { data: 'value' }); - var options = { - headers: {} + const options = { + headers: {}, }; - var client = new Auth0RestClient(API_URL + '/some-resource/:id', options, this.providerMock); - client.get({ id: '1234', other: 'foobar', otherEncoded: 'auth0|6789' }, function(err, data) { + const client = new Auth0RestClient( + `${API_URL}/some-resource/:id`, + options, + this.providerMock + ); + client.get({ id: '1234', other: 'foobar', otherEncoded: 'auth0|6789' }, (err, data) => { expect(err).to.be.null; expect(data).to.deep.equal({ data: 'value' }); done(); nock.cleanAll(); }); }); - it('should accept only a callback', function(done) { - nock(API_URL) - .get('/some-resource') - .reply(200, { data: 'value' }); + it('should accept only a callback', function (done) { + nock(API_URL).get('/some-resource').reply(200, { data: 'value' }); - var options = { - headers: {} + const options = { + headers: {}, }; - var client = new Auth0RestClient(API_URL + '/some-resource', options, this.providerMock); - client.get({}, function(err, data) { + const client = new Auth0RestClient(`${API_URL}/some-resource`, options, this.providerMock); + client.get({}, (err, data) => { expect(data).to.deep.equal({ data: 'value' }); done(); nock.cleanAll(); }); }); - it('should return a promise if no callback is provided', function(done) { - nock(API_URL) - .get('/some-resource') - .reply(200, { data: 'value' }); + it('should return a promise if no callback is provided', function (done) { + nock(API_URL).get('/some-resource').reply(200, { data: 'value' }); - var options = { - headers: {} + const options = { + headers: {}, }; - var client = new Auth0RestClient(API_URL + '/some-resource', options, this.providerMock); - client.get().then(data => { + const client = new Auth0RestClient(`${API_URL}/some-resource`, options, this.providerMock); + client.get().then((data) => { expect(data).to.deep.equal({ data: 'value' }); done(); nock.cleanAll(); @@ -95,17 +100,15 @@ describe('Auth0RestClient', function() { }); describe('`patch`', () => { - it('should encode params.id on `patch` requests', function(done) { - nock(API_URL) - .patch('/some-resource/auth0%7C1234%2F5678') - .reply(200); + it('should encode params.id on `patch` requests', function (done) { + nock(API_URL).patch('/some-resource/auth0%7C1234%2F5678').reply(200); - var client = new Auth0RestClient( - API_URL + '/some-resource/:id', + const client = new Auth0RestClient( + `${API_URL}/some-resource/:id`, { headers: {} }, this.providerMock ); - client.patch({ id: 'auth0|1234/5678' }, { data: 'udpate ' }, function(err, data) { + client.patch({ id: 'auth0|1234/5678' }, { data: 'udpate ' }, (err) => { expect(err).to.be.null; done(); nock.cleanAll(); @@ -114,17 +117,15 @@ describe('Auth0RestClient', function() { }); describe('`update`', () => { - it('should encode params.id on `update` requests', function(done) { - nock(API_URL) - .put('/some-resource/auth0%7C1234%2F5678') - .reply(200); + it('should encode params.id on `update` requests', function (done) { + nock(API_URL).put('/some-resource/auth0%7C1234%2F5678').reply(200); - var client = new Auth0RestClient( - API_URL + '/some-resource/:id', + const client = new Auth0RestClient( + `${API_URL}/some-resource/:id`, { headers: {} }, this.providerMock ); - client.update({ id: 'auth0|1234/5678' }, { data: 'udpate ' }, function(err, data) { + client.update({ id: 'auth0|1234/5678' }, { data: 'udpate ' }, (err) => { expect(err).to.be.null; done(); nock.cleanAll(); @@ -133,17 +134,15 @@ describe('Auth0RestClient', function() { }); describe('`delete`', () => { - it('should encode params.id on `delete` requests', function(done) { - nock(API_URL) - .delete('/some-resource/auth0%7C1234%2F5678') - .reply(200); + it('should encode params.id on `delete` requests', function (done) { + nock(API_URL).delete('/some-resource/auth0%7C1234%2F5678').reply(200); - var client = new Auth0RestClient( - API_URL + '/some-resource/:id', + const client = new Auth0RestClient( + `${API_URL}/some-resource/:id`, { headers: {} }, this.providerMock ); - client.delete({ id: 'auth0|1234/5678' }, function(err, data) { + client.delete({ id: 'auth0|1234/5678' }, (err) => { expect(err).to.be.null; done(); nock.cleanAll(); @@ -151,39 +150,35 @@ describe('Auth0RestClient', function() { }); }); - it('should return a promise if no callback is given', function(done) { - nock(API_URL) - .get('/some-resource') - .reply(200, { data: 'value' }); + it('should return a promise if no callback is given', function (done) { + nock(API_URL).get('/some-resource').reply(200, { data: 'value' }); - var options = { - headers: {} + const options = { + headers: {}, }; - var client = new Auth0RestClient(API_URL + '/some-resource', options, this.providerMock); - client.getAll().then(function(data) { + const client = new Auth0RestClient(`${API_URL}/some-resource`, options, this.providerMock); + client.getAll().then((data) => { expect(data).to.deep.equal({ data: 'value' }); done(); nock.cleanAll(); }); }); - it('should accept a callback and handle errors', function(done) { - var providerMock = { - getAccessToken: function() { + it('should accept a callback and handle errors', (done) => { + const providerMock = { + getAccessToken() { return Promise.reject(new Error('Some Error')); - } + }, }; - nock(API_URL) - .get('/some-resource') - .reply(500); + nock(API_URL).get('/some-resource').reply(500); - var options = { - headers: {} + const options = { + headers: {}, }; - var client = new Auth0RestClient(API_URL + '/some-resource', options, providerMock); - client.getAll(function(err, data) { + const client = new Auth0RestClient(`${API_URL}/some-resource`, options, providerMock); + client.getAll((err) => { expect(err).to.not.null; expect(err.message).to.be.equal('Some Error'); done(); @@ -191,34 +186,30 @@ describe('Auth0RestClient', function() { }); }); - it('should set access token as Authorization header in options object', function(done) { - nock(API_URL) - .get('/some-resource') - .reply(200); + it('should set access token as Authorization header in options object', function (done) { + nock(API_URL).get('/some-resource').reply(200); - var options = { - headers: {} + const options = { + headers: {}, }; - var client = new Auth0RestClient(API_URL + '/some-resource', options, this.providerMock); - client.getAll().then(function(data) { + const client = new Auth0RestClient(`${API_URL}/some-resource`, options, this.providerMock); + client.getAll().then(() => { expect(client.restClient.options.headers['Authorization']).to.be.equal('Bearer access_token'); done(); nock.cleanAll(); }); }); - it('should sanitize error when access token is in authorization header', function(done) { - nock(API_URL) - .get('/some-resource') - .reply(401); + it('should sanitize error when access token is in authorization header', function (done) { + nock(API_URL).get('/some-resource').reply(401); - var options = { - headers: {} + const options = { + headers: {}, }; - var client = new Auth0RestClient(API_URL + '/some-resource', options, this.providerMock); - client.getAll().catch(function(err) { + const client = new Auth0RestClient(`${API_URL}/some-resource`, options, this.providerMock); + client.getAll().catch((err) => { const originalRequestHeader = err.originalError.response.request._header; expect(originalRequestHeader.authorization).to.equal('[REDACTED]'); done(); @@ -226,15 +217,15 @@ describe('Auth0RestClient', function() { }); }); - it('should catch error when provider.getAccessToken throws an error', function(done) { - var providerMock = { - getAccessToken: function() { + it('should catch error when provider.getAccessToken throws an error', (done) => { + const providerMock = { + getAccessToken() { return Promise.reject(new Error('Some Error')); - } + }, }; - var client = new Auth0RestClient('/some-resource', {}, providerMock); - client.getAll().catch(function(err) { + const client = new Auth0RestClient('/some-resource', {}, providerMock); + client.getAll().catch((err) => { expect(err).to.not.null; expect(err.message).to.be.equal('Some Error'); done(); diff --git a/test/auth0.tests.js b/test/auth0.tests.js index bb22ed825..4e2b81f9b 100644 --- a/test/auth0.tests.js +++ b/test/auth0.tests.js @@ -1,16 +1,15 @@ -var expect = require('chai').expect; +const { expect } = require('chai'); -var auth0 = require('../src'); -var AuthenticationClient = require('../src/auth'); -var ManagementClient = require('../src/management'); -var ManagementTokenProvider = require('../src/management/ManagementTokenProvider'); +const auth0 = require('../src'); +const AuthenticationClient = require('../src/auth'); +const ManagementClient = require('../src/management'); -describe('Auth0 module', function() { - it('should expose the AuthenticationClient', function() { +describe('Auth0 module', () => { + it('should expose the AuthenticationClient', () => { expect(auth0.AuthenticationClient).to.equal(AuthenticationClient); }); - it('should expose the ManagementClient', function() { + it('should expose the ManagementClient', () => { expect(auth0.ManagementClient).to.equal(ManagementClient); }); }); diff --git a/test/constants.js b/test/constants.js index cdb00baab..c89219329 100644 --- a/test/constants.js +++ b/test/constants.js @@ -1,4 +1,4 @@ -var constants = (module.exports = {}); +const constants = (module.exports = {}); constants.BASE_API_URL = 'https://login.auth0.com/api/v2/'; constants.EU_BASE_API_URL = 'https://login.eu.auth0.com/api/v2/'; diff --git a/test/errors.tests.js b/test/errors.tests.js index c6d61f5e8..2bdb339bf 100644 --- a/test/errors.tests.js +++ b/test/errors.tests.js @@ -1,70 +1,70 @@ -var expect = require('chai').expect; +const { expect } = require('chai'); -var errors = require('../src/errors'); +const errors = require('../src/errors'); -describe('Errors', function() { - describe('sanitizeErrorRequestData', function() { - describe('when passed in error is missing request data and headers', function() { - var error = { response: { request: {} } }; - var redactedError = errors.sanitizeErrorRequestData(error); +describe('Errors', () => { + describe('sanitizeErrorRequestData', () => { + describe('when passed in error is missing request data and headers', () => { + const error = { response: { request: {} } }; + const redactedError = errors.sanitizeErrorRequestData(error); - it('should return error', function() { + it('should return error', () => { expect(redactedError).to.equal(error); }); }); - describe('when passed in error has request data', function() { + describe('when passed in error has request data', () => { const error = { response: { request: { _data: { DATA_SECRET: 'secret', USER_PASSWORD: 'password', - USER_NAME: 'username' - } - } - } + USER_NAME: 'username', + }, + }, + }, }; const redactedError = errors.sanitizeErrorRequestData(error); const sanitizedData = redactedError.response.request._data; - it('should return [REDACTED] for DATA_SECRET', function() { + it('should return [REDACTED] for DATA_SECRET', () => { expect(sanitizedData.DATA_SECRET).to.equal('[REDACTED]'); }); - it('should return [REDACTED] for DATA_SECRET', function() { + it('should return [REDACTED] for DATA_SECRET', () => { expect(sanitizedData.DATA_SECRET).to.equal('[REDACTED]'); }); - it('should return original value for USER_NAME', function() { + it('should return original value for USER_NAME', () => { expect(sanitizedData.USER_NAME).to.equal(sanitizedData.USER_NAME); }); }); - describe('when passed in error has header data', function() { + describe('when passed in error has header data', () => { const error = { response: { request: { _header: { - authorization: 'Bearer xyz' - } - } - } + authorization: 'Bearer xyz', + }, + }, + }, }; const redactedError = errors.sanitizeErrorRequestData(error); const sanitizedData = redactedError.response.request._header; - it('should return [REDACTED] for authorization', function() { + it('should return [REDACTED] for authorization', () => { expect(sanitizedData.authorization).to.equal('[REDACTED]'); }); }); }); - describe('SanitizedError', function() { - var name = 'ErrorName'; - var message = 'message'; - var status = 500; - var requestInfo = { keyA: 'a', keyB: 'b' }; - var originalError = { response: { request: { _data: { secret: 'secretpassword' } } } }; - var sanitizedError = new errors.SanitizedError( + describe('SanitizedError', () => { + const name = 'ErrorName'; + const message = 'message'; + const status = 500; + const requestInfo = { keyA: 'a', keyB: 'b' }; + const originalError = { response: { request: { _data: { secret: 'secretpassword' } } } }; + const sanitizedError = new errors.SanitizedError( name, message, status, @@ -72,39 +72,39 @@ describe('Errors', function() { originalError ); - it('should be an instance of the builtin Error', function() { + it('should be an instance of the builtin Error', () => { expect(sanitizedError).to.be.an.instanceof(Error); }); - it('should be an instance of its class', function() { + it('should be an instance of its class', () => { expect(sanitizedError).to.be.an.instanceof(errors.SanitizedError); }); - it('should have a name', function() { + it('should have a name', () => { expect(sanitizedError.name).to.eql(name); }); - it('should have a message', function() { + it('should have a message', () => { expect(sanitizedError.message).to.eql(message); }); - it('should have a statusCode', function() { + it('should have a statusCode', () => { expect(sanitizedError.statusCode).to.eql(status); }); - it('should have request info', function() { + it('should have request info', () => { expect(sanitizedError.requestInfo).to.deep.eql(requestInfo); }); - it('should have the original error', function() { + it('should have the original error', () => { expect(sanitizedError.originalError).to.eql(originalError); }); - it('should redact the original error sensitive information', function() { + it('should redact the original error sensitive information', () => { expect(sanitizedError.originalError.response.request._data.secret).to.eql('[REDACTED]'); }); - it('should have a stack with the message and location the error was created', function() { + it('should have a stack with the message and location the error was created', () => { expect(sanitizedError.stack).to.exist; }); }); diff --git a/test/idToken.tests.js b/test/idToken.tests.js index e427e4b2f..2ed53b3b9 100644 --- a/test/idToken.tests.js +++ b/test/idToken.tests.js @@ -1,12 +1,12 @@ -var assert = require('assert'); -var expect = require('chai').expect; -var jws = require('jws'); -var idToken = require('../src/auth/idToken'); +const assert = require('assert'); +const { expect } = require('chai'); +const jws = require('jws'); +const idToken = require('../src/auth/idToken'); -var secretHMAC = 'secret'; +const secretHMAC = 'secret'; //openssl genrsa -out private.pem 2048 //openssl rsa -in private.pem -pubout -out public.pem -var privateKeyRSA = `-----BEGIN PRIVATE KEY----- +const privateKeyRSA = `-----BEGIN PRIVATE KEY----- MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQC4ZtdaIrd1BPIJ tfnF0TjIK5inQAXZ3XlCrUlJdP+XHwIRxdv1FsN12XyMYO/6ymLmo9ryoQeIrsXB XYqlET3zfAY+diwCb0HEsVvhisthwMU4gZQu6TYW2s9LnXZB5rVtcBK69hcSlA2k @@ -37,17 +37,17 @@ rK0/Ikt5ybqUzKCMJZg2VKGTxg== //base date expressed in MS //expected values for a good id token payload -var expectations = { +const expectations = { clientId: 'tokens-test-123', clientIdAlt: 'external-test-999', issuer: 'https://tokens-test.auth0.com/', nonce: 'a1b2c3d4e5', - clock: Date.now() + clock: Date.now(), }; //date helpers -var TODAY_IN_SECONDS = Math.floor(expectations.clock / 1000); -var ONE_DAY_IN_SECONDS = 3600 * 24; +const TODAY_IN_SECONDS = Math.floor(expectations.clock / 1000); +const ONE_DAY_IN_SECONDS = 3600 * 24; function yesterday() { return TODAY_IN_SECONDS - ONE_DAY_IN_SECONDS; } @@ -55,7 +55,7 @@ function tomorrow() { return TODAY_IN_SECONDS + ONE_DAY_IN_SECONDS; } //good id token payload -var payload = { +const payload = { iss: expectations.issuer, sub: 'auth0|123456789', aud: [expectations.clientId, expectations.clientIdAlt], @@ -64,21 +64,21 @@ var payload = { nonce: expectations.nonce, azp: expectations.clientId, org_id: 'test|org', - auth_time: TODAY_IN_SECONDS + auth_time: TODAY_IN_SECONDS, }; -var defaultOptions = { +const defaultOptions = { issuer: expectations.issuer, audience: [expectations.clientId, expectations.clientIdAlt], - nonce: expectations.nonce + nonce: expectations.nonce, }; function generateJWT(bodyOverrides, alg) { - var body = Object.assign({}, payload, bodyOverrides || {}); + const body = Object.assign({}, payload, bodyOverrides || {}); alg = alg || 'RS256'; - var options = { - header: { alg: alg }, - payload: body + const options = { + header: { alg }, + payload: body, }; if (alg === 'RS256') { options.privateKey = privateKeyRSA; @@ -88,197 +88,197 @@ function generateJWT(bodyOverrides, alg) { return jws.sign(options); } -describe('idToken.decode', function() { - it('should decode a valid token', function() { - var alg = 'RS256'; - var token = generateJWT({ name: 'ÁÁutf8' }, alg); - var decoded = idToken.decode(token); +describe('idToken.decode', () => { + it('should decode a valid token', () => { + const alg = 'RS256'; + const token = generateJWT({ name: 'ÁÁutf8' }, alg); + const decoded = idToken.decode(token); assert.equal(decoded._raw, token); assert.equal(decoded.header.alg, alg); - Object.keys(payload).forEach(function(key) { + Object.keys(payload).forEach((key) => { assert.deepEqual(payload[key], decoded.payload[key]); }); }); - it('throws errors on invalid tokens', function() { - var IDTOKEN_ERROR_MESSAGE = 'ID token could not be decoded'; + it('throws errors on invalid tokens', () => { + const IDTOKEN_ERROR_MESSAGE = 'ID token could not be decoded'; - it('throws when there is more or less than 3 parts', function() { + it('throws when there is more or less than 3 parts', () => { assert.throws(idToken.decode('test'), IDTOKEN_ERROR_MESSAGE); assert.throws(idToken.decode('test.'), IDTOKEN_ERROR_MESSAGE); assert.throws(idToken.decode('test.test'), IDTOKEN_ERROR_MESSAGE); assert.throws(idToken.decode('test.test.test.test'), IDTOKEN_ERROR_MESSAGE); }); - it('throws when there is no header', function() { + it('throws when there is no header', () => { assert.throws(idToken.decode('.test.test'), IDTOKEN_ERROR_MESSAGE); }); - it('throws when there is no payload', function() { + it('throws when there is no payload', () => { assert.throws(idToken.decode('test..test'), IDTOKEN_ERROR_MESSAGE); }); - it('throws when there is no signature', function() { + it('throws when there is no signature', () => { assert.throws(idToken.decode('test.test.'), IDTOKEN_ERROR_MESSAGE); }); }); }); -describe('idToken.validate', function() { - var expectedOptions; +describe('idToken.validate', () => { + let expectedOptions; - beforeEach(function() { + beforeEach(() => { expectedOptions = Object.assign({}, defaultOptions); expectedOptions.audience = expectations.clientId; expectedOptions.maxAge = 123; }); - it('should throw when no id token is present', function() { - expect(function() { + it('should throw when no id token is present', () => { + expect(() => { idToken.validate(); }).to.throw('ID token is required but missing'); }); - it('should throw when no Issuer is present in the claim', function() { - expect(function() { + it('should throw when no Issuer is present in the claim', () => { + expect(() => { idToken.validate(generateJWT({ iss: undefined })); }).to.throw('Issuer (iss) claim must be a string present in the ID token'); }); - it('should throw when the expected issuer is not in the claim', function() { - expect(function() { + it('should throw when the expected issuer is not in the claim', () => { + expect(() => { idToken.validate(generateJWT({}), { issuer: 'ExpectedIssuer' }); }).to.throw( 'Issuer (iss) claim mismatch in the ID token; expected "ExpectedIssuer", found "https://tokens-test.auth0.com/"' ); }); - it('should throw when the claim has no Subject', function() { - expect(function() { + it('should throw when the claim has no Subject', () => { + expect(() => { idToken.validate(generateJWT({ sub: undefined }), defaultOptions); }).to.throw('Subject (sub) claim must be a string present in the ID token'); }); - it('should throw when the alg is neither rs256 or hs256', function() { - var token = + it('should throw when the alg is neither rs256 or hs256', () => { + const token = 'eyJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJodHRwczovL3Rva2Vucy10ZXN0LmF1dGgwLmNvbS8iLCJzdWIiOiJhdXRoMHwxMjM0NTY3ODkiLCJhdWQiOiJ0b2tlbnMtdGVzdC0xMjMifQ.cZ4qDwoKdKQx8DtD-F-xVKCxd3rz58wSJh3k28z5qnpzm4x3xRiyHCuUvtxmL2aPdBQ37Zt8Mt5drd9hZhNzFQ'; - expect(function() { + expect(() => { idToken.validate(token, defaultOptions); }).to.throw( 'Signature algorithm of "HS512" is not supported. Expected the ID token to be signed with "RS256" or "HS256".' ); }); - it('should throw when the audience is not a string or array', function() { - expect(function() { + it('should throw when the audience is not a string or array', () => { + expect(() => { idToken.validate(generateJWT({ aud: undefined }), defaultOptions); }).to.throw( 'Audience (aud) claim must be a string or array of strings present in the ID token' ); }); - it('should throw when claim audience is a String and not expected audience', function() { - expect(function() { + it('should throw when claim audience is a String and not expected audience', () => { + expect(() => { idToken.validate(generateJWT({ aud: 'notExpected' }), expectedOptions); }).to.throw( 'Audience (aud) claim mismatch in the ID token; expected "tokens-test-123" but found "notExpected"' ); }); - it('should throw when claim audience is an Array and not expected audience', function() { - expect(function() { + it('should throw when claim audience is an Array and not expected audience', () => { + expect(() => { idToken.validate(generateJWT({ aud: ['notExpected'] }), expectedOptions); }).to.throw( 'Audience (aud) claim mismatch in the ID token; expected "tokens-test-123" but was not one of "notExpected"' ); }); - it('should throw when expected audience is not a String or Array', function() { - expect(function() { + it('should throw when expected audience is not a String or Array', () => { + expect(() => { idToken.validate(generateJWT({ aud: 10000 }), expectedOptions); }).to.throw( 'Audience (aud) claim must be a string or array of strings present in the ID token' ); - expect(function() { + expect(() => { idToken.validate(generateJWT({ aud: {} }), expectedOptions); }).to.throw( 'Audience (aud) claim must be a string or array of strings present in the ID token' ); }); - it('should throw when azp claim not found when aud has multiple values', function() { - expect(function() { + it('should throw when azp claim not found when aud has multiple values', () => { + expect(() => { idToken.validate(generateJWT({ azp: undefined }), expectedOptions); }).to.throw( 'Authorized Party (azp) claim must be a string present in the ID token when Audience (aud) claim has multiple values' ); }); - it('should throw when azp claim doesnt match the expected aud', function() { + it('should throw when azp claim doesnt match the expected aud', () => { expectedOptions.audience = expectations.clientIdAlt; - expect(function() { + expect(() => { idToken.validate(generateJWT({}), expectedOptions); }).to.throw( 'Authorized Party (azp) claim mismatch in the ID token; expected "external-test-999", found "tokens-test-123"' ); }); - it('should throw when nonce is in options, but missing from claim', function() { - expect(function() { + it('should throw when nonce is in options, but missing from claim', () => { + expect(() => { idToken.validate(generateJWT({ nonce: undefined }), expectedOptions); }).to.throw('Nonce (nonce) claim must be a string present in the ID token'); }); - it('should throw when nonce claim doesnt match nonce expected', function() { + it('should throw when nonce claim doesnt match nonce expected', () => { expectedOptions.nonce = 'noncey'; - expect(function() { + expect(() => { idToken.validate(generateJWT({ nonce: 'notExpectedNonce' }), expectedOptions); }).to.throw( 'Nonce (nonce) claim mismatch in the ID token; expected "noncey", found "notExpectedNonce"' ); }); - it('should throw when nonce claim is not a string', function() { - expect(function() { + it('should throw when nonce claim is not a string', () => { + expect(() => { idToken.validate(generateJWT({ nonce: 10000 }), expectedOptions); }).to.throw('Nonce (nonce) claim must be a string present in the ID token'); - expect(function() { + expect(() => { idToken.validate(generateJWT({ nonce: {} }), expectedOptions); }).to.throw('Nonce (nonce) claim must be a string present in the ID token'); }); - it('should throw when auth_time is not a number', function() { - expect(function() { + it('should throw when auth_time is not a number', () => { + expect(() => { idToken.validate(generateJWT({ auth_time: undefined }), expectedOptions); }).to.throw( 'Authentication Time (auth_time) claim must be a number present in the ID token when Max Age (max_age) is specified' ); }); - it('should throw when exp is not a number', function() { - expect(function() { + it('should throw when exp is not a number', () => { + expect(() => { idToken.validate(generateJWT({ exp: 'not a number' }), expectedOptions); }).to.throw('Expiration Time (exp) claim must be a number present in the ID token'); }); - it('should throw when exp has passed', function() { - expect(function() { + it('should throw when exp has passed', () => { + expect(() => { idToken.validate(generateJWT({ exp: yesterday() }), expectedOptions); }).to.throw('is after expiration time'); }); - it('should throw when idtoken indicates too much time has passed', function() { - expect(function() { + it('should throw when idtoken indicates too much time has passed', () => { + expect(() => { idToken.validate(generateJWT({ auth_time: yesterday() }), expectedOptions); }).to.throw( 'Authentication Time (auth_time) claim in the ID token indicates that too much time has passed since the last end-user authentication.' ); }); - it('should throw when organization is in options, but org_id missing from claim', function() { + it('should throw when organization is in options, but org_id missing from claim', () => { expectedOptions.organization = 'testorg'; - expect(function() { + expect(() => { idToken.validate(generateJWT({ org_id: undefined }), expectedOptions); }).to.throw('Organization Id (org_id) claim must be a string present in the ID token'); }); - it('should throw when org claim doesnt match org expected', function() { + it('should throw when org claim doesnt match org expected', () => { expectedOptions.organization = 'testorg'; - expect(function() { + expect(() => { idToken.validate(generateJWT({ org_id: 'notExpectedOrg' }), expectedOptions); }).to.throw( 'Organization Id (org_id) claim value mismatch in the ID token; expected "testorg", found "notExpectedOrg' ); }); - it('should NOT throw when org_id matches expected organization', function() { + it('should NOT throw when org_id matches expected organization', () => { expectedOptions.organization = 'testorg'; - expect(function() { + expect(() => { idToken.validate(generateJWT({ org_id: 'testorg' }), expectedOptions); }).not.to.throw(); }); diff --git a/test/management/actions.tests.js b/test/management/actions.tests.js index f00a69ab6..db85bcfd6 100644 --- a/test/management/actions.tests.js +++ b/test/management/actions.tests.js @@ -1,23 +1,22 @@ -var expect = require('chai').expect; -var nock = require('nock'); +const { expect } = require('chai'); +const nock = require('nock'); -var SRC_DIR = '../../src'; -var API_URL = 'https://tenant.auth0.com'; +const API_URL = 'https://tenant.auth0.com'; -var ActionsManager = require(SRC_DIR + '/management/ActionsManager'); -var ArgumentError = require('rest-facade').ArgumentError; +const ActionsManager = require(`../../src/management/ActionsManager`); +const { ArgumentError } = require('rest-facade'); -describe('ActionsManager', function() { - before(function() { +describe('ActionsManager', () => { + before(function () { this.token = 'TOKEN'; this.actions = new ActionsManager({ - headers: { authorization: 'Bearer ' + this.token }, - baseUrl: API_URL + headers: { authorization: `Bearer ${this.token}` }, + baseUrl: API_URL, }); }); - describe('instance', function() { - var methods = [ + describe('instance', () => { + const methods = [ 'get', 'getAll', 'create', @@ -31,77 +30,70 @@ describe('ActionsManager', function() { 'deployVersion', 'getAllTriggers', 'getTriggerBindings', - 'updateTriggerBindings' + 'updateTriggerBindings', ]; - methods.forEach(function(method) { - it('should have a ' + method + ' method', function() { + methods.forEach((method) => { + it(`should have a ${method} method`, function () { expect(this.actions[method]).to.exist.to.be.an.instanceOf(Function); }); }); }); - describe('#constructor', function() { - it('should error when no options are provided', function() { - expect(ActionsManager).to.throw(ArgumentError, 'Must provide client options'); + describe('#constructor', () => { + it('should error when no options are provided', () => { + expect(() => { + new ActionsManager(); + }).to.throw(ArgumentError, 'Must provide client options'); }); - it('should throw an error when no base URL is provided', function() { - var client = ActionsManager.bind(null, {}); - - expect(client).to.throw(ArgumentError, 'Must provide a base URL for the API'); + it('should throw an error when no base URL is provided', () => { + expect(() => { + new ActionsManager({}); + }).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); - it('should throw an error when the base URL is invalid', function() { - var client = ActionsManager.bind(null, { baseUrl: '' }); - - expect(client).to.throw(ArgumentError, 'The provided base URL is invalid'); + it('should throw an error when the base URL is invalid', () => { + expect(() => { + new ActionsManager({ baseUrl: '' }); + }).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); describe('#actions', () => { - describe('#getAll', function() { - beforeEach(function() { - this.request = nock(API_URL) - .get('/actions/actions') - .reply(200); + describe('#getAll', () => { + beforeEach(function () { + this.request = nock(API_URL).get('/actions/actions').reply(200); }); - it('should accept a callback', function(done) { - this.actions.getAll(function() { + it('should accept a callback', function (done) { + this.actions.getAll(() => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.actions - .getAll() - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.actions.getAll().then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/actions/actions') - .reply(500); + nock(API_URL).get('/actions/actions').reply(500); - this.actions.getAll().catch(function(err) { + this.actions.getAll().catch((err) => { expect(err).to.exist; done(); }); }); - it('should pass the body of the response to the "then" handler', function(done) { + it('should pass the body of the response to the "then" handler', function (done) { nock.cleanAll(); - var data = [{ test: true }]; - var request = nock(API_URL) - .get('/actions/actions') - .reply(200, data); + const data = [{ test: true }]; + nock(API_URL).get('/actions/actions').reply(200, data); - this.actions.getAll().then(function(credentials) { + this.actions.getAll().then((credentials) => { expect(credentials).to.be.an.instanceOf(Array); expect(credentials.length).to.equal(data.length); @@ -112,42 +104,39 @@ describe('ActionsManager', function() { }); }); - it('should perform a GET request', function(done) { - var request = this.request; + it('should perform a GET request', function (done) { + const { request } = this; - this.actions.getAll().then(function() { + this.actions.getAll().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/actions/actions') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.actions.getAll().then(function() { + this.actions.getAll().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the parameters in the query-string', function(done) { + it('should pass the parameters in the query-string', function (done) { nock.cleanAll(); - var params = { + const params = { include_fields: true, - fields: 'test' + fields: 'test', }; - var request = nock(API_URL) - .get('/actions/actions') - .query(params) - .reply(200); + const request = nock(API_URL).get('/actions/actions').query(params).reply(200); - this.actions.getAll(params).then(function() { + this.actions.getAll(params).then(() => { expect(request.isDone()).to.be.true; done(); @@ -155,80 +144,76 @@ describe('ActionsManager', function() { }); }); - describe('#get', function() { - beforeEach(function() { + describe('#get', () => { + beforeEach(function () { this.data = { id: '0d565aa1-d8ce-4802-83e7-82e3d2040222', name: 'Test Action', supported_triggers: [ { id: 'post-login', - version: 'v1' - } + version: 'v1', + }, ], required_configuration: [], required_secrets: [], created_at: '2020-07-29T19:45:15.725999098Z', - updated_at: '2020-07-29T19:45:15.725999098Z' + updated_at: '2020-07-29T19:45:15.725999098Z', }; - this.request = nock(API_URL) - .get('/actions/actions/' + this.data.id) - .reply(200, this.data); + this.request = nock(API_URL).get(`/actions/actions/${this.data.id}`).reply(200, this.data); }); - it('should accept a callback', function(done) { - var params = { id: this.data.id }; + it('should accept a callback', function (done) { + const params = { id: this.data.id }; this.actions.get(params, done.bind(null, null)); }); - it('should be backwards compatible with action_id', function(done) { - var params = { action_id: this.data.id }; + it('should be backwards compatible with action_id', function (done) { + const params = { action_id: this.data.id }; this.actions.get(params, done.bind(null, null)); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.actions .get({ id: this.data.id }) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should perform a GET request', function(done) { - var request = this.request; + it('should perform a GET request', function (done) { + const { request } = this; - this.actions.get({ id: this.data.id }).then(function() { + this.actions.get({ id: this.data.id }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/actions/actions' + this.data.id) - .reply(500); + nock(API_URL).get(`/actions/actions${this.data.id}`).reply(500); - this.actions.get({ id: this.data.id }).catch(function(err) { + this.actions.get({ id: this.data.id }).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/actions/actions/' + this.data.id) - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .get(`/actions/actions/${this.data.id}`) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.actions.get({ id: this.data.id }).then(function() { + this.actions.get({ id: this.data.id }).then(() => { expect(request.isDone()).to.be.true; done(); @@ -236,80 +221,71 @@ describe('ActionsManager', function() { }); }); - describe('#create', function() { - var data = { + describe('#create', () => { + const data = { name: 'my-action-13', supported_triggers: [ { id: 'post-login', - version: 'v1' - } - ] + version: 'v1', + }, + ], }; - beforeEach(function() { - this.request = nock(API_URL) - .post('/actions/actions') - .reply(201); + beforeEach(function () { + this.request = nock(API_URL).post('/actions/actions').reply(201); }); - it('should accept a callback', function(done) { - this.actions.create(data, function() { + it('should accept a callback', function (done) { + this.actions.create(data, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.actions - .create(data) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.actions.create(data).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/actions/actions/') - .reply(500); + nock(API_URL).post('/actions/actions/').reply(500); - this.actions.create(data).catch(function(err) { + this.actions.create(data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a POST request', function(done) { - var request = this.request; + it('should perform a POST request', function (done) { + const { request } = this; - this.actions.create(data).then(function() { + this.actions.create(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the data in the body of the request', function(done) { + it('should pass the data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/actions/actions', data) - .reply(200); + const request = nock(API_URL).post('/actions/actions', data).reply(200); - this.actions.create(data).then(function() { + this.actions.create(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .post('/actions/actions') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.actions.create(data).then(function() { + this.actions.create(data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -317,16 +293,16 @@ describe('ActionsManager', function() { }); }); - describe('#update', function() { - beforeEach(function() { + describe('#update', () => { + beforeEach(function () { this.data = { id: 'ACTION_ID' }; this.request = nock(API_URL) - .patch('/actions/actions/' + this.data.id, { name: 'my-new-action-name' }) + .patch(`/actions/actions/${this.data.id}`, { name: 'my-new-action-name' }) .reply(200, this.data); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.actions.update( { id: 'ACTION_ID' }, { name: 'my-new-action-name' }, @@ -334,104 +310,96 @@ describe('ActionsManager', function() { ); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.actions .update({ id: 'ACTION_ID' }, { name: 'my-new-action-name' }) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should perform a PATCH request', function(done) { - var request = this.request; + it('should perform a PATCH request', function (done) { + const { request } = this; - this.actions.update({ id: 'ACTION_ID' }, { name: 'my-new-action-name' }).then(function() { + this.actions.update({ id: 'ACTION_ID' }, { name: 'my-new-action-name' }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the new data in the body of the request', function(done) { + it('should include the new data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/actions/actions/' + this.data.id, { name: 'my-new-action-name' }) + const request = nock(API_URL) + .patch(`/actions/actions/${this.data.id}`, { name: 'my-new-action-name' }) .reply(200); - this.actions.update({ id: 'ACTION_ID' }, { name: 'my-new-action-name' }).then(function() { + this.actions.update({ id: 'ACTION_ID' }, { name: 'my-new-action-name' }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/actions/actions/' + this.data.id) - .reply(500); + nock(API_URL).patch(`/actions/actions/${this.data.id}`).reply(500); - this.actions - .update({ id: this.data.id }, { name: 'my-new-action-name' }) - .catch(function(err) { - expect(err).to.exist; + this.actions.update({ id: this.data.id }, { name: 'my-new-action-name' }).catch((err) => { + expect(err).to.exist; - done(); - }); + done(); + }); }); }); - describe('#deploy', function() { - var action_id = 'action-id-1'; + describe('#deploy', () => { + const action_id = 'action-id-1'; - beforeEach(function() { - this.request = nock(API_URL) - .post('/actions/actions/' + action_id + '/deploy') - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).post(`/actions/actions/${action_id}/deploy`).reply(200); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.actions.deploy({ action_id }, done.bind(null, null)); }); - it('should return a promise when no callback is given', function(done) { + it('should return a promise when no callback is given', function (done) { this.actions.deploy({ action_id }).then(done.bind(null, null)); }); - it('should perform a post request' + action_id, function(done) { - var request = this.request; + it(`should perform a post request${action_id}`, function (done) { + const { request } = this; - this.actions.deploy({ action_id }).then(function() { + this.actions.deploy({ action_id }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/actions/actions/' + action_id + '/deploy') - .reply(500); + nock(API_URL).post(`/actions/actions/${action_id}/deploy`).reply(500); - this.actions.deploy({ action_id }).catch(function(err) { + this.actions.deploy({ action_id }).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the authorization header', function(done) { + it('should include the token in the authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/actions/actions/' + action_id + '/deploy') - .matchHeader('authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .post(`/actions/actions/${action_id}/deploy`) + .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); - this.actions.deploy({ action_id }).then(function() { + this.actions.deploy({ action_id }).then(() => { expect(request.isDone()).to.be.true; done(); @@ -439,57 +407,53 @@ describe('ActionsManager', function() { }); }); - describe('#test', function() { - var action_id = 'action-id-1'; + describe('#test', () => { + const action_id = 'action-id-1'; const payload = { event: {} }; - beforeEach(function() { - this.request = nock(API_URL) - .post('/actions/actions/' + action_id + '/test') - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).post(`/actions/actions/${action_id}/test`).reply(200); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.actions.test({ action_id }, { payload }, done.bind(null, null)); }); - it('should return a promise when no callback is given', function(done) { + it('should return a promise when no callback is given', function (done) { this.actions.test({ action_id }, { payload }).then(done.bind(null, null)); }); - it('should perform a post request' + action_id, function(done) { - var request = this.request; + it(`should perform a post request${action_id}`, function (done) { + const { request } = this; - this.actions.test({ action_id }, { payload }).then(function() { + this.actions.test({ action_id }, { payload }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/actions/actions/' + action_id + '/test') - .reply(500); + nock(API_URL).post(`/actions/actions/${action_id}/test`).reply(500); - this.actions.test({ action_id }, { payload }).catch(function(err) { + this.actions.test({ action_id }, { payload }).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the authorization header', function(done) { + it('should include the token in the authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/actions/actions/' + action_id + '/test') - .matchHeader('authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .post(`/actions/actions/${action_id}/test`) + .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); - this.actions.test({ action_id }, { payload }).then(function() { + this.actions.test({ action_id }, { payload }).then(() => { expect(request.isDone()).to.be.true; done(); @@ -497,56 +461,52 @@ describe('ActionsManager', function() { }); }); - describe('#delete', function() { - var action_id = 'action-id-1'; + describe('#delete', () => { + const action_id = 'action-id-1'; - beforeEach(function() { - this.request = nock(API_URL) - .delete('/actions/actions/' + action_id) - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).delete(`/actions/actions/${action_id}`).reply(200); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.actions.delete({ action_id }, done.bind(null, null)); }); - it('should return a promise when no callback is given', function(done) { + it('should return a promise when no callback is given', function (done) { this.actions.delete({ action_id }).then(done.bind(null, null)); }); - it('should perform a delete request' + action_id, function(done) { - var request = this.request; + it(`should perform a delete request${action_id}`, function (done) { + const { request } = this; - this.actions.delete({ action_id }).then(function() { + this.actions.delete({ action_id }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete('/actions/actions/' + action_id) - .reply(500); + nock(API_URL).delete(`/actions/actions/${action_id}`).reply(500); - this.actions.delete({ action_id }).catch(function(err) { + this.actions.delete({ action_id }).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the authorization header', function(done) { + it('should include the token in the authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete('/actions/actions/' + action_id) - .matchHeader('authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .delete(`/actions/actions/${action_id}`) + .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); - this.actions.delete({ action_id }).then(function() { + this.actions.delete({ action_id }).then(() => { expect(request.isDone()).to.be.true; done(); @@ -555,66 +515,64 @@ describe('ActionsManager', function() { }); }); - describe('action versions', function() { - describe('#getVersions', function() { - beforeEach(function() { + describe('action versions', () => { + describe('#getVersions', () => { + beforeEach(function () { nock.cleanAll(); this.data = { - id: '0d565aa1-d8ce-4802-83e7-82e3d2040222' + id: '0d565aa1-d8ce-4802-83e7-82e3d2040222', }; this.request = nock(API_URL) - .get('/actions/actions/' + this.data.id + '/versions') + .get(`/actions/actions/${this.data.id}/versions`) .reply(200, this.data); }); - it('should accept a callback', function(done) { - var params = { id: this.data.id }; + it('should accept a callback', function (done) { + const params = { id: this.data.id }; this.actions.getVersions(params, done.bind(null, null)); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.actions .get({ id: this.data.id }) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should perform a GET request', function(done) { - var request = this.request; + it('should perform a GET request', function (done) { + const { request } = this; - this.actions.getVersions({ id: this.data.id }).then(function() { + this.actions.getVersions({ id: this.data.id }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/actions/actions/' + this.data.id + '/versions') - .reply(500); + nock(API_URL).get(`/actions/actions/${this.data.id}/versions`).reply(500); - this.actions.getVersions({ id: this.data.id }).catch(function(err) { + this.actions.getVersions({ id: this.data.id }).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/actions/actions/' + this.data.id + '/versions') - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .get(`/actions/actions/${this.data.id}/versions`) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.actions.getVersions({ id: this.data.id }).then(function() { + this.actions.getVersions({ id: this.data.id }).then(() => { expect(request.isDone()).to.be.true; done(); @@ -622,138 +580,132 @@ describe('ActionsManager', function() { }); }); - describe('#getVersion', function() { - beforeEach(function() { + describe('#getVersion', () => { + beforeEach(function () { nock.cleanAll(); this.data = { id: '0d565aa1-d8ce-4802-83e7-82e3d2040222', - versionId: '7asd8sd9-d8ce-4802-83e7-82e3d2040222' + versionId: '7asd8sd9-d8ce-4802-83e7-82e3d2040222', }; this.request = nock(API_URL) - .get('/actions/actions/' + this.data.id + '/versions/' + this.data.versionId) + .get(`/actions/actions/${this.data.id}/versions/${this.data.versionId}`) .reply(200, this.data); }); - it('should accept a callback', function(done) { - var params = { id: this.data.id, version_id: this.data.versionId }; + it('should accept a callback', function (done) { + const params = { id: this.data.id, version_id: this.data.versionId }; this.actions.getVersion(params, done.bind(null, null)); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.actions .get({ id: this.data.id, version_id: this.data.versionId }) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should perform a GET request', function(done) { - var request = this.request; + it('should perform a GET request', function (done) { + const { request } = this; - this.actions - .getVersion({ id: this.data.id, version_id: this.data.versionId }) - .then(function() { - expect(request.isDone()).to.be.true; + this.actions.getVersion({ id: this.data.id, version_id: this.data.versionId }).then(() => { + expect(request.isDone()).to.be.true; - done(); - }); + done(); + }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/actions/actions/' + this.data.id + '/versions/' + this.data.versionId) + nock(API_URL) + .get(`/actions/actions/${this.data.id}/versions/${this.data.versionId}`) .reply(500); this.actions .getVersion({ id: this.data.id, version_id: this.data.versionId }) - .catch(function(err) { + .catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/actions/actions/' + this.data.id + '/versions/' + this.data.versionId) - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .get(`/actions/actions/${this.data.id}/versions/${this.data.versionId}`) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.actions - .getVersion({ id: this.data.id, version_id: this.data.versionId }) - .then(function() { - expect(request.isDone()).to.be.true; + this.actions.getVersion({ id: this.data.id, version_id: this.data.versionId }).then(() => { + expect(request.isDone()).to.be.true; - done(); - }); + done(); + }); }); }); - describe('#createVersion', function() { - beforeEach(function() { + describe('#createVersion', () => { + beforeEach(function () { nock.cleanAll(); this.data = { - id: '0d565aa1-d8ce-4802-83e7-82e3d2040222' + id: '0d565aa1-d8ce-4802-83e7-82e3d2040222', }; this.request = nock(API_URL) - .post('/actions/actions/' + this.data.id + '/versions') + .post(`/actions/actions/${this.data.id}/versions`) .reply(200, this.data); }); - it('should accept a callback', function(done) { - var params = { id: this.data.id }; + it('should accept a callback', function (done) { + const params = { id: this.data.id }; this.actions.createVersion(params, this.data, done.bind(null, null)); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.actions .createVersion({ id: this.data.id }, {}) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should perform a POST request', function(done) { - var request = this.request; + it('should perform a POST request', function (done) { + const { request } = this; - this.actions.createVersion({ id: this.data.id }, {}).then(function() { + this.actions.createVersion({ id: this.data.id }, {}).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/actions/actions/' + this.data.id + '/versions') - .reply(500); + nock(API_URL).post(`/actions/actions/${this.data.id}/versions`).reply(500); - this.actions.createVersion({ id: this.data.id }, {}).catch(function(err) { + this.actions.createVersion({ id: this.data.id }, {}).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/actions/actions/' + this.data.id + '/versions') - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .post(`/actions/actions/${this.data.id}/versions`) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.actions.createVersion({ id: this.data.id }, {}).then(function() { + this.actions.createVersion({ id: this.data.id }, {}).then(() => { expect(request.isDone()).to.be.true; done(); @@ -761,57 +713,57 @@ describe('ActionsManager', function() { }); }); - describe('#deployVersion', function() { - var action_id = 'action-id-1'; - var version_id = 'action-version-id-1'; + describe('#deployVersion', () => { + const action_id = 'action-id-1'; + const version_id = 'action-version-id-1'; - beforeEach(function() { + beforeEach(function () { this.request = nock(API_URL) - .post('/actions/actions/' + action_id + '/versions/' + version_id + '/deploy') + .post(`/actions/actions/${action_id}/versions/${version_id}/deploy`) .reply(200); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.actions.deployVersion({ action_id, version_id }, done.bind(null, null)); }); - it('should return a promise when no callback is given', function(done) { + it('should return a promise when no callback is given', function (done) { this.actions.deployVersion({ action_id, version_id }).then(done.bind(null, null)); }); - it('should perform a post request', function(done) { - var request = this.request; + it('should perform a post request', function (done) { + const { request } = this; - this.actions.deployVersion({ action_id, version_id }).then(function() { + this.actions.deployVersion({ action_id, version_id }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/actions/actions/' + action_id + '/versions/' + version_id + '/deploy') + nock(API_URL) + .post(`/actions/actions/${action_id}/versions/${version_id}/deploy`) .reply(500); - this.actions.deployVersion({ action_id, version_id }).catch(function(err) { + this.actions.deployVersion({ action_id, version_id }).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the authorization header', function(done) { + it('should include the token in the authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/actions/actions/' + action_id + '/deploy') - .matchHeader('authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .post(`/actions/actions/${action_id}/deploy`) + .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); - this.actions.deploy({ action_id }).then(function() { + this.actions.deploy({ action_id }).then(() => { expect(request.isDone()).to.be.true; done(); @@ -820,70 +772,66 @@ describe('ActionsManager', function() { }); }); - describe('executions', function() { - describe('#getExecution', function() { - beforeEach(function() { + describe('executions', () => { + describe('#getExecution', () => { + beforeEach(function () { this.data = { id: '0d565aa1-d8ce-4802-83e7', - name: 'Execution' + name: 'Execution', }; - this.request = nock(API_URL) - .get('/actions/executions/' + this.data.id) - .reply(200); + this.request = nock(API_URL).get(`/actions/executions/${this.data.id}`).reply(200); }); - it('should accept a callback', function(done) { - var params = { execution_id: this.data.id }; + it('should accept a callback', function (done) { + const params = { execution_id: this.data.id }; this.actions.getExecution(params, done.bind(null, null)); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.actions .getExecution({ execution_id: this.data.id }) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should perform a GET request', function(done) { - var request = this.request; + it('should perform a GET request', function (done) { + const { request } = this; this.actions .getExecution({ execution_id: this.data.id }) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); }) - .catch(function(err) { + .catch((err) => { console.log(err); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/actions/executions/' + this.data.id) - .reply(500); + nock(API_URL).get(`/actions/executions/${this.data.id}`).reply(500); - this.actions.getExecution({ execution_id: this.data.id }).catch(function(err) { + this.actions.getExecution({ execution_id: this.data.id }).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/actions/executions/' + this.data.id) - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .get(`/actions/executions/${this.data.id}`) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.actions.getExecution({ execution_id: this.data.id }).then(function() { + this.actions.getExecution({ execution_id: this.data.id }).then(() => { expect(request.isDone()).to.be.true; done(); @@ -894,48 +842,39 @@ describe('ActionsManager', function() { describe('triggers', () => { const params = { per_page: 2 }; - describe('#getAllTriggers', function() { - beforeEach(function() { - this.request = nock(API_URL) - .get('/actions/triggers') - .reply(200); + describe('#getAllTriggers', () => { + beforeEach(function () { + this.request = nock(API_URL).get('/actions/triggers').reply(200); }); - it('should accept a callback', function(done) { - this.actions.getAllTriggers(params, function() { + it('should accept a callback', function (done) { + this.actions.getAllTriggers(params, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.actions - .getAllTriggers() - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.actions.getAllTriggers().then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/actions/triggers') - .reply(500); + nock(API_URL).get('/actions/triggers').reply(500); - this.actions.getAllTriggers().catch(function(err) { + this.actions.getAllTriggers().catch((err) => { expect(err).to.exist; done(); }); }); - it('should pass the body of the response to the "then" handler', function(done) { + it('should pass the body of the response to the "then" handler', function (done) { nock.cleanAll(); - var data = [{ trigger1: 'rigger1' }]; - var request = nock(API_URL) - .get('/actions/triggers') - .reply(200, data); + const data = [{ trigger1: 'rigger1' }]; + nock(API_URL).get('/actions/triggers').reply(200, data); - this.actions.getAllTriggers().then(function(triggers) { + this.actions.getAllTriggers().then((triggers) => { expect(triggers).to.be.an.instanceOf(Array); expect(triggers.length).to.equal(data.length); @@ -946,42 +885,39 @@ describe('ActionsManager', function() { }); }); - it('should perform a GET request', function(done) { - var request = this.request; + it('should perform a GET request', function (done) { + const { request } = this; - this.actions.getAllTriggers().then(function() { + this.actions.getAllTriggers().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/actions/triggers') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.actions.getAllTriggers().then(function() { + this.actions.getAllTriggers().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the parameters in the query-string', function(done) { + it('should pass the parameters in the query-string', function (done) { nock.cleanAll(); - var params = { + const params = { include_fields: true, - fields: 'test' + fields: 'test', }; - var request = nock(API_URL) - .get('/actions/triggers') - .query(params) - .reply(200); + const request = nock(API_URL).get('/actions/triggers').query(params).reply(200); - this.actions.getAllTriggers(params).then(function() { + this.actions.getAllTriggers(params).then(() => { expect(request.isDone()).to.be.true; done(); @@ -989,60 +925,56 @@ describe('ActionsManager', function() { }); }); - describe('#updateTriggerBindings', function() { + describe('#updateTriggerBindings', () => { const trigger_id = 'post-login'; - beforeEach(function() { + beforeEach(function () { this.data = { bindings: [] }; this.request = nock(API_URL) - .patch('/actions/triggers/' + trigger_id + '/bindings') + .patch(`/actions/triggers/${trigger_id}/bindings`) .reply(200, this.data); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.actions.updateTriggerBindings({ trigger_id }, this.data, done.bind(null, null)); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.actions .updateTriggerBindings({ trigger_id }, this.data) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should perform a PATCH request', function(done) { - var request = this.request; + it('should perform a PATCH request', function (done) { + const { request } = this; - this.actions.updateTriggerBindings({ trigger_id }, this.data).then(function() { + this.actions.updateTriggerBindings({ trigger_id }, this.data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the new data in the body of the request', function(done) { + it('should include the new data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/actions/triggers/' + trigger_id + '/bindings') - .reply(200); + const request = nock(API_URL).patch(`/actions/triggers/${trigger_id}/bindings`).reply(200); - this.actions.updateTriggerBindings({ trigger_id }, this.data).then(function() { + this.actions.updateTriggerBindings({ trigger_id }, this.data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/actions/triggers/' + trigger_id + '/bindings') - .reply(500); + nock(API_URL).patch(`/actions/triggers/${trigger_id}/bindings`).reply(500); - this.actions.updateTriggerBindings({ trigger_id }, this.data).catch(function(err) { + this.actions.updateTriggerBindings({ trigger_id }, this.data).catch((err) => { expect(err).to.exist; done(); @@ -1050,60 +982,56 @@ describe('ActionsManager', function() { }); }); - describe('#getTriggerBindings', function() { + describe('#getTriggerBindings', () => { const trigger_id = 'post-login'; - beforeEach(function() { + beforeEach(function () { this.data = { bindings: {} }; this.request = nock(API_URL) - .get('/actions/triggers/' + trigger_id + '/bindings') + .get(`/actions/triggers/${trigger_id}/bindings`) .reply(200, this.data); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.actions.getTriggerBindings({ trigger_id }, done.bind(null, null)); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.actions .getTriggerBindings({ trigger_id }) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should perform a GET request', function(done) { - var request = this.request; + it('should perform a GET request', function (done) { + const { request } = this; - this.actions.getTriggerBindings({ trigger_id }).then(function() { + this.actions.getTriggerBindings({ trigger_id }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the new data in the body of the request', function(done) { + it('should include the new data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/actions/triggers/' + trigger_id + '/bindings') - .reply(200); + const request = nock(API_URL).get(`/actions/triggers/${trigger_id}/bindings`).reply(200); - this.actions.getTriggerBindings({ trigger_id }).then(function() { + this.actions.getTriggerBindings({ trigger_id }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/actions/triggers/' + trigger_id + '/bindings') - .reply(500); + nock(API_URL).patch(`/actions/triggers/${trigger_id}/bindings`).reply(500); - this.actions.getTriggerBindings({ trigger_id }).catch(function(err) { + this.actions.getTriggerBindings({ trigger_id }).catch((err) => { expect(err).to.exist; done(); diff --git a/test/management/blacklisted-tokens.tests.js b/test/management/blacklisted-tokens.tests.js index 45e95eb75..d5442fe15 100644 --- a/test/management/blacklisted-tokens.tests.js +++ b/test/management/blacklisted-tokens.tests.js @@ -1,91 +1,83 @@ -var expect = require('chai').expect; -var nock = require('nock'); +const { expect } = require('chai'); +const nock = require('nock'); -var SRC_DIR = '../../src'; -var API_URL = 'https://tenant.auth0.com'; +const API_URL = 'https://tenant.auth0.com'; -var BlacklistedTokensManager = require(SRC_DIR + '/management/BlacklistedTokensManager'); -var ArgumentError = require('rest-facade').ArgumentError; +const BlacklistedTokensManager = require(`../../src/management/BlacklistedTokensManager`); +const { ArgumentError } = require('rest-facade'); -describe('BlacklistedTokensManager', function() { - before(function() { +describe('BlacklistedTokensManager', () => { + before(function () { this.token = 'TOKEN'; this.blacklistedTokens = new BlacklistedTokensManager({ - headers: { authorization: 'Bearer ' + this.token }, - baseUrl: API_URL + headers: { authorization: `Bearer ${this.token}` }, + baseUrl: API_URL, }); }); - describe('instance', function() { - var methods = ['add', 'getAll']; + describe('instance', () => { + const methods = ['add', 'getAll']; - methods.forEach(function(method) { - it('should have a ' + method + ' method', function() { + methods.forEach((method) => { + it(`should have a ${method} method`, function () { expect(this.blacklistedTokens[method]).to.exist.to.be.an.instanceOf(Function); }); }); }); - describe('#constructor', function() { - it('should error when no options are provided', function() { - expect(BlacklistedTokensManager).to.throw(ArgumentError, 'Must provide client options'); + describe('#constructor', () => { + it('should error when no options are provided', () => { + expect(() => { + new BlacklistedTokensManager(); + }).to.throw(ArgumentError, 'Must provide client options'); }); - it('should throw an error when no base URL is provided', function() { - var client = BlacklistedTokensManager.bind(null, {}); - - expect(client).to.throw(ArgumentError, 'Must provide a base URL for the API'); + it('should throw an error when no base URL is provided', () => { + expect(() => { + new BlacklistedTokensManager({}); + }).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); - it('should throw an error when the base URL is invalid', function() { - var client = BlacklistedTokensManager.bind(null, { baseUrl: '' }); - - expect(client).to.throw(ArgumentError, 'The provided base URL is invalid'); + it('should throw an error when the base URL is invalid', () => { + expect(() => { + new BlacklistedTokensManager({ baseUrl: '' }); + }).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); - describe('#getAll', function() { - beforeEach(function() { - this.request = nock(API_URL) - .get('/blacklists/tokens') - .reply(200); + describe('#getAll', () => { + beforeEach(function () { + this.request = nock(API_URL).get('/blacklists/tokens').reply(200); }); - it('should accept a callback', function(done) { - this.blacklistedTokens.getAll(function() { + it('should accept a callback', function (done) { + this.blacklistedTokens.getAll(() => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.blacklistedTokens - .getAll() - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.blacklistedTokens.getAll().then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/blacklists/tokens') - .reply(500); + nock(API_URL).get('/blacklists/tokens').reply(500); - this.blacklistedTokens.getAll().catch(function(err) { + this.blacklistedTokens.getAll().catch((err) => { expect(err).to.exist; done(); }); }); - it('should pass the body of the response to the "then" handler', function(done) { + it('should pass the body of the response to the "then" handler', function (done) { nock.cleanAll(); - var data = [{ test: true }]; - var request = nock(API_URL) - .get('/blacklists/tokens') - .reply(200, data); + const data = [{ test: true }]; + nock(API_URL).get('/blacklists/tokens').reply(200, data); - this.blacklistedTokens.getAll().then(function(blacklistedTokens) { + this.blacklistedTokens.getAll().then((blacklistedTokens) => { expect(blacklistedTokens).to.be.an.instanceOf(Array); expect(blacklistedTokens.length).to.equal(data.length); @@ -96,117 +88,111 @@ describe('BlacklistedTokensManager', function() { }); }); - it('should perform a GET request to /api/v2/blacklists/tokens', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/blacklists/tokens', function (done) { + const { request } = this; - this.blacklistedTokens.getAll().then(function() { + this.blacklistedTokens.getAll().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/blacklists/tokens') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.blacklistedTokens.getAll().then(function() { + this.blacklistedTokens.getAll().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the parameters in the query-string', function(done) { + it('should pass the parameters in the query-string', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/blacklists/tokens') .query({ include_fields: true, - fields: 'test' + fields: 'test', }) .reply(200); - this.blacklistedTokens.getAll({ include_fields: true, fields: 'test' }).then(function() { + this.blacklistedTokens.getAll({ include_fields: true, fields: 'test' }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); }); - describe('#add', function() { - var tokenData = { + describe('#add', () => { + const tokenData = { aud: '', - jti: '' + jti: '', }; - beforeEach(function() { - this.request = nock(API_URL) - .post('/blacklists/tokens') - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).post('/blacklists/tokens').reply(200); }); - it('should accept a callback', function(done) { - this.blacklistedTokens.add(tokenData, function() { + it('should accept a callback', function (done) { + this.blacklistedTokens.add(tokenData, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.blacklistedTokens .add(tokenData) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/blacklists/tokens') - .reply(500); + nock(API_URL).post('/blacklists/tokens').reply(500); - this.blacklistedTokens.add(tokenData).catch(function(err) { + this.blacklistedTokens.add(tokenData).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a POST request to /api/v2/blacklists/tokens', function(done) { - var request = this.request; + it('should perform a POST request to /api/v2/blacklists/tokens', function (done) { + const { request } = this; - this.blacklistedTokens.add(tokenData).then(function() { + this.blacklistedTokens.add(tokenData).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the token data in the body of the request', function(done) { + it('should pass the token data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/blacklists/tokens', tokenData) - .reply(200); + const request = nock(API_URL).post('/blacklists/tokens', tokenData).reply(200); - this.blacklistedTokens.add(tokenData).then(function() { + this.blacklistedTokens.add(tokenData).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .post('/blacklists/tokens') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.blacklistedTokens.add(tokenData).then(function() { + this.blacklistedTokens.add(tokenData).then(() => { expect(request.isDone()).to.be.true; done(); }); diff --git a/test/management/branding.tests.js b/test/management/branding.tests.js index e8c69c59c..1e7da3743 100644 --- a/test/management/branding.tests.js +++ b/test/management/branding.tests.js @@ -1,147 +1,134 @@ -var expect = require('chai').expect; -var nock = require('nock'); +const { expect } = require('chai'); +const nock = require('nock'); -var SRC_DIR = '../../src'; -var API_URL = 'https://tenant.auth0.com'; +const API_URL = 'https://tenant.auth0.com'; -var BrandingManager = require(SRC_DIR + '/management/BrandingManager'); -var ArgumentError = require('rest-facade').ArgumentError; +const BrandingManager = require(`../../src/management/BrandingManager`); +const { ArgumentError } = require('rest-facade'); -describe('BrandingManager', function() { - before(function() { +describe('BrandingManager', () => { + before(function () { this.token = 'TOKEN'; this.branding = new BrandingManager({ - headers: { authorization: 'Bearer ' + this.token }, - baseUrl: API_URL + headers: { authorization: `Bearer ${this.token}` }, + baseUrl: API_URL, }); }); - describe('instance', function() { - var methods = ['getSettings', 'updateSettings']; + describe('instance', () => { + const methods = ['getSettings', 'updateSettings']; - methods.forEach(function(method) { - it('should have a ' + method + ' method', function() { + methods.forEach((method) => { + it(`should have a ${method} method`, function () { expect(this.branding[method]).to.exist.to.be.an.instanceOf(Function); }); }); }); - describe('#constructor', function() { - it('should error when no options are provided', function() { + describe('#constructor', () => { + it('should error when no options are provided', () => { expect(BrandingManager).to.throw(ArgumentError, 'Must provide manager options'); }); - it('should throw an error when no base URL is provided', function() { - var client = BrandingManager.bind(null, {}); + it('should throw an error when no base URL is provided', () => { + const client = BrandingManager.bind(null, {}); expect(client).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); - it('should throw an error when the base URL is invalid', function() { - var client = BrandingManager.bind(null, { baseUrl: '' }); + it('should throw an error when the base URL is invalid', () => { + const client = BrandingManager.bind(null, { baseUrl: '' }); expect(client).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); - describe('#getSettings', function() { - var data = { + describe('#getSettings', () => { + const data = { colors: { - primary: '#FFF' + primary: '#FFF', }, favicon_url: 'https://example.com/favicon.ico', logo_url: 'https://example.com/logo.png', font: { - url: 'https://example.com/font.ttf' - } + url: 'https://example.com/font.ttf', + }, }; - beforeEach(function() { - this.request = nock(API_URL) - .get('/branding') - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).get('/branding').reply(200); }); - it('should accept a callback', function(done) { - this.branding.getSettings(function() { + it('should accept a callback', function (done) { + this.branding.getSettings(() => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.branding - .getSettings() - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.branding.getSettings().then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/branding') - .reply(500); + nock(API_URL).get('/branding').reply(500); - this.branding.getSettings().catch(function(err) { + this.branding.getSettings().catch((err) => { expect(err).to.exist; done(); }); }); - it('should pass the body of the response to the "then" handler', function(done) { + it('should pass the body of the response to the "then" handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/branding') - .reply(200, data); + nock(API_URL).get('/branding').reply(200, data); - this.branding.getSettings().then(function(provider) { + this.branding.getSettings().then((provider) => { expect(provider.id).to.equal(data.id); done(); }); }); - it('should perform a GET request to /api/v2/branding', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/branding', function (done) { + const { request } = this; - this.branding.getSettings().then(function() { + this.branding.getSettings().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/branding') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.branding.getSettings().then(function() { + this.branding.getSettings().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the parameters in the query-string', function(done) { + it('should pass the parameters in the query-string', function (done) { nock.cleanAll(); - var params = { + const params = { include_fields: true, - fields: 'test' + fields: 'test', }; - var request = nock(API_URL) - .get('/branding') - .query(params) - .reply(200); + const request = nock(API_URL).get('/branding').query(params).reply(200); - this.branding.getSettings(params).then(function() { + this.branding.getSettings(params).then(() => { expect(request.isDone()).to.be.true; done(); @@ -149,84 +136,78 @@ describe('BrandingManager', function() { }); }); - describe('#updateSettings', function() { - var data = { + describe('#updateSettings', () => { + const data = { colors: { - primary: '#FFF' + primary: '#FFF', }, favicon_url: 'https://example.com/favicon.ico', logo_url: 'https://example.com/logo.png', font: { - url: 'https://example.com/font.ttf' - } + url: 'https://example.com/font.ttf', + }, }; - beforeEach(function() { - this.request = nock(API_URL) - .patch('/branding') - .reply(200, data); + beforeEach(function () { + this.request = nock(API_URL).patch('/branding').reply(200, data); }); - it('should accept a callback', function(done) { - this.branding.updateSettings({}, data, function() { + it('should accept a callback', function (done) { + this.branding.updateSettings({}, data, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.branding .updateSettings({}, data) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/branding/' + data.id) - .reply(500); + nock(API_URL).patch(`/branding/${data.id}`).reply(500); - this.branding.updateSettings({}, data).catch(function(err) { + this.branding.updateSettings({}, data).catch((err) => { expect(err).to.exist.to.be.an.instanceOf(Error); done(); }); }); - it('should perform a PATCH request to /api/v2/branding', function(done) { - var request = this.request; + it('should perform a PATCH request to /api/v2/branding', function (done) { + const { request } = this; - this.branding.updateSettings({}, data).then(function() { + this.branding.updateSettings({}, data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the data in the body of the request', function(done) { + it('should pass the data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/branding', data) - .reply(200); + const request = nock(API_URL).patch('/branding', data).reply(200); - this.branding.updateSettings({}, data).then(function() { + this.branding.updateSettings({}, data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .patch('/branding') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.branding.updateSettings({}, data).then(function() { + this.branding.updateSettings({}, data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -234,79 +215,73 @@ describe('BrandingManager', function() { }); }); - describe('#getUniversalLoginTemplate', function() { - beforeEach(function() { - this.request = nock(API_URL) - .get('/branding/templates/universal-login') - .reply(200); + describe('#getUniversalLoginTemplate', () => { + beforeEach(function () { + this.request = nock(API_URL).get('/branding/templates/universal-login').reply(200); }); - afterEach(function() { + afterEach(() => { nock.cleanAll(); }); - it('should accept a callback', function(done) { - this.branding.getUniversalLoginTemplate(function() { + it('should accept a callback', function (done) { + this.branding.getUniversalLoginTemplate(() => { done(); }); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.branding .getUniversalLoginTemplate() .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/branding/templates/universal-login') - .reply(500); + nock(API_URL).get('/branding/templates/universal-login').reply(500); - this.branding.getUniversalLoginTemplate().catch(function(err) { + this.branding.getUniversalLoginTemplate().catch((err) => { expect(err).to.exist; done(); }); }); - it('should pass the body of the response to the "then" handler', function(done) { - var data = { body: 'test' }; + it('should pass the body of the response to the "then" handler', function (done) { + const data = { body: 'test' }; nock.cleanAll(); - var request = nock(API_URL) - .get('/branding/templates/universal-login') - .reply(200, data); + nock(API_URL).get('/branding/templates/universal-login').reply(200, data); - this.branding.getUniversalLoginTemplate().then(function(response) { + this.branding.getUniversalLoginTemplate().then((response) => { expect(response.body).to.equal(data.body); done(); }); }); - it('should perform a GET request to /api/v2/branding', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/branding', function (done) { + const { request } = this; - this.branding.getUniversalLoginTemplate().then(function() { + this.branding.getUniversalLoginTemplate().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/branding/templates/universal-login') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.branding.getUniversalLoginTemplate().then(function() { + this.branding.getUniversalLoginTemplate().then(() => { expect(request.isDone()).to.be.true; done(); @@ -314,79 +289,73 @@ describe('BrandingManager', function() { }); }); - describe('#setUniversalLoginTemplate', function() { - beforeEach(function() { - this.request = nock(API_URL) - .put('/branding/templates/universal-login') - .reply(200); + describe('#setUniversalLoginTemplate', () => { + beforeEach(function () { + this.request = nock(API_URL).put('/branding/templates/universal-login').reply(200); }); - afterEach(function() { + afterEach(() => { nock.cleanAll(); }); - it('should accept a callback', function(done) { - this.branding.setUniversalLoginTemplate({}, {}, function() { + it('should accept a callback', function (done) { + this.branding.setUniversalLoginTemplate({}, {}, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.branding .setUniversalLoginTemplate({}, {}) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .put('/branding/templates/universal-login') - .reply(500); + nock(API_URL).put('/branding/templates/universal-login').reply(500); - this.branding.setUniversalLoginTemplate({}, {}).catch(function(err) { + this.branding.setUniversalLoginTemplate({}, {}).catch((err) => { expect(err).to.exist; done(); }); }); - it('should pass the body of the response to the "then" handler', function(done) { - var data = { body: 'test' }; + it('should pass the body of the response to the "then" handler', function (done) { + const data = { body: 'test' }; nock.cleanAll(); - var request = nock(API_URL) - .put('/branding/templates/universal-login') - .reply(200, data); + nock(API_URL).put('/branding/templates/universal-login').reply(200, data); - this.branding.setUniversalLoginTemplate({}, data).then(function(response) { + this.branding.setUniversalLoginTemplate({}, data).then((response) => { expect(response.body).to.equal(data.body); done(); }); }); - it('should perform a PUT request to /api/v2/branding/templates/universal-login', function(done) { - var request = this.request; + it('should perform a PUT request to /api/v2/branding/templates/universal-login', function (done) { + const { request } = this; - this.branding.setUniversalLoginTemplate({}, {}).then(function() { + this.branding.setUniversalLoginTemplate({}, {}).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .put('/branding/templates/universal-login') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.branding.setUniversalLoginTemplate({}, {}).then(function() { + this.branding.setUniversalLoginTemplate({}, {}).then(() => { expect(request.isDone()).to.be.true; done(); @@ -394,79 +363,73 @@ describe('BrandingManager', function() { }); }); - describe('#deleteUniversalLoginTemplate', function() { - beforeEach(function() { - this.request = nock(API_URL) - .delete('/branding/templates/universal-login') - .reply(200); + describe('#deleteUniversalLoginTemplate', () => { + beforeEach(function () { + this.request = nock(API_URL).delete('/branding/templates/universal-login').reply(200); }); - afterEach(function() { + afterEach(() => { nock.cleanAll(); }); - it('should accept a callback', function(done) { - this.branding.deleteUniversalLoginTemplate(function() { + it('should accept a callback', function (done) { + this.branding.deleteUniversalLoginTemplate(() => { done(); }); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.branding .deleteUniversalLoginTemplate() .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete('/branding/templates/universal-login') - .reply(500); + nock(API_URL).delete('/branding/templates/universal-login').reply(500); - this.branding.deleteUniversalLoginTemplate().catch(function(err) { + this.branding.deleteUniversalLoginTemplate().catch((err) => { expect(err).to.exist; done(); }); }); - it('should pass the body of the response to the "then" handler', function(done) { - var data = { body: 'test' }; + it('should pass the body of the response to the "then" handler', function (done) { + const data = { body: 'test' }; nock.cleanAll(); - var request = nock(API_URL) - .delete('/branding/templates/universal-login') - .reply(200, data); + nock(API_URL).delete('/branding/templates/universal-login').reply(200, data); - this.branding.deleteUniversalLoginTemplate().then(function(response) { + this.branding.deleteUniversalLoginTemplate().then((response) => { expect(response.body).to.equal(data.body); done(); }); }); - it('should perform a DELETE request to /api/v2/branding/templates/universal-login', function(done) { - var request = this.request; + it('should perform a DELETE request to /api/v2/branding/templates/universal-login', function (done) { + const { request } = this; - this.branding.deleteUniversalLoginTemplate().then(function() { + this.branding.deleteUniversalLoginTemplate().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .delete('/branding/templates/universal-login') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.branding.deleteUniversalLoginTemplate().then(function() { + this.branding.deleteUniversalLoginTemplate().then(() => { expect(request.isDone()).to.be.true; done(); diff --git a/test/management/client-grants.tests.js b/test/management/client-grants.tests.js index 10cca2184..18083626f 100644 --- a/test/management/client-grants.tests.js +++ b/test/management/client-grants.tests.js @@ -1,97 +1,87 @@ -var expect = require('chai').expect; -var nock = require('nock'); +const { expect } = require('chai'); +const nock = require('nock'); -var SRC_DIR = '../../src'; -var API_URL = 'https://tenant.auth0.com'; +const API_URL = 'https://tenant.auth0.com'; -var ClientGrantsManager = require(SRC_DIR + '/management/ClientGrantsManager'); -var ArgumentError = require('rest-facade').ArgumentError; +const ClientGrantsManager = require(`../../src/management/ClientGrantsManager`); +const { ArgumentError } = require('rest-facade'); -describe('ClientGrantsManager', function() { - before(function() { +describe('ClientGrantsManager', () => { + before(function () { this.token = 'TOKEN'; this.grants = new ClientGrantsManager({ headers: { - authorization: 'Bearer ' + this.token + authorization: `Bearer ${this.token}`, }, - baseUrl: API_URL + baseUrl: API_URL, }); }); - afterEach(function() { + afterEach(() => { nock.cleanAll(); }); - describe('instance', function() { - var methods = ['getAll', 'create', 'update', 'delete']; + describe('instance', () => { + const methods = ['getAll', 'create', 'update', 'delete']; - methods.forEach(function(method) { - it('should have a ' + method + ' method', function() { + methods.forEach((method) => { + it(`should have a ${method} method`, function () { expect(this.grants[method]).to.exist.to.be.an.instanceOf(Function); }); }); }); - describe('#constructor', function() { - it('should error when no options are provided', function() { + describe('#constructor', () => { + it('should error when no options are provided', () => { expect(ClientGrantsManager).to.throw(ArgumentError, 'Must provide client options'); }); - it('should throw an error when no base URL is provided', function() { - var grants = ClientGrantsManager.bind(null, {}); + it('should throw an error when no base URL is provided', () => { + const grants = ClientGrantsManager.bind(null, {}); expect(grants).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); - it('should throw an error when the base URL is invalid', function() { - var grants = ClientGrantsManager.bind(null, { baseUrl: '' }); + it('should throw an error when the base URL is invalid', () => { + const grants = ClientGrantsManager.bind(null, { baseUrl: '' }); expect(grants).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); - describe('#getAll', function() { - beforeEach(function() { - this.request = nock(API_URL) - .get('/client-grants') - .reply(200); + describe('#getAll', () => { + beforeEach(function () { + this.request = nock(API_URL).get('/client-grants').reply(200); }); - it('should accept a callback', function(done) { - this.grants.getAll(function() { + it('should accept a callback', function (done) { + this.grants.getAll(() => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.grants - .getAll() - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.grants.getAll().then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/client-grants') - .reply(500); + nock(API_URL).get('/client-grants').reply(500); - this.grants.getAll().catch(function(err) { + this.grants.getAll().catch((err) => { expect(err).to.exist; done(); }); }); - it('should pass the body of the response to the "then" handler', function(done) { + it('should pass the body of the response to the "then" handler', function (done) { nock.cleanAll(); - var data = [{ test: true }]; - var request = nock(API_URL) - .get('/client-grants') - .reply(200, data); + const data = [{ test: true }]; + nock(API_URL).get('/client-grants').reply(200, data); - this.grants.getAll().then(function(grants) { + this.grants.getAll().then((grants) => { expect(grants).to.be.an.instanceOf(Array); expect(grants.length).to.equal(data.length); @@ -102,104 +92,97 @@ describe('ClientGrantsManager', function() { }); }); - it('should perform a GET request to /api/v2/client-grants', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/client-grants', function (done) { + const { request } = this; - this.grants.getAll().then(function() { + this.grants.getAll().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/client-grants') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.grants.getAll().then(function() { + this.grants.getAll().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the parameters in the query-string', function(done) { + it('should pass the parameters in the query-string', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/client-grants') .query({ include_fields: true, - fields: 'test' + fields: 'test', }) .reply(200); - this.grants.getAll({ include_fields: true, fields: 'test' }).then(function() { + this.grants.getAll({ include_fields: true, fields: 'test' }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); }); - describe('#create', function() { - var data = { + describe('#create', () => { + const data = { client_id: 'CLIENT_ID', audience: 'AUDIENCE', - scope: ['user'] + scope: ['user'], }; - beforeEach(function() { - this.request = nock(API_URL) - .post('/client-grants') - .reply(201, data); + beforeEach(function () { + this.request = nock(API_URL).post('/client-grants').reply(201, data); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.grants.create(data, done.bind(null, null)); }); - it('should return a promise if no callback is given', function(done) { - this.grants - .create(data) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.grants.create(data).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should perform a POST request to /api/v2/client-grants', function(done) { - var request = this.request; + it('should perform a POST request to /api/v2/client-grants', function (done) { + const { request } = this; - this.grants.create(data).then(function() { + this.grants.create(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .post('/client-grants') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(201, data); - this.grants.create(data).then(function() { + this.grants.create(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the new client grant data in the request body', function(done) { + it('should include the new client grant data in the request body', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/client-grants', data) - .reply(201, data); + const request = nock(API_URL).post('/client-grants', data).reply(201, data); - this.grants.create(data).then(function() { + this.grants.create(data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -207,44 +190,37 @@ describe('ClientGrantsManager', function() { }); }); - describe('#update', function() { - beforeEach(function() { + describe('#update', () => { + beforeEach(function () { this.data = { id: 5 }; - this.request = nock(API_URL) - .patch('/client-grants/' + this.data.id) - .reply(200, this.data); + this.request = nock(API_URL).patch(`/client-grants/${this.data.id}`).reply(200, this.data); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.grants.update({ id: 5 }, {}, done.bind(null, null)); }); - it('should return a promise if no callback is given', function(done) { - this.grants - .update({ id: 5 }, {}) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.grants.update({ id: 5 }, {}).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should perform a PATCH request to /api/v2/client-grants/5', function(done) { - var request = this.request; + it('should perform a PATCH request to /api/v2/client-grants/5', function (done) { + const { request } = this; - this.grants.update({ id: 5 }, {}).then(function() { + this.grants.update({ id: 5 }, {}).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the new data in the body of the request', function(done) { + it('should include the new data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/client-grants/' + this.data.id, this.data) - .reply(200); + const request = nock(API_URL).patch(`/client-grants/${this.data.id}`, this.data).reply(200); - this.grants.update({ id: 5 }, this.data).then(function() { + this.grants.update({ id: 5 }, this.data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -252,27 +228,25 @@ describe('ClientGrantsManager', function() { }); }); - describe('#delete', function() { - var id = 5; + describe('#delete', () => { + const id = 5; - beforeEach(function() { - this.request = nock(API_URL) - .delete('/client-grants/' + id) - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).delete(`/client-grants/${id}`).reply(200); }); - it('should accept a callback', function(done) { - this.grants.delete({ id: id }, done.bind(null, null)); + it('should accept a callback', function (done) { + this.grants.delete({ id }, done.bind(null, null)); }); - it('should return a promise when no callback is given', function(done) { - this.grants.delete({ id: id }).then(done.bind(null, null)); + it('should return a promise when no callback is given', function (done) { + this.grants.delete({ id }).then(done.bind(null, null)); }); - it('should perform a DELETE request to /client-grants/' + id, function(done) { - var request = this.request; + it(`should perform a DELETE request to /client-grants/${id}`, function (done) { + const { request } = this; - this.grants.delete({ id: id }).then(function() { + this.grants.delete({ id }).then(() => { expect(request.isDone()).to.be.true; done(); diff --git a/test/management/client.tests.js b/test/management/client.tests.js index 34b0be9b4..2860a426a 100644 --- a/test/management/client.tests.js +++ b/test/management/client.tests.js @@ -1,97 +1,87 @@ -var expect = require('chai').expect; -var nock = require('nock'); +const { expect } = require('chai'); +const nock = require('nock'); -var SRC_DIR = '../../src'; -var API_URL = 'https://tenant.auth0.com'; +const API_URL = 'https://tenant.auth0.com'; -var ClientsManager = require(SRC_DIR + '/management/ClientsManager'); -var ArgumentError = require('rest-facade').ArgumentError; +const ClientsManager = require(`../../src/management/ClientsManager`); +const { ArgumentError } = require('rest-facade'); -describe('ClientsManager', function() { - before(function() { +describe('ClientsManager', () => { + before(function () { this.token = 'TOKEN'; this.clients = new ClientsManager({ headers: { - authorization: 'Bearer ' + this.token + authorization: `Bearer ${this.token}`, }, - baseUrl: API_URL + baseUrl: API_URL, }); }); - afterEach(function() { + afterEach(() => { nock.cleanAll(); }); - describe('instance', function() { - var methods = ['getAll', 'get', 'create', 'update', 'delete']; + describe('instance', () => { + const methods = ['getAll', 'get', 'create', 'update', 'delete']; - methods.forEach(function(method) { - it('should have a ' + method + ' method', function() { + methods.forEach((method) => { + it(`should have a ${method} method`, function () { expect(this.clients[method]).to.exist.to.be.an.instanceOf(Function); }); }); }); - describe('#constructor', function() { - it('should error when no options are provided', function() { + describe('#constructor', () => { + it('should error when no options are provided', () => { expect(ClientsManager).to.throw(ArgumentError, 'Must provide client options'); }); - it('should throw an error when no base URL is provided', function() { - var client = ClientsManager.bind(null, {}); + it('should throw an error when no base URL is provided', () => { + const client = ClientsManager.bind(null, {}); expect(client).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); - it('should throw an error when the base URL is invalid', function() { - var client = ClientsManager.bind(null, { baseUrl: '' }); + it('should throw an error when the base URL is invalid', () => { + const client = ClientsManager.bind(null, { baseUrl: '' }); expect(client).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); - describe('#getAll', function() { - beforeEach(function() { - this.request = nock(API_URL) - .get('/clients') - .reply(200); + describe('#getAll', () => { + beforeEach(function () { + this.request = nock(API_URL).get('/clients').reply(200); }); - it('should accept a callback', function(done) { - this.clients.getAll(function() { + it('should accept a callback', function (done) { + this.clients.getAll(() => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.clients - .getAll() - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.clients.getAll().then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/clients') - .reply(500); + nock(API_URL).get('/clients').reply(500); - this.clients.getAll().catch(function(err) { + this.clients.getAll().catch((err) => { expect(err).to.exist; done(); }); }); - it('should pass the body of the response to the "then" handler', function(done) { + it('should pass the body of the response to the "then" handler', function (done) { nock.cleanAll(); - var data = [{ test: true }]; - var request = nock(API_URL) - .get('/clients') - .reply(200, data); + const data = [{ test: true }]; + nock(API_URL).get('/clients').reply(200, data); - this.clients.getAll().then(function(clients) { + this.clients.getAll().then((clients) => { expect(clients).to.be.an.instanceOf(Array); expect(clients.length).to.equal(data.length); @@ -102,100 +92,93 @@ describe('ClientsManager', function() { }); }); - it('should perform a GET request to /api/v2/clients', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/clients', function (done) { + const { request } = this; - this.clients.getAll().then(function() { + this.clients.getAll().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/clients') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.clients.getAll().then(function() { + this.clients.getAll().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the parameters in the query-string', function(done) { + it('should pass the parameters in the query-string', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/clients') .query({ include_fields: true, - fields: 'test' + fields: 'test', }) .reply(200); - this.clients.getAll({ include_fields: true, fields: 'test' }).then(function() { + this.clients.getAll({ include_fields: true, fields: 'test' }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); }); - describe('#create', function() { - var data = { name: 'Test client' }; + describe('#create', () => { + const data = { name: 'Test client' }; - beforeEach(function() { - this.request = nock(API_URL) - .post('/clients') - .reply(201, data); + beforeEach(function () { + this.request = nock(API_URL).post('/clients').reply(201, data); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.clients.create(data, done.bind(null, null)); }); - it('should return a promise if no callback is given', function(done) { - this.clients - .create(data) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.clients.create(data).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should perform a POST request to /api/v2/clients', function(done) { - var request = this.request; + it('should perform a POST request to /api/v2/clients', function (done) { + const { request } = this; - this.clients.create(data).then(function() { + this.clients.create(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .post('/clients') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(201, data); - this.clients.create(data).then(function() { + this.clients.create(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the new client data in the request body', function(done) { + it('should include the new client data in the request body', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/clients', data) - .reply(201, data); + const request = nock(API_URL).post('/clients', data).reply(201, data); - this.clients.create(data).then(function() { + this.clients.create(data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -203,36 +186,34 @@ describe('ClientsManager', function() { }); }); - describe('#get', function() { - beforeEach(function() { + describe('#get', () => { + beforeEach(function () { this.data = { id: 5, name: 'John Doe', - email: 'john@doe.com' + email: 'john@doe.com', }; - this.request = nock(API_URL) - .get('/clients/' + this.data.id) - .reply(201, this.data); + this.request = nock(API_URL).get(`/clients/${this.data.id}`).reply(201, this.data); }); - it('should accept a callback', function(done) { - var params = { id: this.data.id }; + it('should accept a callback', function (done) { + const params = { id: this.data.id }; this.clients.get(params, done.bind(null, null)); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.clients .get({ id: this.data.id }) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should perform a POST request to /api/v2/clients/5', function(done) { - var request = this.request; + it('should perform a POST request to /api/v2/clients/5', function (done) { + const { request } = this; - this.clients.get({ client_id: this.data.id }).then(function() { + this.clients.get({ client_id: this.data.id }).then(() => { expect(request.isDone()).to.be.true; done(); @@ -240,44 +221,40 @@ describe('ClientsManager', function() { }); }); - describe('#update', function() { - beforeEach(function() { + describe('#update', () => { + beforeEach(function () { this.data = { id: 5 }; - this.request = nock(API_URL) - .patch('/clients/' + this.data.id) - .reply(200, this.data); + this.request = nock(API_URL).patch(`/clients/${this.data.id}`).reply(200, this.data); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.clients.update({ client_id: 5 }, {}, done.bind(null, null)); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.clients .update({ client_id: 5 }, {}) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should perform a PATCH request to /api/v2/clients/5', function(done) { - var request = this.request; + it('should perform a PATCH request to /api/v2/clients/5', function (done) { + const { request } = this; - this.clients.update({ client_id: 5 }, {}).then(function() { + this.clients.update({ client_id: 5 }, {}).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the new data in the body of the request', function(done) { + it('should include the new data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/clients/' + this.data.id, this.data) - .reply(200); + const request = nock(API_URL).patch(`/clients/${this.data.id}`, this.data).reply(200); - this.clients.update({ client_id: 5 }, this.data).then(function() { + this.clients.update({ client_id: 5 }, this.data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -285,27 +262,25 @@ describe('ClientsManager', function() { }); }); - describe('#delete', function() { - var id = 5; + describe('#delete', () => { + const id = 5; - beforeEach(function() { - this.request = nock(API_URL) - .delete('/clients/' + id) - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).delete(`/clients/${id}`).reply(200); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.clients.delete({ client_id: id }, done.bind(null, null)); }); - it('should return a promise when no callback is given', function(done) { + it('should return a promise when no callback is given', function (done) { this.clients.delete({ client_id: id }).then(done.bind(null, null)); }); - it('should perform a DELETE request to /clients/' + id, function(done) { - var request = this.request; + it(`should perform a DELETE request to /clients/${id}`, function (done) { + const { request } = this; - this.clients.delete({ client_id: id }).then(function() { + this.clients.delete({ client_id: id }).then(() => { expect(request.isDone()).to.be.true; done(); diff --git a/test/management/connections.tests.js b/test/management/connections.tests.js index 828356252..0a6b497be 100644 --- a/test/management/connections.tests.js +++ b/test/management/connections.tests.js @@ -1,92 +1,82 @@ -var expect = require('chai').expect; -var nock = require('nock'); +const { expect } = require('chai'); +const nock = require('nock'); -var SRC_DIR = '../../src'; -var API_URL = 'https://tenant.auth0.com'; +const API_URL = 'https://tenant.auth0.com'; -var ConnectionsManager = require(SRC_DIR + '/management/ConnectionsManager'); -var ArgumentError = require('rest-facade').ArgumentError; +const ConnectionsManager = require(`../../src/management/ConnectionsManager`); +const { ArgumentError } = require('rest-facade'); -describe('ConnectionsManager', function() { - before(function() { +describe('ConnectionsManager', () => { + before(function () { this.token = 'TOKEN'; this.connections = new ConnectionsManager({ - headers: { authorization: 'Bearer ' + this.token }, - baseUrl: API_URL + headers: { authorization: `Bearer ${this.token}` }, + baseUrl: API_URL, }); }); - describe('instance', function() { - var methods = ['getAll', 'get', 'create', 'update', 'delete']; + describe('instance', () => { + const methods = ['getAll', 'get', 'create', 'update', 'delete']; - methods.forEach(function(method) { - it('should have a ' + method + ' method', function() { + methods.forEach((method) => { + it(`should have a ${method} method`, function () { expect(this.connections[method]).to.exist.to.be.an.instanceOf(Function); }); }); }); - describe('#constructor', function() { - it('should error when no options are provided', function() { + describe('#constructor', () => { + it('should error when no options are provided', () => { expect(ConnectionsManager).to.throw(ArgumentError, 'Must provide client options'); }); - it('should throw an error when no base URL is provided', function() { - var client = ConnectionsManager.bind(null, {}); + it('should throw an error when no base URL is provided', () => { + const client = ConnectionsManager.bind(null, {}); expect(client).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); - it('should throw an error when the base URL is invalid', function() { - var client = ConnectionsManager.bind(null, { baseUrl: '' }); + it('should throw an error when the base URL is invalid', () => { + const client = ConnectionsManager.bind(null, { baseUrl: '' }); expect(client).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); - describe('#getAll', function() { - beforeEach(function() { - this.request = nock(API_URL) - .get('/connections') - .reply(200); + describe('#getAll', () => { + beforeEach(function () { + this.request = nock(API_URL).get('/connections').reply(200); }); - it('should accept a callback', function(done) { - this.connections.getAll(function() { + it('should accept a callback', function (done) { + this.connections.getAll(() => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.connections - .getAll() - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.connections.getAll().then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/connections') - .reply(500); + nock(API_URL).get('/connections').reply(500); - this.connections.getAll().catch(function(err) { + this.connections.getAll().catch((err) => { expect(err).to.exist; done(); }); }); - it('should pass the body of the response to the "then" handler', function(done) { + it('should pass the body of the response to the "then" handler', function (done) { nock.cleanAll(); - var data = [{ test: true }]; - var request = nock(API_URL) - .get('/connections') - .reply(200, data); + const data = [{ test: true }]; + nock(API_URL).get('/connections').reply(200, data); - this.connections.getAll().then(function(connections) { + this.connections.getAll().then((connections) => { expect(connections).to.be.an.instanceOf(Array); expect(connections.length).to.equal(data.length); @@ -97,42 +87,42 @@ describe('ConnectionsManager', function() { }); }); - it('should perform a GET request to /api/v2/connections', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/connections', function (done) { + const { request } = this; - this.connections.getAll().then(function() { + this.connections.getAll().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/connections') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.connections.getAll().then(function() { + this.connections.getAll().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the parameters in the query-string', function(done) { + it('should pass the parameters in the query-string', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/connections') .query({ include_fields: true, - fields: 'test' + fields: 'test', }) .reply(200); - this.connections.getAll({ include_fields: true, fields: 'test' }).then(function() { + this.connections.getAll({ include_fields: true, fields: 'test' }).then(() => { expect(request.isDone()).to.be.true; done(); @@ -140,97 +130,88 @@ describe('ConnectionsManager', function() { }); }); - describe('#get', function() { - var params = { id: 5 }; - var data = { + describe('#get', () => { + const params = { id: 5 }; + const data = { id: params.id, - name: 'Test connection' + name: 'Test connection', }; - beforeEach(function() { - this.request = nock(API_URL) - .get('/connections/' + data.id) - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).get(`/connections/${data.id}`).reply(200); }); - it('should accept a callback', function(done) { - this.connections.get(params, function() { + it('should accept a callback', function (done) { + this.connections.get(params, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.connections - .get(params) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.connections.get(params).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/connections/' + params.id) - .reply(500); + nock(API_URL).get(`/connections/${params.id}`).reply(500); - this.connections.get().catch(function(err) { + this.connections.get().catch((err) => { expect(err).to.exist; done(); }); }); - it('should pass the body of the response to the "then" handler', function(done) { + it('should pass the body of the response to the "then" handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/connections/' + params.id) - .reply(200, data); + nock(API_URL).get(`/connections/${params.id}`).reply(200, data); - this.connections.get(params).then(function(connection) { + this.connections.get(params).then((connection) => { expect(connection.id).to.equal(data.id); done(); }); }); - it('should perform a GET request to /api/v2/connections/:id', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/connections/:id', function (done) { + const { request } = this; - this.connections.get(params).then(function() { + this.connections.get(params).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/connections') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.connections.getAll().then(function() { + this.connections.getAll().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the parameters in the query-string', function(done) { + it('should pass the parameters in the query-string', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/connections') .query({ include_fields: true, - fields: 'test' + fields: 'test', }) .reply(200); - this.connections.getAll({ include_fields: true, fields: 'test' }).then(function() { + this.connections.getAll({ include_fields: true, fields: 'test' }).then(() => { expect(request.isDone()).to.be.true; done(); @@ -238,78 +219,69 @@ describe('ConnectionsManager', function() { }); }); - describe('#create', function() { - var data = { + describe('#create', () => { + const data = { name: 'Test connection', - options: {} + options: {}, }; - beforeEach(function() { - this.request = nock(API_URL) - .post('/connections') - .reply(200, data); + beforeEach(function () { + this.request = nock(API_URL).post('/connections').reply(200, data); }); - it('should accept a callback', function(done) { - this.connections.create(data, function() { + it('should accept a callback', function (done) { + this.connections.create(data, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.connections - .create(data) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.connections.create(data).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/connections') - .reply(500); + nock(API_URL).post('/connections').reply(500); - this.connections.create(data).catch(function(err) { + this.connections.create(data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a POST request to /api/v2/connections', function(done) { - var request = this.request; + it('should perform a POST request to /api/v2/connections', function (done) { + const { request } = this; - this.connections.create(data).then(function() { + this.connections.create(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the data in the body of the request', function(done) { + it('should pass the data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/connections', data) - .reply(200); + const request = nock(API_URL).post('/connections', data).reply(200); - this.connections.create(data).then(function() { + this.connections.create(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .post('/connections') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.connections.create(data).then(function() { + this.connections.create(data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -317,80 +289,74 @@ describe('ConnectionsManager', function() { }); }); - describe('#update', function() { - var params = { id: 5 }; - var data = { + describe('#update', () => { + const params = { id: 5 }; + const data = { id: 5, name: 'Test connection', - options: {} + options: {}, }; - beforeEach(function() { - this.request = nock(API_URL) - .patch('/connections/' + data.id) - .reply(200, data); + beforeEach(function () { + this.request = nock(API_URL).patch(`/connections/${data.id}`).reply(200, data); }); - it('should accept a callback', function(done) { - this.connections.update(params, data, function() { + it('should accept a callback', function (done) { + this.connections.update(params, data, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.connections .update(params, data) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/connections/' + data.id) - .reply(500); + nock(API_URL).patch(`/connections/${data.id}`).reply(500); - this.connections.update(params, data).catch(function(err) { + this.connections.update(params, data).catch((err) => { expect(err).to.exist.to.be.an.instanceOf(Error); done(); }); }); - it('should perform a PATCH request to /api/v2/connections/:id', function(done) { - var request = this.request; + it('should perform a PATCH request to /api/v2/connections/:id', function (done) { + const { request } = this; - this.connections.update(params, data).then(function() { + this.connections.update(params, data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the data in the body of the request', function(done) { + it('should pass the data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/connections/' + data.id, data) - .reply(200); + const request = nock(API_URL).patch(`/connections/${data.id}`, data).reply(200); - this.connections.update(params, data).then(function() { + this.connections.update(params, data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/connections/' + data.id) - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .patch(`/connections/${data.id}`) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.connections.update(params, data).then(function() { + this.connections.update(params, data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -398,56 +364,52 @@ describe('ConnectionsManager', function() { }); }); - describe('#delete', function() { - var id = 5; + describe('#delete', () => { + const id = 5; - beforeEach(function() { - this.request = nock(API_URL) - .delete('/connections/' + id) - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).delete(`/connections/${id}`).reply(200); }); - it('should accept a callback', function(done) { - this.connections.delete({ id: id }, done.bind(null, null)); + it('should accept a callback', function (done) { + this.connections.delete({ id }, done.bind(null, null)); }); - it('should return a promise when no callback is given', function(done) { - this.connections.delete({ id: id }).then(done.bind(null, null)); + it('should return a promise when no callback is given', function (done) { + this.connections.delete({ id }).then(done.bind(null, null)); }); - it('should perform a DELETE request to /connections/' + id, function(done) { - var request = this.request; + it(`should perform a DELETE request to /connections/${id}`, function (done) { + const { request } = this; - this.connections.delete({ id: id }).then(function() { + this.connections.delete({ id }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete('/connections/' + id) - .reply(500); + nock(API_URL).delete(`/connections/${id}`).reply(500); - this.connections.delete({ id: id }).catch(function(err) { + this.connections.delete({ id }).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete('/connections/' + id) - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .delete(`/connections/${id}`) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.connections.delete({ id: id }).then(function() { + this.connections.delete({ id }).then(() => { expect(request.isDone()).to.be.true; done(); @@ -455,72 +417,68 @@ describe('ConnectionsManager', function() { }); }); - describe('#delete user', function() { - var id = 5; - var email = 'user@domain.com'; - var endpoint = '/connections/' + id + '/users?email=' + encodeURIComponent(email); + describe('#delete user', () => { + const id = 5; + const email = 'user@domain.com'; + const endpoint = `/connections/${id}/users?email=${encodeURIComponent(email)}`; - beforeEach(function() { - this.request = nock(API_URL) - .delete(endpoint, {}) - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).delete(endpoint, {}).reply(200); }); - it('should accept a callback', function(done) { - this.connections.deleteUserByEmail({ id: id, email: email }, done.bind(null, null)); + it('should accept a callback', function (done) { + this.connections.deleteUserByEmail({ id, email }, done.bind(null, null)); }); - it('should return a promise when no callback is given', function(done) { - this.connections.deleteUserByEmail({ id: id, email: email }).then(done.bind(null, null)); + it('should return a promise when no callback is given', function (done) { + this.connections.deleteUserByEmail({ id, email }).then(done.bind(null, null)); }); - it('should perform a DELETE request to ' + endpoint, function(done) { - var request = this.request; + it(`should perform a DELETE request to ${endpoint}`, function (done) { + const { request } = this; - this.connections.deleteUserByEmail({ id: id, email: email }).then(function() { + this.connections.deleteUserByEmail({ id, email }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete(endpoint, {}) - .reply(500); + nock(API_URL).delete(endpoint, {}).reply(500); - this.connections.deleteUserByEmail({ id: id, email: email }).catch(function(err) { + this.connections.deleteUserByEmail({ id, email }).catch((err) => { expect(err).to.exist; done(); }); }); - it('should require a connection id', function() { - expect(this.connections.deleteUserByEmail.bind(null, { email: email })).to.throw( + it('should require a connection id', function () { + expect(this.connections.deleteUserByEmail.bind(null, { email })).to.throw( ArgumentError, 'The connection id cannot be null or undefined' ); }); - it('should require an email', function() { - expect(this.connections.deleteUserByEmail.bind(null, { id: id })).to.throw( + it('should require an email', function () { + expect(this.connections.deleteUserByEmail.bind(null, { id })).to.throw( ArgumentError, 'You must provide an email for the deleteUserByEmail method' ); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .delete(endpoint, {}) - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.connections.deleteUserByEmail({ id: id, email: email }).then(function() { + this.connections.deleteUserByEmail({ id, email }).then(() => { expect(request.isDone()).to.be.true; done(); diff --git a/test/management/custom-domains.tests.js b/test/management/custom-domains.tests.js index 1afcc5433..6442ea2a7 100644 --- a/test/management/custom-domains.tests.js +++ b/test/management/custom-domains.tests.js @@ -1,91 +1,81 @@ -var expect = require('chai').expect; -var nock = require('nock'); +const { expect } = require('chai'); +const nock = require('nock'); -var SRC_DIR = '../../src'; -var API_URL = 'https://tenant.auth0.com'; +const API_URL = 'https://tenant.auth0.com'; -var CustomDomainsManager = require(SRC_DIR + '/management/CustomDomainsManager'); -var ArgumentError = require('rest-facade').ArgumentError; +const CustomDomainsManager = require(`../../src/management/CustomDomainsManager`); +const { ArgumentError } = require('rest-facade'); -describe('CustomDomainsManager', function() { - before(function() { +describe('CustomDomainsManager', () => { + before(function () { this.token = 'TOKEN'; this.customDomains = new CustomDomainsManager({ - headers: { authorization: 'Bearer ' + this.token }, - baseUrl: API_URL + headers: { authorization: `Bearer ${this.token}` }, + baseUrl: API_URL, }); }); - describe('instance', function() { - var methods = ['get', 'getAll', 'create', 'delete', 'verify']; + describe('instance', () => { + const methods = ['get', 'getAll', 'create', 'delete', 'verify']; - methods.forEach(function(method) { - it('should have a ' + method + ' method', function() { + methods.forEach((method) => { + it(`should have a ${method} method`, function () { expect(this.customDomains[method]).to.exist.to.be.an.instanceOf(Function); }); }); }); - describe('#constructor', function() { - it('should error when no options are provided', function() { + describe('#constructor', () => { + it('should error when no options are provided', () => { expect(CustomDomainsManager).to.throw(ArgumentError, 'Must provide manager options'); }); - it('should throw an error when no base URL is provided', function() { - var client = CustomDomainsManager.bind(null, {}); + it('should throw an error when no base URL is provided', () => { + const client = CustomDomainsManager.bind(null, {}); expect(client).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); - it('should throw an error when the base URL is invalid', function() { - var client = CustomDomainsManager.bind(null, { baseUrl: '' }); + it('should throw an error when the base URL is invalid', () => { + const client = CustomDomainsManager.bind(null, { baseUrl: '' }); expect(client).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); - describe('#getAll', function() { - beforeEach(function() { - this.request = nock(API_URL) - .get('/custom-domains') - .reply(200); + describe('#getAll', () => { + beforeEach(function () { + this.request = nock(API_URL).get('/custom-domains').reply(200); }); - it('should accept a callback', function(done) { - this.customDomains.getAll(function() { + it('should accept a callback', function (done) { + this.customDomains.getAll(() => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.customDomains - .getAll() - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.customDomains.getAll().then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/custom-domains') - .reply(500); + nock(API_URL).get('/custom-domains').reply(500); - this.customDomains.getAll().catch(function(err) { + this.customDomains.getAll().catch((err) => { expect(err).to.exist; done(); }); }); - it('should pass the body of the response to the "then" handler', function(done) { + it('should pass the body of the response to the "then" handler', function (done) { nock.cleanAll(); - var data = [{ custom_domain_id: 'cd_0000000000000001' }]; - var request = nock(API_URL) - .get('/custom-domains') - .reply(200, data); + const data = [{ custom_domain_id: 'cd_0000000000000001' }]; + nock(API_URL).get('/custom-domains').reply(200, data); - this.customDomains.getAll().then(function(customDomains) { + this.customDomains.getAll().then((customDomains) => { expect(customDomains).to.be.an.instanceOf(Array); expect(customDomains.length).to.equal(data.length); @@ -96,32 +86,32 @@ describe('CustomDomainsManager', function() { }); }); - it('should perform a GET request to /api/v2/custom-domains', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/custom-domains', function (done) { + const { request } = this; - this.customDomains.getAll().then(function() { + this.customDomains.getAll().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/custom-domains') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.customDomains.getAll().then(function() { + this.customDomains.getAll().then(() => { expect(request.isDone()).to.be.true; done(); }); }); }); - describe('#get', function() { - beforeEach(function() { + describe('#get', () => { + beforeEach(function () { this.data = [ { custom_domain_id: 'cd_0000000000000001', @@ -131,62 +121,60 @@ describe('CustomDomainsManager', function() { type: 'self_managed_certs', origin_domain_name: 'mycompany_cd_0000000000000001.edge.tenants.auth0.com', verification: { - methods: ['object'] - } - } + methods: ['object'], + }, + }, ]; this.request = nock(API_URL) - .get('/custom-domains/' + this.data[0].custom_domain_id) + .get(`/custom-domains/${this.data[0].custom_domain_id}`) .reply(200, this.data); }); - it('should accept a callback', function(done) { - var params = { id: this.data[0].custom_domain_id }; + it('should accept a callback', function (done) { + const params = { id: this.data[0].custom_domain_id }; this.customDomains.get(params, done.bind(null, null)); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.customDomains .get({ id: this.data[0].custom_domain_id }) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should perform a POST request to /api/v2/custom-domains/cd_0000000000000001', function(done) { - var request = this.request; + it('should perform a POST request to /api/v2/custom-domains/cd_0000000000000001', function (done) { + const { request } = this; - this.customDomains.get({ id: this.data[0].custom_domain_id }).then(function() { + this.customDomains.get({ id: this.data[0].custom_domain_id }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/custom-domains/' + this.data.id) - .reply(500); + nock(API_URL).get(`/custom-domains/${this.data.id}`).reply(500); - this.customDomains.get({ id: this.data.id }).catch(function(err) { + this.customDomains.get({ id: this.data.id }).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/custom-domains/' + this.data.id) - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .get(`/custom-domains/${this.data.id}`) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.customDomains.get({ id: this.data.id }).then(function() { + this.customDomains.get({ id: this.data.id }).then(() => { expect(request.isDone()).to.be.true; done(); @@ -194,8 +182,8 @@ describe('CustomDomainsManager', function() { }); }); - describe('#create', function() { - var data = { + describe('#create', () => { + const data = { custom_domain_id: 'cd_0000000000000001', domain: 'login.mycompany.com', primary: false, @@ -203,76 +191,67 @@ describe('CustomDomainsManager', function() { type: 'self_managed_certs', origin_domain_name: 'mycompany_cd_0000000000000001.edge.tenants.auth0.com', verification: { - methods: ['object'] - } + methods: ['object'], + }, }; - beforeEach(function() { - this.request = nock(API_URL) - .post('/custom-domains') - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).post('/custom-domains').reply(200); }); - it('should accept a callback', function(done) { - this.customDomains.create(data, function() { + it('should accept a callback', function (done) { + this.customDomains.create(data, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.customDomains - .create(data) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.customDomains.create(data).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/custom-domains') - .reply(500); + nock(API_URL).post('/custom-domains').reply(500); - this.customDomains.create(data).catch(function(err) { + this.customDomains.create(data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a POST request to /api/v2/custom-domains', function(done) { - var request = this.request; + it('should perform a POST request to /api/v2/custom-domains', function (done) { + const { request } = this; - this.customDomains.create(data).then(function() { + this.customDomains.create(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the data in the body of the request', function(done) { + it('should pass the data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/custom-domains', data) - .reply(200); + const request = nock(API_URL).post('/custom-domains', data).reply(200); - this.customDomains.create(data).then(function() { + this.customDomains.create(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .post('/custom-domains') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.customDomains.create(data).then(function() { + this.customDomains.create(data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -280,56 +259,52 @@ describe('CustomDomainsManager', function() { }); }); - describe('#delete', function() { - var id = 'cd_0000000000000001'; + describe('#delete', () => { + const id = 'cd_0000000000000001'; - beforeEach(function() { - this.request = nock(API_URL) - .delete('/custom-domains/' + id) - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).delete(`/custom-domains/${id}`).reply(200); }); - it('should accept a callback', function(done) { - this.customDomains.delete({ id: id }, done.bind(null, null)); + it('should accept a callback', function (done) { + this.customDomains.delete({ id }, done.bind(null, null)); }); - it('should return a promise when no callback is given', function(done) { - this.customDomains.delete({ id: id }).then(done.bind(null, null)); + it('should return a promise when no callback is given', function (done) { + this.customDomains.delete({ id }).then(done.bind(null, null)); }); - it('should perform a delete request to /custom-domains/' + id, function(done) { - var request = this.request; + it(`should perform a delete request to /custom-domains/${id}`, function (done) { + const { request } = this; - this.customDomains.delete({ id: id }).then(function() { + this.customDomains.delete({ id }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete('/custom-domains/' + id) - .reply(500); + nock(API_URL).delete(`/custom-domains/${id}`).reply(500); - this.customDomains.delete({ id: id }).catch(function(err) { + this.customDomains.delete({ id }).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the authorization header', function(done) { + it('should include the token in the authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete('/custom-domains/' + id) - .matchHeader('authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .delete(`/custom-domains/${id}`) + .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); - this.customDomains.delete({ id: id }).then(function() { + this.customDomains.delete({ id }).then(() => { expect(request.isDone()).to.be.true; done(); @@ -337,58 +312,54 @@ describe('CustomDomainsManager', function() { }); }); - describe('#verify', function() { - beforeEach(function() { + describe('#verify', () => { + beforeEach(function () { this.data = { id: 'cd_0000000000000001' }; this.request = nock(API_URL) - .post('/custom-domains/' + this.data.id + '/verify') + .post(`/custom-domains/${this.data.id}/verify`) .reply(200, this.data); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.customDomains.verify({ id: this.data.id }, done.bind(null, null)); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.customDomains .verify({ id: this.data.id }, {}) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should perform a POST request to /api/v2/custom-domains/cd_0000000000000001/verify', function(done) { - var request = this.request; + it('should perform a POST request to /api/v2/custom-domains/cd_0000000000000001/verify', function (done) { + const { request } = this; - this.customDomains.verify({ id: this.data.id }).then(function() { + this.customDomains.verify({ id: this.data.id }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the new data in the body of the request', function(done) { + it('should include the new data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/custom-domains/' + this.data.id + '/verify') - .reply(200); + const request = nock(API_URL).post(`/custom-domains/${this.data.id}/verify`).reply(200); - this.customDomains.verify({ id: this.data.id }).then(function() { + this.customDomains.verify({ id: this.data.id }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/custom-domains/' + this.data.id + '/verify') - .reply(500); + nock(API_URL).post(`/custom-domains/${this.data.id}/verify`).reply(500); - this.customDomains.verify({ id: this.data.id }).catch(function(err) { + this.customDomains.verify({ id: this.data.id }).catch((err) => { expect(err).to.exist; done(); diff --git a/test/management/device-credentials.tests.js b/test/management/device-credentials.tests.js index 5f1c50d07..fcf2f7b2d 100644 --- a/test/management/device-credentials.tests.js +++ b/test/management/device-credentials.tests.js @@ -1,91 +1,81 @@ -var expect = require('chai').expect; -var nock = require('nock'); +const { expect } = require('chai'); +const nock = require('nock'); -var SRC_DIR = '../../src'; -var API_URL = 'https://tenant.auth0.com'; +const API_URL = 'https://tenant.auth0.com'; -var DeviceCredentialsManager = require(SRC_DIR + '/management/DeviceCredentialsManager'); -var ArgumentError = require('rest-facade').ArgumentError; +const DeviceCredentialsManager = require(`../../src/management/DeviceCredentialsManager`); +const { ArgumentError } = require('rest-facade'); -describe('DeviceCredentialsManager', function() { - before(function() { +describe('DeviceCredentialsManager', () => { + before(function () { this.token = 'TOKEN'; this.credentials = new DeviceCredentialsManager({ - headers: { authorization: 'Bearer ' + this.token }, - baseUrl: API_URL + headers: { authorization: `Bearer ${this.token}` }, + baseUrl: API_URL, }); }); - describe('instance', function() { - var methods = ['createPublicKey', 'getAll', 'delete']; + describe('instance', () => { + const methods = ['createPublicKey', 'getAll', 'delete']; - methods.forEach(function(method) { - it('should have a ' + method + ' method', function() { + methods.forEach((method) => { + it(`should have a ${method} method`, function () { expect(this.credentials[method]).to.exist.to.be.an.instanceOf(Function); }); }); }); - describe('#constructor', function() { - it('should error when no options are provided', function() { + describe('#constructor', () => { + it('should error when no options are provided', () => { expect(DeviceCredentialsManager).to.throw(ArgumentError, 'Must provide manager options'); }); - it('should throw an error when no base URL is provided', function() { - var client = DeviceCredentialsManager.bind(null, {}); + it('should throw an error when no base URL is provided', () => { + const client = DeviceCredentialsManager.bind(null, {}); expect(client).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); - it('should throw an error when the base URL is invalid', function() { - var client = DeviceCredentialsManager.bind(null, { baseUrl: '' }); + it('should throw an error when the base URL is invalid', () => { + const client = DeviceCredentialsManager.bind(null, { baseUrl: '' }); expect(client).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); - describe('#getAll', function() { - beforeEach(function() { - this.request = nock(API_URL) - .get('/device-credentials') - .reply(200); + describe('#getAll', () => { + beforeEach(function () { + this.request = nock(API_URL).get('/device-credentials').reply(200); }); - it('should accept a callback', function(done) { - this.credentials.getAll(function() { + it('should accept a callback', function (done) { + this.credentials.getAll(() => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.credentials - .getAll() - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.credentials.getAll().then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/device-credentials') - .reply(500); + nock(API_URL).get('/device-credentials').reply(500); - this.credentials.getAll().catch(function(err) { + this.credentials.getAll().catch((err) => { expect(err).to.exist; done(); }); }); - it('should pass the body of the response to the "then" handler', function(done) { + it('should pass the body of the response to the "then" handler', function (done) { nock.cleanAll(); - var data = [{ test: true }]; - var request = nock(API_URL) - .get('/device-credentials') - .reply(200, data); + const data = [{ test: true }]; + nock(API_URL).get('/device-credentials').reply(200, data); - this.credentials.getAll().then(function(credentials) { + this.credentials.getAll().then((credentials) => { expect(credentials).to.be.an.instanceOf(Array); expect(credentials.length).to.equal(data.length); @@ -96,42 +86,39 @@ describe('DeviceCredentialsManager', function() { }); }); - it('should perform a GET request to /api/v2/device-credentials', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/device-credentials', function (done) { + const { request } = this; - this.credentials.getAll().then(function() { + this.credentials.getAll().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/device-credentials') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.credentials.getAll().then(function() { + this.credentials.getAll().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the parameters in the query-string', function(done) { + it('should pass the parameters in the query-string', function (done) { nock.cleanAll(); - var params = { + const params = { include_fields: true, - fields: 'test' + fields: 'test', }; - var request = nock(API_URL) - .get('/device-credentials') - .query(params) - .reply(200); + const request = nock(API_URL).get('/device-credentials').query(params).reply(200); - this.credentials.getAll(params).then(function() { + this.credentials.getAll(params).then(() => { expect(request.isDone()).to.be.true; done(); @@ -139,79 +126,73 @@ describe('DeviceCredentialsManager', function() { }); }); - describe('#createPublicKey', function() { - var data = { + describe('#createPublicKey', () => { + const data = { device_name: 'Sample device', type: 'public_key', - user_id: 'github|1234' + user_id: 'github|1234', }; - beforeEach(function() { - this.request = nock(API_URL) - .post('/device-credentials') - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).post('/device-credentials').reply(200); }); - it('should accept a callback', function(done) { - this.credentials.createPublicKey(data, function() { + it('should accept a callback', function (done) { + this.credentials.createPublicKey(data, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.credentials .createPublicKey(data) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/device-credentials') - .reply(500); + nock(API_URL).post('/device-credentials').reply(500); - this.credentials.createPublicKey(data).catch(function(err) { + this.credentials.createPublicKey(data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a POST request to /api/v2/device-credentials', function(done) { - var request = this.request; + it('should perform a POST request to /api/v2/device-credentials', function (done) { + const { request } = this; - this.credentials.createPublicKey(data).then(function() { + this.credentials.createPublicKey(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the data in the body of the request', function(done) { + it('should pass the data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/device-credentials', data) - .reply(200); + const request = nock(API_URL).post('/device-credentials', data).reply(200); - this.credentials.createPublicKey(data).then(function() { + this.credentials.createPublicKey(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .post('/device-credentials') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.credentials.createPublicKey(data).then(function() { + this.credentials.createPublicKey(data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -219,56 +200,52 @@ describe('DeviceCredentialsManager', function() { }); }); - describe('#delete', function() { - var id = 5; + describe('#delete', () => { + const id = 5; - beforeEach(function() { - this.request = nock(API_URL) - .delete('/device-credentials/' + id) - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).delete(`/device-credentials/${id}`).reply(200); }); - it('should accept a callback', function(done) { - this.credentials.delete({ id: id }, done.bind(null, null)); + it('should accept a callback', function (done) { + this.credentials.delete({ id }, done.bind(null, null)); }); - it('should return a promise when no callback is given', function(done) { - this.credentials.delete({ id: id }).then(done.bind(null, null)); + it('should return a promise when no callback is given', function (done) { + this.credentials.delete({ id }).then(done.bind(null, null)); }); - it('should perform a delete request to /device-credentials/' + id, function(done) { - var request = this.request; + it(`should perform a delete request to /device-credentials/${id}`, function (done) { + const { request } = this; - this.credentials.delete({ id: id }).then(function() { + this.credentials.delete({ id }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete('/device-credentials/' + id) - .reply(500); + nock(API_URL).delete(`/device-credentials/${id}`).reply(500); - this.credentials.delete({ id: id }).catch(function(err) { + this.credentials.delete({ id }).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the authorization header', function(done) { + it('should include the token in the authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete('/device-credentials/' + id) - .matchHeader('authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .delete(`/device-credentials/${id}`) + .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); - this.credentials.delete({ id: id }).then(function() { + this.credentials.delete({ id }).then(() => { expect(request.isDone()).to.be.true; done(); diff --git a/test/management/email-provider.tests.js b/test/management/email-provider.tests.js index 2d059b639..520ff1a54 100644 --- a/test/management/email-provider.tests.js +++ b/test/management/email-provider.tests.js @@ -1,141 +1,128 @@ -var expect = require('chai').expect; -var nock = require('nock'); +const { expect } = require('chai'); +const nock = require('nock'); -var SRC_DIR = '../../src'; -var API_URL = 'https://tenant.auth0.com'; +const API_URL = 'https://tenant.auth0.com'; -var EmailProviderManager = require(SRC_DIR + '/management/EmailProviderManager'); -var ArgumentError = require('rest-facade').ArgumentError; +const EmailProviderManager = require(`../../src/management/EmailProviderManager`); +const { ArgumentError } = require('rest-facade'); -describe('EmailProviderManager', function() { - before(function() { +describe('EmailProviderManager', () => { + before(function () { this.token = 'TOKEN'; this.emailProvider = new EmailProviderManager({ - headers: { authorization: 'Bearer ' + this.token }, - baseUrl: API_URL + headers: { authorization: `Bearer ${this.token}` }, + baseUrl: API_URL, }); }); - describe('instance', function() { - var methods = ['configure', 'get', 'update', 'delete']; + describe('instance', () => { + const methods = ['configure', 'get', 'update', 'delete']; - methods.forEach(function(method) { - it('should have a ' + method + ' method', function() { + methods.forEach((method) => { + it(`should have a ${method} method`, function () { expect(this.emailProvider[method]).to.exist.to.be.an.instanceOf(Function); }); }); }); - describe('#constructor', function() { - it('should error when no options are provided', function() { + describe('#constructor', () => { + it('should error when no options are provided', () => { expect(EmailProviderManager).to.throw(ArgumentError, 'Must provide client options'); }); - it('should throw an error when no base URL is provided', function() { - var client = EmailProviderManager.bind(null, {}); + it('should throw an error when no base URL is provided', () => { + const client = EmailProviderManager.bind(null, {}); expect(client).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); - it('should throw an error when the base URL is invalid', function() { - var client = EmailProviderManager.bind(null, { baseUrl: '' }); + it('should throw an error when the base URL is invalid', () => { + const client = EmailProviderManager.bind(null, { baseUrl: '' }); expect(client).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); - describe('#get', function() { - var data = { + describe('#get', () => { + const data = { name: 'Test provider', - options: {} + options: {}, }; - beforeEach(function() { - this.request = nock(API_URL) - .get('/emails/provider') - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).get('/emails/provider').reply(200); }); - it('should accept a callback', function(done) { - this.emailProvider.get(function() { + it('should accept a callback', function (done) { + this.emailProvider.get(() => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.emailProvider - .get() - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.emailProvider.get().then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/emails/provider') - .reply(500); + nock(API_URL).get('/emails/provider').reply(500); - this.emailProvider.get().catch(function(err) { + this.emailProvider.get().catch((err) => { expect(err).to.exist; done(); }); }); - it('should pass the body of the response to the "then" handler', function(done) { + it('should pass the body of the response to the "then" handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/emails/provider') - .reply(200, data); + nock(API_URL).get('/emails/provider').reply(200, data); - this.emailProvider.get().then(function(provider) { + this.emailProvider.get().then((provider) => { expect(provider.id).to.equal(data.id); done(); }); }); - it('should perform a GET request to /api/v2/emails/provider', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/emails/provider', function (done) { + const { request } = this; - this.emailProvider.get().then(function() { + this.emailProvider.get().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/emails/provider') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.emailProvider.get().then(function() { + this.emailProvider.get().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the parameters in the query-string', function(done) { + it('should pass the parameters in the query-string', function (done) { nock.cleanAll(); - var params = { + const params = { include_fields: true, - fields: 'test' + fields: 'test', }; - var request = nock(API_URL) - .get('/emails/provider') - .query(params) - .reply(200); + const request = nock(API_URL).get('/emails/provider').query(params).reply(200); - this.emailProvider.get(params).then(function() { + this.emailProvider.get(params).then(() => { expect(request.isDone()).to.be.true; done(); @@ -143,78 +130,69 @@ describe('EmailProviderManager', function() { }); }); - describe('#configure', function() { - var data = { + describe('#configure', () => { + const data = { name: 'Test provider', - credentials: {} + credentials: {}, }; - beforeEach(function() { - this.request = nock(API_URL) - .post('/emails/provider') - .reply(200, data); + beforeEach(function () { + this.request = nock(API_URL).post('/emails/provider').reply(200, data); }); - it('should accept a callback', function(done) { - this.emailProvider.configure(data, function() { + it('should accept a callback', function (done) { + this.emailProvider.configure(data, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.emailProvider - .configure(data) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.emailProvider.configure(data).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/emails/provider') - .reply(500); + nock(API_URL).post('/emails/provider').reply(500); - this.emailProvider.configure(data).catch(function(err) { + this.emailProvider.configure(data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a POST request to /api/v2/emails/provider', function(done) { - var request = this.request; + it('should perform a POST request to /api/v2/emails/provider', function (done) { + const { request } = this; - this.emailProvider.configure(data).then(function() { + this.emailProvider.configure(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the data in the body of the request', function(done) { + it('should pass the data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/emails/provider', data) - .reply(200); + const request = nock(API_URL).post('/emails/provider', data).reply(200); - this.emailProvider.configure(data).then(function() { + this.emailProvider.configure(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .post('/emails/provider') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.emailProvider.configure(data).then(function() { + this.emailProvider.configure(data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -222,78 +200,69 @@ describe('EmailProviderManager', function() { }); }); - describe('#update', function() { - var data = { + describe('#update', () => { + const data = { name: 'Test provider', - credentials: {} + credentials: {}, }; - beforeEach(function() { - this.request = nock(API_URL) - .patch('/emails/provider') - .reply(200, data); + beforeEach(function () { + this.request = nock(API_URL).patch('/emails/provider').reply(200, data); }); - it('should accept a callback', function(done) { - this.emailProvider.update({}, data, function() { + it('should accept a callback', function (done) { + this.emailProvider.update({}, data, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.emailProvider - .update({}, data) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.emailProvider.update({}, data).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/emails/provider/' + data.id) - .reply(500); + nock(API_URL).patch(`/emails/provider/${data.id}`).reply(500); - this.emailProvider.update({}, data).catch(function(err) { + this.emailProvider.update({}, data).catch((err) => { expect(err).to.exist.to.be.an.instanceOf(Error); done(); }); }); - it('should perform a PATCH request to /api/v2/emails/provider', function(done) { - var request = this.request; + it('should perform a PATCH request to /api/v2/emails/provider', function (done) { + const { request } = this; - this.emailProvider.update({}, data).then(function() { + this.emailProvider.update({}, data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the data in the body of the request', function(done) { + it('should pass the data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/emails/provider', data) - .reply(200); + const request = nock(API_URL).patch('/emails/provider', data).reply(200); - this.emailProvider.update({}, data).then(function() { + this.emailProvider.update({}, data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .patch('/emails/provider') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.emailProvider.update({}, data).then(function() { + this.emailProvider.update({}, data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -301,54 +270,50 @@ describe('EmailProviderManager', function() { }); }); - describe('#delete', function() { - beforeEach(function() { - this.request = nock(API_URL) - .delete('/emails/provider') - .reply(200); + describe('#delete', () => { + beforeEach(function () { + this.request = nock(API_URL).delete('/emails/provider').reply(200); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.emailProvider.delete({}, done.bind(null, null)); }); - it('should return a promise when no callback is given', function(done) { + it('should return a promise when no callback is given', function (done) { this.emailProvider.delete().then(done.bind(null, null)); }); - it('should perform a DELETE request to /emails/provider', function(done) { - var request = this.request; + it('should perform a DELETE request to /emails/provider', function (done) { + const { request } = this; - this.emailProvider.delete().then(function() { + this.emailProvider.delete().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete('/emails/provider') - .reply(500); + nock(API_URL).delete('/emails/provider').reply(500); - this.emailProvider.delete().catch(function(err) { + this.emailProvider.delete().catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .delete('/emails/provider') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.emailProvider.delete().then(function() { + this.emailProvider.delete().then(() => { expect(request.isDone()).to.be.true; done(); diff --git a/test/management/email-templates.tests.js b/test/management/email-templates.tests.js index 24139e5f9..5e737f8b7 100644 --- a/test/management/email-templates.tests.js +++ b/test/management/email-templates.tests.js @@ -1,9 +1,9 @@ -var expect = require('chai').expect; -var nock = require('nock'); -var EmailTemplatesManager = require('../../src/management/EmailTemplatesManager'); -var ArgumentError = require('rest-facade').ArgumentError; +const { expect } = require('chai'); +const nock = require('nock'); +const EmailTemplatesManager = require('../../src/management/EmailTemplatesManager'); +const { ArgumentError } = require('rest-facade'); -var API_URL = 'https://tenant.auth0.com'; +const API_URL = 'https://tenant.auth0.com'; const TEMPLATE_NAME = 'foobar'; const DEFAULT_PARAMS = { name: TEMPLATE_NAME }; const DEFAULT_DATA = { @@ -14,95 +14,93 @@ const DEFAULT_DATA = { subject: '', syntax: 'liquid', urlLifetimeInSeconds: 0, - enabled: false + enabled: false, }; -describe('EmailTemplatesManager', function() { - before(function() { +describe('EmailTemplatesManager', () => { + before(function () { this.token = 'TOKEN'; this.emailTemplates = new EmailTemplatesManager({ - headers: { authorization: 'Bearer ' + this.token }, - baseUrl: API_URL + headers: { authorization: `Bearer ${this.token}` }, + baseUrl: API_URL, }); }); - describe('instance', function() { - var methods = ['get', 'create', 'update']; + describe('instance', () => { + const methods = ['get', 'create', 'update']; - methods.forEach(function(method) { - it('should have a ' + method + ' method', function() { + methods.forEach((method) => { + it(`should have a ${method} method`, function () { expect(this.emailTemplates[method]).to.exist.to.be.an.instanceOf(Function); }); }); }); - describe('#constructor', function() { - it('should error when no options are provided', function() { + describe('#constructor', () => { + it('should error when no options are provided', () => { expect(EmailTemplatesManager).to.throw(ArgumentError, 'Must provide manager options'); }); - it('should throw an error when no base URL is provided', function() { - var client = EmailTemplatesManager.bind(null, {}); + it('should throw an error when no base URL is provided', () => { + const client = EmailTemplatesManager.bind(null, {}); expect(client).to.throw(ArgumentError, 'Must provide a valid string as base URL for the API'); }); - it('should throw an error when the base URL is invalid', function() { - var client = EmailTemplatesManager.bind(null, { baseUrl: '' }); + it('should throw an error when the base URL is invalid', () => { + const client = EmailTemplatesManager.bind(null, { baseUrl: '' }); expect(client).to.throw(ArgumentError, 'Must provide a valid string as base URL for the API'); }); }); - describe('#get', function() { - beforeEach(function() { + describe('#get', () => { + beforeEach(function () { this.request = nock(API_URL) - .get('/email-templates/' + TEMPLATE_NAME) + .get(`/email-templates/${TEMPLATE_NAME}`) .reply(200, DEFAULT_DATA); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.emailTemplates.get(DEFAULT_PARAMS, done.bind(null, null)); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.emailTemplates .get(DEFAULT_PARAMS) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should perform a GET request to /api/v2/email-templates/' + TEMPLATE_NAME, function(done) { - var request = this.request; - this.emailTemplates.get(DEFAULT_PARAMS).then(function() { + it(`should perform a GET request to /api/v2/email-templates/${TEMPLATE_NAME}`, function (done) { + const { request } = this; + this.emailTemplates.get(DEFAULT_PARAMS).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/email-templates/' + TEMPLATE_NAME) - .reply(500); + nock(API_URL).get(`/email-templates/${TEMPLATE_NAME}`).reply(500); - this.emailTemplates.get(DEFAULT_PARAMS).catch(function(err) { + this.emailTemplates.get(DEFAULT_PARAMS).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/email-templates/' + TEMPLATE_NAME) - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .get(`/email-templates/${TEMPLATE_NAME}`) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.emailTemplates.get(DEFAULT_PARAMS).then(function() { + this.emailTemplates.get(DEFAULT_PARAMS).then(() => { expect(request.isDone()).to.be.true; done(); @@ -110,73 +108,67 @@ describe('EmailTemplatesManager', function() { }); }); - describe('#create', function() { - beforeEach(function() { - this.request = nock(API_URL) - .post('/email-templates') - .reply(200); + describe('#create', () => { + beforeEach(function () { + this.request = nock(API_URL).post('/email-templates').reply(200); }); - it('should accept a callback', function(done) { - this.emailTemplates.create(DEFAULT_DATA, function() { + it('should accept a callback', function (done) { + this.emailTemplates.create(DEFAULT_DATA, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.emailTemplates .create(DEFAULT_DATA) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/email-templates') - .reply(500); + nock(API_URL).post('/email-templates').reply(500); - this.emailTemplates.create(DEFAULT_DATA).catch(function(err) { + this.emailTemplates.create(DEFAULT_DATA).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a POST request to /api/v2/email-templates', function(done) { - var request = this.request; + it('should perform a POST request to /api/v2/email-templates', function (done) { + const { request } = this; - this.emailTemplates.create(DEFAULT_DATA).then(function() { + this.emailTemplates.create(DEFAULT_DATA).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the data in the body of the request', function(done) { + it('should pass the data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/email-templates', DEFAULT_DATA) - .reply(200); + const request = nock(API_URL).post('/email-templates', DEFAULT_DATA).reply(200); - this.emailTemplates.create(DEFAULT_DATA).then(function() { + this.emailTemplates.create(DEFAULT_DATA).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .post('/email-templates') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.emailTemplates.create(DEFAULT_DATA).then(function() { + this.emailTemplates.create(DEFAULT_DATA).then(() => { expect(request.isDone()).to.be.true; done(); @@ -184,60 +176,56 @@ describe('EmailTemplatesManager', function() { }); }); - describe('#update', function() { - beforeEach(function() { + describe('#update', () => { + beforeEach(function () { this.patchData = { from: 'new@email.com' }; this.request = nock(API_URL) - .patch('/email-templates/' + TEMPLATE_NAME) + .patch(`/email-templates/${TEMPLATE_NAME}`) .reply(200, DEFAULT_DATA); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.emailTemplates.update(DEFAULT_PARAMS, {}, done.bind(null, null)); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.emailTemplates .update(DEFAULT_PARAMS, {}) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should perform a PATCH request to /api/v2/email-templates/' + TEMPLATE_NAME, function( - done - ) { - var request = this.request; + it(`should perform a PATCH request to /api/v2/email-templates/${TEMPLATE_NAME}`, function (done) { + const { request } = this; - this.emailTemplates.update(DEFAULT_PARAMS, {}).then(function() { + this.emailTemplates.update(DEFAULT_PARAMS, {}).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the new data in the body of the request', function(done) { + it('should include the new data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/email-templates/' + TEMPLATE_NAME, this.patchData) + const request = nock(API_URL) + .patch(`/email-templates/${TEMPLATE_NAME}`, this.patchData) .reply(200); - this.emailTemplates.update(DEFAULT_PARAMS, this.patchData).then(function() { + this.emailTemplates.update(DEFAULT_PARAMS, this.patchData).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/email-templates/' + TEMPLATE_NAME) - .reply(500); + nock(API_URL).patch(`/email-templates/${TEMPLATE_NAME}`).reply(500); - this.emailTemplates.update(DEFAULT_PARAMS, this.patchData).catch(function(err) { + this.emailTemplates.update(DEFAULT_PARAMS, this.patchData).catch((err) => { expect(err).to.exist; done(); diff --git a/test/management/grants.tests.js b/test/management/grants.tests.js index a2ec904db..816217130 100644 --- a/test/management/grants.tests.js +++ b/test/management/grants.tests.js @@ -1,97 +1,87 @@ -var expect = require('chai').expect; -var nock = require('nock'); +const { expect } = require('chai'); +const nock = require('nock'); -var SRC_DIR = '../../src'; -var API_URL = 'https://tenant.auth0.com'; +const API_URL = 'https://tenant.auth0.com'; -var GrantsManager = require(SRC_DIR + '/management/GrantsManager'); -var ArgumentError = require('rest-facade').ArgumentError; +const GrantsManager = require(`../../src/management/GrantsManager`); +const { ArgumentError } = require('rest-facade'); -describe('GrantsManager', function() { - before(function() { +describe('GrantsManager', () => { + before(function () { this.token = 'TOKEN'; this.grants = new GrantsManager({ headers: { - authorization: 'Bearer ' + this.token + authorization: `Bearer ${this.token}`, }, - baseUrl: API_URL + baseUrl: API_URL, }); }); - afterEach(function() { + afterEach(() => { nock.cleanAll(); }); - describe('instance', function() { - var methods = ['getAll', 'delete']; + describe('instance', () => { + const methods = ['getAll', 'delete']; - methods.forEach(function(method) { - it('should have a ' + method + ' method', function() { + methods.forEach((method) => { + it(`should have a ${method} method`, function () { expect(this.grants[method]).to.exist.to.be.an.instanceOf(Function); }); }); }); - describe('#constructor', function() { - it('should error when no options are provided', function() { + describe('#constructor', () => { + it('should error when no options are provided', () => { expect(GrantsManager).to.throw(ArgumentError, 'Must provide client options'); }); - it('should throw an error when no base URL is provided', function() { - var grants = GrantsManager.bind(null, {}); + it('should throw an error when no base URL is provided', () => { + const grants = GrantsManager.bind(null, {}); expect(grants).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); - it('should throw an error when the base URL is invalid', function() { - var grants = GrantsManager.bind(null, { baseUrl: '' }); + it('should throw an error when the base URL is invalid', () => { + const grants = GrantsManager.bind(null, { baseUrl: '' }); expect(grants).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); - describe('#getAll', function() { - beforeEach(function() { - this.request = nock(API_URL) - .get('/grants') - .reply(200); + describe('#getAll', () => { + beforeEach(function () { + this.request = nock(API_URL).get('/grants').reply(200); }); - it('should accept a callback', function(done) { - this.grants.getAll(function() { + it('should accept a callback', function (done) { + this.grants.getAll(() => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.grants - .getAll() - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.grants.getAll().then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/grants') - .reply(500); + nock(API_URL).get('/grants').reply(500); - this.grants.getAll().catch(function(err) { + this.grants.getAll().catch((err) => { expect(err).to.exist; done(); }); }); - it('should pass the body of the response to the "then" handler', function(done) { + it('should pass the body of the response to the "then" handler', function (done) { nock.cleanAll(); - var data = [{ test: true }]; - var request = nock(API_URL) - .get('/grants') - .reply(200, data); + const data = [{ test: true }]; + nock(API_URL).get('/grants').reply(200, data); - this.grants.getAll().then(function(grants) { + this.grants.getAll().then((grants) => { expect(grants).to.be.an.instanceOf(Array); expect(grants.length).to.equal(data.length); @@ -102,68 +92,66 @@ describe('GrantsManager', function() { }); }); - it('should perform a GET request to /api/v2/grants', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/grants', function (done) { + const { request } = this; - this.grants.getAll().then(function() { + this.grants.getAll().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/grants') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.grants.getAll().then(function() { + this.grants.getAll().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the parameters in the query-string', function(done) { + it('should pass the parameters in the query-string', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/grants') .query({ include_fields: true, - fields: 'test' + fields: 'test', }) .reply(200); - this.grants.getAll({ include_fields: true, fields: 'test' }).then(function() { + this.grants.getAll({ include_fields: true, fields: 'test' }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); }); - describe('#delete', function() { - var id = 5; + describe('#delete', () => { + const id = 5; - beforeEach(function() { - this.request = nock(API_URL) - .delete('/grants/' + id) - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).delete(`/grants/${id}`).reply(200); }); - it('should accept a callback', function(done) { - this.grants.delete({ id: id }, done.bind(null, null)); + it('should accept a callback', function (done) { + this.grants.delete({ id }, done.bind(null, null)); }); - it('should return a promise when no callback is given', function(done) { - this.grants.delete({ id: id }).then(done.bind(null, null)); + it('should return a promise when no callback is given', function (done) { + this.grants.delete({ id }).then(done.bind(null, null)); }); - it('should perform a DELETE request to /grants/' + id, function(done) { - var request = this.request; + it(`should perform a DELETE request to /grants/${id}`, function (done) { + const { request } = this; - this.grants.delete({ id: id }).then(function() { + this.grants.delete({ id }).then(() => { expect(request.isDone()).to.be.true; done(); diff --git a/test/management/guardian.tests.js b/test/management/guardian.tests.js index 9f313f220..66f38d678 100644 --- a/test/management/guardian.tests.js +++ b/test/management/guardian.tests.js @@ -1,23 +1,22 @@ -var expect = require('chai').expect; -var nock = require('nock'); +const { expect } = require('chai'); +const nock = require('nock'); -var SRC_DIR = '../../src'; -var API_URL = 'https://tenants.auth0.com'; +const API_URL = 'https://tenants.auth0.com'; -var GuardianManager = require(SRC_DIR + '/management/GuardianManager'); -var ArgumentError = require('rest-facade').ArgumentError; +const GuardianManager = require(`../../src/management/GuardianManager`); +const { ArgumentError } = require('rest-facade'); -describe('GuardianManager', function() { - before(function() { +describe('GuardianManager', () => { + before(function () { this.token = 'TOKEN'; this.guardian = new GuardianManager({ - headers: { authorization: 'Bearer ' + this.token }, - baseUrl: API_URL + headers: { authorization: `Bearer ${this.token}` }, + baseUrl: API_URL, }); }); - describe('instance', function() { - var methods = [ + describe('instance', () => { + const methods = [ 'getGuardianEnrollment', 'deleteGuardianEnrollment', 'getFactors', @@ -31,170 +30,159 @@ describe('GuardianManager', function() { 'getPhoneFactorSelectedProvider', 'updatePhoneFactorSelectedProvider', 'getPhoneFactorMessageTypes', - 'updatePhoneFactorMessageTypes' + 'updatePhoneFactorMessageTypes', ]; - methods.forEach(function(method) { - it('should have a ' + method + ' method', function() { + methods.forEach((method) => { + it(`should have a ${method} method`, function () { expect(this.guardian[method]).to.exist.to.be.an.instanceOf(Function); }); }); }); - describe('#constructor', function() { - it('should error when no options are provided', function() { + describe('#constructor', () => { + it('should error when no options are provided', () => { expect(GuardianManager).to.throw(ArgumentError, 'Must provide manager options'); }); - it('should throw an error when no base URL is provided', function() { - var manager = GuardianManager.bind(null, {}); + it('should throw an error when no base URL is provided', () => { + const manager = GuardianManager.bind(null, {}); expect(manager).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); - it('should throw an error when the base URL is invalid', function() { - var manager = GuardianManager.bind(null, { baseUrl: '' }); + it('should throw an error when the base URL is invalid', () => { + const manager = GuardianManager.bind(null, { baseUrl: '' }); expect(manager).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); - describe('#getGuardianEnrollment', function() { - beforeEach(function() { + describe('#getGuardianEnrollment', () => { + beforeEach(function () { this.data = { - id: 'dev_0000000000000001' + id: 'dev_0000000000000001', }; this.params = { id: this.data.id }; - this.request = nock(API_URL) - .get('/guardian/enrollments/' + this.data.id) - .reply(200); + this.request = nock(API_URL).get(`/guardian/enrollments/${this.data.id}`).reply(200); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.guardian.getGuardianEnrollment(this.params, done.bind(null, null)); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.guardian .getGuardianEnrollment(this.params) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/guardian/enrollment') - .reply(500); + nock(API_URL).get('/guardian/enrollment').reply(500); - this.guardian.getGuardianEnrollment(this.params).catch(function(err) { + this.guardian.getGuardianEnrollment(this.params).catch((err) => { expect(err).to.exist; done(); }); }); - it('should pass the body of the response to the "then" handler', function(done) { + it('should pass the body of the response to the "then" handler', function (done) { nock.cleanAll(); - var data = { + const data = { id: 'dev_0000000000000001', status: 'pending', name: 'iPhone 7', identifier: '76dc-a90c-a88c-a90c-a88c-a88c-a90c', phone_number: '+1 999999999999', enrolled_at: '2016-07-12T17:56:26.804Z', - last_auth: '2016-07-12T17:56:26.804Z' + last_auth: '2016-07-12T17:56:26.804Z', }; - var request = nock(API_URL) - .get('/guardian/enrollments/' + data.id) - .reply(200, data); + nock(API_URL).get(`/guardian/enrollments/${data.id}`).reply(200, data); - this.guardian.getGuardianEnrollment(this.params).then(function(enrollment) { + this.guardian.getGuardianEnrollment(this.params).then((enrollment) => { expect(enrollment).to.deep.equal(data); done(); }); }); - it('should perform a GET request to /api/v2/guardian/enrollments', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/guardian/enrollments', function (done) { + const { request } = this; - var params = { id: this.data.id }; - this.guardian.getGuardianEnrollment(this.params).then(function() { + this.guardian.getGuardianEnrollment(this.params).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/guardian/enrollments/' + this.data.id) - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .get(`/guardian/enrollments/${this.data.id}`) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.guardian.getGuardianEnrollment(this.params).then(function() { + this.guardian.getGuardianEnrollment(this.params).then(() => { expect(request.isDone()).to.be.true; done(); }); }); }); - describe('#deleteGuardianEnrollment', function() { - beforeEach(function() { + describe('#deleteGuardianEnrollment', () => { + beforeEach(function () { this.data = { - id: 'dev_0000000000000001' + id: 'dev_0000000000000001', }; - this.request = nock(API_URL) - .delete('/guardian/enrollments/' + this.data.id) - .reply(200); + this.request = nock(API_URL).delete(`/guardian/enrollments/${this.data.id}`).reply(200); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.guardian.deleteGuardianEnrollment(this.data, done.bind(null, null)); }); - it('should return a promise when no callback is given', function(done) { + it('should return a promise when no callback is given', function (done) { this.guardian.deleteGuardianEnrollment(this.data).then(done.bind(null, null)); }); - it('should perform a DELETE request to /guardian/enrollments/:id', function(done) { - var request = this.request; + it('should perform a DELETE request to /guardian/enrollments/:id', function (done) { + const { request } = this; - this.guardian.deleteGuardianEnrollment(this.data).then(function() { + this.guardian.deleteGuardianEnrollment(this.data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete('/guardian/enrollments/' + this.data.id) - .reply(500); + nock(API_URL).delete(`/guardian/enrollments/${this.data.id}`).reply(500); - this.guardian.deleteGuardianEnrollment(this.data).catch(function(err) { + this.guardian.deleteGuardianEnrollment(this.data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the authorization header', function(done) { + it('should include the token in the authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete('/guardian/enrollments/' + this.data.id) - .matchHeader('authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .delete(`/guardian/enrollments/${this.data.id}`) + .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); - this.guardian.deleteGuardianEnrollment(this.data).then(function() { + this.guardian.deleteGuardianEnrollment(this.data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -202,79 +190,73 @@ describe('GuardianManager', function() { }); }); - describe('#createEnrollmentTicket', function() { - var data = { + describe('#createEnrollmentTicket', () => { + const data = { user_id: '', email: '', - send_mail: false + send_mail: false, }; - beforeEach(function() { - this.request = nock(API_URL) - .post('/guardian/enrollments/ticket') - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).post('/guardian/enrollments/ticket').reply(200); }); - it('should accept a callback', function(done) { - this.guardian.createEnrollmentTicket(data, function() { + it('should accept a callback', function (done) { + this.guardian.createEnrollmentTicket(data, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.guardian .createEnrollmentTicket(data) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/guardian/enrollments/ticket') - .reply(500); + nock(API_URL).post('/guardian/enrollments/ticket').reply(500); - this.guardian.createEnrollmentTicket(data).catch(function(err) { + this.guardian.createEnrollmentTicket(data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a POST request to /api/v2/guardian/enrollments/ticket', function(done) { - var request = this.request; + it('should perform a POST request to /api/v2/guardian/enrollments/ticket', function (done) { + const { request } = this; - this.guardian.createEnrollmentTicket(data).then(function() { + this.guardian.createEnrollmentTicket(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the data in the body of the request', function(done) { + it('should pass the data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/guardian/enrollments/ticket', data) - .reply(200); + const request = nock(API_URL).post('/guardian/enrollments/ticket', data).reply(200); - this.guardian.createEnrollmentTicket(data).then(function() { + this.guardian.createEnrollmentTicket(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .post('/guardian/enrollments/ticket') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.guardian.createEnrollmentTicket(data).then(function() { + this.guardian.createEnrollmentTicket(data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -282,65 +264,58 @@ describe('GuardianManager', function() { }); }); - describe('#getFactors', function() { - beforeEach(function() { + describe('#getFactors', () => { + beforeEach(function () { this.data = [ { name: 'sms', enabled: true, trial_expired: false }, { name: 'push-notification', enabled: false, trial_expired: false }, { name: 'otp', enabled: false, trial_expired: false }, { name: 'email', enabled: false, trial_expired: false }, - { name: 'duo', enabled: false, trial_expired: false } + { name: 'duo', enabled: false, trial_expired: false }, ]; - this.request = nock(API_URL) - .get('/guardian/factors') - .reply(200, this.data); + this.request = nock(API_URL).get('/guardian/factors').reply(200, this.data); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.guardian.getFactors(done.bind(null, null)); }); - it('should return a promise if no callback is given', function(done) { - this.guardian - .getFactors() - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.guardian.getFactors().then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should perform a GET request to /api/v2/guardian/factors', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/guardian/factors', function (done) { + const { request } = this; - this.guardian.getFactors().then(function() { + this.guardian.getFactors().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/guardian/factors') - .reply(500); + nock(API_URL).get('/guardian/factors').reply(500); - this.guardian.getFactors().catch(function(err) { + this.guardian.getFactors().catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/guardian/factors') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.guardian.getFactors().then(function() { + this.guardian.getFactors().then(() => { expect(request.isDone()).to.be.true; done(); @@ -348,62 +323,60 @@ describe('GuardianManager', function() { }); }); - describe('#getFactorSettings', function() { - beforeEach(function() { + describe('#getFactorSettings', () => { + beforeEach(function () { this.params = { name: 'webauthn-roaming' }; this.data = { userVerification: 'discouraged', - overrideRelyingParty: false + overrideRelyingParty: false, }; this.request = nock(API_URL) - .get('/guardian/factors/' + this.params.name + '/settings') + .get(`/guardian/factors/${this.params.name}/settings`) .reply(200, this.data); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.guardian.getFactorSettings(this.params, done.bind(null, null)); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.guardian .getFactorSettings(this.params) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should perform a GET request to /api/v2/guardian/factors/webauthn-roaming/settings', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/guardian/factors/webauthn-roaming/settings', function (done) { + const { request } = this; - this.guardian.getFactorSettings(this.params).then(function() { + this.guardian.getFactorSettings(this.params).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/guardian/factors/' + this.params.name + '/settings') - .reply(500); + nock(API_URL).get(`/guardian/factors/${this.params.name}/settings`).reply(500); - this.guardian.getFactorSettings(this.params).catch(function(err) { + this.guardian.getFactorSettings(this.params).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/guardian/factors/' + this.params.name + '/settings') - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .get(`/guardian/factors/${this.params.name}/settings`) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.guardian.getFactorSettings(this.params).then(function() { + this.guardian.getFactorSettings(this.params).then(() => { expect(request.isDone()).to.be.true; done(); @@ -411,65 +384,65 @@ describe('GuardianManager', function() { }); }); - describe('#getFactorProvider', function() { - beforeEach(function() { + describe('#getFactorProvider', () => { + beforeEach(function () { this.params = { name: 'sms', provider: 'twilio' }; this.data = { from: '+1223323', messaging_service_sid: '5dEkAiHLPCuQ1uJj4qNXcAnERFAL6cpq', auth_token: 'zw5Ku6z2sxhd0ZVXto5SDHX6KPDByJPU', - sid: 'wywA2BH4VqTpfywiDuyDAYZL3xQjoO40' + sid: 'wywA2BH4VqTpfywiDuyDAYZL3xQjoO40', }; this.request = nock(API_URL) - .get('/guardian/factors/' + this.params.name + '/providers/' + this.params.provider) + .get(`/guardian/factors/${this.params.name}/providers/${this.params.provider}`) .reply(200, this.data); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.guardian.getFactorProvider(this.params, done.bind(null, null)); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.guardian .getFactorProvider(this.params) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should perform a GET request to /api/v2/guardian/factors/sms/twilio', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/guardian/factors/sms/twilio', function (done) { + const { request } = this; - this.guardian.getFactorProvider(this.params).then(function() { + this.guardian.getFactorProvider(this.params).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('guardian/factors/' + this.params.name + '/providers/' + this.params.provider) + nock(API_URL) + .get(`guardian/factors/${this.params.name}/providers/${this.params.provider}`) .reply(500); - this.guardian.getFactorProvider(this.params).catch(function(err) { + this.guardian.getFactorProvider(this.params).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/guardian/factors/' + this.params.name + '/providers/' + this.params.provider) - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .get(`/guardian/factors/${this.params.name}/providers/${this.params.provider}`) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.guardian.getFactorProvider(this.params).then(function() { + this.guardian.getFactorProvider(this.params).then(() => { expect(request.isDone()).to.be.true; done(); @@ -477,80 +450,77 @@ describe('GuardianManager', function() { }); }); - describe('#updateFactorProvider', function() { - beforeEach(function() { + describe('#updateFactorProvider', () => { + beforeEach(function () { this.params = { name: 'sms', provider: 'twilio' }; this.data = { from: '+1223323', messaging_service_sid: '5dEkAiHLPCuQ1uJj4qNXcAnERFAL6cpq', auth_token: 'zw5Ku6z2sxhd0ZVXto5SDHX6KPDByJPU', - sid: 'wywA2BH4VqTpfywiDuyDAYZL3xQjoO40' + sid: 'wywA2BH4VqTpfywiDuyDAYZL3xQjoO40', }; }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.guardian.updateFactorProvider({ id: 5 }, {}, done.bind(null, null)); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.guardian .updateFactorProvider(this.params, {}) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should perform a PUT request to /api/v2/guardian/factors/sms/providers/twilio', function(done) { - var request = nock(API_URL) - .put('/guardian/factors/' + this.params.name + '/providers/' + this.params.provider) + it('should perform a PUT request to /api/v2/guardian/factors/sms/providers/twilio', function (done) { + const request = nock(API_URL) + .put(`/guardian/factors/${this.params.name}/providers/${this.params.provider}`) .reply(200, this.data); - this.guardian.updateFactorProvider(this.params, this.data).then(function() { + this.guardian.updateFactorProvider(this.params, this.data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the new data in the body of the request', function(done) { + it('should include the new data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .put( - '/guardian/factors/' + this.params.name + '/providers/' + this.params.provider, - this.data - ) + const request = nock(API_URL) + .put(`/guardian/factors/${this.params.name}/providers/${this.params.provider}`, this.data) .reply(200); - this.guardian.updateFactorProvider(this.params, this.data).then(function() { + this.guardian.updateFactorProvider(this.params, this.data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .put('/guardian/factors/' + this.params.name + '/providers/' + this.params.provider) + nock(API_URL) + .put(`/guardian/factors/${this.params.name}/providers/${this.params.provider}`) .reply(500); - this.guardian.updateFactorProvider(this.params, this.data).catch(function(err) { + this.guardian.updateFactorProvider(this.params, this.data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .put('/guardian/factors/' + this.params.name + '/providers/' + this.params.provider) - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .put(`/guardian/factors/${this.params.name}/providers/${this.params.provider}`) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.guardian.updateFactorProvider(this.params, this.data).then(function() { + this.guardian.updateFactorProvider(this.params, this.data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -558,65 +528,61 @@ describe('GuardianManager', function() { }); }); - describe('#getFactorTemplates', function() { - beforeEach(function() { + describe('#getFactorTemplates', () => { + beforeEach(function () { this.params = { name: 'sms' }; this.data = { enrollment_message: '{{code}} is your verification code for {{tenant.friendly_name}}. Please enter this code to verify your enrollment.', - verification_message: '{{code}} is your verification code for {{tenant.friendly_name}}' + verification_message: '{{code}} is your verification code for {{tenant.friendly_name}}', }; - this.request = nock(API_URL) - .get('/guardian/factors/sms/templates') - .reply(200, this.data); + this.request = nock(API_URL).get('/guardian/factors/sms/templates').reply(200, this.data); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.guardian.getFactorTemplates(this.params, done.bind(null, null)); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.guardian .getFactorTemplates(this.params) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should perform a GET request to /api/v2/guardian/factors/sms/templates', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/guardian/factors/sms/templates', function (done) { + const { request } = this; - this.guardian.getFactorTemplates(this.params).then(function() { + this.guardian.getFactorTemplates(this.params).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/guardian/factors/sms/templates') - .reply(500); + nock(API_URL).get('/guardian/factors/sms/templates').reply(500); - this.guardian.getFactorTemplates(this.params).catch(function(err) { + this.guardian.getFactorTemplates(this.params).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/guardian/factors/sms/templates') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.guardian.getFactorTemplates(this.params).then(function() { + this.guardian.getFactorTemplates(this.params).then(() => { expect(request.isDone()).to.be.true; done(); @@ -624,76 +590,74 @@ describe('GuardianManager', function() { }); }); - describe('#updateFactorTemplates', function() { - beforeEach(function() { + describe('#updateFactorTemplates', () => { + beforeEach(function () { this.params = { name: 'sms' }; this.data = { enrollment_message: '{{code}} is your verification code for {{tenant.friendly_name}}. Please enter this code to verify your enrollment.', - verification_message: '{{code}} is your verification code for {{tenant.friendly_name}}' + verification_message: '{{code}} is your verification code for {{tenant.friendly_name}}', }; }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.guardian.updateFactorTemplates(this.params, {}, done.bind(null, null)); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.guardian .updateFactorTemplates(this.params, this.data) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should perform a PUT request to /api/v2/guardian/factors/sms/templates', function(done) { - var request = nock(API_URL) - .put('/guardian/factors/' + this.params.name + '/templates') + it('should perform a PUT request to /api/v2/guardian/factors/sms/templates', function (done) { + const request = nock(API_URL) + .put(`/guardian/factors/${this.params.name}/templates`) .reply(200, this.data); - this.guardian.updateFactorTemplates(this.params, this.data).then(function() { + this.guardian.updateFactorTemplates(this.params, this.data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the new data in the body of the request', function(done) { + it('should include the new data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .put('/guardian/factors/' + this.params.name + '/templates', this.data) + const request = nock(API_URL) + .put(`/guardian/factors/${this.params.name}/templates`, this.data) .reply(200); - this.guardian.updateFactorTemplates(this.params, this.data).then(function() { + this.guardian.updateFactorTemplates(this.params, this.data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .put('/guardian/factors/' + this.params.name + '/templates') - .reply(500); + nock(API_URL).put(`/guardian/factors/${this.params.name}/templates`).reply(500); - this.guardian.updateFactorTemplates(this.params, this.data).catch(function(err) { + this.guardian.updateFactorTemplates(this.params, this.data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .put('/guardian/factors/' + this.params.name + '/templates') - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .put(`/guardian/factors/${this.params.name}/templates`) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.guardian.updateFactorTemplates(this.params, this.data).then(function() { + this.guardian.updateFactorTemplates(this.params, this.data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -701,74 +665,72 @@ describe('GuardianManager', function() { }); }); - describe('#updateFactor', function() { - beforeEach(function() { + describe('#updateFactor', () => { + beforeEach(function () { this.params = { name: 'sms' }; this.data = { - enabled: true + enabled: true, }; }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.guardian.updateFactor(this.params, {}, done.bind(null, null)); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.guardian .updateFactor(this.params, this.data) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should perform a PUT request to /api/v2/guardian/factors/sms', function(done) { - var request = nock(API_URL) - .put('/guardian/factors/' + this.params.name) + it('should perform a PUT request to /api/v2/guardian/factors/sms', function (done) { + const request = nock(API_URL) + .put(`/guardian/factors/${this.params.name}`) .reply(200, this.data); - this.guardian.updateFactor(this.params, this.data).then(function() { + this.guardian.updateFactor(this.params, this.data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the new data in the body of the request', function(done) { + it('should include the new data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .put('/guardian/factors/' + this.params.name, this.data) + const request = nock(API_URL) + .put(`/guardian/factors/${this.params.name}`, this.data) .reply(200); - this.guardian.updateFactor(this.params, this.data).then(function() { + this.guardian.updateFactor(this.params, this.data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .put('/guardian/factors/' + this.params.name) - .reply(500); + nock(API_URL).put(`/guardian/factors/${this.params.name}`).reply(500); - this.guardian.updateFactor(this.params, this.data).catch(function(err) { + this.guardian.updateFactor(this.params, this.data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .put('/guardian/factors/' + this.params.name) - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .put(`/guardian/factors/${this.params.name}`) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.guardian.updateFactor(this.params, this.data).then(function() { + this.guardian.updateFactor(this.params, this.data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -776,75 +738,73 @@ describe('GuardianManager', function() { }); }); - describe('#updateFactorSettings', function() { - beforeEach(function() { + describe('#updateFactorSettings', () => { + beforeEach(function () { this.params = { name: 'webauthn-roaming' }; this.data = { userVerification: 'discouraged', - overrideRelyingParty: false + overrideRelyingParty: false, }; }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.guardian.updateFactorSettings({ id: 5 }, {}, done.bind(null, null)); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.guardian .updateFactorSettings(this.params, {}) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should perform a PUT request to /api/v2/guardian/factors/webauthn-roaming/settings', function(done) { - var request = nock(API_URL) - .put('/guardian/factors/' + this.params.name + '/settings') + it('should perform a PUT request to /api/v2/guardian/factors/webauthn-roaming/settings', function (done) { + const request = nock(API_URL) + .put(`/guardian/factors/${this.params.name}/settings`) .reply(200, this.data); - this.guardian.updateFactorSettings(this.params, this.data).then(function() { + this.guardian.updateFactorSettings(this.params, this.data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the new data in the body of the request', function(done) { + it('should include the new data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .put('/guardian/factors/' + this.params.name + '/settings', this.data) + const request = nock(API_URL) + .put(`/guardian/factors/${this.params.name}/settings`, this.data) .reply(200); - this.guardian.updateFactorSettings(this.params, this.data).then(function() { + this.guardian.updateFactorSettings(this.params, this.data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .put('/guardian/factors/' + this.params.name + '/settings') - .reply(500); + nock(API_URL).put(`/guardian/factors/${this.params.name}/settings`).reply(500); - this.guardian.updateFactorSettings(this.params, this.data).catch(function(err) { + this.guardian.updateFactorSettings(this.params, this.data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .put('/guardian/factors/' + this.params.name + '/settings') - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .put(`/guardian/factors/${this.params.name}/settings`) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.guardian.updateFactorSettings(this.params, this.data).then(function() { + this.guardian.updateFactorSettings(this.params, this.data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -852,59 +812,52 @@ describe('GuardianManager', function() { }); }); - describe('#getPolicies', function() { - beforeEach(function() { + describe('#getPolicies', () => { + beforeEach(function () { this.data = ['all-applications']; - this.request = nock(API_URL) - .get('/guardian/policies') - .reply(200, this.data); + this.request = nock(API_URL).get('/guardian/policies').reply(200, this.data); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.guardian.getPolicies(done.bind(null, null)); }); - it('should return a promise if no callback is given', function(done) { - this.guardian - .getPolicies() - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.guardian.getPolicies().then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should perform a GET request to /api/v2/guardian/policies', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/guardian/policies', function (done) { + const { request } = this; - this.guardian.getPolicies().then(function() { + this.guardian.getPolicies().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/guardian/policies') - .reply(500); + nock(API_URL).get('/guardian/policies').reply(500); - this.guardian.getPolicies().catch(function(err) { + this.guardian.getPolicies().catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/guardian/policies') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.guardian.getPolicies().then(function() { + this.guardian.getPolicies().then(() => { expect(request.isDone()).to.be.true; done(); @@ -912,72 +865,66 @@ describe('GuardianManager', function() { }); }); - describe('#updatePolicies', function() { - beforeEach(function() { + describe('#updatePolicies', () => { + beforeEach(function () { this.params = {}; this.data = ['all-applications']; }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.guardian.updatePolicies(this.params, this.data, done.bind(null, null)); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.guardian .updatePolicies(this.params, this.data) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should perform a PUT request to /api/v2/guardian/policies', function(done) { - var request = nock(API_URL) - .put('/guardian/policies') - .reply(200, this.data); + it('should perform a PUT request to /api/v2/guardian/policies', function (done) { + const request = nock(API_URL).put('/guardian/policies').reply(200, this.data); - this.guardian.updatePolicies(this.params, this.data).then(function() { + this.guardian.updatePolicies(this.params, this.data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the new data in the body of the request', function(done) { + it('should include the new data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .put('/guardian/policies', this.data) - .reply(200); + const request = nock(API_URL).put('/guardian/policies', this.data).reply(200); - this.guardian.updatePolicies(this.params, this.data).then(function() { + this.guardian.updatePolicies(this.params, this.data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .put('/guardian/policies') - .reply(500); + nock(API_URL).put('/guardian/policies').reply(500); - this.guardian.updatePolicies(this.params, this.data).catch(function(err) { + this.guardian.updatePolicies(this.params, this.data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .put('/guardian/policies') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.guardian.updatePolicies(this.params, this.data).then(function() { + this.guardian.updatePolicies(this.params, this.data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -985,10 +932,10 @@ describe('GuardianManager', function() { }); }); - describe('#getPhoneFactorSelectedProvider', function() { - beforeEach(function() { + describe('#getPhoneFactorSelectedProvider', () => { + beforeEach(function () { this.data = { - provider: 'twilio' + provider: 'twilio', }; this.request = nock(API_URL) @@ -996,50 +943,48 @@ describe('GuardianManager', function() { .reply(200, this.data); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.guardian.getPhoneFactorSelectedProvider(done.bind(null, null)); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.guardian .getPhoneFactorSelectedProvider() .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should perform a GET request to /api/v2/guardian/factors/sms/selected-provider', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/guardian/factors/sms/selected-provider', function (done) { + const { request } = this; - this.guardian.getPhoneFactorSelectedProvider().then(function() { + this.guardian.getPhoneFactorSelectedProvider().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/guardian/factors/sms/selected-provider') - .reply(500); + nock(API_URL).get('/guardian/factors/sms/selected-provider').reply(500); - this.guardian.getPhoneFactorSelectedProvider().catch(function(err) { + this.guardian.getPhoneFactorSelectedProvider().catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/guardian/factors/sms/selected-provider') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.guardian.getPhoneFactorSelectedProvider().then(function() { + this.guardian.getPhoneFactorSelectedProvider().then(() => { expect(request.isDone()).to.be.true; done(); @@ -1047,15 +992,15 @@ describe('GuardianManager', function() { }); }); - describe('#updatePhoneFactorSelectedProvider', function() { - beforeEach(function() { + describe('#updatePhoneFactorSelectedProvider', () => { + beforeEach(function () { this.params = {}; this.data = { - provider: 'twilio' + provider: 'twilio', }; }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.guardian.updatePhoneFactorSelectedProvider( this.params, this.data, @@ -1063,62 +1008,60 @@ describe('GuardianManager', function() { ); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.guardian .updatePhoneFactorSelectedProvider(this.params, this.data) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should perform a PUT request to /api/v2/guardian/factors/sms/selected-provider', function(done) { - var request = nock(API_URL) + it('should perform a PUT request to /api/v2/guardian/factors/sms/selected-provider', function (done) { + const request = nock(API_URL) .put('/guardian/factors/sms/selected-provider') .reply(200, this.data); - this.guardian.updatePhoneFactorSelectedProvider(this.params, this.data).then(function() { + this.guardian.updatePhoneFactorSelectedProvider(this.params, this.data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the new data in the body of the request', function(done) { + it('should include the new data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .put('/guardian/factors/sms/selected-provider', this.data) .reply(200); - this.guardian.updatePhoneFactorSelectedProvider(this.params, this.data).then(function() { + this.guardian.updatePhoneFactorSelectedProvider(this.params, this.data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .put('/guardian/factors/sms/selected-provider') - .reply(500); + nock(API_URL).put('/guardian/factors/sms/selected-provider').reply(500); - this.guardian.updatePhoneFactorSelectedProvider(this.params, this.data).catch(function(err) { + this.guardian.updatePhoneFactorSelectedProvider(this.params, this.data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .put('/guardian/factors/sms/selected-provider') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.guardian.updatePhoneFactorSelectedProvider(this.params, this.data).then(function() { + this.guardian.updatePhoneFactorSelectedProvider(this.params, this.data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -1126,10 +1069,10 @@ describe('GuardianManager', function() { }); }); - describe('#getPhoneFactorMessageTypes', function() { - beforeEach(function() { + describe('#getPhoneFactorMessageTypes', () => { + beforeEach(function () { this.data = { - message_types: ['sms', 'voice'] + message_types: ['sms', 'voice'], }; this.request = nock(API_URL) @@ -1137,50 +1080,48 @@ describe('GuardianManager', function() { .reply(200, this.data); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.guardian.getPhoneFactorMessageTypes(done.bind(null, null)); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.guardian .getPhoneFactorMessageTypes() .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should perform a GET request to /api/v2/guardian/factors/phone/message-types', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/guardian/factors/phone/message-types', function (done) { + const { request } = this; - this.guardian.getPhoneFactorMessageTypes().then(function() { + this.guardian.getPhoneFactorMessageTypes().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/guardian/factors/phone/message-types') - .reply(500); + nock(API_URL).get('/guardian/factors/phone/message-types').reply(500); - this.guardian.getPhoneFactorMessageTypes().catch(function(err) { + this.guardian.getPhoneFactorMessageTypes().catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/guardian/factors/phone/message-types') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.guardian.getPhoneFactorMessageTypes().then(function() { + this.guardian.getPhoneFactorMessageTypes().then(() => { expect(request.isDone()).to.be.true; done(); @@ -1188,74 +1129,72 @@ describe('GuardianManager', function() { }); }); - describe('#updatePhoneFactorMessageTypes', function() { - beforeEach(function() { + describe('#updatePhoneFactorMessageTypes', () => { + beforeEach(function () { this.params = {}; this.data = { - message_types: ['sms', 'voice'] + message_types: ['sms', 'voice'], }; }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.guardian.updatePhoneFactorMessageTypes(this.params, this.data, done.bind(null, null)); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.guardian .updatePhoneFactorMessageTypes(this.params, this.data) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should perform a PUT request to /api/v2/guardian/factors/phone/message-types', function(done) { - var request = nock(API_URL) + it('should perform a PUT request to /api/v2/guardian/factors/phone/message-types', function (done) { + const request = nock(API_URL) .put('/guardian/factors/phone/message-types') .reply(200, this.data); - this.guardian.updatePhoneFactorMessageTypes(this.params, this.data).then(function() { + this.guardian.updatePhoneFactorMessageTypes(this.params, this.data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the new data in the body of the request', function(done) { + it('should include the new data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .put('/guardian/factors/phone/message-types', this.data) .reply(200); - this.guardian.updatePhoneFactorMessageTypes(this.params, this.data).then(function() { + this.guardian.updatePhoneFactorMessageTypes(this.params, this.data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .put('/guardian/factors/phone/message-types') - .reply(500); + nock(API_URL).put('/guardian/factors/phone/message-types').reply(500); - this.guardian.updatePhoneFactorMessageTypes(this.params, this.data).catch(function(err) { + this.guardian.updatePhoneFactorMessageTypes(this.params, this.data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .put('/guardian/factors/phone/message-types') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.guardian.updatePhoneFactorMessageTypes(this.params, this.data).then(function() { + this.guardian.updatePhoneFactorMessageTypes(this.params, this.data).then(() => { expect(request.isDone()).to.be.true; done(); diff --git a/test/management/hooks.tests.js b/test/management/hooks.tests.js index 7afc756b7..a5169b510 100644 --- a/test/management/hooks.tests.js +++ b/test/management/hooks.tests.js @@ -1,23 +1,22 @@ -var expect = require('chai').expect; -var nock = require('nock'); +const { expect } = require('chai'); +const nock = require('nock'); -var SRC_DIR = '../../src'; -var API_URL = 'https://tenant.auth0.com'; +const API_URL = 'https://tenant.auth0.com'; -var HookManager = require(SRC_DIR + '/management/HooksManager'); -var ArgumentError = require('rest-facade').ArgumentError; +const HookManager = require(`../../src/management/HooksManager`); +const { ArgumentError } = require('rest-facade'); -describe('HookManager', function() { - before(function() { +describe('HookManager', () => { + before(function () { this.token = 'TOKEN'; this.hooks = new HookManager({ - headers: { authorization: 'Bearer ' + this.token }, - baseUrl: API_URL + headers: { authorization: `Bearer ${this.token}` }, + baseUrl: API_URL, }); }); - describe('instance', function() { - var methods = [ + describe('instance', () => { + const methods = [ 'get', 'getAll', 'create', @@ -26,76 +25,67 @@ describe('HookManager', function() { 'getSecrets', 'addSecrets', 'updateSecrets', - 'removeSecrets' + 'removeSecrets', ]; - methods.forEach(function(method) { - it('should have a ' + method + ' method', function() { + methods.forEach((method) => { + it(`should have a ${method} method`, function () { expect(this.hooks[method]).to.exist.to.be.an.instanceOf(Function); }); }); }); - describe('#constructor', function() { - it('should error when no options are provided', function() { + describe('#constructor', () => { + it('should error when no options are provided', () => { expect(HookManager).to.throw(ArgumentError, 'Must provide manager options'); }); - it('should throw an error when no base URL is provided', function() { - var client = HookManager.bind(null, {}); + it('should throw an error when no base URL is provided', () => { + const client = HookManager.bind(null, {}); expect(client).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); - it('should throw an error when the base URL is invalid', function() { - var client = HookManager.bind(null, { baseUrl: '' }); + it('should throw an error when the base URL is invalid', () => { + const client = HookManager.bind(null, { baseUrl: '' }); expect(client).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); - describe('#getAll', function() { - beforeEach(function() { - this.request = nock(API_URL) - .get('/hooks') - .reply(200); + describe('#getAll', () => { + beforeEach(function () { + this.request = nock(API_URL).get('/hooks').reply(200); }); - it('should accept a callback', function(done) { - this.hooks.getAll(function() { + it('should accept a callback', function (done) { + this.hooks.getAll(() => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.hooks - .getAll() - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.hooks.getAll().then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/hooks') - .reply(500); + nock(API_URL).get('/hooks').reply(500); - this.hooks.getAll().catch(function(err) { + this.hooks.getAll().catch((err) => { expect(err).to.exist; done(); }); }); - it('should pass the body of the response to the "then" handler', function(done) { + it('should pass the body of the response to the "then" handler', function (done) { nock.cleanAll(); - var data = [{ test: true }]; - var request = nock(API_URL) - .get('/hooks') - .reply(200, data); + const data = [{ test: true }]; + nock(API_URL).get('/hooks').reply(200, data); - this.hooks.getAll().then(function(credentials) { + this.hooks.getAll().then((credentials) => { expect(credentials).to.be.an.instanceOf(Array); expect(credentials.length).to.equal(data.length); @@ -106,42 +96,39 @@ describe('HookManager', function() { }); }); - it('should perform a GET request to /api/v2/hooks', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/hooks', function (done) { + const { request } = this; - this.hooks.getAll().then(function() { + this.hooks.getAll().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/hooks') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.hooks.getAll().then(function() { + this.hooks.getAll().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the parameters in the query-string', function(done) { + it('should pass the parameters in the query-string', function (done) { nock.cleanAll(); - var params = { + const params = { include_fields: true, - fields: 'test' + fields: 'test', }; - var request = nock(API_URL) - .get('/hooks') - .query(params) - .reply(200); + const request = nock(API_URL).get('/hooks').query(params).reply(200); - this.hooks.getAll(params).then(function() { + this.hooks.getAll(params).then(() => { expect(request.isDone()).to.be.true; done(); @@ -149,67 +136,60 @@ describe('HookManager', function() { }); }); - describe('#get', function() { - beforeEach(function() { + describe('#get', () => { + beforeEach(function () { this.data = { id: 5, name: 'Test hook', enabled: true, script: "function (user, contest, callback) { console.log('Test'); }", - stage: 'login_success' + stage: 'login_success', }; - this.request = nock(API_URL) - .get('/hooks/' + this.data.id) - .reply(200, this.data); + this.request = nock(API_URL).get(`/hooks/${this.data.id}`).reply(200, this.data); }); - it('should accept a callback', function(done) { - var params = { id: this.data.id }; + it('should accept a callback', function (done) { + const params = { id: this.data.id }; this.hooks.get(params, done.bind(null, null)); }); - it('should return a promise if no callback is given', function(done) { - this.hooks - .get({ id: this.data.id }) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.hooks.get({ id: this.data.id }).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should perform a POST request to /api/v2/hooks/5', function(done) { - var request = this.request; + it('should perform a POST request to /api/v2/hooks/5', function (done) { + const { request } = this; - this.hooks.get({ id: this.data.id }).then(function() { + this.hooks.get({ id: this.data.id }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/hooks/' + this.data.id) - .reply(500); + nock(API_URL).get(`/hooks/${this.data.id}`).reply(500); - this.hooks.get({ id: this.data.id }).catch(function(err) { + this.hooks.get({ id: this.data.id }).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/hooks/' + this.data.id) - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .get(`/hooks/${this.data.id}`) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.hooks.get({ id: this.data.id }).then(function() { + this.hooks.get({ id: this.data.id }).then(() => { expect(request.isDone()).to.be.true; done(); @@ -217,81 +197,72 @@ describe('HookManager', function() { }); }); - describe('#create', function() { - var data = { + describe('#create', () => { + const data = { id: 5, name: 'Test hook', enabled: true, script: "function (user, contest, callback) { console.log('Test'); }", - stage: 'login_success' + stage: 'login_success', }; - beforeEach(function() { - this.request = nock(API_URL) - .post('/hooks') - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).post('/hooks').reply(200); }); - it('should accept a callback', function(done) { - this.hooks.create(data, function() { + it('should accept a callback', function (done) { + this.hooks.create(data, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.hooks - .create(data) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.hooks.create(data).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/hooks') - .reply(500); + nock(API_URL).post('/hooks').reply(500); - this.hooks.create(data).catch(function(err) { + this.hooks.create(data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a POST request to /api/v2/hooks', function(done) { - var request = this.request; + it('should perform a POST request to /api/v2/hooks', function (done) { + const { request } = this; - this.hooks.create(data).then(function() { + this.hooks.create(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the data in the body of the request', function(done) { + it('should pass the data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/hooks', data) - .reply(200); + const request = nock(API_URL).post('/hooks', data).reply(200); - this.hooks.create(data).then(function() { + this.hooks.create(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .post('/hooks') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.hooks.create(data).then(function() { + this.hooks.create(data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -299,58 +270,49 @@ describe('HookManager', function() { }); }); - describe('#update', function() { - beforeEach(function() { + describe('#update', () => { + beforeEach(function () { this.data = { id: 5 }; - this.request = nock(API_URL) - .patch('/hooks/' + this.data.id) - .reply(200, this.data); + this.request = nock(API_URL).patch(`/hooks/${this.data.id}`).reply(200, this.data); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.hooks.update({ id: 5 }, {}, done.bind(null, null)); }); - it('should return a promise if no callback is given', function(done) { - this.hooks - .update({ id: 5 }, {}) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.hooks.update({ id: 5 }, {}).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should perform a PATCH request to /api/v2/hooks/5', function(done) { - var request = this.request; + it('should perform a PATCH request to /api/v2/hooks/5', function (done) { + const { request } = this; - this.hooks.update({ id: 5 }, {}).then(function() { + this.hooks.update({ id: 5 }, {}).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the new data in the body of the request', function(done) { + it('should include the new data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/hooks/' + this.data.id, this.data) - .reply(200); + const request = nock(API_URL).patch(`/hooks/${this.data.id}`, this.data).reply(200); - this.hooks.update({ id: 5 }, this.data).then(function() { + this.hooks.update({ id: 5 }, this.data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/hooks/' + this.data.id) - .reply(500); + nock(API_URL).patch(`/hooks/${this.data.id}`).reply(500); - this.hooks.update({ id: this.data.id }, this.data).catch(function(err) { + this.hooks.update({ id: this.data.id }, this.data).catch((err) => { expect(err).to.exist; done(); @@ -358,56 +320,52 @@ describe('HookManager', function() { }); }); - describe('#delete', function() { - var id = 5; + describe('#delete', () => { + const id = 5; - beforeEach(function() { - this.request = nock(API_URL) - .delete('/hooks/' + id) - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).delete(`/hooks/${id}`).reply(200); }); - it('should accept a callback', function(done) { - this.hooks.delete({ id: id }, done.bind(null, null)); + it('should accept a callback', function (done) { + this.hooks.delete({ id }, done.bind(null, null)); }); - it('should return a promise when no callback is given', function(done) { - this.hooks.delete({ id: id }).then(done.bind(null, null)); + it('should return a promise when no callback is given', function (done) { + this.hooks.delete({ id }).then(done.bind(null, null)); }); - it('should perform a delete request to /hooks/' + id, function(done) { - var request = this.request; + it(`should perform a delete request to /hooks/${id}`, function (done) { + const { request } = this; - this.hooks.delete({ id: id }).then(function() { + this.hooks.delete({ id }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete('/hooks/' + id) - .reply(500); + nock(API_URL).delete(`/hooks/${id}`).reply(500); - this.hooks.delete({ id: id }).catch(function(err) { + this.hooks.delete({ id }).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the authorization header', function(done) { + it('should include the token in the authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete('/hooks/' + id) - .matchHeader('authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .delete(`/hooks/${id}`) + .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); - this.hooks.delete({ id: id }).then(function() { + this.hooks.delete({ id }).then(() => { expect(request.isDone()).to.be.true; done(); @@ -415,58 +373,54 @@ describe('HookManager', function() { }); }); - describe('#getSecrets', function() { - var data = { - id: 'hook_id' + describe('#getSecrets', () => { + const data = { + id: 'hook_id', }; - beforeEach(function() { - this.request = nock(API_URL) - .get('/hooks/' + data.id + '/secrets') - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).get(`/hooks/${data.id}/secrets`).reply(200); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.hooks.getSecrets(data, done.bind(null, null)); }); - it('should return a promise when no callback is given', function(done) { + it('should return a promise when no callback is given', function (done) { this.hooks.getSecrets(data).then(done.bind(null, null)); }); - it('should perform a GET request to /api/v2/hooks/hook_id/secrets', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/hooks/hook_id/secrets', function (done) { + const { request } = this; - this.hooks.getSecrets(data).then(function() { + this.hooks.getSecrets(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/hooks/' + data.id + '/secrets') - .reply(500); + nock(API_URL).get(`/hooks/${data.id}/secrets`).reply(500); - this.hooks.getSecrets(data).catch(function(err) { + this.hooks.getSecrets(data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the authorization header', function(done) { + it('should include the token in the authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/hooks/' + data.id + '/secrets') - .matchHeader('authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .get(`/hooks/${data.id}/secrets`) + .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); - this.hooks.getSecrets(data).then(function() { + this.hooks.getSecrets(data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -474,78 +428,69 @@ describe('HookManager', function() { }); }); - describe('#addSecrets', function() { - beforeEach(function() { + describe('#addSecrets', () => { + beforeEach(function () { this.data = { - id: 'hook_id' + id: 'hook_id', }; this.body = { permission_name: 'My Permission', resource_server_identifier: 'test123' }; - this.request = nock(API_URL) - .post('/hooks/' + this.data.id + '/secrets') - .reply(200); + this.request = nock(API_URL).post(`/hooks/${this.data.id}/secrets`).reply(200); }); - it('should accept a callback', function(done) { - this.hooks.addSecrets(this.data, {}, function() { + it('should accept a callback', function (done) { + this.hooks.addSecrets(this.data, {}, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.hooks - .addSecrets(this.data, {}) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.hooks.addSecrets(this.data, {}).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/hooks/' + this.data.id + '/secrets') - .reply(500); + nock(API_URL).post(`/hooks/${this.data.id}/secrets`).reply(500); - this.hooks.addSecrets(this.data, {}).catch(function(err) { + this.hooks.addSecrets(this.data, {}).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a POST request to /api/v2/hooks/hook_id/secrets', function(done) { - var request = this.request; + it('should perform a POST request to /api/v2/hooks/hook_id/secrets', function (done) { + const { request } = this; - this.hooks.addSecrets(this.data, {}).then(function() { + this.hooks.addSecrets(this.data, {}).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the data in the body of the request', function(done) { + it('should pass the data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/hooks/' + this.data.id + '/secrets', this.body) - .reply(200); + const request = nock(API_URL).post(`/hooks/${this.data.id}/secrets`, this.body).reply(200); - this.hooks.addSecrets(this.data, this.body).then(function() { + this.hooks.addSecrets(this.data, this.body).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/hooks/' + this.data.id + '/secrets') - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .post(`/hooks/${this.data.id}/secrets`) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.hooks.addSecrets(this.data, {}).then(function() { + this.hooks.addSecrets(this.data, {}).then(() => { expect(request.isDone()).to.be.true; done(); @@ -553,78 +498,72 @@ describe('HookManager', function() { }); }); - describe('#updateSecrets', function() { - beforeEach(function() { + describe('#updateSecrets', () => { + beforeEach(function () { this.data = { - id: 'hook_id' + id: 'hook_id', }; this.body = { DB_PASSWORD: 'abcd1234', APITOKEN: 'foosecret' }; - this.request = nock(API_URL) - .patch('/hooks/' + this.data.id + '/secrets') - .reply(200); + this.request = nock(API_URL).patch(`/hooks/${this.data.id}/secrets`).reply(200); }); - it('should accept a callback', function(done) { - this.hooks.updateSecrets(this.data, {}, function() { + it('should accept a callback', function (done) { + this.hooks.updateSecrets(this.data, {}, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.hooks .updateSecrets(this.data, {}) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/hooks/' + this.data.id + '/secrets') - .reply(500); + nock(API_URL).patch(`/hooks/${this.data.id}/secrets`).reply(500); - this.hooks.updateSecrets(this.data, {}).catch(function(err) { + this.hooks.updateSecrets(this.data, {}).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a POST request to /api/v2/hooks/hook_id/secrets', function(done) { - var request = this.request; + it('should perform a POST request to /api/v2/hooks/hook_id/secrets', function (done) { + const { request } = this; - this.hooks.updateSecrets(this.data, {}).then(function() { + this.hooks.updateSecrets(this.data, {}).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the data in the body of the request', function(done) { + it('should pass the data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/hooks/' + this.data.id + '/secrets', this.body) - .reply(200); + const request = nock(API_URL).patch(`/hooks/${this.data.id}/secrets`, this.body).reply(200); - this.hooks.updateSecrets(this.data, this.body).then(function() { + this.hooks.updateSecrets(this.data, this.body).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/hooks/' + this.data.id + '/secrets') - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .patch(`/hooks/${this.data.id}/secrets`) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.hooks.updateSecrets(this.data, {}).then(function() { + this.hooks.updateSecrets(this.data, {}).then(() => { expect(request.isDone()).to.be.true; done(); @@ -632,92 +571,84 @@ describe('HookManager', function() { }); }); - describe('#removeSecrets', function() { - beforeEach(function() { + describe('#removeSecrets', () => { + beforeEach(function () { this.data = { - id: 'hook_id' + id: 'hook_id', }; this.body = { DB_PASSWORD: 'abcd1234', APITOKEN: 'foosecret' }; - this.request = nock(API_URL) - .delete('/hooks/' + this.data.id + '/secrets', {}) - .reply(200); + this.request = nock(API_URL).delete(`/hooks/${this.data.id}/secrets`, {}).reply(200); }); - it('should validate empty hookId', function() { - var _this = this; - expect(function() { - _this.hooks.removeSecrets({ id: null }, _this.body, function() {}); + it('should validate empty hookId', function () { + const _this = this; + expect(() => { + _this.hooks.removeSecrets({ id: null }, _this.body, () => {}); }).to.throw('The id passed in params cannot be null or undefined'); }); - it('should validate non-string hookId', function() { - var _this = this; - expect(function() { - _this.hooks.removeSecrets({ id: 123 }, _this.body, function() {}); + it('should validate non-string hookId', function () { + const _this = this; + expect(() => { + _this.hooks.removeSecrets({ id: 123 }, _this.body, () => {}); }).to.throw('The hook Id has to be a string'); }); - it('should accept a callback', function(done) { - this.hooks.removeSecrets(this.data, {}, function() { + it('should accept a callback', function (done) { + this.hooks.removeSecrets(this.data, {}, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.hooks .removeSecrets(this.data, {}) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/hooks/' + this.data.id + '/secrets') - .reply(500); + nock(API_URL).post(`/hooks/${this.data.id}/secrets`).reply(500); - this.hooks.removeSecrets(this.data, {}).catch(function(err) { + this.hooks.removeSecrets(this.data, {}).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a DELETE request to /api/v2/hooks/hook_id/secrets', function(done) { - var request = this.request; - - this.hooks.removeSecrets(this.data, {}).then(function() { - expect(request.isDone()).to.be.true; + it('should perform a DELETE request to /api/v2/hooks/hook_id/secrets', function (done) { + this.hooks.removeSecrets(this.data, {}).then(() => { + expect(this.request.isDone()).to.be.true; done(); }); }); - it('should pass the data in the body of the request', function(done) { + it('should pass the data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete('/hooks/' + this.data.id + '/secrets', this.body) - .reply(200); + const request = nock(API_URL).delete(`/hooks/${this.data.id}/secrets`, this.body).reply(200); - this.hooks.removeSecrets(this.data, this.body).then(function() { + this.hooks.removeSecrets(this.data, this.body).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete('/hooks/' + this.data.id + '/secrets') - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .delete(`/hooks/${this.data.id}/secrets`) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.hooks.removeSecrets(this.data, {}).then(function() { + this.hooks.removeSecrets(this.data, {}).then(() => { expect(request.isDone()).to.be.true; done(); diff --git a/test/management/jobs.tests.js b/test/management/jobs.tests.js index 8a6fb6a2a..32c76fe38 100644 --- a/test/management/jobs.tests.js +++ b/test/management/jobs.tests.js @@ -1,110 +1,100 @@ -var path = require('path'); -var expect = require('chai').expect; -var nock = require('nock'); -var extractParts = require('../utils').extractParts; -var fs = require('fs'); +const path = require('path'); +const { expect } = require('chai'); +const nock = require('nock'); +const { extractParts } = require('../utils'); +const fs = require('fs'); -var SRC_DIR = '../../src'; -var API_URL = 'https://tenant.auth0.com'; +const API_URL = 'https://tenant.auth0.com'; -var JobsManager = require(SRC_DIR + '/management/JobsManager'); -var ArgumentError = require('rest-facade').ArgumentError; +const JobsManager = require(`../../src/management/JobsManager`); +const { ArgumentError } = require('rest-facade'); -var token = 'TOKEN'; +const token = 'TOKEN'; -describe('JobsManager', function() { - before(function() { +describe('JobsManager', () => { + before(function () { this.id = 'testJob'; this.jobs = new JobsManager({ tokenProvider: { - getAccessToken: function() { + getAccessToken() { return Promise.resolve(token); - } + }, }, headers: {}, - baseUrl: API_URL + baseUrl: API_URL, }); }); - describe('instance', function() { - var methods = ['verifyEmail', 'importUsers', 'exportUsers', 'get']; + describe('instance', () => { + const methods = ['verifyEmail', 'importUsers', 'exportUsers', 'get']; - methods.forEach(function(method) { - it('should have a ' + method + ' method', function() { + methods.forEach((method) => { + it(`should have a ${method} method`, function () { expect(this.jobs[method]).to.exist.to.be.an.instanceOf(Function); }); }); }); - describe('#constructor', function() { - it('should error when no options are provided', function() { + describe('#constructor', () => { + it('should error when no options are provided', () => { expect(JobsManager).to.throw(ArgumentError, 'Must provide client options'); }); - it('should throw an error when no base URL is provided', function() { - var client = JobsManager.bind(null, {}); + it('should throw an error when no base URL is provided', () => { + const client = JobsManager.bind(null, {}); expect(client).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); - it('should throw an error when the base URL is invalid', function() { - var client = JobsManager.bind(null, { baseUrl: '' }); + it('should throw an error when the base URL is invalid', () => { + const client = JobsManager.bind(null, { baseUrl: '' }); expect(client).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); - describe('#get', function() { - beforeEach(function() { - this.request = nock(API_URL) - .get('/jobs/' + this.id) - .reply(200); + describe('#get', () => { + beforeEach(function () { + this.request = nock(API_URL).get(`/jobs/${this.id}`).reply(200); }); - it('should accept a callback', function(done) { - this.jobs.get({ id: this.id }, function() { + it('should accept a callback', function (done) { + this.jobs.get({ id: this.id }, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.jobs - .get({ id: this.id }) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.jobs.get({ id: this.id }).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/jobs/' + this.id) - .reply(500); + nock(API_URL).get(`/jobs/${this.id}`).reply(500); - this.jobs.get({ id: this.id }).catch(function(err) { + this.jobs.get({ id: this.id }).catch((err) => { expect(err).to.exist; done(); }); }); - it('should throw an ArgumentError if an invalid id is passed', function(done) { + it('should throw an ArgumentError if an invalid id is passed', function (done) { try { - this.jobs.errors({ id: 12345 }, function() {}); + this.jobs.errors({ id: 12345 }, () => {}); } catch (err) { expect(err).to.exist; done(); } }); - it('should pass the body of the response to the "then" handler', function(done) { + it('should pass the body of the response to the "then" handler', function (done) { nock.cleanAll(); - var data = [{ test: true }]; - var request = nock(API_URL) - .get('/jobs/' + this.id) - .reply(200, data); + const data = [{ test: true }]; + nock(API_URL).get(`/jobs/${this.id}`).reply(200, data); - this.jobs.get({ id: this.id }).then(function(blacklistedTokens) { + this.jobs.get({ id: this.id }).then((blacklistedTokens) => { expect(blacklistedTokens).to.be.an.instanceOf(Array); expect(blacklistedTokens.length).to.equal(data.length); @@ -115,42 +105,42 @@ describe('JobsManager', function() { }); }); - it('should perform a GET request to /api/v2/jobs', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/jobs', function (done) { + const { request } = this; - this.jobs.get({ id: this.id }).then(function() { + this.jobs.get({ id: this.id }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/jobs/' + this.id) - .matchHeader('Authorization', 'Bearer ' + token) + const request = nock(API_URL) + .get(`/jobs/${this.id}`) + .matchHeader('Authorization', `Bearer ${token}`) .reply(200); - this.jobs.get({ id: this.id }).then(function() { + this.jobs.get({ id: this.id }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the parameters in the query-string', function(done) { + it('should pass the parameters in the query-string', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/jobs/' + this.id) + const request = nock(API_URL) + .get(`/jobs/${this.id}`) .query({ include_fields: true, - fields: 'test' + fields: 'test', }) .reply(200); - this.jobs.get({ id: this.id, include_fields: true, fields: 'test' }).then(function() { + this.jobs.get({ id: this.id, include_fields: true, fields: 'test' }).then(() => { expect(request.isDone()).to.be.true; done(); }); @@ -158,57 +148,48 @@ describe('JobsManager', function() { }); // Error retrieval tests - describe('#errors', function() { - beforeEach(function() { - this.request = nock(API_URL) - .get('/jobs/' + this.id + '/errors') - .reply(200); + describe('#errors', () => { + beforeEach(function () { + this.request = nock(API_URL).get(`/jobs/${this.id}/errors`).reply(200); }); - it('should accept a callback', function(done) { - this.jobs.errors({ id: this.id }, function() { + it('should accept a callback', function (done) { + this.jobs.errors({ id: this.id }, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.jobs - .errors({ id: this.id }) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.jobs.errors({ id: this.id }).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/jobs/' + this.id + '/errors') - .reply(500); + nock(API_URL).get(`/jobs/${this.id}/errors`).reply(500); - this.jobs.errors({ id: this.id }).catch(function(err) { + this.jobs.errors({ id: this.id }).catch((err) => { expect(err).to.exist; done(); }); }); - it('should throw an ArgumentError if an invalid id is passed', function(done) { + it('should throw an ArgumentError if an invalid id is passed', function (done) { try { - this.jobs.errors({ id: null }, function() {}); + this.jobs.errors({ id: null }, () => {}); } catch (err) { expect(err).to.exist; done(); } }); - it('should pass the body of the response to the "then" handler', function(done) { + it('should pass the body of the response to the "then" handler', function (done) { nock.cleanAll(); - var data = [{ test: true }]; - var request = nock(API_URL) - .get('/jobs/' + this.id + '/errors') - .reply(200, data); + const data = [{ test: true }]; + nock(API_URL).get(`/jobs/${this.id}/errors`).reply(200, data); - this.jobs.errors({ id: this.id }).then(function(blacklistedTokens) { + this.jobs.errors({ id: this.id }).then((blacklistedTokens) => { expect(blacklistedTokens).to.be.an.instanceOf(Array); expect(blacklistedTokens.length).to.equal(data.length); @@ -219,42 +200,42 @@ describe('JobsManager', function() { }); }); - it('should perform a GET request to /api/v2/jobs/:id/errors', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/jobs/:id/errors', function (done) { + const { request } = this; - this.jobs.errors({ id: this.id }).then(function() { + this.jobs.errors({ id: this.id }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/jobs/' + this.id + '/errors') - .matchHeader('Authorization', 'Bearer ' + token) + const request = nock(API_URL) + .get(`/jobs/${this.id}/errors`) + .matchHeader('Authorization', `Bearer ${token}`) .reply(200); - this.jobs.errors({ id: this.id }).then(function() { + this.jobs.errors({ id: this.id }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the parameters in the query-string', function(done) { + it('should pass the parameters in the query-string', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/jobs/' + this.id) + const request = nock(API_URL) + .get(`/jobs/${this.id}`) .query({ include_fields: true, - fields: 'test' + fields: 'test', }) .reply(200); - this.jobs.get({ id: this.id, include_fields: true, fields: 'test' }).then(function() { + this.jobs.get({ id: this.id, include_fields: true, fields: 'test' }).then(() => { expect(request.isDone()).to.be.true; done(); }); @@ -263,34 +244,29 @@ describe('JobsManager', function() { const usersFilePath = path.join(__dirname, '../data/users.json'); - describe('#importUsers', function() { - var data = { + describe('#importUsers', () => { + const data = { users: usersFilePath, - connection_id: 'con_test' + connection_id: 'con_test', }; - beforeEach(function() { - this.request = nock(API_URL) - .post('/jobs/users-imports') - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).post('/jobs/users-imports').reply(200); }); - it('should accept a callback', function(done) { - this.jobs.importUsers(data, function() { + it('should accept a callback', function (done) { + this.jobs.importUsers(data, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.jobs - .importUsers(data) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.jobs.importUsers(data).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should have the payload in response.data', function(done) { + it('should have the payload in response.data', function (done) { nock.cleanAll(); - var payload = { + const payload = { status: 'pending', type: 'users_import', created_at: '', @@ -298,42 +274,36 @@ describe('JobsManager', function() { connection_id: 'con_0000000000000001', upsert: false, external_id: '', - send_completion_email: true + send_completion_email: true, }; - var request = nock(API_URL) - .post('/jobs/users-imports') - .reply(200, payload); + nock(API_URL).post('/jobs/users-imports').reply(200, payload); this.jobs .importUsers(data) - .then(response => { + .then((response) => { expect(response.data).to.deep.equal(payload); done(); }) - .catch(err => done(err)); + .catch((err) => done(err)); }); - it('should pass request errors to the promise catch handler', function(done) { + it('should pass request errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/jobs/users-imports') - .replyWithError('printer on fire'); + nock(API_URL).post('/jobs/users-imports').replyWithError('printer on fire'); - this.jobs.importUsers(data).catch(function(err) { + this.jobs.importUsers(data).catch((err) => { expect(err.message).to.equal('printer on fire'); done(); }); }); - it('should pass HTTP errors to the promise catch handler', function(done) { + it('should pass HTTP errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/jobs/users-imports') - .reply(500); + nock(API_URL).post('/jobs/users-imports').reply(500); - this.jobs.importUsers(data).catch(function(err) { + this.jobs.importUsers(data).catch((err) => { expect(err.message).to.equal( 'cannot POST https://tenant.auth0.com/jobs/users-imports (500)' ); @@ -341,23 +311,21 @@ describe('JobsManager', function() { }); }); - it('should pass rest-api json error messages to the promise catch handler', function(done) { + it('should pass rest-api json error messages to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) + nock(API_URL) .post('/jobs/users-imports') - .reply((uri, requestBody) => { - return [ - 429, - { - statusCode: 429, - error: 'Too Many Requests', - message: 'There are 4 active import users jobs' - } - ]; - }); - - this.jobs.importUsers(data).catch(function(err) { + .reply(() => [ + 429, + { + statusCode: 429, + error: 'Too Many Requests', + message: 'There are 4 active import users jobs', + }, + ]); + + this.jobs.importUsers(data).catch((err) => { expect(err.message).to.equal( 'cannot POST https://tenant.auth0.com/jobs/users-imports (429)' ); @@ -366,60 +334,52 @@ describe('JobsManager', function() { }); }); - it('should perform a POST request to /api/v2/jobs/users-imports', function(done) { - var request = this.request; + it('should perform a POST request to /api/v2/jobs/users-imports', function (done) { + const { request } = this; - this.jobs.importUsers(data).then(function() { + this.jobs.importUsers(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should be a multipart request', function(done) { + it('should be a multipart request', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .post('/jobs/users-imports') - .matchHeader('Content-Type', function(header) { - return header.indexOf('multipart/form-data') === 0; - }) + .matchHeader('Content-Type', (header) => header.indexOf('multipart/form-data') === 0) .reply(200); - this.jobs.importUsers(data).then(function() { + this.jobs.importUsers(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should have four parts: connection_id, users file, upsert and send_completion_email', function(done) { + it('should have four parts: connection_id, users file, upsert and send_completion_email', function (done) { nock.cleanAll(); - var boundary = null; + let boundary = null; - var request = nock(API_URL) - .matchHeader('Content-Type', function(header) { - boundary = '--' + header.match(/boundary=([^\n]*)/)[1]; + const request = nock(API_URL) + .matchHeader('Content-Type', (header) => { + boundary = `--${header.match(/boundary=([^\n]*)/)[1]}`; return true; }) - .post('/jobs/users-imports', function(body) { - var parts = extractParts(body, boundary); + .post('/jobs/users-imports', (body) => { + const parts = extractParts(body, boundary); // Validate the connection id. - expect(parts.connection_id) - .to.exist.to.be.a('string') - .to.equal(data.connection_id); + expect(parts.connection_id).to.exist.to.be.a('string').to.equal(data.connection_id); // Validate the upsert param - default is false - expect(parts.upsert) - .to.exist.to.be.a('string') - .to.equal('false'); + expect(parts.upsert).to.exist.to.be.a('string').to.equal('false'); // Validate the send_completion_email param - default is true - expect(parts.send_completion_email) - .to.exist.to.be.a('string') - .to.equal('true'); + expect(parts.send_completion_email).to.exist.to.be.a('string').to.equal('true'); // Validate the content type of the users JSON. expect(parts.users) @@ -435,80 +395,76 @@ describe('JobsManager', function() { }) .reply(200); - this.jobs.importUsers(data).then(function() { + this.jobs.importUsers(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should set upsert parameter correctly', function(done) { + it('should set upsert parameter correctly', function (done) { nock.cleanAll(); - var boundary = null; + let boundary = null; - var request = nock(API_URL) - .matchHeader('Content-Type', function(header) { - boundary = '--' + header.match(/boundary=([^\n]*)/)[1]; + const request = nock(API_URL) + .matchHeader('Content-Type', (header) => { + boundary = `--${header.match(/boundary=([^\n]*)/)[1]}`; return true; }) - .post('/jobs/users-imports', function(body) { - var parts = extractParts(body, boundary); + .post('/jobs/users-imports', (body) => { + const parts = extractParts(body, boundary); // Validate the upsert param - expect(parts.upsert) - .to.exist.to.be.a('string') - .to.equal('true'); + expect(parts.upsert).to.exist.to.be.a('string').to.equal('true'); return true; }) .reply(200); - this.jobs.importUsers(Object.assign({ upsert: true }, data)).then(function() { + this.jobs.importUsers(Object.assign({ upsert: true }, data)).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should set send_completion_email parameter correctly', function(done) { + it('should set send_completion_email parameter correctly', function (done) { nock.cleanAll(); - var boundary = null; + let boundary = null; - var request = nock(API_URL) - .matchHeader('Content-Type', function(header) { - boundary = '--' + header.match(/boundary=([^\n]*)/)[1]; + const request = nock(API_URL) + .matchHeader('Content-Type', (header) => { + boundary = `--${header.match(/boundary=([^\n]*)/)[1]}`; return true; }) - .post('/jobs/users-imports', function(body) { - var parts = extractParts(body, boundary); + .post('/jobs/users-imports', (body) => { + const parts = extractParts(body, boundary); // Validate the upsert param - expect(parts.send_completion_email) - .to.exist.to.be.a('string') - .to.equal('false'); + expect(parts.send_completion_email).to.exist.to.be.a('string').to.equal('false'); return true; }) .reply(200); - this.jobs.importUsers(Object.assign({ send_completion_email: false }, data)).then(function() { + this.jobs.importUsers(Object.assign({ send_completion_email: false }, data)).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .post('/jobs/users-imports') - .matchHeader('Authorization', 'Bearer ' + token) + .matchHeader('Authorization', `Bearer ${token}`) .reply(200); - this.jobs.importUsers(data).then(function() { + this.jobs.importUsers(data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -516,30 +472,28 @@ describe('JobsManager', function() { }); }); - describe('#importUsers with JSON data', function() { - var data = { + describe('#importUsers with JSON data', () => { + const data = { users_json: fs.readFileSync(usersFilePath, 'utf8'), - connection_id: 'con_test' + connection_id: 'con_test', }; - beforeEach(function() { - this.request = nock(API_URL) - .post('/jobs/users-imports') - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).post('/jobs/users-imports').reply(200); }); - it('should correctly include user JSON', function(done) { + it('should correctly include user JSON', function (done) { nock.cleanAll(); - var boundary = null; + let boundary = null; - var request = nock(API_URL) - .matchHeader('Content-Type', function(header) { - boundary = '--' + header.match(/boundary=([^\n]*)/)[1]; + const request = nock(API_URL) + .matchHeader('Content-Type', (header) => { + boundary = `--${header.match(/boundary=([^\n]*)/)[1]}`; return true; }) - .post('/jobs/users-imports', function(body) { - var parts = extractParts(body, boundary); + .post('/jobs/users-imports', (body) => { + const parts = extractParts(body, boundary); // Validate the content type of the users JSON. expect(parts.users) @@ -555,7 +509,7 @@ describe('JobsManager', function() { }) .reply(200); - this.jobs.importUsers(data).then(function() { + this.jobs.importUsers(data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -563,35 +517,30 @@ describe('JobsManager', function() { }); }); - describe('#importUsersJob', function() { - var data = { + describe('#importUsersJob', () => { + const data = { users: usersFilePath, - connection_id: 'con_test' + connection_id: 'con_test', }; - beforeEach(function() { - this.request = nock(API_URL) - .post('/jobs/users-imports') - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).post('/jobs/users-imports').reply(200); }); - it('should accept a callback', function(done) { - this.jobs.importUsersJob(data, function() { + it('should accept a callback', function (done) { + this.jobs.importUsersJob(data, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.jobs - .importUsersJob(data) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.jobs.importUsersJob(data).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should extract data from the response', function(done) { + it('should extract data from the response', function (done) { nock.cleanAll(); - var payload = { + const payload = { status: 'pending', type: 'users_import', created_at: '', @@ -599,169 +548,152 @@ describe('JobsManager', function() { connection_id: 'con_0000000000000001', upsert: false, external_id: '', - send_completion_email: true + send_completion_email: true, }; - var request = nock(API_URL) - .post('/jobs/users-imports') - .reply(200, payload); + nock(API_URL).post('/jobs/users-imports').reply(200, payload); this.jobs .importUsersJob(data) - .then(response => { + .then((response) => { expect(response).to.deep.equal(payload); done(); }) - .catch(err => done(err)); + .catch((err) => done(err)); }); }); - describe('#exportUsers', function() { - beforeEach(function() { - this.request = nock(API_URL) - .post('/jobs/users-exports') - .reply(200); + describe('#exportUsers', () => { + beforeEach(function () { + this.request = nock(API_URL).post('/jobs/users-exports').reply(200); }); - it('should accept a callback', function(done) { - this.jobs.exportUsers({ format: 'csv' }, function() { + it('should accept a callback', function (done) { + this.jobs.exportUsers({ format: 'csv' }, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.jobs .exportUsers({ format: 'csv' }) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - nock(API_URL) - .post('/jobs/users-exports') - .reply(500); + nock(API_URL).post('/jobs/users-exports').reply(500); - this.jobs.exportUsers({ format: 'csv' }).catch(function(err) { + this.jobs.exportUsers({ format: 'csv' }).catch((err) => { expect(err).to.exist; done(); }); }); - it('should pass the body of the response to the "then" handler', function(done) { + it('should pass the body of the response to the "then" handler', function (done) { nock.cleanAll(); - var data = { + const data = { type: 'users_export', status: 'pending', format: 'csv', created_at: '', - id: 'job_0000000000000001' + id: 'job_0000000000000001', }; - nock(API_URL) - .post('/jobs/users-exports') - .reply(200, data); + nock(API_URL).post('/jobs/users-exports').reply(200, data); - this.jobs.exportUsers({ format: 'csv' }).then(function(response) { + this.jobs.exportUsers({ format: 'csv' }).then((response) => { expect(response).to.be.an.instanceOf(Object); expect(response.status).to.equal('pending'); done(); }); }); - it('should perform a POST request to /api/v2/jobs/users-exports', function(done) { - var request = this.request; + it('should perform a POST request to /api/v2/jobs/users-exports', function (done) { + const { request } = this; - this.jobs.exportUsers({ format: 'csv' }).then(function() { + this.jobs.exportUsers({ format: 'csv' }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .post('/jobs/users-exports') - .matchHeader('Authorization', 'Bearer ' + token) + .matchHeader('Authorization', `Bearer ${token}`) .reply(200); - this.jobs.exportUsers({ format: 'csv' }).then(function() { + this.jobs.exportUsers({ format: 'csv' }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); }); - describe('#verifyEmail', function() { - var data = { - user_id: 'github|12345' + describe('#verifyEmail', () => { + const data = { + user_id: 'github|12345', }; - beforeEach(function() { - this.request = nock(API_URL) - .post('/jobs/verification-email') - .reply(200, data); + beforeEach(function () { + this.request = nock(API_URL).post('/jobs/verification-email').reply(200, data); }); - it('should accept a callback', function(done) { - this.jobs.verifyEmail(data, function() { + it('should accept a callback', function (done) { + this.jobs.verifyEmail(data, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.jobs - .verifyEmail(data) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.jobs.verifyEmail(data).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/jobs/verification-email') - .reply(500); + nock(API_URL).post('/jobs/verification-email').reply(500); - this.jobs.verifyEmail(data).catch(function(err) { + this.jobs.verifyEmail(data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a POST request to /api/v2/jobs/verification-email', function(done) { - var request = this.request; + it('should perform a POST request to /api/v2/jobs/verification-email', function (done) { + const { request } = this; - this.jobs.verifyEmail(data).then(function() { + this.jobs.verifyEmail(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the data in the body of the request', function(done) { + it('should pass the data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/jobs/verification-email', data) - .reply(200); + const request = nock(API_URL).post('/jobs/verification-email', data).reply(200); - this.jobs.verifyEmail(data).then(function() { + this.jobs.verifyEmail(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .post('/jobs/verification-email') - .matchHeader('Authorization', 'Bearer ' + token) + .matchHeader('Authorization', `Bearer ${token}`) .reply(200); - this.jobs.verifyEmail(data).then(function() { + this.jobs.verifyEmail(data).then(() => { expect(request.isDone()).to.be.true; done(); diff --git a/test/management/log-streams.tests.js b/test/management/log-streams.tests.js index a0fcf8681..0b339f5f7 100644 --- a/test/management/log-streams.tests.js +++ b/test/management/log-streams.tests.js @@ -1,92 +1,82 @@ -var expect = require('chai').expect; -var nock = require('nock'); +const { expect } = require('chai'); +const nock = require('nock'); -var SRC_DIR = '../../src'; -var API_URL = 'https://tenant.auth0.com'; +const API_URL = 'https://tenant.auth0.com'; -var LogStreamsManager = require(SRC_DIR + '/management/LogStreamsManager'); -var ArgumentError = require('rest-facade').ArgumentError; +const LogStreamsManager = require(`../../src/management/LogStreamsManager`); +const { ArgumentError } = require('rest-facade'); -describe('LogStreamsManager', function() { - before(function() { +describe('LogStreamsManager', () => { + before(function () { this.token = 'TOKEN'; this.logStreams = new LogStreamsManager({ - headers: { authorization: 'Bearer ' + this.token }, - baseUrl: API_URL + headers: { authorization: `Bearer ${this.token}` }, + baseUrl: API_URL, }); }); - describe('instance', function() { - var methods = ['getAll', 'get', 'create', 'update', 'delete']; + describe('instance', () => { + const methods = ['getAll', 'get', 'create', 'update', 'delete']; - methods.forEach(function(method) { - it('should have a ' + method + ' method', function() { + methods.forEach((method) => { + it(`should have a ${method} method`, function () { expect(this.logStreams[method]).to.exist.to.be.an.instanceOf(Function); }); }); }); - describe('#constructor', function() { - it('should error when no options are provided', function() { + describe('#constructor', () => { + it('should error when no options are provided', () => { expect(LogStreamsManager).to.throw(ArgumentError, 'Must provide client options'); }); - it('should throw an error when no base URL is provided', function() { - var client = LogStreamsManager.bind(null, {}); + it('should throw an error when no base URL is provided', () => { + const client = LogStreamsManager.bind(null, {}); expect(client).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); - it('should throw an error when the base URL is invalid', function() { - var client = LogStreamsManager.bind(null, { baseUrl: '' }); + it('should throw an error when the base URL is invalid', () => { + const client = LogStreamsManager.bind(null, { baseUrl: '' }); expect(client).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); - describe('#getAll', function() { - beforeEach(function() { - this.request = nock(API_URL) - .get('/log-streams') - .reply(200); + describe('#getAll', () => { + beforeEach(function () { + this.request = nock(API_URL).get('/log-streams').reply(200); }); - it('should accept a callback', function(done) { - this.logStreams.getAll(function() { + it('should accept a callback', function (done) { + this.logStreams.getAll(() => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.logStreams - .getAll() - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.logStreams.getAll().then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/log-streams') - .reply(500); + nock(API_URL).get('/log-streams').reply(500); - this.logStreams.getAll().catch(function(err) { + this.logStreams.getAll().catch((err) => { expect(err).to.exist; done(); }); }); - it('should pass the body of the response to the "then" handler', function(done) { + it('should pass the body of the response to the "then" handler', function (done) { nock.cleanAll(); - var data = [{ test: true }]; - var request = nock(API_URL) - .get('/log-streams') - .reply(200, data); + const data = [{ test: true }]; + nock(API_URL).get('/log-streams').reply(200, data); - this.logStreams.getAll().then(function(logStreams) { + this.logStreams.getAll().then((logStreams) => { expect(logStreams).to.be.an.instanceOf(Array); expect(logStreams.length).to.equal(data.length); @@ -97,122 +87,113 @@ describe('LogStreamsManager', function() { }); }); - it('should perform a GET request to /api/v2/log-streams', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/log-streams', function (done) { + const { request } = this; - this.logStreams.getAll().then(function() { + this.logStreams.getAll().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/log-streams') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.logStreams.getAll().then(function() { + this.logStreams.getAll().then(() => { expect(request.isDone()).to.be.true; done(); }); }); }); - describe('#get', function() { - var params = { id: 5 }; - var data = { + describe('#get', () => { + const params = { id: 5 }; + const data = { id: params.id, - name: 'Test log' + name: 'Test log', }; - beforeEach(function() { - this.request = nock(API_URL) - .get('/log-streams/' + data.id) - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).get(`/log-streams/${data.id}`).reply(200); }); - it('should accept a callback', function(done) { - this.logStreams.get(params, function() { + it('should accept a callback', function (done) { + this.logStreams.get(params, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.logStreams - .get(params) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.logStreams.get(params).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/log-streams/' + params.id) - .reply(500); + nock(API_URL).get(`/log-streams/${params.id}`).reply(500); - this.logStreams.get().catch(function(err) { + this.logStreams.get().catch((err) => { expect(err).to.exist; done(); }); }); - it('should pass the body of the response to the "then" handler', function(done) { + it('should pass the body of the response to the "then" handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/log-streams/' + params.id) - .reply(200, data); + nock(API_URL).get(`/log-streams/${params.id}`).reply(200, data); - this.logStreams.get(params).then(function(log) { + this.logStreams.get(params).then((log) => { expect(log.id).to.equal(data.id); done(); }); }); - it('should perform a GET request to /api/v2/log-streams/:id', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/log-streams/:id', function (done) { + const { request } = this; - this.logStreams.get(params).then(function() { + this.logStreams.get(params).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/log-streams') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.logStreams.getAll().then(function() { + this.logStreams.getAll().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the parameters in the query-string', function(done) { + it('should pass the parameters in the query-string', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/log-streams') .query({ include_fields: true, - fields: 'test' + fields: 'test', }) .reply(200); - this.logStreams.getAll({ include_fields: true, fields: 'test' }).then(function() { + this.logStreams.getAll({ include_fields: true, fields: 'test' }).then(() => { expect(request.isDone()).to.be.true; done(); @@ -220,76 +201,67 @@ describe('LogStreamsManager', function() { }); }); - describe('#create', function() { - var data = { - name: 'Test log stream' + describe('#create', () => { + const data = { + name: 'Test log stream', }; - beforeEach(function() { - this.request = nock(API_URL) - .post('/log-streams') - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).post('/log-streams').reply(200); }); - it('should accept a callback', function(done) { - this.logStreams.create(data, function() { + it('should accept a callback', function (done) { + this.logStreams.create(data, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.logStreams - .create(data) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.logStreams.create(data).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/log-streams') - .reply(500); + nock(API_URL).post('/log-streams').reply(500); - this.logStreams.create(data).catch(function(err) { + this.logStreams.create(data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a POST request to /api/v2/log-streams', function(done) { - var request = this.request; + it('should perform a POST request to /api/v2/log-streams', function (done) { + const { request } = this; - this.logStreams.create(data).then(function() { + this.logStreams.create(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the data in the body of the request', function(done) { + it('should pass the data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/log-streams', data) - .reply(200); + const request = nock(API_URL).post('/log-streams', data).reply(200); - this.logStreams.create(data).then(function() { + this.logStreams.create(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .post('/log-streams') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.logStreams.create(data).then(function() { + this.logStreams.create(data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -297,58 +269,52 @@ describe('LogStreamsManager', function() { }); }); - describe('#update', function() { - beforeEach(function() { + describe('#update', () => { + beforeEach(function () { this.data = { id: 5 }; - this.request = nock(API_URL) - .patch('/log-streams/' + this.data.id) - .reply(200, this.data); + this.request = nock(API_URL).patch(`/log-streams/${this.data.id}`).reply(200, this.data); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.logStreams.update({ id: 5 }, {}, done.bind(null, null)); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.logStreams .update({ id: 5 }, {}) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should perform a PATCH request to /api/v2/log-streams/5', function(done) { - var request = this.request; + it('should perform a PATCH request to /api/v2/log-streams/5', function (done) { + const { request } = this; - this.logStreams.update({ id: 5 }, {}).then(function() { + this.logStreams.update({ id: 5 }, {}).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the new data in the body of the request', function(done) { + it('should include the new data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/log-streams/' + this.data.id, this.data) - .reply(200); + const request = nock(API_URL).patch(`/log-streams/${this.data.id}`, this.data).reply(200); - this.logStreams.update({ id: 5 }, this.data).then(function() { + this.logStreams.update({ id: 5 }, this.data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/log-streams/' + this.data.id) - .reply(500); + nock(API_URL).patch(`/log-streams/${this.data.id}`).reply(500); - this.logStreams.update({ id: this.data.id }, this.data).catch(function(err) { + this.logStreams.update({ id: this.data.id }, this.data).catch((err) => { expect(err).to.exist; done(); @@ -356,56 +322,52 @@ describe('LogStreamsManager', function() { }); }); - describe('#delete', function() { - var id = 5; + describe('#delete', () => { + const id = 5; - beforeEach(function() { - this.request = nock(API_URL) - .delete('/log-streams/' + id) - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).delete(`/log-streams/${id}`).reply(200); }); - it('should accept a callback', function(done) { - this.logStreams.delete({ id: id }, done.bind(null, null)); + it('should accept a callback', function (done) { + this.logStreams.delete({ id }, done.bind(null, null)); }); - it('should return a promise when no callback is given', function(done) { - this.logStreams.delete({ id: id }).then(done.bind(null, null)); + it('should return a promise when no callback is given', function (done) { + this.logStreams.delete({ id }).then(done.bind(null, null)); }); - it('should perform a delete request to /log-streams/' + id, function(done) { - var request = this.request; + it(`should perform a delete request to /log-streams/${id}`, function (done) { + const { request } = this; - this.logStreams.delete({ id: id }).then(function() { + this.logStreams.delete({ id }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete('/log-streams/' + id) - .reply(500); + nock(API_URL).delete(`/log-streams/${id}`).reply(500); - this.logStreams.delete({ id: id }).catch(function(err) { + this.logStreams.delete({ id }).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the authorization header', function(done) { + it('should include the token in the authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete('/log-streams/' + id) - .matchHeader('authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .delete(`/log-streams/${id}`) + .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); - this.logStreams.delete({ id: id }).then(function() { + this.logStreams.delete({ id }).then(() => { expect(request.isDone()).to.be.true; done(); diff --git a/test/management/logs.tests.js b/test/management/logs.tests.js index 37e6ed5e6..d40814f16 100644 --- a/test/management/logs.tests.js +++ b/test/management/logs.tests.js @@ -1,92 +1,82 @@ -var expect = require('chai').expect; -var nock = require('nock'); +const { expect } = require('chai'); +const nock = require('nock'); -var SRC_DIR = '../../src'; -var API_URL = 'https://tenant.auth0.com'; +const API_URL = 'https://tenant.auth0.com'; -var LogsManager = require(SRC_DIR + '/management/LogsManager'); -var ArgumentError = require('rest-facade').ArgumentError; +const LogsManager = require(`../../src/management/LogsManager`); +const { ArgumentError } = require('rest-facade'); -describe('LogsManager', function() { - before(function() { +describe('LogsManager', () => { + before(function () { this.token = 'TOKEN'; this.logs = new LogsManager({ - headers: { authorization: 'Bearer ' + this.token }, - baseUrl: API_URL + headers: { authorization: `Bearer ${this.token}` }, + baseUrl: API_URL, }); }); - describe('instance', function() { - var methods = ['getAll', 'get']; + describe('instance', () => { + const methods = ['getAll', 'get']; - methods.forEach(function(method) { - it('should have a ' + method + ' method', function() { + methods.forEach((method) => { + it(`should have a ${method} method`, function () { expect(this.logs[method]).to.exist.to.be.an.instanceOf(Function); }); }); }); - describe('#constructor', function() { - it('should error when no options are provided', function() { + describe('#constructor', () => { + it('should error when no options are provided', () => { expect(LogsManager).to.throw(ArgumentError, 'Must provide client options'); }); - it('should throw an error when no base URL is provided', function() { - var client = LogsManager.bind(null, {}); + it('should throw an error when no base URL is provided', () => { + const client = LogsManager.bind(null, {}); expect(client).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); - it('should throw an error when the base URL is invalid', function() { - var client = LogsManager.bind(null, { baseUrl: '' }); + it('should throw an error when the base URL is invalid', () => { + const client = LogsManager.bind(null, { baseUrl: '' }); expect(client).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); - describe('#getAll', function() { - beforeEach(function() { - this.request = nock(API_URL) - .get('/logs') - .reply(200); + describe('#getAll', () => { + beforeEach(function () { + this.request = nock(API_URL).get('/logs').reply(200); }); - it('should accept a callback', function(done) { - this.logs.getAll(function() { + it('should accept a callback', function (done) { + this.logs.getAll(() => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.logs - .getAll() - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.logs.getAll().then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/logs') - .reply(500); + nock(API_URL).get('/logs').reply(500); - this.logs.getAll().catch(function(err) { + this.logs.getAll().catch((err) => { expect(err).to.exist; done(); }); }); - it('should pass the body of the response to the "then" handler', function(done) { + it('should pass the body of the response to the "then" handler', function (done) { nock.cleanAll(); - var data = [{ test: true }]; - var request = nock(API_URL) - .get('/logs') - .reply(200, data); + const data = [{ test: true }]; + nock(API_URL).get('/logs').reply(200, data); - this.logs.getAll().then(function(logs) { + this.logs.getAll().then((logs) => { expect(logs).to.be.an.instanceOf(Array); expect(logs.length).to.equal(data.length); @@ -97,42 +87,42 @@ describe('LogsManager', function() { }); }); - it('should perform a GET request to /api/v2/logs', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/logs', function (done) { + const { request } = this; - this.logs.getAll().then(function() { + this.logs.getAll().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/logs') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.logs.getAll().then(function() { + this.logs.getAll().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the parameters in the query-string', function(done) { + it('should pass the parameters in the query-string', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/logs') .query({ include_fields: true, - fields: 'test' + fields: 'test', }) .reply(200); - this.logs.getAll({ include_fields: true, fields: 'test' }).then(function() { + this.logs.getAll({ include_fields: true, fields: 'test' }).then(() => { expect(request.isDone()).to.be.true; done(); @@ -140,97 +130,88 @@ describe('LogsManager', function() { }); }); - describe('#get', function() { - var params = { id: 5 }; - var data = { + describe('#get', () => { + const params = { id: 5 }; + const data = { id: params.id, - name: 'Test log' + name: 'Test log', }; - beforeEach(function() { - this.request = nock(API_URL) - .get('/logs/' + data.id) - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).get(`/logs/${data.id}`).reply(200); }); - it('should accept a callback', function(done) { - this.logs.get(params, function() { + it('should accept a callback', function (done) { + this.logs.get(params, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.logs - .get(params) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.logs.get(params).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/logs/' + params.id) - .reply(500); + nock(API_URL).get(`/logs/${params.id}`).reply(500); - this.logs.get().catch(function(err) { + this.logs.get().catch((err) => { expect(err).to.exist; done(); }); }); - it('should pass the body of the response to the "then" handler', function(done) { + it('should pass the body of the response to the "then" handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/logs/' + params.id) - .reply(200, data); + nock(API_URL).get(`/logs/${params.id}`).reply(200, data); - this.logs.get(params).then(function(log) { + this.logs.get(params).then((log) => { expect(log.id).to.equal(data.id); done(); }); }); - it('should perform a GET request to /api/v2/logs/:id', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/logs/:id', function (done) { + const { request } = this; - this.logs.get(params).then(function() { + this.logs.get(params).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/logs') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.logs.getAll().then(function() { + this.logs.getAll().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the parameters in the query-string', function(done) { + it('should pass the parameters in the query-string', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/logs') .query({ include_fields: true, - fields: 'test' + fields: 'test', }) .reply(200); - this.logs.getAll({ include_fields: true, fields: 'test' }).then(function() { + this.logs.getAll({ include_fields: true, fields: 'test' }).then(() => { expect(request.isDone()).to.be.true; done(); diff --git a/test/management/management-client.tests.js b/test/management/management-client.tests.js index fee7794f6..01aa16aa9 100644 --- a/test/management/management-client.tests.js +++ b/test/management/management-client.tests.js @@ -1,133 +1,133 @@ -var expect = require('chai').expect; -var nock = require('nock'); -var sinon = require('sinon'); -var proxyquire = require('proxyquire'); - -var ManagementClient = require('../../src/management'); - -var ArgumentError = require('rest-facade').ArgumentError; -var UsersManager = require('../../src/management/UsersManager'); -var UserBlocksManager = require('../../src/management/UserBlocksManager'); -var BlacklistedTokensManager = require('../../src/management/BlacklistedTokensManager'); -var ClientsManager = require('../../src/management/ClientsManager'); -var ClientGrantsManager = require('../../src/management/ClientGrantsManager'); -var GrantsManager = require('../../src/management/GrantsManager'); -var ConnectionsManager = require('../../src/management/ConnectionsManager'); -var DeviceCredentialsManager = require('../../src/management/DeviceCredentialsManager'); -var EmailProviderManager = require('../../src/management/EmailProviderManager'); -var EmailTemplatesManager = require('../../src/management/EmailTemplatesManager'); -var JobsManager = require('../../src/management/JobsManager'); -var RulesManager = require('../../src/management/RulesManager'); -var StatsManager = require('../../src/management/StatsManager'); -var RulesConfigsManager = require('../../src/management/RulesConfigsManager'); -var TenantManager = require('../../src/management/TenantManager'); - -describe('ManagementClient', function() { - var withTokenProviderConfig = { +const { expect } = require('chai'); +const nock = require('nock'); +const sinon = require('sinon'); +const proxyquire = require('proxyquire'); + +const ManagementClient = require('../../src/management'); + +const { ArgumentError } = require('rest-facade'); +const UsersManager = require('../../src/management/UsersManager'); +const UserBlocksManager = require('../../src/management/UserBlocksManager'); +const BlacklistedTokensManager = require('../../src/management/BlacklistedTokensManager'); +const ClientsManager = require('../../src/management/ClientsManager'); +const ClientGrantsManager = require('../../src/management/ClientGrantsManager'); +const GrantsManager = require('../../src/management/GrantsManager'); +const ConnectionsManager = require('../../src/management/ConnectionsManager'); +const DeviceCredentialsManager = require('../../src/management/DeviceCredentialsManager'); +const EmailProviderManager = require('../../src/management/EmailProviderManager'); +const EmailTemplatesManager = require('../../src/management/EmailTemplatesManager'); +const JobsManager = require('../../src/management/JobsManager'); +const RulesManager = require('../../src/management/RulesManager'); +const StatsManager = require('../../src/management/StatsManager'); +const RulesConfigsManager = require('../../src/management/RulesConfigsManager'); +const TenantManager = require('../../src/management/TenantManager'); + +describe('ManagementClient', () => { + const withTokenProviderConfig = { clientId: 'clientId', clientSecret: 'clientSecret', domain: 'auth0-node-sdk.auth0.com', tokenProvider: { - enableCache: false - } + enableCache: false, + }, }; - var withTokenConfig = { + const withTokenConfig = { domain: 'auth0-node-sdk.auth0.com', - token: 'fake-token' + token: 'fake-token', }; - it('should expose an instance of ManagementClient when withTokenConfig is passed', function() { + it('should expose an instance of ManagementClient when withTokenConfig is passed', () => { expect(new ManagementClient(withTokenConfig)).to.exist.to.be.an.instanceOf(ManagementClient); }); - it('should expose an instance of ManagementClient when withTokenProviderConfig is passed', function() { + it('should expose an instance of ManagementClient when withTokenProviderConfig is passed', () => { expect(new ManagementClient(withTokenProviderConfig)).to.exist.to.be.an.instanceOf( ManagementClient ); }); - it('should expose an instance of ManagementClient when withTokenProviderConfig and audience is passed', function() { - var config = Object.assign( + it('should expose an instance of ManagementClient when withTokenProviderConfig and audience is passed', () => { + const config = Object.assign( { audience: 'https://auth0-node-sdk.auth0.com/api/v2/' }, withTokenConfig ); expect(new ManagementClient(config)).to.exist.to.be.an.instanceOf(ManagementClient); }); - it('should raise an error when no options object is provided', function() { + it('should raise an error when no options object is provided', () => { expect(ManagementClient).to.throw( ArgumentError, 'Management API SDK options must be an object' ); }); - it('should raise an error when the domain is not set', function() { - var config = Object.assign({}, withTokenConfig); + it('should raise an error when the domain is not set', () => { + const config = Object.assign({}, withTokenConfig); delete config.domain; - var client = ManagementClient.bind(null, config); + const client = ManagementClient.bind(null, config); expect(client).to.throw(ArgumentError, 'Must provide a domain'); }); - it('should raise an error when the domain is not valid', function() { - var config = Object.assign({}, withTokenConfig); + it('should raise an error when the domain is not valid', () => { + const config = Object.assign({}, withTokenConfig); config.domain = ''; - var client = ManagementClient.bind(null, config); + const client = ManagementClient.bind(null, config); expect(client).to.throw(ArgumentError, 'Must provide a domain'); }); - it('should raise an error when the token is not valid', function() { - var config = Object.assign({}, withTokenConfig); + it('should raise an error when the token is not valid', () => { + const config = Object.assign({}, withTokenConfig); config.token = ''; - var client = ManagementClient.bind(null, config); + const client = ManagementClient.bind(null, config); expect(client).to.throw(ArgumentError, 'Must provide a token'); }); - it('should raise an error when the token and clientId are not set', function() { - var config = Object.assign({}, withTokenProviderConfig); + it('should raise an error when the token and clientId are not set', () => { + const config = Object.assign({}, withTokenProviderConfig); delete config.clientId; - var client = ManagementClient.bind(null, config); + const client = ManagementClient.bind(null, config); expect(client).to.throw(ArgumentError, 'Must provide a clientId'); }); - it('should raise an error when the token and clientSecret are not set', function() { - var config = Object.assign({}, withTokenProviderConfig); + it('should raise an error when the token and clientSecret are not set', () => { + const config = Object.assign({}, withTokenProviderConfig); delete config.clientSecret; - var client = ManagementClient.bind(null, config); + const client = ManagementClient.bind(null, config); expect(client).to.throw(ArgumentError, 'Must provide a clientSecret'); }); - describe('getAccessToken', function() { - it('should return token provided in config', function(done) { - var config = Object.assign({}, withTokenConfig); - var client = new ManagementClient(config); + describe('getAccessToken', () => { + it('should return token provided in config', (done) => { + const config = Object.assign({}, withTokenConfig); + const client = new ManagementClient(config); - client.getAccessToken().then(function(accessToken) { + client.getAccessToken().then((accessToken) => { expect(accessToken).to.equal(withTokenConfig.token); done(); }); }); - it('should return token from provider', function(done) { - var config = Object.assign({}, withTokenProviderConfig); - var client = new ManagementClient(config); + it('should return token from provider', (done) => { + const config = Object.assign({}, withTokenProviderConfig); + const client = new ManagementClient(config); - nock('https://' + config.domain) - .post('/oauth/token', function(body) { + nock(`https://${config.domain}`) + .post('/oauth/token', (body) => { expect(body.client_id).to.equal(config.clientId); expect(body.client_secret).to.equal(config.clientSecret); expect(body.grant_type).to.equal('client_credentials'); return true; }) - .reply(function(uri, requestBody, cb) { - return cb(null, [200, { access_token: 'token', expires_in: 3600 }]); - }); + .reply((uri, requestBody, cb) => + cb(null, [200, { access_token: 'token', expires_in: 3600 }]) + ); - client.getAccessToken().then(function(data) { + client.getAccessToken().then((data) => { expect(data).to.equal('token'); done(); nock.cleanAll(); @@ -135,119 +135,117 @@ describe('ManagementClient', function() { }); }); - describe('instance properties', function() { - var manager; - var managers = { + describe('instance properties', () => { + let manager; + const managers = { UsersManager: { property: 'users', - cls: UsersManager + cls: UsersManager, }, UserBlocksManager: { property: 'userBlocks', - cls: UserBlocksManager + cls: UserBlocksManager, }, BlacklistedTokensManager: { property: 'blacklistedTokens', - cls: BlacklistedTokensManager + cls: BlacklistedTokensManager, }, ClientsManager: { property: 'clients', - cls: ClientsManager + cls: ClientsManager, }, ClientGrantsManager: { property: 'clientGrants', - cls: ClientGrantsManager + cls: ClientGrantsManager, }, GrantsManager: { property: 'grants', - cls: GrantsManager + cls: GrantsManager, }, ConnectionsManager: { property: 'connections', - cls: ConnectionsManager + cls: ConnectionsManager, }, DeviceCredentialsManager: { property: 'deviceCredentials', - cls: DeviceCredentialsManager + cls: DeviceCredentialsManager, }, EmailProviderManager: { property: 'emailProvider', - cls: EmailProviderManager + cls: EmailProviderManager, }, EmailTemplatesManager: { property: 'emailTemplates', - cls: EmailTemplatesManager + cls: EmailTemplatesManager, }, JobsManager: { property: 'jobs', - cls: JobsManager + cls: JobsManager, }, RulesManager: { property: 'rules', - cls: RulesManager + cls: RulesManager, }, StatsManager: { property: 'stats', - cls: StatsManager + cls: StatsManager, }, TenantManager: { property: 'tenant', - cls: TenantManager + cls: TenantManager, }, RulesConfigsManager: { property: 'rulesConfigs', - cls: RulesConfigsManager - } + cls: RulesConfigsManager, + }, }; - describe('user agent', function() { - for (var name in managers) { + describe('user agent', () => { + for (const name in managers) { manager = managers[name]; - it(manager + ' should use the node version by default', function() { - var client = new ManagementClient(withTokenConfig); + it(`${manager} should use the node version by default`, () => { + const client = new ManagementClient(withTokenConfig); expect( client[manager.property].resource.restClient.restClient.options.headers ).to.contain({ - 'User-Agent': 'node.js/' + process.version.replace('v', '') + 'User-Agent': `node.js/${process.version.replace('v', '')}`, }); }); - it(manager + ' should include additional headers when provided', function() { - var customHeaders = { + it(`${manager} should include additional headers when provided`, () => { + const customHeaders = { 'User-Agent': 'my-user-agent', - 'Another-header': 'test-header' + 'Another-header': 'test-header', }; - var options = Object.assign({ headers: customHeaders }, withTokenConfig); - var client = new ManagementClient(options); + const options = Object.assign({ headers: customHeaders }, withTokenConfig); + const client = new ManagementClient(options); expect( client[manager.property].resource.restClient.restClient.options.headers ).to.contain({ 'User-Agent': 'my-user-agent', - 'Another-header': 'test-header' + 'Another-header': 'test-header', }); }); } }); - describe('client info', function() { - it('should configure instances with default telemetry header', function() { - var utilsStub = { - generateClientInfo: sinon.spy(function() { - return { name: 'test-sdk', version: 'ver-123' }; - }) + describe('client info', () => { + it('should configure instances with default telemetry header', () => { + const utilsStub = { + generateClientInfo: sinon.spy(() => ({ name: 'test-sdk', version: 'ver-123' })), }; - var ManagementClientProxy = proxyquire('../../src/management/', { - '../utils': utilsStub + const ManagementClientProxy = proxyquire('../../src/management/', { + '../utils': utilsStub, }); - var client = new ManagementClientProxy(withTokenConfig); + const client = new ManagementClientProxy(withTokenConfig); - var requestHeaders = { + const requestHeaders = { 'Auth0-Client': 'eyJuYW1lIjoidGVzdC1zZGsiLCJ2ZXJzaW9uIjoidmVyLTEyMyJ9', - 'Content-Type': 'application/json' + 'Content-Type': 'application/json', }; expect(client.clients.resource.restClient.restClient.options.headers).to.contain( @@ -384,18 +382,18 @@ describe('ManagementClient', function() { expect(client.roles.users.restClient.restClient.options.headers).to.contain(requestHeaders); }); - it('should configure instances with custom telemetry header', function() { - var customTelemetry = { name: 'custom', version: 'beta-01', env: { node: 'v10' } }; - var client = new ManagementClient({ + it('should configure instances with custom telemetry header', () => { + const customTelemetry = { name: 'custom', version: 'beta-01', env: { node: 'v10' } }; + const client = new ManagementClient({ token: 'token', domain: 'auth0.com', - clientInfo: customTelemetry + clientInfo: customTelemetry, }); - var requestHeaders = { + const requestHeaders = { 'Auth0-Client': 'eyJuYW1lIjoiY3VzdG9tIiwidmVyc2lvbiI6ImJldGEtMDEiLCJlbnYiOnsibm9kZSI6InYxMCJ9fQ', - 'Content-Type': 'application/json' + 'Content-Type': 'application/json', }; expect(client.clients.resource.restClient.restClient.options.headers).to.contain( @@ -532,12 +530,12 @@ describe('ManagementClient', function() { expect(client.roles.users.restClient.restClient.options.headers).to.contain(requestHeaders); }); - it('should configure instances without telemetry when "name" property is empty', function() { - var customTelemetry = { name: '', version: 'beta-01', env: { node: 'v10' } }; - var client = new ManagementClient({ + it('should configure instances without telemetry when "name" property is empty', () => { + const customTelemetry = { name: '', version: 'beta-01', env: { node: 'v10' } }; + const client = new ManagementClient({ token: 'token', domain: 'auth0.com', - clientInfo: customTelemetry + clientInfo: customTelemetry, }); expect(client.clients.resource.restClient.restClient.options.headers).to.not.have.property( @@ -682,11 +680,11 @@ describe('ManagementClient', function() { ); }); - it('should configure instances without telemetry header when disabled', function() { - var client = new ManagementClient({ + it('should configure instances without telemetry header when disabled', () => { + const client = new ManagementClient({ token: 'token', domain: 'auth0.com', - telemetry: false + telemetry: false, }); expect(client.clients.resource.restClient.restClient.options.headers).to.not.have.property( @@ -832,23 +830,23 @@ describe('ManagementClient', function() { }); }); - before(function() { - var config = Object.assign({}, withTokenConfig); + before(function () { + const config = Object.assign({}, withTokenConfig); this.client = new ManagementClient(config); }); // Tests common to all managers. - for (var name in managers) { + for (const name in managers) { manager = managers[name]; - it('should expose an instance of ' + name, function() { + it(`should expose an instance of ${name}`, function () { expect(this.client[manager.property]).to.exist.to.be.an.instanceOf(manager.cls); }); } }); - describe('instance methods', function() { - var methods = [ + describe('instance methods', () => { + const methods = [ 'getConnections', 'createConnection', 'getConnection', @@ -918,16 +916,16 @@ describe('ManagementClient', function() { 'unblockUserByIdentifier', 'getAccessToken', 'getPromptsSettings', - 'updatePromptsSettings' + 'updatePromptsSettings', ]; - before(function() { - var config = Object.assign({}, withTokenConfig); + before(function () { + const config = Object.assign({}, withTokenConfig); this.client = new ManagementClient(config); }); - methods.forEach(function(method) { - it('should have a ' + method + ' method', function() { + methods.forEach((method) => { + it(`should have a ${method} method`, function () { expect(this.client[method]).to.exist.to.be.an.instanceOf(Function); }); }); diff --git a/test/management/management-token-provider.tests.js b/test/management/management-token-provider.tests.js index 84f4fa056..78fc71698 100644 --- a/test/management/management-token-provider.tests.js +++ b/test/management/management-token-provider.tests.js @@ -1,176 +1,172 @@ -var expect = require('chai').expect; -var nock = require('nock'); -var ArgumentError = require('rest-facade').ArgumentError; -var SanitizedError = require('../../src/errors').SanitizedError; +const { expect } = require('chai'); +const nock = require('nock'); +const { ArgumentError } = require('rest-facade'); +const { SanitizedError } = require('../../src/errors'); -var ManagementTokenProvider = require('../../src/management/ManagementTokenProvider'); +const ManagementTokenProvider = require('../../src/management/ManagementTokenProvider'); -describe('ManagementTokenProvider', function() { - var defaultConfig = { +describe('ManagementTokenProvider', () => { + const defaultConfig = { clientId: 'clientId', clientSecret: 'clientSecret', domain: 'auth0-node-sdk.auth0.com', - audience: 'https://auth0-node-sdk.auth0.com/api/v2/' + audience: 'https://auth0-node-sdk.auth0.com/api/v2/', }; - it('should expose an instance of ManagementTokenProvider', function() { + it('should expose an instance of ManagementTokenProvider', () => { expect(new ManagementTokenProvider(defaultConfig)).to.exist.to.be.an.instanceOf( ManagementTokenProvider ); }); - it('should raise an error when no options object is provided', function() { + it('should raise an error when no options object is provided', () => { expect(ManagementTokenProvider).to.throw(ArgumentError, 'Options must be an object'); }); - it('should raise an error when domain is not set', function() { - var config = Object.assign({}, defaultConfig); + it('should raise an error when domain is not set', () => { + const config = Object.assign({}, defaultConfig); delete config.domain; - var provider = ManagementTokenProvider.bind(null, config); + const provider = ManagementTokenProvider.bind(null, config); expect(provider).to.throw(ArgumentError, 'Must provide a domain'); }); - it('should raise an error when domain is not valid', function() { - var config = Object.assign({}, defaultConfig); + it('should raise an error when domain is not valid', () => { + const config = Object.assign({}, defaultConfig); config.domain = ''; - var provider = ManagementTokenProvider.bind(null, config); + const provider = ManagementTokenProvider.bind(null, config); expect(provider).to.throw(ArgumentError, 'Must provide a domain'); }); - it('should raise an error when clientId is not set', function() { - var config = Object.assign({}, defaultConfig); + it('should raise an error when clientId is not set', () => { + const config = Object.assign({}, defaultConfig); delete config.clientId; - var provider = ManagementTokenProvider.bind(null, config); + const provider = ManagementTokenProvider.bind(null, config); expect(provider).to.throw(ArgumentError, 'Must provide a clientId'); }); - it('should raise an error when clientId is not valid', function() { - var config = Object.assign({}, defaultConfig); + it('should raise an error when clientId is not valid', () => { + const config = Object.assign({}, defaultConfig); config.clientId = ''; - var provider = ManagementTokenProvider.bind(null, config); + const provider = ManagementTokenProvider.bind(null, config); expect(provider).to.throw(ArgumentError, 'Must provide a clientId'); }); - it('should raise an error when clientSecret is not set', function() { - var config = Object.assign({}, defaultConfig); + it('should raise an error when clientSecret is not set', () => { + const config = Object.assign({}, defaultConfig); delete config.clientSecret; - var provider = ManagementTokenProvider.bind(null, config); + const provider = ManagementTokenProvider.bind(null, config); expect(provider).to.throw(ArgumentError, 'Must provide a clientSecret'); }); - it('should raise an error when clientSecret is not valid', function() { - var config = Object.assign({}, defaultConfig); + it('should raise an error when clientSecret is not valid', () => { + const config = Object.assign({}, defaultConfig); config.clientSecret = ''; - var provider = ManagementTokenProvider.bind(null, config); + const provider = ManagementTokenProvider.bind(null, config); expect(provider).to.throw(ArgumentError, 'Must provide a clientSecret'); }); - it('should raise an error when enableCache is not of type boolean', function() { - var config = Object.assign({}, defaultConfig); + it('should raise an error when enableCache is not of type boolean', () => { + const config = Object.assign({}, defaultConfig); config.enableCache = 'string'; - var provider = ManagementTokenProvider.bind(null, config); + const provider = ManagementTokenProvider.bind(null, config); expect(provider).to.throw(ArgumentError, 'enableCache must be a boolean'); }); - it('should raise an error when scope is not of type string', function() { - var config = Object.assign({}, defaultConfig); + it('should raise an error when scope is not of type string', () => { + const config = Object.assign({}, defaultConfig); config.scope = ['foo', 'bar']; - var provider = ManagementTokenProvider.bind(null, config); + const provider = ManagementTokenProvider.bind(null, config); expect(provider).to.throw(ArgumentError, 'scope must be a string'); }); - it('should set scope to read:users when passed as read:users', function() { - var config = Object.assign({}, defaultConfig); + it('should set scope to read:users when passed as read:users', () => { + const config = Object.assign({}, defaultConfig); config.scope = 'read:users'; - var provider = new ManagementTokenProvider(config); + const provider = new ManagementTokenProvider(config); expect(provider.options.scope).to.be.equal('read:users'); }); - it('should set enableCache to true when not specified', function() { - var config = Object.assign({}, defaultConfig); + it('should set enableCache to true when not specified', () => { + const config = Object.assign({}, defaultConfig); delete config.enableCache; - var provider = new ManagementTokenProvider(config); + const provider = new ManagementTokenProvider(config); expect(provider.options.enableCache).to.be.true; }); - it('should set enableCache to true when passed as true', function() { - var config = Object.assign({}, defaultConfig); + it('should set enableCache to true when passed as true', () => { + const config = Object.assign({}, defaultConfig); config.enableCache = true; - var provider = new ManagementTokenProvider(config); + const provider = new ManagementTokenProvider(config); expect(provider.options.enableCache).to.be.true; }); - it('should set enableCache to false when passed as false', function() { - var config = Object.assign({}, defaultConfig); + it('should set enableCache to false when passed as false', () => { + const config = Object.assign({}, defaultConfig); config.enableCache = false; - var provider = new ManagementTokenProvider(config); + const provider = new ManagementTokenProvider(config); expect(provider.options.enableCache).to.be.false; }); - it('should raise an error when the cacheTTLInSeconds is not of type number', function() { - var config = Object.assign({}, defaultConfig); + it('should raise an error when the cacheTTLInSeconds is not of type number', () => { + const config = Object.assign({}, defaultConfig); config.cacheTTLInSeconds = 'string'; - var provider = ManagementTokenProvider.bind(null, config); + const provider = ManagementTokenProvider.bind(null, config); expect(provider).to.throw(ArgumentError, 'cacheTTLInSeconds must be a number'); }); - it('should raise an error when the cacheTTLInSeconds is not a greater than 0', function() { - var config = Object.assign({}, defaultConfig); + it('should raise an error when the cacheTTLInSeconds is not a greater than 0', () => { + const config = Object.assign({}, defaultConfig); config.cacheTTLInSeconds = -1; - var provider = ManagementTokenProvider.bind(null, config); + const provider = ManagementTokenProvider.bind(null, config); expect(provider).to.throw(ArgumentError, 'cacheTTLInSeconds must be a greater than 0'); }); - it('should set cacheTTLInSeconds to 15 when passed as 15', function() { - var config = Object.assign({}, defaultConfig); + it('should set cacheTTLInSeconds to 15 when passed as 15', () => { + const config = Object.assign({}, defaultConfig); config.cacheTTLInSeconds = 15; - var provider = new ManagementTokenProvider(config); + const provider = new ManagementTokenProvider(config); expect(provider.options.cacheTTLInSeconds).to.be.equal(15); }); - it('should set headers when passed into options', function() { - var config = Object.assign({}, defaultConfig); + it('should set headers when passed into options', () => { + const config = Object.assign({}, defaultConfig); config.headers = { 'User-Agent': 'node.js', - 'Content-Type': 'application/json' + 'Content-Type': 'application/json', }; - var provider = new ManagementTokenProvider(config); + const provider = new ManagementTokenProvider(config); expect(provider.options.headers).to.be.equal(config.headers); }); - it('should handle network errors correctly', function(done) { - var config = Object.assign({}, defaultConfig); + it('should handle network errors correctly', (done) => { + const config = Object.assign({}, defaultConfig); config.domain = 'domain'; - var client = new ManagementTokenProvider(config); + const client = new ManagementTokenProvider(config); - nock('https://' + config.domain) - .post('/oauth/token') - .reply(401); + nock(`https://${config.domain}`).post('/oauth/token').reply(401); - client.getAccessToken().catch(function(err) { + client.getAccessToken().catch((err) => { expect(err).to.exist; done(); nock.cleanAll(); }); }); - it('should handle unauthorized errors correctly', function(done) { - var client = new ManagementTokenProvider(defaultConfig); - nock('https://' + defaultConfig.domain) - .post('/oauth/token') - .reply(401); + it('should handle unauthorized errors correctly', (done) => { + const client = new ManagementTokenProvider(defaultConfig); + nock(`https://${defaultConfig.domain}`).post('/oauth/token').reply(401); - client.getAccessToken().catch(function(err) { + client.getAccessToken().catch((err) => { expect(err).to.exist.to.be.an.instanceOf(SanitizedError); expect(err.statusCode).to.be.equal(401); done(); @@ -178,21 +174,19 @@ describe('ManagementTokenProvider', function() { }); }); function timeout(ms) { - return new Promise(resolve => setTimeout(resolve, ms)); + return new Promise((resolve) => setTimeout(resolve, ms)); } - it('should expire access token from cache by the expires_in setting', async function() { + it('should expire access token from cache by the expires_in setting', async function () { this.timeout(15000); // buffer time to test an artificial delay of 10s - var config = Object.assign({}, defaultConfig); + const config = Object.assign({}, defaultConfig); config.domain = 'auth0-node-sdk-1.auth0.com'; - var client = new ManagementTokenProvider(config); + const client = new ManagementTokenProvider(config); - nock('https://' + config.domain) - .post('/oauth/token') - .reply(200, { - access_token: 'token', - expires_in: 10 - }); + nock(`https://${config.domain}`).post('/oauth/token').reply(200, { + access_token: 'token', + expires_in: 10, + }); const access_token = await client.getAccessToken(); expect(access_token).to.exist; @@ -200,12 +194,10 @@ describe('ManagementTokenProvider', function() { await client.getAccessToken(); await timeout(10000); - nock('https://' + config.domain) - .post('/oauth/token') - .reply(200, { - access_token: 'token2', - expires_in: 10 - }); + nock(`https://${config.domain}`).post('/oauth/token').reply(200, { + access_token: 'token2', + expires_in: 10, + }); const access_token2 = await client.getAccessToken(); expect(access_token2).to.exist; expect(access_token2).to.be.equal('token2'); @@ -213,19 +205,17 @@ describe('ManagementTokenProvider', function() { nock.cleanAll(); }); - it('should return access token', function(done) { - var config = Object.assign({}, defaultConfig); + it('should return access token', (done) => { + const config = Object.assign({}, defaultConfig); config.domain = 'auth0-node-sdk-1.auth0.com'; - var client = new ManagementTokenProvider(config); + const client = new ManagementTokenProvider(config); - nock('https://' + config.domain) - .post('/oauth/token') - .reply(200, { - access_token: 'token', - expires_in: 3600 - }); + nock(`https://${config.domain}`).post('/oauth/token').reply(200, { + access_token: 'token', + expires_in: 3600, + }); - client.getAccessToken().then(function(access_token) { + client.getAccessToken().then((access_token) => { expect(access_token).to.exist; expect(access_token).to.be.equal('token'); done(); @@ -233,224 +223,221 @@ describe('ManagementTokenProvider', function() { }); }); - it('should contain correct body payload', function(done) { - var config = Object.assign({}, defaultConfig); + it('should contain correct body payload', (done) => { + const config = Object.assign({}, defaultConfig); config.domain = 'auth0-node-sdk-2.auth0.com'; - var client = new ManagementTokenProvider(config); + const client = new ManagementTokenProvider(config); - nock('https://' + config.domain) - .post('/oauth/token', function(body) { + nock(`https://${config.domain}`) + .post('/oauth/token', (body) => { expect(body.client_id).to.equal('clientId'); expect(body.client_secret).to.equal('clientSecret'); expect(body.grant_type).to.equal('client_credentials'); return true; }) - .reply(function(uri, requestBody, cb) { - return cb(null, [200, { access_token: 'token', expires_in: 3600 }]); - }); + .reply((uri, requestBody, cb) => + cb(null, [200, { access_token: 'token', expires_in: 3600 }]) + ); - client.getAccessToken().then(function(data) { + client.getAccessToken().then(() => { done(); nock.cleanAll(); }); }); - it('should return access token from the cache the second call', function(done) { - var config = Object.assign({}, defaultConfig); + it('should return access token from the cache the second call', (done) => { + const config = Object.assign({}, defaultConfig); config.domain = 'auth0-node-sdk-3.auth0.com'; - var client = new ManagementTokenProvider(config); + const client = new ManagementTokenProvider(config); - nock('https://' + config.domain) - .post('/oauth/token') - .once() - .reply(200, { - access_token: 'access_token', - expires_in: 3600 - }); + nock(`https://${config.domain}`).post('/oauth/token').once().reply(200, { + access_token: 'access_token', + expires_in: 3600, + }); - client.getAccessToken().then(function(access_token) { + client.getAccessToken().then((access_token) => { expect(access_token).to.exist; expect(access_token).to.be.equal('access_token'); - setTimeout(function() { + setTimeout(() => { client .getAccessToken() - .then(function(access_token) { + .then((access_token) => { expect(access_token).to.exist; expect(access_token).to.be.equal('access_token'); done(); nock.cleanAll(); }) - .catch(function(err) { + .catch(() => { expect.fail(); done(); nock.cleanAll(); }); - }, 40); // 40ms + }, 40); }); }); - it('should request new access token when cache is expired', function(done) { - var config = Object.assign({}, defaultConfig); + it('should request new access token when cache is expired', (done) => { + const config = Object.assign({}, defaultConfig); config.domain = 'auth0-node-sdk-4.auth0.com'; - var client = new ManagementTokenProvider(config); + const client = new ManagementTokenProvider(config); - nock('https://' + config.domain) + nock(`https://${config.domain}`) .post('/oauth/token') .reply(200, { access_token: 'access_token', - expires_in: 1 / 40 // 1sec / 40 = 25ms + expires_in: 1 / 40, // 1sec / 40 = 25ms }) .post('/oauth/token') .reply(200, { access_token: 'new_access_token', - expires_in: 3600 + expires_in: 3600, }); - client.getAccessToken().then(function(access_token) { + client.getAccessToken().then((access_token) => { expect(access_token).to.exist; expect(access_token).to.be.equal('access_token'); - setTimeout(function() { + setTimeout(() => { client .getAccessToken() - .then(function(access_token) { + .then((access_token) => { expect(access_token).to.exist; expect(access_token).to.be.equal('new_access_token'); done(); nock.cleanAll(); }) - .catch(function(err) { + .catch(() => { expect.fail(); done(); nock.cleanAll(); }); - }, 40); // 40ms + }, 40); }); }); - it('should return new access token on the second call when cache is disabled', function(done) { - var config = Object.assign({}, defaultConfig); + it('should return new access token on the second call when cache is disabled', (done) => { + const config = Object.assign({}, defaultConfig); config.enableCache = false; config.domain = 'auth0-node-sdk-3.auth0.com'; - var client = new ManagementTokenProvider(config); + const client = new ManagementTokenProvider(config); - nock('https://' + config.domain) + nock(`https://${config.domain}`) .post('/oauth/token') .reply(200, { access_token: 'access_token', - expires_in: 3600 + expires_in: 3600, }) .post('/oauth/token') .reply(200, { access_token: 'new_access_token', - expires_in: 3600 + expires_in: 3600, }); - client.getAccessToken().then(function(access_token) { + client.getAccessToken().then((access_token) => { expect(access_token).to.exist; expect(access_token).to.be.equal('access_token'); - setTimeout(function() { + setTimeout(() => { client .getAccessToken() - .then(function(access_token) { + .then((access_token) => { expect(access_token).to.exist; expect(access_token).to.be.equal('new_access_token'); done(); nock.cleanAll(); }) - .catch(function(err) { + .catch(() => { expect.fail(); done(); nock.cleanAll(); }); - }, 40); // 40ms + }, 40); }); }); - it('should return cached access token on the second call when cacheTTLInSeconds is not passed', function(done) { - var config = Object.assign({}, defaultConfig); + it('should return cached access token on the second call when cacheTTLInSeconds is not passed', (done) => { + const config = Object.assign({}, defaultConfig); config.domain = 'auth0-node-sdk-5.auth0.com'; config.cacheTTLInSeconds = 10; // 1sec / 40 = 25ms; - var client = new ManagementTokenProvider(config); + const client = new ManagementTokenProvider(config); - nock('https://' + config.domain) + nock(`https://${config.domain}`) .post('/oauth/token') .reply(200, { - access_token: 'access_token' + access_token: 'access_token', }) .post('/oauth/token') .reply(200, { - access_token: 'new_access_token' + access_token: 'new_access_token', }); - client.getAccessToken().then(function(access_token) { + client.getAccessToken().then((access_token) => { expect(access_token).to.exist; expect(access_token).to.be.equal('access_token'); - setTimeout(function() { + setTimeout(() => { client .getAccessToken() - .then(function(access_token) { + .then((access_token) => { expect(access_token).to.exist; expect(access_token).to.be.equal('access_token'); done(); nock.cleanAll(); }) - .catch(function(err) { + .catch(() => { expect.fail(); done(); nock.cleanAll(); }); - }, 40); // 40ms + }, 40); }); }); - it('should return new access token on the second call when cacheTTLInSeconds is passed', function(done) { - var config = Object.assign({}, defaultConfig); + it('should return new access token on the second call when cacheTTLInSeconds is passed', (done) => { + const config = Object.assign({}, defaultConfig); config.domain = 'auth0-node-sdk-6.auth0.com'; config.cacheTTLInSeconds = 1 / 40; // 1sec / 40 = 25ms - var client = new ManagementTokenProvider(config); + const client = new ManagementTokenProvider(config); - nock('https://' + config.domain) + nock(`https://${config.domain}`) .post('/oauth/token') .reply(200, { - access_token: 'access_token' + access_token: 'access_token', }) .post('/oauth/token') .reply(200, { - access_token: 'new_access_token' + access_token: 'new_access_token', }); - client.getAccessToken().then(function(access_token) { + client.getAccessToken().then((access_token) => { expect(access_token).to.exist; expect(access_token).to.be.equal('access_token'); - setTimeout(function() { + setTimeout(() => { client .getAccessToken() - .then(function(access_token) { + .then((access_token) => { expect(access_token).to.exist; expect(access_token).to.be.equal('new_access_token'); done(); nock.cleanAll(); }) - .catch(function(err) { + .catch(() => { expect.fail(); done(); nock.cleanAll(); }); - }, 40); // 40ms + }, 40); }); }); - it('should pass the correct payload in the body of the oauth/token request with cache enabled', function(done) { - var config = Object.assign({}, defaultConfig); - var client = new ManagementTokenProvider(config); + it('should pass the correct payload in the body of the oauth/token request with cache enabled', (done) => { + const config = Object.assign({}, defaultConfig); + const client = new ManagementTokenProvider(config); - nock('https://' + config.domain) - .post('/oauth/token', function(payload) { + nock(`https://${config.domain}`) + .post('/oauth/token', (payload) => { expect(payload).to.exist; expect(payload.client_id).to.be.equal('clientId'); expect(payload.client_secret).to.be.equal('clientSecret'); @@ -459,19 +446,19 @@ describe('ManagementTokenProvider', function() { }) .reply(200); - client.getAccessToken().then(function(access_token) { + client.getAccessToken().then(() => { done(); nock.cleanAll(); }); }); - it('should pass the correct payload in the body of the oauth/token request with cache disabled', function(done) { - var config = Object.assign({}, defaultConfig); + it('should pass the correct payload in the body of the oauth/token request with cache disabled', (done) => { + const config = Object.assign({}, defaultConfig); config.enableCache = false; - var client = new ManagementTokenProvider(config); + const client = new ManagementTokenProvider(config); - nock('https://' + config.domain) - .post('/oauth/token', function(payload) { + nock(`https://${config.domain}`) + .post('/oauth/token', (payload) => { expect(payload).to.exist; expect(payload.client_id).to.be.equal('clientId'); expect(payload.client_secret).to.be.equal('clientSecret'); @@ -480,7 +467,7 @@ describe('ManagementTokenProvider', function() { }) .reply(200); - client.getAccessToken().then(function(access_token) { + client.getAccessToken().then(() => { done(); nock.cleanAll(); }); diff --git a/test/management/migrations.tests.js b/test/management/migrations.tests.js index 5a6db82d9..e68554cf6 100644 --- a/test/management/migrations.tests.js +++ b/test/management/migrations.tests.js @@ -1,91 +1,81 @@ -var expect = require('chai').expect; -var nock = require('nock'); +const { expect } = require('chai'); +const nock = require('nock'); -var SRC_DIR = '../../src'; -var API_URL = 'https://tenants.auth0.com'; +const API_URL = 'https://tenants.auth0.com'; -var MigrationsManager = require(SRC_DIR + '/management/MigrationsManager'); -var ArgumentError = require('rest-facade').ArgumentError; +const MigrationsManager = require(`../../src/management/MigrationsManager`); +const { ArgumentError } = require('rest-facade'); -describe('MigrationsManager', function() { - before(function() { +describe('MigrationsManager', () => { + before(function () { this.token = 'TOKEN'; this.migrations = new MigrationsManager({ - headers: { authorization: 'Bearer ' + this.token }, - baseUrl: API_URL + headers: { authorization: `Bearer ${this.token}` }, + baseUrl: API_URL, }); }); - describe('instance', function() { - var methods = ['updateMigrations', 'getMigrations']; + describe('instance', () => { + const methods = ['updateMigrations', 'getMigrations']; - methods.forEach(function(method) { - it('should have a ' + method + ' method', function() { + methods.forEach((method) => { + it(`should have a ${method} method`, function () { expect(this.migrations[method]).to.exist.to.be.an.instanceOf(Function); }); }); }); - describe('#constructor', function() { - it('should error when no options are provided', function() { + describe('#constructor', () => { + it('should error when no options are provided', () => { expect(MigrationsManager).to.throw(ArgumentError, 'Must provide manager options'); }); - it('should throw an error when no base URL is provided', function() { - var manager = MigrationsManager.bind(null, {}); + it('should throw an error when no base URL is provided', () => { + const manager = MigrationsManager.bind(null, {}); expect(manager).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); - it('should throw an error when the base URL is invalid', function() { - var manager = MigrationsManager.bind(null, { baseUrl: '' }); + it('should throw an error when the base URL is invalid', () => { + const manager = MigrationsManager.bind(null, { baseUrl: '' }); expect(manager).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); - describe('#getMigrations', function() { - beforeEach(function() { - this.request = nock(API_URL) - .get('/migrations') - .reply(200); + describe('#getMigrations', () => { + beforeEach(function () { + this.request = nock(API_URL).get('/migrations').reply(200); }); - it('should accept a callback', function(done) { - this.migrations.getMigrations(function() { + it('should accept a callback', function (done) { + this.migrations.getMigrations(() => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.migrations - .getMigrations() - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.migrations.getMigrations().then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/migrations') - .reply(500); + nock(API_URL).get('/migrations').reply(500); - this.migrations.getMigrations().catch(function(err) { + this.migrations.getMigrations().catch((err) => { expect(err).to.exist; done(); }); }); - it('should pass the body of the response to the "then" handler', function(done) { + it('should pass the body of the response to the "then" handler', function (done) { nock.cleanAll(); - var data = { flags: { migration_flag: true } }; - var request = nock(API_URL) - .get('/migrations') - .reply(200, data); + const data = { flags: { migration_flag: true } }; + nock(API_URL).get('/migrations').reply(200, data); - this.migrations.getMigrations().then(function(migrations) { + this.migrations.getMigrations().then((migrations) => { expect(migrations).to.be.an('object'); expect(migrations).to.have.nested.property('flags.migration_flag', true); @@ -94,117 +84,109 @@ describe('MigrationsManager', function() { }); }); - it('should perform a GET request to /api/v2/migrations', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/migrations', function (done) { + const { request } = this; - this.migrations.getMigrations().then(function() { + this.migrations.getMigrations().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/migrations') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.migrations.getMigrations().then(function() { + this.migrations.getMigrations().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the parameters in the query-string', function(done) { + it('should pass the parameters in the query-string', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/migrations') .query({ - any: 'test' + any: 'test', }) .reply(200); - this.migrations.getMigrations({ any: 'test' }).then(function() { + this.migrations.getMigrations({ any: 'test' }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); }); - describe('#updateMigrations', function() { - var data = { + describe('#updateMigrations', () => { + const data = { flags: { - migration: false - } + migration: false, + }, }; - beforeEach(function() { - this.request = nock(API_URL) - .patch('/migrations') - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).patch('/migrations').reply(200); }); - it('should accept a callback', function(done) { - this.migrations.updateMigrations(data, function() { + it('should accept a callback', function (done) { + this.migrations.updateMigrations(data, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.migrations .updateMigrations(data) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/migrations') - .reply(500); + nock(API_URL).patch('/migrations').reply(500); - this.migrations.updateMigrations(data).catch(function(err) { + this.migrations.updateMigrations(data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a PATCH request to /api/v2migrations', function(done) { - var request = this.request; + it('should perform a PATCH request to /api/v2migrations', function (done) { + const { request } = this; - this.migrations.updateMigrations(data).then(function() { + this.migrations.updateMigrations(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the data in the body of the request', function(done) { + it('should pass the data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/migrations', data) - .reply(200); + const request = nock(API_URL).patch('/migrations', data).reply(200); - this.migrations.updateMigrations(data).then(function() { + this.migrations.updateMigrations(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the body of the response to the "then" handler', function(done) { + it('should pass the body of the response to the "then" handler', function (done) { nock.cleanAll(); - var result = { flags: { migration_flag: true } }; - var request = nock(API_URL) - .patch('/migrations') - .reply(200, result); + const result = { flags: { migration_flag: true } }; + nock(API_URL).patch('/migrations').reply(200, result); - this.migrations.updateMigrations(data).then(function(migrations) { + this.migrations.updateMigrations(data).then((migrations) => { expect(migrations).to.be.an('object'); expect(migrations).to.have.nested.property('flags.migration_flag', true); @@ -213,15 +195,15 @@ describe('MigrationsManager', function() { }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .patch('/migrations') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.migrations.updateMigrations(data).then(function() { + this.migrations.updateMigrations(data).then(() => { expect(request.isDone()).to.be.true; done(); }); diff --git a/test/management/organizations.tests.js b/test/management/organizations.tests.js index 2bbc28616..077770eab 100644 --- a/test/management/organizations.tests.js +++ b/test/management/organizations.tests.js @@ -1,23 +1,22 @@ -var expect = require('chai').expect; -var nock = require('nock'); +const { expect } = require('chai'); +const nock = require('nock'); -var SRC_DIR = '../../src'; -var API_URL = 'https://tenant.auth0.com'; +const API_URL = 'https://tenant.auth0.com'; -var OrganizationsManager = require(SRC_DIR + '/management/OrganizationsManager'); -var ArgumentError = require('rest-facade').ArgumentError; +const OrganizationsManager = require(`../../src/management/OrganizationsManager`); +const { ArgumentError } = require('rest-facade'); -describe('OrganizationsManager', function() { - before(function() { +describe('OrganizationsManager', () => { + before(function () { this.token = 'TOKEN'; this.organizations = new OrganizationsManager({ - headers: { authorization: 'Bearer ' + this.token }, - baseUrl: API_URL + headers: { authorization: `Bearer ${this.token}` }, + baseUrl: API_URL, }); }); - describe('instance', function() { - var methods = [ + describe('instance', () => { + const methods = [ 'getByID', 'getByName', 'getAll', @@ -38,76 +37,67 @@ describe('OrganizationsManager', function() { 'getInvitations', 'getInvitation', 'createInvitation', - 'deleteInvitation' + 'deleteInvitation', ]; - methods.forEach(function(method) { - it('should have a ' + method + ' method', function() { + methods.forEach((method) => { + it(`should have a ${method} method`, function () { expect(this.organizations[method]).to.exist.to.be.an.instanceOf(Function); }); }); }); - describe('#constructor', function() { - it('should error when no options are provided', function() { + describe('#constructor', () => { + it('should error when no options are provided', () => { expect(OrganizationsManager).to.throw(ArgumentError, 'Must provide manager options'); }); - it('should throw an error when no base URL is provided', function() { - var client = OrganizationsManager.bind(null, {}); + it('should throw an error when no base URL is provided', () => { + const client = OrganizationsManager.bind(null, {}); expect(client).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); - it('should throw an error when the base URL is invalid', function() { - var client = OrganizationsManager.bind(null, { baseUrl: '' }); + it('should throw an error when the base URL is invalid', () => { + const client = OrganizationsManager.bind(null, { baseUrl: '' }); expect(client).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); - describe('#getAll', function() { - beforeEach(function() { - this.request = nock(API_URL) - .get('/organizations') - .reply(200); + describe('#getAll', () => { + beforeEach(function () { + this.request = nock(API_URL).get('/organizations').reply(200); }); - it('should accept a callback', function(done) { - this.organizations.getAll(function() { + it('should accept a callback', function (done) { + this.organizations.getAll(() => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.organizations - .getAll() - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.organizations.getAll().then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/organizations') - .reply(500); + nock(API_URL).get('/organizations').reply(500); - this.organizations.getAll().catch(function(err) { + this.organizations.getAll().catch((err) => { expect(err).to.exist; done(); }); }); - it('should pass the body of the response to the "then" handler', function(done) { + it('should pass the body of the response to the "then" handler', function (done) { nock.cleanAll(); - var data = [{ test: true }]; - var request = nock(API_URL) - .get('/organizations') - .reply(200, data); + const data = [{ test: true }]; + nock(API_URL).get('/organizations').reply(200, data); - this.organizations.getAll().then(function(credentials) { + this.organizations.getAll().then((credentials) => { expect(credentials).to.be.an.instanceOf(Array); expect(credentials.length).to.equal(data.length); @@ -118,42 +108,39 @@ describe('OrganizationsManager', function() { }); }); - it('should perform a GET request to /api/v2/organizations', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/organizations', function (done) { + const { request } = this; - this.organizations.getAll().then(function() { + this.organizations.getAll().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/organizations') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.organizations.getAll().then(function() { + this.organizations.getAll().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the parameters in the query-string', function(done) { + it('should pass the parameters in the query-string', function (done) { nock.cleanAll(); - var params = { + const params = { include_fields: true, - fields: 'test' + fields: 'test', }; - var request = nock(API_URL) - .get('/organizations') - .query(params) - .reply(200); + const request = nock(API_URL).get('/organizations').query(params).reply(200); - this.organizations.getAll(params).then(function() { + this.organizations.getAll(params).then(() => { expect(request.isDone()).to.be.true; done(); @@ -161,65 +148,61 @@ describe('OrganizationsManager', function() { }); }); - describe('#getByID', function() { - beforeEach(function() { + describe('#getByID', () => { + beforeEach(function () { this.data = { id: 'org_123456', name: 'organizations', - display_name: 'My organization' + display_name: 'My organization', }; - this.request = nock(API_URL) - .get('/organizations/' + this.data.id) - .reply(200, this.data); + this.request = nock(API_URL).get(`/organizations/${this.data.id}`).reply(200, this.data); }); - it('should accept a callback', function(done) { - var params = { id: this.data.id }; + it('should accept a callback', function (done) { + const params = { id: this.data.id }; this.organizations.getByID(params, done.bind(null, null)); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.organizations .getByID({ id: this.data.id }) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should perform a GET request to /api/v2/organizations/:id', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/organizations/:id', function (done) { + const { request } = this; - this.organizations.getByID({ id: this.data.id }).then(function() { + this.organizations.getByID({ id: this.data.id }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/organizations/' + this.data.id) - .reply(500); + nock(API_URL).get(`/organizations/${this.data.id}`).reply(500); - this.organizations.getByID({ id: this.data.id }).catch(function(err) { + this.organizations.getByID({ id: this.data.id }).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/organizations/' + this.data.id) - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .get(`/organizations/${this.data.id}`) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.organizations.getByID({ id: this.data.id }).then(function() { + this.organizations.getByID({ id: this.data.id }).then(() => { expect(request.isDone()).to.be.true; done(); @@ -227,65 +210,63 @@ describe('OrganizationsManager', function() { }); }); - describe('#getByName', function() { - beforeEach(function() { + describe('#getByName', () => { + beforeEach(function () { this.data = { id: 'org_123456', name: 'organizations', - display_name: 'My organization' + display_name: 'My organization', }; this.request = nock(API_URL) - .get('/organizations/name/' + this.data.name) + .get(`/organizations/name/${this.data.name}`) .reply(200, this.data); }); - it('should accept a callback', function(done) { - var params = { name: this.data.name }; + it('should accept a callback', function (done) { + const params = { name: this.data.name }; this.organizations.getByName(params, done.bind(null, null)); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.organizations .getByName({ name: this.data.name }) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should perform a GET request to /api/v2/organizations/name/:name', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/organizations/name/:name', function (done) { + const { request } = this; - this.organizations.getByName({ name: this.data.name }).then(function() { + this.organizations.getByName({ name: this.data.name }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/organizations/' + this.data.name) - .reply(500); + nock(API_URL).get(`/organizations/${this.data.name}`).reply(500); - this.organizations.getByName({ name: this.data.name }).catch(function(err) { + this.organizations.getByName({ name: this.data.name }).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/organizations/name/' + this.data.name) - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .get(`/organizations/name/${this.data.name}`) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.organizations.getByName({ name: this.data.name }).then(function() { + this.organizations.getByName({ name: this.data.name }).then(() => { expect(request.isDone()).to.be.true; done(); @@ -293,79 +274,70 @@ describe('OrganizationsManager', function() { }); }); - describe('#create', function() { - var data = { + describe('#create', () => { + const data = { id: 'org_123', name: 'org_name', - display_name: 'My Organization' + display_name: 'My Organization', }; - beforeEach(function() { - this.request = nock(API_URL) - .post('/organizations') - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).post('/organizations').reply(200); }); - it('should accept a callback', function(done) { - this.organizations.create(data, function() { + it('should accept a callback', function (done) { + this.organizations.create(data, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.organizations - .create(data) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.organizations.create(data).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/organizations') - .reply(500); + nock(API_URL).post('/organizations').reply(500); - this.organizations.create(data).catch(function(err) { + this.organizations.create(data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a POST request to /api/v2/organizations', function(done) { - var request = this.request; + it('should perform a POST request to /api/v2/organizations', function (done) { + const { request } = this; - this.organizations.create(data).then(function() { + this.organizations.create(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the data in the body of the request', function(done) { + it('should pass the data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/organizations', data) - .reply(200); + const request = nock(API_URL).post('/organizations', data).reply(200); - this.organizations.create(data).then(function() { + this.organizations.create(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .post('/organizations') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.organizations.create(data).then(function() { + this.organizations.create(data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -373,58 +345,52 @@ describe('OrganizationsManager', function() { }); }); - describe('#update', function() { - beforeEach(function() { + describe('#update', () => { + beforeEach(function () { this.data = { id: 'org_123' }; - this.request = nock(API_URL) - .patch('/organizations/' + this.data.id) - .reply(200, this.data); + this.request = nock(API_URL).patch(`/organizations/${this.data.id}`).reply(200, this.data); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.organizations.update({ id: 'org_123' }, {}, done.bind(null, null)); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.organizations .update({ id: 'org_123' }, {}) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should perform a PATCH request to /api/v2/organizations/org_123', function(done) { - var request = this.request; + it('should perform a PATCH request to /api/v2/organizations/org_123', function (done) { + const { request } = this; - this.organizations.update({ id: 'org_123' }, {}).then(function() { + this.organizations.update({ id: 'org_123' }, {}).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the new data in the body of the request', function(done) { + it('should include the new data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/organizations/' + this.data.id, this.data) - .reply(200); + const request = nock(API_URL).patch(`/organizations/${this.data.id}`, this.data).reply(200); - this.organizations.update({ id: 'org_123' }, this.data).then(function() { + this.organizations.update({ id: 'org_123' }, this.data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/organizations/' + this.data.id) - .reply(500); + nock(API_URL).patch(`/organizations/${this.data.id}`).reply(500); - this.organizations.update({ id: this.data.id }, this.data).catch(function(err) { + this.organizations.update({ id: this.data.id }, this.data).catch((err) => { expect(err).to.exist; done(); @@ -432,56 +398,52 @@ describe('OrganizationsManager', function() { }); }); - describe('#delete', function() { - var id = 'rol_ID'; + describe('#delete', () => { + const id = 'rol_ID'; - beforeEach(function() { - this.request = nock(API_URL) - .delete('/organizations/' + id) - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).delete(`/organizations/${id}`).reply(200); }); - it('should accept a callback', function(done) { - this.organizations.delete({ id: id }, done.bind(null, null)); + it('should accept a callback', function (done) { + this.organizations.delete({ id }, done.bind(null, null)); }); - it('should return a promise when no callback is given', function(done) { - this.organizations.delete({ id: id }).then(done.bind(null, null)); + it('should return a promise when no callback is given', function (done) { + this.organizations.delete({ id }).then(done.bind(null, null)); }); - it('should perform a delete request to /organizations/' + id, function(done) { - var request = this.request; + it(`should perform a delete request to /organizations/${id}`, function (done) { + const { request } = this; - this.organizations.delete({ id: id }).then(function() { + this.organizations.delete({ id }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete('/organizations/' + id) - .reply(500); + nock(API_URL).delete(`/organizations/${id}`).reply(500); - this.organizations.delete({ id: id }).catch(function(err) { + this.organizations.delete({ id }).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the authorization header', function(done) { + it('should include the token in the authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete('/organizations/' + id) - .matchHeader('authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .delete(`/organizations/${id}`) + .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); - this.organizations.delete({ id: id }).then(function() { + this.organizations.delete({ id }).then(() => { expect(request.isDone()).to.be.true; done(); @@ -490,58 +452,54 @@ describe('OrganizationsManager', function() { }); //// Connections - describe('#getEnabledConnections', function() { - var data = { - id: 'org_id' + describe('#getEnabledConnections', () => { + const data = { + id: 'org_id', }; - beforeEach(function() { - this.request = nock(API_URL) - .get('/organizations/' + data.id + '/enabled_connections') - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).get(`/organizations/${data.id}/enabled_connections`).reply(200); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.organizations.getEnabledConnections(data, done.bind(null, null)); }); - it('should return a promise when no callback is given', function(done) { + it('should return a promise when no callback is given', function (done) { this.organizations.getEnabledConnections(data).then(done.bind(null, null)); }); - it('should perform a GET request to /api/v2/organizations/org_id/enabled_connections', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/organizations/org_id/enabled_connections', function (done) { + const { request } = this; - this.organizations.getEnabledConnections(data).then(function() { + this.organizations.getEnabledConnections(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/organizations/' + data.id + '/enabled_connections') - .reply(500); + nock(API_URL).get(`/organizations/${data.id}/enabled_connections`).reply(500); - this.organizations.getEnabledConnections(data).catch(function(err) { + this.organizations.getEnabledConnections(data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the authorization header', function(done) { + it('should include the token in the authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/organizations/' + data.id + '/enabled_connections') - .matchHeader('authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .get(`/organizations/${data.id}/enabled_connections`) + .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); - this.organizations.getEnabledConnections(data).then(function() { + this.organizations.getEnabledConnections(data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -549,59 +507,59 @@ describe('OrganizationsManager', function() { }); }); - describe('#getEnabledConnection', function() { - var data = { + describe('#getEnabledConnection', () => { + const data = { id: 'org_id', - connection_id: 'conn_id' + connection_id: 'conn_id', }; - beforeEach(function() { + beforeEach(function () { this.request = nock(API_URL) - .get('/organizations/' + data.id + '/enabled_connections/' + data.connection_id) + .get(`/organizations/${data.id}/enabled_connections/${data.connection_id}`) .reply(200); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.organizations.getEnabledConnection(data, done.bind(null, null)); }); - it('should return a promise when no callback is given', function(done) { + it('should return a promise when no callback is given', function (done) { this.organizations.getEnabledConnection(data).then(done.bind(null, null)); }); - it('should perform a GET request to /api/v2/organizations/rol_ID/enabled_connections/con_id', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/organizations/rol_ID/enabled_connections/con_id', function (done) { + const { request } = this; - this.organizations.getEnabledConnection(data).then(function() { + this.organizations.getEnabledConnection(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/organizations/' + data.id + '/enabled_connections/' + data.connection_id) + nock(API_URL) + .get(`/organizations/${data.id}/enabled_connections/${data.connection_id}`) .reply(500); - this.organizations.getEnabledConnection(data).catch(function(err) { + this.organizations.getEnabledConnection(data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the authorization header', function(done) { + it('should include the token in the authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/organizations/' + data.id + '/enabled_connections/' + data.connection_id) - .matchHeader('authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .get(`/organizations/${data.id}/enabled_connections/${data.connection_id}`) + .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); - this.organizations.getEnabledConnection(data).then(function() { + this.organizations.getEnabledConnection(data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -609,92 +567,90 @@ describe('OrganizationsManager', function() { }); }); - describe('#addEnabledConnection', function() { - beforeEach(function() { + describe('#addEnabledConnection', () => { + beforeEach(function () { this.data = { - id: 'org_123' + id: 'org_123', }; this.body = { connection_id: '123', assign_membership_on_login: false }; this.request = nock(API_URL) - .post('/organizations/' + this.data.id + '/enabled_connections') + .post(`/organizations/${this.data.id}/enabled_connections`) .reply(200); }); - it('should accept a callback', function(done) { - this.organizations.addEnabledConnection(this.data, {}, function() { + it('should accept a callback', function (done) { + this.organizations.addEnabledConnection(this.data, {}, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.organizations .addEnabledConnection(this.data, {}) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/organizations/' + this.data.id + '/enabled_connections') - .reply(500); + nock(API_URL).post(`/organizations/${this.data.id}/enabled_connections`).reply(500); - this.organizations.addEnabledConnection(this.data, {}).catch(function(err) { + this.organizations.addEnabledConnection(this.data, {}).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a POST request to /api/v2/organizations/org_id/enabled_connections', function(done) { - var request = this.request; + it('should perform a POST request to /api/v2/organizations/org_id/enabled_connections', function (done) { + const { request } = this; - this.organizations.addEnabledConnection(this.data, this.body).then(function() { + this.organizations.addEnabledConnection(this.data, this.body).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should return error when id is not sent', function() { - var _this = this; - expect(function() { - _this.organizations.addEnabledConnection({ id: null }, {}, function() {}); + it('should return error when id is not sent', function () { + const _this = this; + expect(() => { + _this.organizations.addEnabledConnection({ id: null }, {}, () => {}); }).to.throw('The organization ID passed in params cannot be null or undefined'); }); - it('should return error when id is not a string', function() { - var _this = this; - expect(function() { - _this.organizations.addEnabledConnection({ id: 123 }, {}, function() {}); + it('should return error when id is not a string', function () { + const _this = this; + expect(() => { + _this.organizations.addEnabledConnection({ id: 123 }, {}, () => {}); }).to.throw('The organization ID has to be a string'); }); - it('should pass the data in the body of the request', function(done) { + it('should pass the data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/organizations/' + this.data.id + '/enabled_connections', this.body) + const request = nock(API_URL) + .post(`/organizations/${this.data.id}/enabled_connections`, this.body) .reply(200); - this.organizations.addEnabledConnection(this.data, this.body).then(function() { + this.organizations.addEnabledConnection(this.data, this.body).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/organizations/' + this.data.id + '/enabled_connections') - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .post(`/organizations/${this.data.id}/enabled_connections`) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.organizations.addEnabledConnection(this.data, {}).then(function() { + this.organizations.addEnabledConnection(this.data, {}).then(() => { expect(request.isDone()).to.be.true; done(); @@ -702,118 +658,118 @@ describe('OrganizationsManager', function() { }); }); - describe('#updateEnabledConnection', function() { - beforeEach(function() { + describe('#updateEnabledConnection', () => { + beforeEach(function () { this.data = { id: 'org_123', - connection_id: '123' + connection_id: '123', }; this.body = { assign_membership_on_login: false }; this.request = nock(API_URL) - .patch('/organizations/' + this.data.id + '/enabled_connections/' + this.data.connection_id) + .patch(`/organizations/${this.data.id}/enabled_connections/${this.data.connection_id}`) .reply(200); }); - it('should accept a callback', function(done) { - this.organizations.updateEnabledConnection(this.data, this.body, function() { + it('should accept a callback', function (done) { + this.organizations.updateEnabledConnection(this.data, this.body, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.organizations .updateEnabledConnection(this.data, this.body) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/organizations/' + this.data.id + '/enabled_connections/' + this.data.connection_id) + nock(API_URL) + .patch(`/organizations/${this.data.id}/enabled_connections/${this.data.connection_id}`) .reply(500); - this.organizations.updateEnabledConnection(this.data, this.body).catch(function(err) { + this.organizations.updateEnabledConnection(this.data, this.body).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a PATCH request to /api/v2/organizations/org_id/enabled_connections/conn_id', function(done) { - var request = this.request; + it('should perform a PATCH request to /api/v2/organizations/org_id/enabled_connections/conn_id', function (done) { + const { request } = this; - this.organizations.updateEnabledConnection(this.data, this.body).then(function() { + this.organizations.updateEnabledConnection(this.data, this.body).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should return error when id is not sent', function() { - var _this = this; - expect(function() { - _this.organizations.updateEnabledConnection({ id: null }, {}, function() {}); + it('should return error when id is not sent', function () { + const _this = this; + expect(() => { + _this.organizations.updateEnabledConnection({ id: null }, {}, () => {}); }).to.throw('The organization ID passed in params cannot be null or undefined'); }); - it('should return error when id is not a string', function() { - var _this = this; - expect(function() { - _this.organizations.updateEnabledConnection({ id: 123 }, {}, function() {}); + it('should return error when id is not a string', function () { + const _this = this; + expect(() => { + _this.organizations.updateEnabledConnection({ id: 123 }, {}, () => {}); }).to.throw('The organization ID has to be a string'); }); - it('should return error when connection_id is not sent', function() { - var _this = this; - expect(function() { + it('should return error when connection_id is not sent', function () { + const _this = this; + expect(() => { _this.organizations.updateEnabledConnection( { id: 'org_123', connection_id: null }, {}, - function() {} + () => {} ); }).to.throw('The connection ID passed in params cannot be null or undefined'); }); - it('should return error when connection_id is not a string', function() { - var _this = this; - expect(function() { + it('should return error when connection_id is not a string', function () { + const _this = this; + expect(() => { _this.organizations.updateEnabledConnection( { id: 'org_123', connection_id: 123 }, {}, - function() {} + () => {} ); }).to.throw('The connection ID has to be a string'); }); - it('should pass the data in the body of the request', function(done) { + it('should pass the data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .patch( - '/organizations/' + this.data.id + '/enabled_connections/' + this.data.connection_id, + `/organizations/${this.data.id}/enabled_connections/${this.data.connection_id}`, this.body ) .reply(200); - this.organizations.updateEnabledConnection(this.data, this.body).then(function() { + this.organizations.updateEnabledConnection(this.data, this.body).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/organizations/' + this.data.id + '/enabled_connections/' + this.data.connection_id) - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .patch(`/organizations/${this.data.id}/enabled_connections/${this.data.connection_id}`) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.organizations.updateEnabledConnection(this.data, this.body).then(function() { + this.organizations.updateEnabledConnection(this.data, this.body).then(() => { expect(request.isDone()).to.be.true; done(); @@ -821,102 +777,95 @@ describe('OrganizationsManager', function() { }); }); - describe('#removeEnabledConnection', function() { - beforeEach(function() { + describe('#removeEnabledConnection', () => { + beforeEach(function () { this.data = { id: 'org_123', - connection_id: '123' + connection_id: '123', }; this.request = nock(API_URL) - .delete( - '/organizations/' + this.data.id + '/enabled_connections/' + this.data.connection_id, - {} - ) + .delete(`/organizations/${this.data.id}/enabled_connections/${this.data.connection_id}`, {}) .reply(200); }); - it('should validate empty organizationId', function() { - var _this = this; - expect(function() { - _this.organizations.removeEnabledConnection({ id: null }, function() {}); + it('should validate empty organizationId', function () { + const _this = this; + expect(() => { + _this.organizations.removeEnabledConnection({ id: null }, () => {}); }).to.throw('The organization ID passed in params cannot be null or undefined'); }); - it('should validate empty connectionId', function() { - var _this = this; - expect(function() { - _this.organizations.removeEnabledConnection({ id: _this.data.id }, function() {}); + it('should validate empty connectionId', function () { + const _this = this; + expect(() => { + _this.organizations.removeEnabledConnection({ id: _this.data.id }, () => {}); }).to.throw('The connection ID passed in params cannot be null or undefined'); }); - it('should validate non-string organizationId', function() { - var _this = this; - expect(function() { - _this.organizations.removeEnabledConnection({ id: 123 }, function() {}); + it('should validate non-string organizationId', function () { + const _this = this; + expect(() => { + _this.organizations.removeEnabledConnection({ id: 123 }, () => {}); }).to.throw('The organization ID has to be a string'); }); - it('should validate non-string connectionId', function() { - var _this = this; - expect(function() { + it('should validate non-string connectionId', function () { + const _this = this; + expect(() => { _this.organizations.removeEnabledConnection( { id: _this.data.id, connection_id: 123 }, - function() {} + () => {} ); }).to.throw('The connection ID has to be a string'); }); - it('should accept a callback', function(done) { - this.organizations.removeEnabledConnection(this.data, function() { + it('should accept a callback', function (done) { + this.organizations.removeEnabledConnection(this.data, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.organizations .removeEnabledConnection(this.data) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete( - '/organizations/' + this.data.id + '/enabled_connections/' + this.data.connection_id - ) + nock(API_URL) + .delete(`/organizations/${this.data.id}/enabled_connections/${this.data.connection_id}`) .reply(500); - this.organizations.removeEnabledConnection(this.data, {}).catch(function(err) { + this.organizations.removeEnabledConnection(this.data, {}).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a DELETE request to /api/v2/organizations/organization_id/enabled_connections/connection_id', function(done) { - var request = this.request; + it('should perform a DELETE request to /api/v2/organizations/organization_id/enabled_connections/connection_id', function (done) { + const { request } = this; - this.organizations.removeEnabledConnection(this.data).then(function() { + this.organizations.removeEnabledConnection(this.data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete( - '/organizations/' + this.data.id + '/enabled_connections/' + this.data.connection_id - ) - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .delete(`/organizations/${this.data.id}/enabled_connections/${this.data.connection_id}`) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.organizations.removeEnabledConnection(this.data, {}).then(function() { + this.organizations.removeEnabledConnection(this.data, {}).then(() => { expect(request.isDone()).to.be.true; done(); @@ -925,58 +874,54 @@ describe('OrganizationsManager', function() { }); //// Members - describe('#getMembers', function() { - var data = { - id: 'org_id' + describe('#getMembers', () => { + const data = { + id: 'org_id', }; - beforeEach(function() { - this.request = nock(API_URL) - .get('/organizations/' + data.id + '/members') - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).get(`/organizations/${data.id}/members`).reply(200); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.organizations.getMembers(data, done.bind(null, null)); }); - it('should return a promise when no callback is given', function(done) { + it('should return a promise when no callback is given', function (done) { this.organizations.getMembers(data).then(done.bind(null, null)); }); - it('should perform a GET request to /api/v2/organizations/org_ID/members', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/organizations/org_ID/members', function (done) { + const { request } = this; - this.organizations.getMembers(data).then(function() { + this.organizations.getMembers(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/organizations/' + data.id + '/members') - .reply(500); + nock(API_URL).get(`/organizations/${data.id}/members`).reply(500); - this.organizations.getMembers(data).catch(function(err) { + this.organizations.getMembers(data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the authorization header', function(done) { + it('should include the token in the authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/organizations/' + data.id + '/members') - .matchHeader('authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .get(`/organizations/${data.id}/members`) + .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); - this.organizations.getMembers(data).then(function() { + this.organizations.getMembers(data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -984,92 +929,88 @@ describe('OrganizationsManager', function() { }); }); - describe('#addMembers', function() { - beforeEach(function() { + describe('#addMembers', () => { + beforeEach(function () { this.data = { - id: 'org_123' + id: 'org_123', }; this.body = ['user_id']; - this.request = nock(API_URL) - .post('/organizations/' + this.data.id + '/members', {}) - .reply(200); + this.request = nock(API_URL).post(`/organizations/${this.data.id}/members`, {}).reply(200); }); - it('should accept a callback', function(done) { - this.organizations.addMembers(this.data, {}, function() { + it('should accept a callback', function (done) { + this.organizations.addMembers(this.data, {}, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.organizations .addMembers(this.data, {}) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/organizations/' + this.data.id + '/members') - .reply(500); + nock(API_URL).post(`/organizations/${this.data.id}/members`).reply(500); - this.organizations.addMembers(this.data, {}).catch(function(err) { + this.organizations.addMembers(this.data, {}).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a POST request to /api/v2/organizations/org_id/members', function(done) { - var request = this.request; + it('should perform a POST request to /api/v2/organizations/org_id/members', function (done) { + const { request } = this; - this.organizations.addMembers(this.data, {}).then(function() { + this.organizations.addMembers(this.data, {}).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should return error when id is not sent', function() { - var _this = this; - expect(function() { - _this.organizations.addMembers({ id: null }, {}, function() {}); + it('should return error when id is not sent', function () { + const _this = this; + expect(() => { + _this.organizations.addMembers({ id: null }, {}, () => {}); }).to.throw('The organization ID passed in params cannot be null or undefined'); }); - it('should return error when id is not sent', function() { - var _this = this; - expect(function() { - _this.organizations.addMembers({ id: 123 }, {}, function() {}); + it('should return error when id is not sent', function () { + const _this = this; + expect(() => { + _this.organizations.addMembers({ id: 123 }, {}, () => {}); }).to.throw('The organization ID has to be a string'); }); - it('should pass the data in the body of the request', function(done) { + it('should pass the data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/organizations/' + this.data.id + '/members', this.body) + const request = nock(API_URL) + .post(`/organizations/${this.data.id}/members`, this.body) .reply(200); - this.organizations.addMembers(this.data, this.body).then(function() { + this.organizations.addMembers(this.data, this.body).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/organizations/' + this.data.id + '/members') - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .post(`/organizations/${this.data.id}/members`) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.organizations.addMembers(this.data, {}).then(function() { + this.organizations.addMembers(this.data, {}).then(() => { expect(request.isDone()).to.be.true; done(); @@ -1077,77 +1018,71 @@ describe('OrganizationsManager', function() { }); }); - describe('#removeMembers', function() { - beforeEach(function() { + describe('#removeMembers', () => { + beforeEach(function () { this.data = { - id: 'org_123' + id: 'org_123', }; this.body = ['user_id']; - this.request = nock(API_URL) - .delete('/organizations/' + this.data.id + '/members', {}) - .reply(200); + this.request = nock(API_URL).delete(`/organizations/${this.data.id}/members`, {}).reply(200); }); - it('should validate empty organizationId', function() { - var _this = this; - expect(function() { - _this.organizations.removeMembers({ id: null }, this.body, function() {}); + it('should validate empty organizationId', function () { + const _this = this; + expect(function () { + _this.organizations.removeMembers({ id: null }, this.body, () => {}); }).to.throw('The organization ID passed in params cannot be null or undefined'); }); - it('should validate non-string organizationId', function() { - var _this = this; - expect(function() { - _this.organizations.removeMembers({ id: 123 }, _this.body, function() {}); + it('should validate non-string organizationId', function () { + const _this = this; + expect(() => { + _this.organizations.removeMembers({ id: 123 }, _this.body, () => {}); }).to.throw('The organization ID has to be a string'); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.organizations .removeMembers(this.data, this.body) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete('/organizations/' + this.data.id + '/members') - .reply(500); + nock(API_URL).delete(`/organizations/${this.data.id}/members`).reply(500); - this.organizations.removeMembers(this.data, this.body).catch(function(err) { + this.organizations.removeMembers(this.data, this.body).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a DELETE request to /api/v2/organizations/organization_id/members', function(done) { - var request = this.request; - - var request = nock(API_URL) - .delete('/organizations/' + this.data.id + '/members', this.body) + it('should perform a DELETE request to /api/v2/organizations/organization_id/members', function (done) { + const request = nock(API_URL) + .delete(`/organizations/${this.data.id}/members`, this.body) .reply(200); - this.organizations.removeMembers(this.data, this.body, function() { + this.organizations.removeMembers(this.data, this.body, () => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete('/organizations/' + this.data.id + '/members', this.body) - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .delete(`/organizations/${this.data.id}/members`, this.body) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.organizations.removeMembers(this.data, this.body).then(function() { + this.organizations.removeMembers(this.data, this.body).then(() => { expect(request.isDone()).to.be.true; done(); @@ -1156,59 +1091,57 @@ describe('OrganizationsManager', function() { }); //// Roles - describe('#getMemberRoles', function() { - var data = { + describe('#getMemberRoles', () => { + const data = { id: 'org_id', - user_id: 'user_123' + user_id: 'user_123', }; - beforeEach(function() { + beforeEach(function () { this.request = nock(API_URL) - .get('/organizations/' + data.id + '/members/' + data.user_id + '/roles') + .get(`/organizations/${data.id}/members/${data.user_id}/roles`) .reply(200); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.organizations.getMemberRoles(data, done.bind(null, null)); }); - it('should return a promise when no callback is given', function(done) { + it('should return a promise when no callback is given', function (done) { this.organizations.getMemberRoles(data).then(done.bind(null, null)); }); - it('should perform a GET request to /api/v2/organizations/org_ID/members/user_id/roles', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/organizations/org_ID/members/user_id/roles', function (done) { + const { request } = this; - this.organizations.getMemberRoles(data).then(function() { + this.organizations.getMemberRoles(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/organizations/' + data.id + '/members/' + data.user_id + '/roles') - .reply(500); + nock(API_URL).get(`/organizations/${data.id}/members/${data.user_id}/roles`).reply(500); - this.organizations.getMemberRoles(data).catch(function(err) { + this.organizations.getMemberRoles(data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the authorization header', function(done) { + it('should include the token in the authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/organizations/' + data.id + '/members/' + data.user_id + '/roles') - .matchHeader('authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .get(`/organizations/${data.id}/members/${data.user_id}/roles`) + .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); - this.organizations.getMemberRoles(data).then(function() { + this.organizations.getMemberRoles(data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -1216,113 +1149,107 @@ describe('OrganizationsManager', function() { }); }); - describe('#addMemberRoles', function() { - beforeEach(function() { + describe('#addMemberRoles', () => { + beforeEach(function () { this.data = { id: 'org_123', - user_id: 'user_id' + user_id: 'user_id', }; this.body = { roles: ['user_id'] }; this.request = nock(API_URL) - .post( - '/organizations/' + this.data.id + '/members/' + this.data.user_id + '/roles', - this.body - ) + .post(`/organizations/${this.data.id}/members/${this.data.user_id}/roles`, this.body) .reply(200); }); - it('should accept a callback', function(done) { - this.organizations.addMemberRoles(this.data, this.body, function() { + it('should accept a callback', function (done) { + this.organizations.addMemberRoles(this.data, this.body, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.organizations .addMemberRoles(this.data, this.body) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/organizations/' + this.data.id + '/members/' + this.data.user_id + '/roles') + nock(API_URL) + .post(`/organizations/${this.data.id}/members/${this.data.user_id}/roles`) .reply(500); - this.organizations.addMemberRoles(this.data, {}).catch(function(err) { + this.organizations.addMemberRoles(this.data, {}).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a POST request to /api/v2/organizations/org_id/members/user_id/roles', function(done) { - var request = this.request; + it('should perform a POST request to /api/v2/organizations/org_id/members/user_id/roles', function (done) { + const { request } = this; - this.organizations.addMemberRoles(this.data, this.body).then(function() { + this.organizations.addMemberRoles(this.data, this.body).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should return error when id is not sent', function() { - var _this = this; - expect(function() { - _this.organizations.addMemberRoles({ id: null }, {}, function() {}); + it('should return error when id is not sent', function () { + const _this = this; + expect(() => { + _this.organizations.addMemberRoles({ id: null }, {}, () => {}); }).to.throw('The organization ID passed in params cannot be null or undefined'); }); - it('should return error when id is not sent', function() { - var _this = this; - expect(function() { - _this.organizations.addMemberRoles({ id: 123 }, {}, function() {}); + it('should return error when id is not sent', function () { + const _this = this; + expect(() => { + _this.organizations.addMemberRoles({ id: 123 }, {}, () => {}); }).to.throw('The organization ID has to be a string'); }); - it('should return error when id is not sent', function() { - var _this = this; - expect(function() { - _this.organizations.addMemberRoles({ id: 'org_123', user_id: null }, {}, function() {}); + it('should return error when id is not sent', function () { + const _this = this; + expect(() => { + _this.organizations.addMemberRoles({ id: 'org_123', user_id: null }, {}, () => {}); }).to.throw('The user ID passed in params cannot be null or undefined'); }); - it('should return error when id is not sent', function() { - var _this = this; - expect(function() { - _this.organizations.addMemberRoles({ id: 'org_123', user_id: 123 }, {}, function() {}); + it('should return error when id is not sent', function () { + const _this = this; + expect(() => { + _this.organizations.addMemberRoles({ id: 'org_123', user_id: 123 }, {}, () => {}); }).to.throw('The user ID has to be a string'); }); - it('should pass the data in the body of the request', function(done) { + it('should pass the data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post( - '/organizations/' + this.data.id + '/members/' + this.data.user_id + '/roles', - this.body - ) + const request = nock(API_URL) + .post(`/organizations/${this.data.id}/members/${this.data.user_id}/roles`, this.body) .reply(200); - this.organizations.addMemberRoles(this.data, this.body).then(function() { + this.organizations.addMemberRoles(this.data, this.body).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/organizations/' + this.data.id + '/members/' + this.data.user_id + '/roles') - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .post(`/organizations/${this.data.id}/members/${this.data.user_id}/roles`) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.organizations.addMemberRoles(this.data, {}).then(function() { + this.organizations.addMemberRoles(this.data, {}).then(() => { expect(request.isDone()).to.be.true; done(); @@ -1330,98 +1257,90 @@ describe('OrganizationsManager', function() { }); }); - describe('#removeMemberRoles', function() { - beforeEach(function() { + describe('#removeMemberRoles', () => { + beforeEach(function () { this.data = { id: 'org_123', - user_id: 'user_123' + user_id: 'user_123', }; this.body = { roles: ['user_id'] }; this.request = nock(API_URL) - .delete('/organizations/' + this.data.id + '/members/' + this.data.user_id + '/roles', {}) + .delete(`/organizations/${this.data.id}/members/${this.data.user_id}/roles`, {}) .reply(200); }); - it('should validate empty organizationId', function() { - var _this = this; - expect(function() { - _this.organizations.removeMemberRoles({ id: null }, this.body, function() {}); + it('should validate empty organizationId', function () { + const _this = this; + expect(function () { + _this.organizations.removeMemberRoles({ id: null }, this.body, () => {}); }).to.throw('The organization ID passed in params cannot be null or undefined'); }); - it('should validate non-string organizationId', function() { - var _this = this; - expect(function() { - _this.organizations.removeMemberRoles({ id: 123 }, _this.body, function() {}); + it('should validate non-string organizationId', function () { + const _this = this; + expect(() => { + _this.organizations.removeMemberRoles({ id: 123 }, _this.body, () => {}); }).to.throw('The organization ID has to be a string'); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.organizations .removeMemberRoles(this.data, this.body) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete('/organizations/' + this.data.id + '/members/' + this.data.user_id + '/roles') + nock(API_URL) + .delete(`/organizations/${this.data.id}/members/${this.data.user_id}/roles`) .reply(500); - this.organizations.removeMemberRoles(this.data, this.body).catch(function(err) { + this.organizations.removeMemberRoles(this.data, this.body).catch((err) => { expect(err).to.exist; done(); }); }); - it('should return error when id is not sent', function() { - var _this = this; - expect(function() { - _this.organizations.removeMemberRoles({ id: 'org_123', user_id: null }, {}, function() {}); + it('should return error when id is not sent', function () { + const _this = this; + expect(() => { + _this.organizations.removeMemberRoles({ id: 'org_123', user_id: null }, {}, () => {}); }).to.throw('The user ID passed in params cannot be null or undefined'); }); - it('should return error when id is not sent', function() { - var _this = this; - expect(function() { - _this.organizations.removeMemberRoles({ id: 'org_123', user_id: 123 }, {}, function() {}); + it('should return error when id is not sent', function () { + const _this = this; + expect(() => { + _this.organizations.removeMemberRoles({ id: 'org_123', user_id: 123 }, {}, () => {}); }).to.throw('The user ID has to be a string'); }); - it('should perform a DELETE request to /api/v2/organizations/organization_id/members/user_id/roles', function(done) { - var request = this.request; - - var request = nock(API_URL) - .delete( - '/organizations/' + this.data.id + '/members/' + this.data.user_id + '/roles', - this.body - ) + it('should perform a DELETE request to /api/v2/organizations/organization_id/members/user_id/roles', function (done) { + const request = nock(API_URL) + .delete(`/organizations/${this.data.id}/members/${this.data.user_id}/roles`, this.body) .reply(200); - this.organizations.removeMemberRoles(this.data, this.body, function() { + this.organizations.removeMemberRoles(this.data, this.body, () => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete( - '/organizations/' + this.data.id + '/members/' + this.data.user_id + '/roles', - this.body - ) - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .delete(`/organizations/${this.data.id}/members/${this.data.user_id}/roles`, this.body) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.organizations.removeMemberRoles(this.data, this.body).then(function() { + this.organizations.removeMemberRoles(this.data, this.body).then(() => { expect(request.isDone()).to.be.true; done(); @@ -1430,58 +1349,54 @@ describe('OrganizationsManager', function() { }); //// Invites - describe('#getInvitations', function() { - var data = { - id: 'org_id' + describe('#getInvitations', () => { + const data = { + id: 'org_id', }; - beforeEach(function() { - this.request = nock(API_URL) - .get('/organizations/' + data.id + '/invitations') - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).get(`/organizations/${data.id}/invitations`).reply(200); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.organizations.getInvitations(data, done.bind(null, null)); }); - it('should return a promise when no callback is given', function(done) { + it('should return a promise when no callback is given', function (done) { this.organizations.getInvitations(data).then(done.bind(null, null)); }); - it('should perform a GET request to /api/v2/organizations/org_ID/invitations', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/organizations/org_ID/invitations', function (done) { + const { request } = this; - this.organizations.getInvitations(data).then(function() { + this.organizations.getInvitations(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/organizations/' + data.id + '/invitations') - .reply(500); + nock(API_URL).get(`/organizations/${data.id}/invitations`).reply(500); - this.organizations.getInvitations(data).catch(function(err) { + this.organizations.getInvitations(data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the authorization header', function(done) { + it('should include the token in the authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/organizations/' + data.id + '/invitations') - .matchHeader('authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .get(`/organizations/${data.id}/invitations`) + .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); - this.organizations.getInvitations(data).then(function() { + this.organizations.getInvitations(data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -1489,87 +1404,85 @@ describe('OrganizationsManager', function() { }); }); - describe('#getInvitation', function() { - var data = { + describe('#getInvitation', () => { + const data = { id: 'org_id', - invitation_id: 'inv_123' + invitation_id: 'inv_123', }; - beforeEach(function() { + beforeEach(function () { this.request = nock(API_URL) - .get('/organizations/' + data.id + '/invitations/' + data.invitation_id) + .get(`/organizations/${data.id}/invitations/${data.invitation_id}`) .reply(200); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.organizations.getInvitation(data, done.bind(null, null)); }); - it('should return a promise when no callback is given', function(done) { + it('should return a promise when no callback is given', function (done) { this.organizations.getInvitation(data).then(done.bind(null, null)); }); - it('should perform a GET request to /api/v2/organizations/rol_ID/invitations/inv_id', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/organizations/rol_ID/invitations/inv_id', function (done) { + const { request } = this; - this.organizations.getInvitation(data).then(function() { + this.organizations.getInvitation(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/organizations/' + data.id + '/invitations/' + data.invitation_id) - .reply(500); + nock(API_URL).get(`/organizations/${data.id}/invitations/${data.invitation_id}`).reply(500); - this.organizations.getInvitation(data).catch(function(err) { + this.organizations.getInvitation(data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should return error when id is not sent', function() { - var _this = this; - expect(function() { - _this.organizations.getInvitation({ id: null }, function() {}); + it('should return error when id is not sent', function () { + const _this = this; + expect(() => { + _this.organizations.getInvitation({ id: null }, () => {}); }).to.throw('The organization ID passed in params cannot be null or undefined'); }); - it('should return error when id is not sent', function() { - var _this = this; - expect(function() { - _this.organizations.getInvitation({ id: 123 }, function() {}); + it('should return error when id is not sent', function () { + const _this = this; + expect(() => { + _this.organizations.getInvitation({ id: 123 }, () => {}); }).to.throw('The organization ID has to be a string'); }); - it('should return error when id is not sent', function() { - var _this = this; - expect(function() { - _this.organizations.getInvitation({ id: 'org_123', invitation_id: null }, function() {}); + it('should return error when id is not sent', function () { + const _this = this; + expect(() => { + _this.organizations.getInvitation({ id: 'org_123', invitation_id: null }, () => {}); }).to.throw('The invitation ID passed in params cannot be null or undefined'); }); - it('should return error when id is not sent', function() { - var _this = this; - expect(function() { - _this.organizations.getInvitation({ id: 'org_123', invitation_id: 123 }, function() {}); + it('should return error when id is not sent', function () { + const _this = this; + expect(() => { + _this.organizations.getInvitation({ id: 'org_123', invitation_id: 123 }, () => {}); }).to.throw('The invitation ID has to be a string'); }); - it('should include the token in the authorization header', function(done) { + it('should include the token in the authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/organizations/' + data.id + '/invitations/' + data.invitation_id) - .matchHeader('authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .get(`/organizations/${data.id}/invitations/${data.invitation_id}`) + .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); - this.organizations.getInvitation(data).then(function() { + this.organizations.getInvitation(data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -1577,95 +1490,93 @@ describe('OrganizationsManager', function() { }); }); - describe('#createInvitation', function() { - beforeEach(function() { + describe('#createInvitation', () => { + beforeEach(function () { this.data = { - id: 'org_123' + id: 'org_123', }; this.body = { invitee: 'inv', - client_id: 'cid' + client_id: 'cid', }; this.request = nock(API_URL) - .post('/organizations/' + this.data.id + '/invitations', {}) + .post(`/organizations/${this.data.id}/invitations`, {}) .reply(200); }); - it('should accept a callback', function(done) { - this.organizations.createInvitation(this.data, {}, function() { + it('should accept a callback', function (done) { + this.organizations.createInvitation(this.data, {}, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.organizations .createInvitation(this.data, {}) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/organizations/' + this.data.id + '/invitations') - .reply(500); + nock(API_URL).post(`/organizations/${this.data.id}/invitations`).reply(500); - this.organizations.createInvitation(this.data, {}).catch(function(err) { + this.organizations.createInvitation(this.data, {}).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a POST request to /api/v2/organizations/org_id/invitations', function(done) { - var request = this.request; + it('should perform a POST request to /api/v2/organizations/org_id/invitations', function (done) { + const { request } = this; - this.organizations.createInvitation(this.data, {}).then(function() { + this.organizations.createInvitation(this.data, {}).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should return error when id is not sent', function() { - var _this = this; - expect(function() { - _this.organizations.createInvitation({ id: null }, {}, function() {}); + it('should return error when id is not sent', function () { + const _this = this; + expect(() => { + _this.organizations.createInvitation({ id: null }, {}, () => {}); }).to.throw('The organization ID passed in params cannot be null or undefined'); }); - it('should return error when id is not sent', function() { - var _this = this; - expect(function() { - _this.organizations.createInvitation({ id: 123 }, {}, function() {}); + it('should return error when id is not sent', function () { + const _this = this; + expect(() => { + _this.organizations.createInvitation({ id: 123 }, {}, () => {}); }).to.throw('The organization ID has to be a string'); }); - it('should pass the data in the body of the request', function(done) { + it('should pass the data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/organizations/' + this.data.id + '/invitations', this.body) + const request = nock(API_URL) + .post(`/organizations/${this.data.id}/invitations`, this.body) .reply(200); - this.organizations.createInvitation(this.data, this.body).then(function() { + this.organizations.createInvitation(this.data, this.body).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/organizations/' + this.data.id + '/invitations') - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .post(`/organizations/${this.data.id}/invitations`) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.organizations.createInvitation(this.data, {}).then(function() { + this.organizations.createInvitation(this.data, {}).then(() => { expect(request.isDone()).to.be.true; done(); @@ -1673,90 +1584,90 @@ describe('OrganizationsManager', function() { }); }); - describe('#deleteInvitation', function() { - beforeEach(function() { + describe('#deleteInvitation', () => { + beforeEach(function () { this.data = { id: 'org_123', - invitation_id: 'inv_123' + invitation_id: 'inv_123', }; this.request = nock(API_URL) - .delete('/organizations/' + this.data.id + '/invitations/' + this.data.invitation_id, {}) + .delete(`/organizations/${this.data.id}/invitations/${this.data.invitation_id}`, {}) .reply(200); }); - it('should validate empty organizationId', function() { - var _this = this; - expect(function() { - _this.organizations.deleteInvitation({ id: null }, function() {}); + it('should validate empty organizationId', function () { + const _this = this; + expect(() => { + _this.organizations.deleteInvitation({ id: null }, () => {}); }).to.throw('The organization ID passed in params cannot be null or undefined'); }); - it('should validate non-string organizationId', function() { - var _this = this; - expect(function() { - _this.organizations.deleteInvitation({ id: 123 }, function() {}); + it('should validate non-string organizationId', function () { + const _this = this; + expect(() => { + _this.organizations.deleteInvitation({ id: 123 }, () => {}); }).to.throw('The organization ID has to be a string'); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.organizations .removeMembers(this.data) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete('/organizations/' + this.data.id + '/invitations/' + this.data.invitation_id, {}) + nock(API_URL) + .delete(`/organizations/${this.data.id}/invitations/${this.data.invitation_id}`, {}) .reply(500); - this.organizations.deleteInvitation(this.data).catch(function(err) { + this.organizations.deleteInvitation(this.data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a DELETE request to /api/v2/organizations/organization_id/invitations/inv_id', function(done) { + it('should perform a DELETE request to /api/v2/organizations/organization_id/invitations/inv_id', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete('/organizations/' + this.data.id + '/invitations/' + this.data.invitation_id, {}) + const request = nock(API_URL) + .delete(`/organizations/${this.data.id}/invitations/${this.data.invitation_id}`, {}) .reply(200); - this.organizations.deleteInvitation(this.data, function(err) { + this.organizations.deleteInvitation(this.data, () => { expect(request.isDone()).to.be.true; done(); }); }); - it('should return error when id is not sent', function() { - var _this = this; - expect(function() { - _this.organizations.deleteInvitation({ id: 'org_123', invitation_id: null }, function() {}); + it('should return error when id is not sent', function () { + const _this = this; + expect(() => { + _this.organizations.deleteInvitation({ id: 'org_123', invitation_id: null }, () => {}); }).to.throw('The invitation ID passed in params cannot be null or undefined'); }); - it('should return error when id is not sent', function() { - var _this = this; - expect(function() { - _this.organizations.deleteInvitation({ id: 'org_123', invitation_id: 123 }, function() {}); + it('should return error when id is not sent', function () { + const _this = this; + expect(() => { + _this.organizations.deleteInvitation({ id: 'org_123', invitation_id: 123 }, () => {}); }).to.throw('The invitation ID has to be a string'); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete('/organizations/' + this.data.id + '/invitations/' + this.data.invitation_id, {}) - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .delete(`/organizations/${this.data.id}/invitations/${this.data.invitation_id}`, {}) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.organizations.deleteInvitation(this.data).then(function() { + this.organizations.deleteInvitation(this.data).then(() => { expect(request.isDone()).to.be.true; done(); diff --git a/test/management/prompts.tests.js b/test/management/prompts.tests.js index 14543f800..e08920b04 100644 --- a/test/management/prompts.tests.js +++ b/test/management/prompts.tests.js @@ -1,140 +1,127 @@ -var expect = require('chai').expect; -var nock = require('nock'); +const { expect } = require('chai'); +const nock = require('nock'); -var SRC_DIR = '../../src'; -var API_URL = 'https://tenant.auth0.com'; +const API_URL = 'https://tenant.auth0.com'; -var PromptsManager = require(SRC_DIR + '/management/PromptsManager'); -var ArgumentError = require('rest-facade').ArgumentError; +const PromptsManager = require(`../../src/management/PromptsManager`); +const { ArgumentError } = require('rest-facade'); -describe('PromptsManager', function() { - before(function() { +describe('PromptsManager', () => { + before(function () { this.token = 'TOKEN'; this.prompts = new PromptsManager({ - headers: { authorization: 'Bearer ' + this.token }, - baseUrl: API_URL + headers: { authorization: `Bearer ${this.token}` }, + baseUrl: API_URL, }); }); - describe('instance', function() { - var methods = ['getSettings', 'updateSettings']; + describe('instance', () => { + const methods = ['getSettings', 'updateSettings']; - methods.forEach(function(method) { - it('should have a ' + method + ' method', function() { + methods.forEach((method) => { + it(`should have a ${method} method`, function () { expect(this.prompts[method]).to.exist.to.be.an.instanceOf(Function); }); }); }); - describe('#constructor', function() { - it('should error when no options are provided', function() { + describe('#constructor', () => { + it('should error when no options are provided', () => { expect(PromptsManager).to.throw(ArgumentError, 'Must provide manager options'); }); - it('should throw an error when no base URL is provided', function() { - var client = PromptsManager.bind(null, {}); + it('should throw an error when no base URL is provided', () => { + const client = PromptsManager.bind(null, {}); expect(client).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); - it('should throw an error when the base URL is invalid', function() { - var client = PromptsManager.bind(null, { baseUrl: '' }); + it('should throw an error when the base URL is invalid', () => { + const client = PromptsManager.bind(null, { baseUrl: '' }); expect(client).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); - describe('#getSettings', function() { - var data = { - universal_login_experience: '' + describe('#getSettings', () => { + const data = { + universal_login_experience: '', }; - beforeEach(function() { - this.request = nock(API_URL) - .get('/prompts') - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).get('/prompts').reply(200); }); - it('should accept a callback', function(done) { - this.prompts.getSettings(function() { + it('should accept a callback', function (done) { + this.prompts.getSettings(() => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.prompts - .getSettings() - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.prompts.getSettings().then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/prompts') - .reply(500); + nock(API_URL).get('/prompts').reply(500); - this.prompts.getSettings().catch(function(err) { + this.prompts.getSettings().catch((err) => { expect(err).to.exist; done(); }); }); - it('should pass the body of the response to the "then" handler', function(done) { + it('should pass the body of the response to the "then" handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/prompts') - .reply(200, data); + nock(API_URL).get('/prompts').reply(200, data); - this.prompts.getSettings().then(function(provider) { + this.prompts.getSettings().then((provider) => { expect(provider.id).to.equal(data.id); done(); }); }); - it('should perform a GET request to /api/v2/prompts', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/prompts', function (done) { + const { request } = this; - this.prompts.getSettings().then(function() { + this.prompts.getSettings().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/prompts') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.prompts.getSettings().then(function() { + this.prompts.getSettings().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the parameters in the query-string', function(done) { + it('should pass the parameters in the query-string', function (done) { nock.cleanAll(); - var params = { + const params = { include_fields: true, - fields: 'test' + fields: 'test', }; - var request = nock(API_URL) - .get('/prompts') - .query(params) - .reply(200); + const request = nock(API_URL).get('/prompts').query(params).reply(200); - this.prompts.getSettings(params).then(function() { + this.prompts.getSettings(params).then(() => { expect(request.isDone()).to.be.true; done(); @@ -142,77 +129,71 @@ describe('PromptsManager', function() { }); }); - describe('#updateSettings', function() { - var data = { - universal_login_experience: 'new' + describe('#updateSettings', () => { + const data = { + universal_login_experience: 'new', }; - beforeEach(function() { - this.request = nock(API_URL) - .patch('/prompts') - .reply(200, data); + beforeEach(function () { + this.request = nock(API_URL).patch('/prompts').reply(200, data); }); - it('should accept a callback', function(done) { - this.prompts.updateSettings({}, data, function() { + it('should accept a callback', function (done) { + this.prompts.updateSettings({}, data, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.prompts .updateSettings({}, data) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/prompts/' + data.id) - .reply(500); + nock(API_URL).patch(`/prompts/${data.id}`).reply(500); - this.prompts.updateSettings({}, data).catch(function(err) { + this.prompts.updateSettings({}, data).catch((err) => { expect(err).to.exist.to.be.an.instanceOf(Error); done(); }); }); - it('should perform a PATCH request to /api/v2/prompts', function(done) { - var request = this.request; + it('should perform a PATCH request to /api/v2/prompts', function (done) { + const { request } = this; - this.prompts.updateSettings({}, data).then(function() { + this.prompts.updateSettings({}, data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the data in the body of the request', function(done) { + it('should pass the data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/prompts', data) - .reply(200); + const request = nock(API_URL).patch('/prompts', data).reply(200); - this.prompts.updateSettings({}, data).then(function() { + this.prompts.updateSettings({}, data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .patch('/prompts') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.prompts.updateSettings({}, data).then(function() { + this.prompts.updateSettings({}, data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -220,78 +201,73 @@ describe('PromptsManager', function() { }); }); - describe('#getCustomTextByLanguage', function() { - var data = {}; - var params = { + describe('#getCustomTextByLanguage', () => { + const params = { prompt: 'test', - language: 'english' + language: 'english', }; - beforeEach(function() { - this.request = nock(API_URL) - .get('/prompts/test/custom-text/english') - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).get('/prompts/test/custom-text/english').reply(200); }); - it('should validate empty prompt parameter', function() { - var _this = this; - expect(function() { - _this.prompts.getCustomTextByLanguage({}, _this.body, function() {}); + it('should validate empty prompt parameter', function () { + const _this = this; + expect(() => { + _this.prompts.getCustomTextByLanguage({}, _this.body, () => {}); }).to.throw('The prompt parameter must be a string'); }); - it('should validate empty language parameter', function() { - var _this = this; - expect(function() { - _this.prompts.getCustomTextByLanguage({ prompt: 'test' }, _this.body, function() {}); + it('should validate empty language parameter', function () { + const _this = this; + expect(() => { + _this.prompts.getCustomTextByLanguage({ prompt: 'test' }, _this.body, () => {}); }).to.throw('The language parameter must be a string'); }); - it('should accept a callback', function(done) { - this.prompts.getCustomTextByLanguage(params, function() { + it('should accept a callback', function (done) { + this.prompts.getCustomTextByLanguage(params, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.prompts .getCustomTextByLanguage(params) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/prompts/test/custom-text/english') - .reply(500); + nock(API_URL).get('/prompts/test/custom-text/english').reply(500); - this.prompts.getCustomTextByLanguage(params).catch(function(err) { + this.prompts.getCustomTextByLanguage(params).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a GET request to /api/v2/prompts/test/custom-text/english', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/prompts/test/custom-text/english', function (done) { + const { request } = this; - this.prompts.getCustomTextByLanguage(params).then(function() { + this.prompts.getCustomTextByLanguage(params).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/prompts/test/custom-text/english') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.prompts.getCustomTextByLanguage(params).then(function() { + this.prompts.getCustomTextByLanguage(params).then(() => { expect(request.isDone()).to.be.true; done(); @@ -299,107 +275,107 @@ describe('PromptsManager', function() { }); }); - describe('#updateCustomTextByLanguage', function() { - var data = {}; - var params = { + describe('#updateCustomTextByLanguage', () => { + const params = { prompt: 'test', language: 'english', - body: { login: { title: 'Hello!' } } + body: { login: { title: 'Hello!' } }, }; - beforeEach(function() { - this.request = nock(API_URL) - .put('/prompts/test/custom-text/english') - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).put('/prompts/test/custom-text/english').reply(200); }); - it('should validate empty prompt parameter', function() { - var _this = this; - expect(function() { - _this.prompts.updateCustomTextByLanguage({}, _this.body, function() {}); + it('should validate empty prompt parameter', function () { + const _this = this; + expect(() => { + _this.prompts.updateCustomTextByLanguage({}, _this.body, () => {}); }).to.throw('The prompt parameter must be a string'); }); - it('should validate empty language parameter', function() { - var _this = this; - expect(function() { - _this.prompts.updateCustomTextByLanguage({ prompt: 'test' }, _this.body, function() {}); + it('should validate empty language parameter', function () { + const _this = this; + expect(() => { + _this.prompts.updateCustomTextByLanguage({ prompt: 'test' }, _this.body, () => {}); }).to.throw('The language parameter must be a string'); }); - it('should validate empty body parameter', function() { - var _this = this; - expect(function() { + it('should validate empty body parameter', function () { + const _this = this; + expect(() => { _this.prompts.updateCustomTextByLanguage( { prompt: 'test', language: 'english' }, _this.body, - function() {} + () => {} ); }).to.throw('The body parameter must be an object'); }); - it('should accept a callback', function(done) { - this.prompts.updateCustomTextByLanguage(params, function() { + it('should accept a callback', function (done) { + this.prompts.updateCustomTextByLanguage(params, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.prompts .updateCustomTextByLanguage(params) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .put('/prompts/test/custom-text/english') - .reply(500); + nock(API_URL).put('/prompts/test/custom-text/english').reply(500); - this.prompts.updateCustomTextByLanguage(params).catch(function(err) { + this.prompts.updateCustomTextByLanguage(params).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a PUT request to /api/v2/prompts/test/custom-text/english', function(done) { - var request = this.request; + it('should perform a PUT request to /api/v2/prompts/test/custom-text/english', function (done) { + const { request } = this; - this.prompts.updateCustomTextByLanguage(params).then(function() { - expect(request.isDone()).to.be.true; - done(); - }); + this.prompts + .updateCustomTextByLanguage(params) + .then(() => { + expect(request.isDone()).to.be.true; + done(); + }) + .catch((e) => { + console.error(e); + }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .put('/prompts/test/custom-text/english') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.prompts.updateCustomTextByLanguage(params).then(function() { + this.prompts.updateCustomTextByLanguage(params).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should send the payload to the body', function(done) { + it('should send the payload to the body', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .put( '/prompts/test/custom-text/english', - body => body && body.login && body.login.title === 'Hello!' + (body) => body && body.login && body.login.title === 'Hello!' ) .reply(200); - this.prompts.updateCustomTextByLanguage(params).then(function() { + this.prompts.updateCustomTextByLanguage(params).then(() => { expect(request.isDone()).to.be.true; done(); diff --git a/test/management/resource-servers.tests.js b/test/management/resource-servers.tests.js index 0b9af30f3..88261f995 100644 --- a/test/management/resource-servers.tests.js +++ b/test/management/resource-servers.tests.js @@ -1,101 +1,91 @@ -var expect = require('chai').expect; -var nock = require('nock'); +const { expect } = require('chai'); +const nock = require('nock'); -var SRC_DIR = '../../src'; -var API_URL = 'https://tenant.auth0.com'; +const API_URL = 'https://tenant.auth0.com'; -var ResourceServersManager = require(SRC_DIR + '/management/ResourceServersManager'); -var ArgumentError = require('rest-facade').ArgumentError; +const ResourceServersManager = require(`../../src/management/ResourceServersManager`); +const { ArgumentError } = require('rest-facade'); -describe('ResourceServersManager', function() { - before(function() { +describe('ResourceServersManager', () => { + before(function () { this.token = 'TOKEN'; this.resourceServers = new ResourceServersManager({ headers: { - authorization: 'Bearer ' + this.token + authorization: `Bearer ${this.token}`, }, - baseUrl: API_URL + baseUrl: API_URL, }); }); - afterEach(function() { + afterEach(() => { nock.cleanAll(); }); - describe('instance', function() { - var methods = ['get', 'create', 'update', 'delete']; + describe('instance', () => { + const methods = ['get', 'create', 'update', 'delete']; - methods.forEach(function(method) { - it('should have a ' + method + ' method', function() { + methods.forEach((method) => { + it(`should have a ${method} method`, function () { expect(this.resourceServers[method]).to.exist.to.be.an.instanceOf(Function); }); }); }); - describe('#constructor', function() { - it('should error when no options are provided', function() { + describe('#constructor', () => { + it('should error when no options are provided', () => { expect(ResourceServersManager).to.throw( ArgumentError, 'Must provide resource server options' ); }); - it('should throw an error when no base URL is provided', function() { - var resourceServerManager = ResourceServersManager.bind(null, {}); + it('should throw an error when no base URL is provided', () => { + const resourceServerManager = ResourceServersManager.bind(null, {}); expect(resourceServerManager).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); - it('should throw an error when the base URL is invalid', function() { - var resourceServerManager = ResourceServersManager.bind(null, { baseUrl: '' }); + it('should throw an error when the base URL is invalid', () => { + const resourceServerManager = ResourceServersManager.bind(null, { baseUrl: '' }); expect(resourceServerManager).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); - describe('#getAll', function() { - beforeEach(function() { - this.request = nock(API_URL) - .get('/resource-servers') - .reply(200); + describe('#getAll', () => { + beforeEach(function () { + this.request = nock(API_URL).get('/resource-servers').reply(200); }); - it('should accept a callback', function(done) { - this.resourceServers.getAll(function() { + it('should accept a callback', function (done) { + this.resourceServers.getAll(() => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.resourceServers - .getAll() - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.resourceServers.getAll().then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/resource-servers') - .reply(500); + nock(API_URL).get('/resource-servers').reply(500); - this.resourceServers.getAll().catch(function(err) { + this.resourceServers.getAll().catch((err) => { expect(err).to.exist; done(); }); }); - it('should pass the body of the response to the "then" handler', function(done) { + it('should pass the body of the response to the "then" handler', function (done) { nock.cleanAll(); - var data = [{ test: true }]; - var request = nock(API_URL) - .get('/resource-servers') - .reply(200, data); + const data = [{ test: true }]; + nock(API_URL).get('/resource-servers').reply(200, data); - this.resourceServers.getAll().then(function(resourceServers) { + this.resourceServers.getAll().then((resourceServers) => { expect(resourceServers).to.be.an.instanceOf(Array); expect(resourceServers.length).to.equal(data.length); @@ -106,104 +96,95 @@ describe('ResourceServersManager', function() { }); }); - it('should perform a GET request to /api/v2/resource-servers', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/resource-servers', function (done) { + const { request } = this; - this.resourceServers.getAll().then(function() { + this.resourceServers.getAll().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/resource-servers') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.resourceServers.getAll().then(function() { + this.resourceServers.getAll().then(() => { expect(request.isDone()).to.be.true; done(); }); }); }); - describe('#get', function() { - var params = { id: 5 }; - var data = { + describe('#get', () => { + const params = { id: 5 }; + const data = { id: params.id, - name: 'Test Resource Server' + name: 'Test Resource Server', }; - beforeEach(function() { - this.request = nock(API_URL) - .get('/resource-servers/' + data.id) - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).get(`/resource-servers/${data.id}`).reply(200); }); - it('should accept a callback', function(done) { - this.resourceServers.get(params, function() { + it('should accept a callback', function (done) { + this.resourceServers.get(params, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.resourceServers - .get(params) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.resourceServers.get(params).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/resource-servers/' + params.id) - .reply(500); + nock(API_URL).get(`/resource-servers/${params.id}`).reply(500); - this.resourceServers.get().catch(function(err) { + this.resourceServers.get().catch((err) => { expect(err).to.exist; done(); }); }); - it('should pass the body of the response to the "then" handler', function(done) { + it('should pass the body of the response to the "then" handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/resource-servers/' + params.id) - .reply(200, data); + nock(API_URL).get(`/resource-servers/${params.id}`).reply(200, data); - this.resourceServers.get(params).then(function(connection) { + this.resourceServers.get(params).then((connection) => { expect(connection.id).to.equal(data.id); done(); }); }); - it('should perform a GET request to /api/v2/resource-servers/:id', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/resource-servers/:id', function (done) { + const { request } = this; - this.resourceServers.get(params).then(function() { + this.resourceServers.get(params).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/resource-servers') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.resourceServers.get().then(function() { + this.resourceServers.get().then(() => { expect(request.isDone()).to.be.true; done(); @@ -211,78 +192,69 @@ describe('ResourceServersManager', function() { }); }); - describe('#create', function() { - var data = { + describe('#create', () => { + const data = { name: 'Acme Backend API', - options: {} + options: {}, }; - beforeEach(function() { - this.request = nock(API_URL) - .post('/resource-servers') - .reply(200, data); + beforeEach(function () { + this.request = nock(API_URL).post('/resource-servers').reply(200, data); }); - it('should accept a callback', function(done) { - this.resourceServers.create(data, function() { + it('should accept a callback', function (done) { + this.resourceServers.create(data, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.resourceServers - .create(data) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.resourceServers.create(data).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/resource-servers') - .reply(500); + nock(API_URL).post('/resource-servers').reply(500); - this.resourceServers.create(data).catch(function(err) { + this.resourceServers.create(data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a POST request to /api/v2/resource-servers', function(done) { - var request = this.request; + it('should perform a POST request to /api/v2/resource-servers', function (done) { + const { request } = this; - this.resourceServers.create(data).then(function() { + this.resourceServers.create(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the data in the body of the request', function(done) { + it('should pass the data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/resource-servers', data) - .reply(200); + const request = nock(API_URL).post('/resource-servers', data).reply(200); - this.resourceServers.create(data).then(function() { + this.resourceServers.create(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .post('/resource-servers') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.resourceServers.create(data).then(function() { + this.resourceServers.create(data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -290,80 +262,74 @@ describe('ResourceServersManager', function() { }); }); - describe('#update', function() { - var params = { id: 5 }; - var data = { + describe('#update', () => { + const params = { id: 5 }; + const data = { id: 5, name: 'Acme Backend API', - options: {} + options: {}, }; - beforeEach(function() { - this.request = nock(API_URL) - .patch('/resource-servers/' + data.id) - .reply(200, data); + beforeEach(function () { + this.request = nock(API_URL).patch(`/resource-servers/${data.id}`).reply(200, data); }); - it('should accept a callback', function(done) { - this.resourceServers.update(params, data, function() { + it('should accept a callback', function (done) { + this.resourceServers.update(params, data, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.resourceServers .update(params, data) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/resource-servers/' + data.id) - .reply(500); + nock(API_URL).patch(`/resource-servers/${data.id}`).reply(500); - this.resourceServers.update(params, data).catch(function(err) { + this.resourceServers.update(params, data).catch((err) => { expect(err).to.exist.to.be.an.instanceOf(Error); done(); }); }); - it('should perform a PATCH request to /api/v2/resource-servers/:id', function(done) { - var request = this.request; + it('should perform a PATCH request to /api/v2/resource-servers/:id', function (done) { + const { request } = this; - this.resourceServers.update(params, data).then(function() { + this.resourceServers.update(params, data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the data in the body of the request', function(done) { + it('should pass the data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/resource-servers/' + data.id, data) - .reply(200); + const request = nock(API_URL).patch(`/resource-servers/${data.id}`, data).reply(200); - this.resourceServers.update(params, data).then(function() { + this.resourceServers.update(params, data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/resource-servers/' + data.id) - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .patch(`/resource-servers/${data.id}`) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.resourceServers.update(params, data).then(function() { + this.resourceServers.update(params, data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -371,56 +337,52 @@ describe('ResourceServersManager', function() { }); }); - describe('#delete', function() { - var id = 5; + describe('#delete', () => { + const id = 5; - beforeEach(function() { - this.request = nock(API_URL) - .delete('/resource-servers/' + id) - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).delete(`/resource-servers/${id}`).reply(200); }); - it('should accept a callback', function(done) { - this.resourceServers.delete({ id: id }, done.bind(null, null)); + it('should accept a callback', function (done) { + this.resourceServers.delete({ id }, done.bind(null, null)); }); - it('should return a promise when no callback is given', function(done) { - this.resourceServers.delete({ id: id }).then(done.bind(null, null)); + it('should return a promise when no callback is given', function (done) { + this.resourceServers.delete({ id }).then(done.bind(null, null)); }); - it('should perform a DELETE request to /resource-servers/' + id, function(done) { - var request = this.request; + it(`should perform a DELETE request to /resource-servers/${id}`, function (done) { + const { request } = this; - this.resourceServers.delete({ id: id }).then(function() { + this.resourceServers.delete({ id }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete('/resource-servers/' + id) - .reply(500); + nock(API_URL).delete(`/resource-servers/${id}`).reply(500); - this.resourceServers.delete({ id: id }).catch(function(err) { + this.resourceServers.delete({ id }).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete('/resource-servers/' + id) - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .delete(`/resource-servers/${id}`) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.resourceServers.delete({ id: id }).then(function() { + this.resourceServers.delete({ id }).then(() => { expect(request.isDone()).to.be.true; done(); diff --git a/test/management/roles.tests.js b/test/management/roles.tests.js index fa336e1ae..7ce428fde 100644 --- a/test/management/roles.tests.js +++ b/test/management/roles.tests.js @@ -1,23 +1,22 @@ -var expect = require('chai').expect; -var nock = require('nock'); +const { expect } = require('chai'); +const nock = require('nock'); -var SRC_DIR = '../../src'; -var API_URL = 'https://tenant.auth0.com'; +const API_URL = 'https://tenant.auth0.com'; -var RolesManager = require(SRC_DIR + '/management/RolesManager'); -var ArgumentError = require('rest-facade').ArgumentError; +const RolesManager = require(`../../src/management/RolesManager`); +const { ArgumentError } = require('rest-facade'); -describe('RolesManager', function() { - before(function() { +describe('RolesManager', () => { + before(function () { this.token = 'TOKEN'; this.roles = new RolesManager({ - headers: { authorization: 'Bearer ' + this.token }, - baseUrl: API_URL + headers: { authorization: `Bearer ${this.token}` }, + baseUrl: API_URL, }); }); - describe('instance', function() { - var methods = [ + describe('instance', () => { + const methods = [ 'get', 'getAll', 'create', @@ -27,76 +26,67 @@ describe('RolesManager', function() { 'addPermissions', 'removePermissions', 'getUsers', - 'assignUsers' + 'assignUsers', ]; - methods.forEach(function(method) { - it('should have a ' + method + ' method', function() { + methods.forEach((method) => { + it(`should have a ${method} method`, function () { expect(this.roles[method]).to.exist.to.be.an.instanceOf(Function); }); }); }); - describe('#constructor', function() { - it('should error when no options are provided', function() { + describe('#constructor', () => { + it('should error when no options are provided', () => { expect(RolesManager).to.throw(ArgumentError, 'Must provide manager options'); }); - it('should throw an error when no base URL is provided', function() { - var client = RolesManager.bind(null, {}); + it('should throw an error when no base URL is provided', () => { + const client = RolesManager.bind(null, {}); expect(client).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); - it('should throw an error when the base URL is invalid', function() { - var client = RolesManager.bind(null, { baseUrl: '' }); + it('should throw an error when the base URL is invalid', () => { + const client = RolesManager.bind(null, { baseUrl: '' }); expect(client).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); - describe('#getAll', function() { - beforeEach(function() { - this.request = nock(API_URL) - .get('/roles') - .reply(200); + describe('#getAll', () => { + beforeEach(function () { + this.request = nock(API_URL).get('/roles').reply(200); }); - it('should accept a callback', function(done) { - this.roles.getAll(function() { + it('should accept a callback', function (done) { + this.roles.getAll(() => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.roles - .getAll() - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.roles.getAll().then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/roles') - .reply(500); + nock(API_URL).get('/roles').reply(500); - this.roles.getAll().catch(function(err) { + this.roles.getAll().catch((err) => { expect(err).to.exist; done(); }); }); - it('should pass the body of the response to the "then" handler', function(done) { + it('should pass the body of the response to the "then" handler', function (done) { nock.cleanAll(); - var data = [{ test: true }]; - var request = nock(API_URL) - .get('/roles') - .reply(200, data); + const data = [{ test: true }]; + nock(API_URL).get('/roles').reply(200, data); - this.roles.getAll().then(function(credentials) { + this.roles.getAll().then((credentials) => { expect(credentials).to.be.an.instanceOf(Array); expect(credentials.length).to.equal(data.length); @@ -107,42 +97,39 @@ describe('RolesManager', function() { }); }); - it('should perform a GET request to /api/v2/roles', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/roles', function (done) { + const { request } = this; - this.roles.getAll().then(function() { + this.roles.getAll().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/roles') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.roles.getAll().then(function() { + this.roles.getAll().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the parameters in the query-string', function(done) { + it('should pass the parameters in the query-string', function (done) { nock.cleanAll(); - var params = { + const params = { include_fields: true, - fields: 'test' + fields: 'test', }; - var request = nock(API_URL) - .get('/roles') - .query(params) - .reply(200); + const request = nock(API_URL).get('/roles').query(params).reply(200); - this.roles.getAll(params).then(function() { + this.roles.getAll(params).then(() => { expect(request.isDone()).to.be.true; done(); @@ -150,65 +137,58 @@ describe('RolesManager', function() { }); }); - describe('#get', function() { - beforeEach(function() { + describe('#get', () => { + beforeEach(function () { this.data = { id: 'rol_ID', name: 'My role', - description: 'This is my role' + description: 'This is my role', }; - this.request = nock(API_URL) - .get('/roles/' + this.data.id) - .reply(200, this.data); + this.request = nock(API_URL).get(`/roles/${this.data.id}`).reply(200, this.data); }); - it('should accept a callback', function(done) { - var params = { id: this.data.id }; + it('should accept a callback', function (done) { + const params = { id: this.data.id }; this.roles.get(params, done.bind(null, null)); }); - it('should return a promise if no callback is given', function(done) { - this.roles - .get({ id: this.data.id }) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.roles.get({ id: this.data.id }).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should perform a POST request to /api/v2/roles/rol_ID', function(done) { - var request = this.request; + it('should perform a POST request to /api/v2/roles/rol_ID', function (done) { + const { request } = this; - this.roles.get({ id: this.data.id }).then(function() { + this.roles.get({ id: this.data.id }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/roles/' + this.data.id) - .reply(500); + nock(API_URL).get(`/roles/${this.data.id}`).reply(500); - this.roles.get({ id: this.data.id }).catch(function(err) { + this.roles.get({ id: this.data.id }).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/roles/' + this.data.id) - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .get(`/roles/${this.data.id}`) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.roles.get({ id: this.data.id }).then(function() { + this.roles.get({ id: this.data.id }).then(() => { expect(request.isDone()).to.be.true; done(); @@ -216,79 +196,70 @@ describe('RolesManager', function() { }); }); - describe('#create', function() { - var data = { + describe('#create', () => { + const data = { id: 'rol_ID', name: 'My role', - description: 'This is my role' + description: 'This is my role', }; - beforeEach(function() { - this.request = nock(API_URL) - .post('/roles') - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).post('/roles').reply(200); }); - it('should accept a callback', function(done) { - this.roles.create(data, function() { + it('should accept a callback', function (done) { + this.roles.create(data, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.roles - .create(data) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.roles.create(data).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/roles') - .reply(500); + nock(API_URL).post('/roles').reply(500); - this.roles.create(data).catch(function(err) { + this.roles.create(data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a POST request to /api/v2/roles', function(done) { - var request = this.request; + it('should perform a POST request to /api/v2/roles', function (done) { + const { request } = this; - this.roles.create(data).then(function() { + this.roles.create(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the data in the body of the request', function(done) { + it('should pass the data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/roles', data) - .reply(200); + const request = nock(API_URL).post('/roles', data).reply(200); - this.roles.create(data).then(function() { + this.roles.create(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .post('/roles') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.roles.create(data).then(function() { + this.roles.create(data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -296,58 +267,52 @@ describe('RolesManager', function() { }); }); - describe('#update', function() { - beforeEach(function() { + describe('#update', () => { + beforeEach(function () { this.data = { id: 'rol_ID' }; - this.request = nock(API_URL) - .patch('/roles/' + this.data.id) - .reply(200, this.data); + this.request = nock(API_URL).patch(`/roles/${this.data.id}`).reply(200, this.data); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.roles.update({ id: 'rol_ID' }, {}, done.bind(null, null)); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.roles .update({ id: 'rol_ID' }, {}) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should perform a PATCH request to /api/v2/roles/rol_ID', function(done) { - var request = this.request; + it('should perform a PATCH request to /api/v2/roles/rol_ID', function (done) { + const { request } = this; - this.roles.update({ id: 'rol_ID' }, {}).then(function() { + this.roles.update({ id: 'rol_ID' }, {}).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the new data in the body of the request', function(done) { + it('should include the new data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/roles/' + this.data.id, this.data) - .reply(200); + const request = nock(API_URL).patch(`/roles/${this.data.id}`, this.data).reply(200); - this.roles.update({ id: 'rol_ID' }, this.data).then(function() { + this.roles.update({ id: 'rol_ID' }, this.data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/roles/' + this.data.id) - .reply(500); + nock(API_URL).patch(`/roles/${this.data.id}`).reply(500); - this.roles.update({ id: this.data.id }, this.data).catch(function(err) { + this.roles.update({ id: this.data.id }, this.data).catch((err) => { expect(err).to.exist; done(); @@ -355,56 +320,52 @@ describe('RolesManager', function() { }); }); - describe('#delete', function() { - var id = 'rol_ID'; + describe('#delete', () => { + const id = 'rol_ID'; - beforeEach(function() { - this.request = nock(API_URL) - .delete('/roles/' + id) - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).delete(`/roles/${id}`).reply(200); }); - it('should accept a callback', function(done) { - this.roles.delete({ id: id }, done.bind(null, null)); + it('should accept a callback', function (done) { + this.roles.delete({ id }, done.bind(null, null)); }); - it('should return a promise when no callback is given', function(done) { - this.roles.delete({ id: id }).then(done.bind(null, null)); + it('should return a promise when no callback is given', function (done) { + this.roles.delete({ id }).then(done.bind(null, null)); }); - it('should perform a delete request to /roles/' + id, function(done) { - var request = this.request; + it(`should perform a delete request to /roles/${id}`, function (done) { + const { request } = this; - this.roles.delete({ id: id }).then(function() { + this.roles.delete({ id }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete('/roles/' + id) - .reply(500); + nock(API_URL).delete(`/roles/${id}`).reply(500); - this.roles.delete({ id: id }).catch(function(err) { + this.roles.delete({ id }).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the authorization header', function(done) { + it('should include the token in the authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete('/roles/' + id) - .matchHeader('authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .delete(`/roles/${id}`) + .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); - this.roles.delete({ id: id }).then(function() { + this.roles.delete({ id }).then(() => { expect(request.isDone()).to.be.true; done(); @@ -412,58 +373,54 @@ describe('RolesManager', function() { }); }); - describe('#getPermissions', function() { - var data = { - id: 'role_id' + describe('#getPermissions', () => { + const data = { + id: 'role_id', }; - beforeEach(function() { - this.request = nock(API_URL) - .get('/roles/' + data.id + '/permissions') - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).get(`/roles/${data.id}/permissions`).reply(200); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.roles.getPermissions(data, done.bind(null, null)); }); - it('should return a promise when no callback is given', function(done) { + it('should return a promise when no callback is given', function (done) { this.roles.getPermissions(data).then(done.bind(null, null)); }); - it('should perform a GET request to /api/v2/roles/rol_ID/permissions', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/roles/rol_ID/permissions', function (done) { + const { request } = this; - this.roles.getPermissions(data).then(function() { + this.roles.getPermissions(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/roles/' + data.id + '/permissions') - .reply(500); + nock(API_URL).get(`/roles/${data.id}/permissions`).reply(500); - this.roles.getPermissions(data).catch(function(err) { + this.roles.getPermissions(data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the authorization header', function(done) { + it('should include the token in the authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/roles/' + data.id + '/permissions') - .matchHeader('authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .get(`/roles/${data.id}/permissions`) + .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); - this.roles.getPermissions(data).then(function() { + this.roles.getPermissions(data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -471,78 +428,74 @@ describe('RolesManager', function() { }); }); - describe('#addPermissions', function() { - beforeEach(function() { + describe('#addPermissions', () => { + beforeEach(function () { this.data = { - id: 'rol_ID' + id: 'rol_ID', }; this.body = { permission_name: 'My Permission', resource_server_identifier: 'test123' }; - this.request = nock(API_URL) - .post('/roles/' + this.data.id + '/permissions') - .reply(200); + this.request = nock(API_URL).post(`/roles/${this.data.id}/permissions`).reply(200); }); - it('should accept a callback', function(done) { - this.roles.addPermissions(this.data, {}, function() { + it('should accept a callback', function (done) { + this.roles.addPermissions(this.data, {}, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.roles .addPermissions(this.data, {}) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/roles/' + this.data.id + '/permissions') - .reply(500); + nock(API_URL).post(`/roles/${this.data.id}/permissions`).reply(500); - this.roles.addPermissions(this.data, {}).catch(function(err) { + this.roles.addPermissions(this.data, {}).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a POST request to /api/v2/roles/rol_ID/permissions', function(done) { - var request = this.request; + it('should perform a POST request to /api/v2/roles/rol_ID/permissions', function (done) { + const { request } = this; - this.roles.addPermissions(this.data, {}).then(function() { + this.roles.addPermissions(this.data, {}).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the data in the body of the request', function(done) { + it('should pass the data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/roles/' + this.data.id + '/permissions', this.body) + const request = nock(API_URL) + .post(`/roles/${this.data.id}/permissions`, this.body) .reply(200); - this.roles.addPermissions(this.data, this.body).then(function() { + this.roles.addPermissions(this.data, this.body).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/roles/' + this.data.id + '/permissions') - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .post(`/roles/${this.data.id}/permissions`) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.roles.addPermissions(this.data, {}).then(function() { + this.roles.addPermissions(this.data, {}).then(() => { expect(request.isDone()).to.be.true; done(); @@ -550,92 +503,88 @@ describe('RolesManager', function() { }); }); - describe('#removePermissions', function() { - beforeEach(function() { + describe('#removePermissions', () => { + beforeEach(function () { this.data = { - id: 'rol_ID' + id: 'rol_ID', }; this.body = { permission_name: 'My Permission', resource_server_identifier: 'test123' }; - this.request = nock(API_URL) - .delete('/roles/' + this.data.id + '/permissions', {}) - .reply(200); + this.request = nock(API_URL).delete(`/roles/${this.data.id}/permissions`, {}).reply(200); }); - it('should validate empty roleId', function() { - var _this = this; - expect(function() { - _this.roles.removePermissions({ id: null }, _this.body, function() {}); + it('should validate empty roleId', function () { + const _this = this; + expect(() => { + _this.roles.removePermissions({ id: null }, _this.body, () => {}); }).to.throw('The roleId passed in params cannot be null or undefined'); }); - it('should validate non-string roleId', function() { - var _this = this; - expect(function() { - _this.roles.removePermissions({ id: 123 }, _this.body, function() {}); + it('should validate non-string roleId', function () { + const _this = this; + expect(() => { + _this.roles.removePermissions({ id: 123 }, _this.body, () => {}); }).to.throw('The role Id has to be a string'); }); - it('should accept a callback', function(done) { - this.roles.removePermissions(this.data, {}, function() { + it('should accept a callback', function (done) { + this.roles.removePermissions(this.data, {}, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.roles .removePermissions(this.data, {}) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/roles/' + this.data.id + '/permissions') - .reply(500); + nock(API_URL).post(`/roles/${this.data.id}/permissions`).reply(500); - this.roles.removePermissions(this.data, {}).catch(function(err) { + this.roles.removePermissions(this.data, {}).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a DELETE request to /api/v2/roles/rol_ID/permissions', function(done) { - var request = this.request; + it('should perform a DELETE request to /api/v2/roles/rol_ID/permissions', function (done) { + const { request } = this; - this.roles.removePermissions(this.data, {}).then(function() { + this.roles.removePermissions(this.data, {}).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the data in the body of the request', function(done) { + it('should pass the data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete('/roles/' + this.data.id + '/permissions', this.body) + const request = nock(API_URL) + .delete(`/roles/${this.data.id}/permissions`, this.body) .reply(200); - this.roles.removePermissions(this.data, this.body).then(function() { + this.roles.removePermissions(this.data, this.body).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete('/roles/' + this.data.id + '/permissions') - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .delete(`/roles/${this.data.id}/permissions`) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.roles.removePermissions(this.data, {}).then(function() { + this.roles.removePermissions(this.data, {}).then(() => { expect(request.isDone()).to.be.true; done(); @@ -643,58 +592,54 @@ describe('RolesManager', function() { }); }); - describe('#getUsers', function() { - var data = { - id: 'role_id' + describe('#getUsers', () => { + const data = { + id: 'role_id', }; - beforeEach(function() { - this.request = nock(API_URL) - .get('/roles/' + data.id + '/users') - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).get(`/roles/${data.id}/users`).reply(200); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.roles.getUsers(data, done.bind(null, null)); }); - it('should return a promise when no callback is given', function(done) { + it('should return a promise when no callback is given', function (done) { this.roles.getUsers(data).then(done.bind(null, null)); }); - it('should perform a GET request to /api/v2/roles/rol_Id/users', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/roles/rol_Id/users', function (done) { + const { request } = this; - this.roles.getUsers(data).then(function() { + this.roles.getUsers(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/roles/' + data.id + '/users') - .reply(500); + nock(API_URL).get(`/roles/${data.id}/users`).reply(500); - this.roles.getUsers(data).catch(function(err) { + this.roles.getUsers(data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the authorization header', function(done) { + it('should include the token in the authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/roles/' + data.id + '/users') - .matchHeader('authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .get(`/roles/${data.id}/users`) + .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); - this.roles.getUsers(data).then(function() { + this.roles.getUsers(data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -702,92 +647,86 @@ describe('RolesManager', function() { }); }); - describe('#assignUsers', function() { - beforeEach(function() { + describe('#assignUsers', () => { + beforeEach(function () { this.data = { - id: 'rol_ID' + id: 'rol_ID', }; this.body = { users: ['userID1'] }; - this.request = nock(API_URL) - .post('/roles/' + this.data.id + '/users') - .reply(200); + this.request = nock(API_URL).post(`/roles/${this.data.id}/users`).reply(200); }); - it('should validate empty roleId', function() { - var _this = this; - expect(function() { - _this.roles.assignUsers({ id: null }, _this.body, function() {}); + it('should validate empty roleId', function () { + const _this = this; + expect(() => { + _this.roles.assignUsers({ id: null }, _this.body, () => {}); }).to.throw('The roleId passed in params cannot be null or undefined'); }); - it('should validate non-string roleId', function() { - var _this = this; - expect(function() { - _this.roles.assignUsers({ id: 123 }, _this.body, function() {}); + it('should validate non-string roleId', function () { + const _this = this; + expect(() => { + _this.roles.assignUsers({ id: 123 }, _this.body, () => {}); }).to.throw('The role Id has to be a string'); }); - it('should accept a callback', function(done) { - this.roles.assignUsers(this.data, {}, function() { + it('should accept a callback', function (done) { + this.roles.assignUsers(this.data, {}, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.roles .assignUsers(this.data, {}) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/roles/' + this.data.id + '/users') - .reply(500); + nock(API_URL).post(`/roles/${this.data.id}/users`).reply(500); - this.roles.assignUsers(this.data, {}).catch(function(err) { + this.roles.assignUsers(this.data, {}).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a POST request to /api/v2/roles/rol_ID/users', function(done) { - var request = this.request; + it('should perform a POST request to /api/v2/roles/rol_ID/users', function (done) { + const { request } = this; - this.roles.assignUsers(this.data, {}).then(function() { + this.roles.assignUsers(this.data, {}).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the data in the body of the request', function(done) { + it('should pass the data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/roles/' + this.data.id + '/users', this.body) - .reply(200); + const request = nock(API_URL).post(`/roles/${this.data.id}/users`, this.body).reply(200); - this.roles.assignUsers(this.data, this.body).then(function() { + this.roles.assignUsers(this.data, this.body).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/roles/' + this.data.id + '/users') - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .post(`/roles/${this.data.id}/users`) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.roles.assignUsers(this.data, {}).then(function() { + this.roles.assignUsers(this.data, {}).then(() => { expect(request.isDone()).to.be.true; done(); diff --git a/test/management/rules-configs.tests.js b/test/management/rules-configs.tests.js index 4814a5d20..97c819471 100644 --- a/test/management/rules-configs.tests.js +++ b/test/management/rules-configs.tests.js @@ -1,85 +1,77 @@ -var expect = require('chai').expect; -var nock = require('nock'); +const { expect } = require('chai'); +const nock = require('nock'); -var SRC_DIR = '../../src'; -var API_URL = 'https://tenant.auth0.com'; +const API_URL = 'https://tenant.auth0.com'; -var RulesConfigsManager = require(SRC_DIR + '/management/RulesConfigsManager'); -var ArgumentError = require('rest-facade').ArgumentError; +const RulesConfigsManager = require(`../../src/management/RulesConfigsManager`); +const { ArgumentError } = require('rest-facade'); -describe('RulesConfigsManager', function() { - before(function() { +describe('RulesConfigsManager', () => { + before(function () { this.token = 'TOKEN'; this.rulesConfigs = new RulesConfigsManager({ - headers: { authorization: 'Bearer ' + this.token }, - baseUrl: API_URL + headers: { authorization: `Bearer ${this.token}` }, + baseUrl: API_URL, }); }); - describe('instance', function() { - var methods = ['set', 'getAll', 'delete']; + describe('instance', () => { + const methods = ['set', 'getAll', 'delete']; - methods.forEach(function(method) { - it('should have a ' + method + ' method', function() { + methods.forEach((method) => { + it(`should have a ${method} method`, function () { expect(this.rulesConfigs[method]).to.exist.to.be.an.instanceOf(Function); }); }); }); - describe('#constructor', function() { - it('should error when no options are provided', function() { + describe('#constructor', () => { + it('should error when no options are provided', () => { expect(RulesConfigsManager).to.throw(ArgumentError, 'Must provide manager options'); }); - it('should throw an error when no base URL is provided', function() { - var client = RulesConfigsManager.bind(null, {}); + it('should throw an error when no base URL is provided', () => { + const client = RulesConfigsManager.bind(null, {}); expect(client).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); - it('should throw an error when the base URL is invalid', function() { - var client = RulesConfigsManager.bind(null, { baseUrl: '' }); + it('should throw an error when the base URL is invalid', () => { + const client = RulesConfigsManager.bind(null, { baseUrl: '' }); expect(client).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); - describe('#getAll', function() { - it('should accept a callback', function(done) { - this.rulesConfigs.getAll(function() { + describe('#getAll', () => { + it('should accept a callback', function (done) { + this.rulesConfigs.getAll(() => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.rulesConfigs - .getAll() - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.rulesConfigs.getAll().then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/rules-configs') - .reply(500); + nock(API_URL).get('/rules-configs').reply(500); - this.rulesConfigs.getAll().catch(function(err) { + this.rulesConfigs.getAll().catch((err) => { expect(err).to.exist; done(); }); }); - it('should pass the body of the response to the "then" handler', function(done) { + it('should pass the body of the response to the "then" handler', function (done) { nock.cleanAll(); - var data = [{ key: 'dbconnectionstring' }]; - var request = nock(API_URL) - .get('/rules-configs') - .reply(200, data); + const data = [{ key: 'dbconnectionstring' }]; + nock(API_URL).get('/rules-configs').reply(200, data); - this.rulesConfigs.getAll().then(function(rulesConfigs) { + this.rulesConfigs.getAll().then((rulesConfigs) => { expect(rulesConfigs).to.be.an.instanceOf(Array); expect(rulesConfigs.length).to.equal(data.length); @@ -90,46 +82,41 @@ describe('RulesConfigsManager', function() { }); }); - it('should perform a GET request to rules-configs', function(done) { + it('should perform a GET request to rules-configs', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/rules-configs') - .reply(200); + const request = nock(API_URL).get('/rules-configs').reply(200); - this.rulesConfigs.getAll().then(function() { + this.rulesConfigs.getAll().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/rules-configs') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.rulesConfigs.getAll().then(function() { + this.rulesConfigs.getAll().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the parameters in the query-string', function(done) { + it('should pass the parameters in the query-string', function (done) { nock.cleanAll(); - var params = { + const params = { include_fields: true, - fields: 'test' + fields: 'test', }; - var request = nock(API_URL) - .get('/rules-configs') - .query(params) - .reply(200); + const request = nock(API_URL).get('/rules-configs').query(params).reply(200); - this.rulesConfigs.getAll(params).then(function() { + this.rulesConfigs.getAll(params).then(() => { expect(request.isDone()).to.be.true; done(); @@ -137,83 +124,77 @@ describe('RulesConfigsManager', function() { }); }); - describe('#set', function() { - beforeEach(function() { + describe('#set', () => { + beforeEach(function () { this.data = { value: 'foobar' }; this.params = { key: 'KEY' }; }); - it('should accept a callback', function(done) { - this.rulesConfigs.set(this.params, this.data, function() { + it('should accept a callback', function (done) { + this.rulesConfigs.set(this.params, this.data, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.rulesConfigs .set(this.params, this.data) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .put('/rules-configs/' + this.params.key) - .reply(500); + nock(API_URL).put(`/rules-configs/${this.params.key}`).reply(500); - this.rulesConfigs.set(this.params, this.data).catch(function(err) { + this.rulesConfigs.set(this.params, this.data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a PUT request to /rules-configs/{KEY}', function(done) { + it('should perform a PUT request to /rules-configs/{KEY}', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .put('/rules-configs/' + this.params.key, this.data) - .reply(200); + const request = nock(API_URL).put(`/rules-configs/${this.params.key}`, this.data).reply(200); this.rulesConfigs .set(this.params, this.data) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); }) - .catch(function(err) { + .catch((err) => { console.error(err); expect.fail(); done(); }); }); - it('should pass the data in the body of the request', function(done) { + it('should pass the data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .put('/rules-configs/' + this.params.key, this.data) - .reply(200); + const request = nock(API_URL).put(`/rules-configs/${this.params.key}`, this.data).reply(200); - this.rulesConfigs.set(this.params, this.data).then(function() { + this.rulesConfigs.set(this.params, this.data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .put('/rules-configs/' + this.params.key, this.data) - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .put(`/rules-configs/${this.params.key}`, this.data) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.rulesConfigs.set(this.params, this.data).then(function() { + this.rulesConfigs.set(this.params, this.data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -221,56 +202,52 @@ describe('RulesConfigsManager', function() { }); }); - describe('#delete', function() { - var key = 'KEY'; + describe('#delete', () => { + const key = 'KEY'; - beforeEach(function() { - this.request = nock(API_URL) - .delete('/rules-configs/' + key) - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).delete(`/rules-configs/${key}`).reply(200); }); - it('should accept a callback', function(done) { - this.rulesConfigs.delete({ key: key }, done.bind(null, null)); + it('should accept a callback', function (done) { + this.rulesConfigs.delete({ key }, done.bind(null, null)); }); - it('should return a promise when no callback is given', function(done) { - this.rulesConfigs.delete({ key: key }).then(done.bind(null, null)); + it('should return a promise when no callback is given', function (done) { + this.rulesConfigs.delete({ key }).then(done.bind(null, null)); }); - it('should perform a delete request to /rules-configs/' + key, function(done) { - var request = this.request; + it(`should perform a delete request to /rules-configs/${key}`, function (done) { + const { request } = this; - this.rulesConfigs.delete({ key: key }).then(function() { + this.rulesConfigs.delete({ key }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete('/rules-configs/' + key) - .reply(500); + nock(API_URL).delete(`/rules-configs/${key}`).reply(500); - this.rulesConfigs.delete({ key: key }).catch(function(err) { + this.rulesConfigs.delete({ key }).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the authorization header', function(done) { + it('should include the token in the authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete('/rules-configs/' + key) - .matchHeader('authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .delete(`/rules-configs/${key}`) + .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); - this.rulesConfigs.delete({ key: key }).then(function() { + this.rulesConfigs.delete({ key }).then(() => { expect(request.isDone()).to.be.true; done(); diff --git a/test/management/rules.tests.js b/test/management/rules.tests.js index dcf900952..565e99b24 100644 --- a/test/management/rules.tests.js +++ b/test/management/rules.tests.js @@ -1,91 +1,86 @@ -var expect = require('chai').expect; -var nock = require('nock'); +const { expect } = require('chai'); +const nock = require('nock'); -var SRC_DIR = '../../src'; -var API_URL = 'https://tenant.auth0.com'; +const API_URL = 'https://tenant.auth0.com'; -var RulesManager = require(SRC_DIR + '/management/RulesManager'); -var ArgumentError = require('rest-facade').ArgumentError; +const RulesManager = require(`../../src/management/RulesManager`); +const { ArgumentError } = require('rest-facade'); -describe('RulesManager', function() { - before(function() { +describe('RulesManager', () => { + before(function () { this.token = 'TOKEN'; this.rules = new RulesManager({ - headers: { authorization: 'Bearer ' + this.token }, - baseUrl: API_URL + headers: { authorization: `Bearer ${this.token}` }, + baseUrl: API_URL, }); }); - describe('instance', function() { - var methods = ['get', 'getAll', 'create', 'update', 'delete']; + describe('instance', () => { + const methods = ['get', 'getAll', 'create', 'update', 'delete']; - methods.forEach(function(method) { - it('should have a ' + method + ' method', function() { + methods.forEach((method) => { + it(`should have a ${method} method`, function () { expect(this.rules[method]).to.exist.to.be.an.instanceOf(Function); }); }); }); - describe('#constructor', function() { - it('should error when no options are provided', function() { + describe('#constructor', () => { + it('should error when no options are provided', () => { expect(RulesManager).to.throw(ArgumentError, 'Must provide manager options'); }); - it('should throw an error when no base URL is provided', function() { - var client = RulesManager.bind(null, {}); + it('should throw an error when no base URL is provided', () => { + const client = RulesManager.bind(null, {}); expect(client).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); - it('should throw an error when the base URL is invalid', function() { - var client = RulesManager.bind(null, { baseUrl: '' }); + it('should throw an error when the base URL is invalid', () => { + const client = RulesManager.bind(null, { baseUrl: '' }); expect(client).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); - describe('#getAll', function() { - beforeEach(function() { - this.request = nock(API_URL) - .get('/rules') - .reply(200); + describe('#getAll', () => { + beforeEach(function () { + this.request = nock(API_URL).get('/rules').reply(200); }); - it('should accept a callback', function(done) { - this.rules.getAll(function() { + it('should accept a callback', function (done) { + this.rules.getAll(() => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.rules - .getAll() - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.rules.getAll().then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/rules') - .reply(500); + nock(API_URL).get('/rules').reply(500); - this.rules.getAll().catch(function(err) { - expect(err).to.exist; - done(); - }); + this.rules + .getAll() + .then((fg) => { + console.log(fg); + }) + .catch((err) => { + expect(err).to.exist; + done(); + }); }); - it('should pass the body of the response to the "then" handler', function(done) { + it('should pass the body of the response to the "then" handler', function (done) { nock.cleanAll(); - var data = [{ test: true }]; - var request = nock(API_URL) - .get('/rules') - .reply(200, data); + const data = [{ test: true }]; + nock(API_URL).get('/rules').reply(200, data); - this.rules.getAll().then(function(credentials) { + this.rules.getAll().then((credentials) => { expect(credentials).to.be.an.instanceOf(Array); expect(credentials.length).to.equal(data.length); @@ -96,42 +91,39 @@ describe('RulesManager', function() { }); }); - it('should perform a GET request to /api/v2/rules', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/rules', function (done) { + const { request } = this; - this.rules.getAll().then(function() { + this.rules.getAll().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/rules') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.rules.getAll().then(function() { + this.rules.getAll().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the parameters in the query-string', function(done) { + it('should pass the parameters in the query-string', function (done) { nock.cleanAll(); - var params = { + const params = { include_fields: true, - fields: 'test' + fields: 'test', }; - var request = nock(API_URL) - .get('/rules') - .query(params) - .reply(200); + const request = nock(API_URL).get('/rules').query(params).reply(200); - this.rules.getAll(params).then(function() { + this.rules.getAll(params).then(() => { expect(request.isDone()).to.be.true; done(); @@ -139,67 +131,60 @@ describe('RulesManager', function() { }); }); - describe('#get', function() { - beforeEach(function() { + describe('#get', () => { + beforeEach(function () { this.data = { id: 5, name: 'Test rule', enabled: true, script: "function (user, contest, callback) { console.log('Test'); }", - stage: 'login_success' + stage: 'login_success', }; - this.request = nock(API_URL) - .get('/rules/' + this.data.id) - .reply(200, this.data); + this.request = nock(API_URL).get(`/rules/${this.data.id}`).reply(200, this.data); }); - it('should accept a callback', function(done) { - var params = { id: this.data.id }; + it('should accept a callback', function (done) { + const params = { id: this.data.id }; this.rules.get(params, done.bind(null, null)); }); - it('should return a promise if no callback is given', function(done) { - this.rules - .get({ id: this.data.id }) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.rules.get({ id: this.data.id }).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should perform a POST request to /api/v2/rules/5', function(done) { - var request = this.request; + it('should perform a POST request to /api/v2/rules/5', function (done) { + const { request } = this; - this.rules.get({ id: this.data.id }).then(function() { + this.rules.get({ id: this.data.id }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/rules/' + this.data.id) - .reply(500); + nock(API_URL).get(`/rules/${this.data.id}`).reply(500); - this.rules.get({ id: this.data.id }).catch(function(err) { + this.rules.get({ id: this.data.id }).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/rules/' + this.data.id) - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .get(`/rules/${this.data.id}`) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.rules.get({ id: this.data.id }).then(function() { + this.rules.get({ id: this.data.id }).then(() => { expect(request.isDone()).to.be.true; done(); @@ -207,81 +192,72 @@ describe('RulesManager', function() { }); }); - describe('#create', function() { - var data = { + describe('#create', () => { + const data = { id: 5, name: 'Test rule', enabled: true, script: "function (user, contest, callback) { console.log('Test'); }", - stage: 'login_success' + stage: 'login_success', }; - beforeEach(function() { - this.request = nock(API_URL) - .post('/rules') - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).post('/rules').reply(200); }); - it('should accept a callback', function(done) { - this.rules.create(data, function() { + it('should accept a callback', function (done) { + this.rules.create(data, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.rules - .create(data) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.rules.create(data).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/rules') - .reply(500); + nock(API_URL).post('/rules').reply(500); - this.rules.create(data).catch(function(err) { + this.rules.create(data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a POST request to /api/v2/rules', function(done) { - var request = this.request; + it('should perform a POST request to /api/v2/rules', function (done) { + const { request } = this; - this.rules.create(data).then(function() { + this.rules.create(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the data in the body of the request', function(done) { + it('should pass the data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/rules', data) - .reply(200); + const request = nock(API_URL).post('/rules', data).reply(200); - this.rules.create(data).then(function() { + this.rules.create(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .post('/rules') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.rules.create(data).then(function() { + this.rules.create(data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -289,58 +265,49 @@ describe('RulesManager', function() { }); }); - describe('#update', function() { - beforeEach(function() { + describe('#update', () => { + beforeEach(function () { this.data = { id: 5 }; - this.request = nock(API_URL) - .patch('/rules/' + this.data.id) - .reply(200, this.data); + this.request = nock(API_URL).patch(`/rules/${this.data.id}`).reply(200, this.data); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.rules.update({ id: 5 }, {}, done.bind(null, null)); }); - it('should return a promise if no callback is given', function(done) { - this.rules - .update({ id: 5 }, {}) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.rules.update({ id: 5 }, {}).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should perform a PATCH request to /api/v2/rules/5', function(done) { - var request = this.request; + it('should perform a PATCH request to /api/v2/rules/5', function (done) { + const { request } = this; - this.rules.update({ id: 5 }, {}).then(function() { + this.rules.update({ id: 5 }, {}).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the new data in the body of the request', function(done) { + it('should include the new data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/rules/' + this.data.id, this.data) - .reply(200); + const request = nock(API_URL).patch(`/rules/${this.data.id}`, this.data).reply(200); - this.rules.update({ id: 5 }, this.data).then(function() { + this.rules.update({ id: 5 }, this.data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/rules/' + this.data.id) - .reply(500); + nock(API_URL).patch(`/rules/${this.data.id}`).reply(500); - this.rules.update({ id: this.data.id }, this.data).catch(function(err) { + this.rules.update({ id: this.data.id }, this.data).catch((err) => { expect(err).to.exist; done(); @@ -348,56 +315,52 @@ describe('RulesManager', function() { }); }); - describe('#delete', function() { - var id = 5; + describe('#delete', () => { + const id = 5; - beforeEach(function() { - this.request = nock(API_URL) - .delete('/rules/' + id) - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).delete(`/rules/${id}`).reply(200); }); - it('should accept a callback', function(done) { - this.rules.delete({ id: id }, done.bind(null, null)); + it('should accept a callback', function (done) { + this.rules.delete({ id }, done.bind(null, null)); }); - it('should return a promise when no callback is given', function(done) { - this.rules.delete({ id: id }).then(done.bind(null, null)); + it('should return a promise when no callback is given', function (done) { + this.rules.delete({ id }).then(done.bind(null, null)); }); - it('should perform a delete request to /rules/' + id, function(done) { - var request = this.request; + it(`should perform a delete request to /rules/${id}`, function (done) { + const { request } = this; - this.rules.delete({ id: id }).then(function() { + this.rules.delete({ id }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete('/rules/' + id) - .reply(500); + nock(API_URL).delete(`/rules/${id}`).reply(500); - this.rules.delete({ id: id }).catch(function(err) { + this.rules.delete({ id }).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the authorization header', function(done) { + it('should include the token in the authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete('/rules/' + id) - .matchHeader('authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .delete(`/rules/${id}`) + .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); - this.rules.delete({ id: id }).then(function() { + this.rules.delete({ id }).then(() => { expect(request.isDone()).to.be.true; done(); diff --git a/test/management/stats.tests.js b/test/management/stats.tests.js index eac10c623..38ebcf98d 100644 --- a/test/management/stats.tests.js +++ b/test/management/stats.tests.js @@ -1,91 +1,81 @@ -var expect = require('chai').expect; -var nock = require('nock'); +const { expect } = require('chai'); +const nock = require('nock'); -var SRC_DIR = '../../src'; -var API_URL = 'https://tenant.auth0.com'; +const API_URL = 'https://tenant.auth0.com'; -var StatsManager = require(SRC_DIR + '/management/StatsManager'); -var ArgumentError = require('rest-facade').ArgumentError; +const StatsManager = require(`../../src/management/StatsManager`); +const { ArgumentError } = require('rest-facade'); -describe('StatsManager', function() { - before(function() { +describe('StatsManager', () => { + before(function () { this.token = 'TOKEN'; this.stats = new StatsManager({ - headers: { authorization: 'Bearer ' + this.token }, - baseUrl: API_URL + headers: { authorization: `Bearer ${this.token}` }, + baseUrl: API_URL, }); }); - describe('instance', function() { - var methods = ['getActiveUsersCount', 'getDaily']; + describe('instance', () => { + const methods = ['getActiveUsersCount', 'getDaily']; - methods.forEach(function(method) { - it('should have a ' + method + ' method', function() { + methods.forEach((method) => { + it(`should have a ${method} method`, function () { expect(this.stats[method]).to.exist.to.be.an.instanceOf(Function); }); }); }); - describe('#constructor', function() { - it('should error when no options are provided', function() { + describe('#constructor', () => { + it('should error when no options are provided', () => { expect(StatsManager).to.throw(ArgumentError, 'Must provide manager options'); }); - it('should throw an error when no base URL is provided', function() { - var client = StatsManager.bind(null, {}); + it('should throw an error when no base URL is provided', () => { + const client = StatsManager.bind(null, {}); expect(client).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); - it('should throw an error when the base URL is invalid', function() { - var client = StatsManager.bind(null, { baseUrl: '' }); + it('should throw an error when the base URL is invalid', () => { + const client = StatsManager.bind(null, { baseUrl: '' }); expect(client).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); - describe('#getDaily', function() { - beforeEach(function() { - this.request = nock(API_URL) - .get('/stats/daily') - .reply(200); + describe('#getDaily', () => { + beforeEach(function () { + this.request = nock(API_URL).get('/stats/daily').reply(200); }); - it('should accept a callback', function(done) { - this.stats.getDaily({}, function() { + it('should accept a callback', function (done) { + this.stats.getDaily({}, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.stats - .getDaily() - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.stats.getDaily().then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/stats/daily') - .reply(500); + nock(API_URL).get('/stats/daily').reply(500); - this.stats.getDaily().catch(function(err) { + this.stats.getDaily().catch((err) => { expect(err).to.exist; done(); }); }); - it('should pass the body of the response to the "then" handler', function(done) { + it('should pass the body of the response to the "then" handler', function (done) { nock.cleanAll(); - var data = [{ test: true }]; - var request = nock(API_URL) - .get('/stats/daily') - .reply(200, data); + const data = [{ test: true }]; + nock(API_URL).get('/stats/daily').reply(200, data); - this.stats.getDaily().then(function(blacklistedTokens) { + this.stats.getDaily().then((blacklistedTokens) => { expect(blacklistedTokens).to.be.an.instanceOf(Array); expect(blacklistedTokens.length).to.equal(data.length); @@ -96,112 +86,103 @@ describe('StatsManager', function() { }); }); - it('should perform a GET request to /api/v2/stats/daily', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/stats/daily', function (done) { + const { request } = this; - this.stats.getDaily().then(function() { + this.stats.getDaily().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/stats/daily') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.stats.getDaily().then(function() { + this.stats.getDaily().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the parameters in the query-string', function(done) { + it('should pass the parameters in the query-string', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/stats/daily') .query({ include_fields: true, - fields: 'test' + fields: 'test', }) .reply(200); - this.stats.getDaily({ include_fields: true, fields: 'test' }).then(function() { + this.stats.getDaily({ include_fields: true, fields: 'test' }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); }); - describe('#getActiveUsersCount', function() { - beforeEach(function() { - this.request = nock(API_URL) - .get('/stats/active-users') - .reply(200); + describe('#getActiveUsersCount', () => { + beforeEach(function () { + this.request = nock(API_URL).get('/stats/active-users').reply(200); }); - it('should accept a callback', function(done) { - this.stats.getActiveUsersCount(function() { + it('should accept a callback', function (done) { + this.stats.getActiveUsersCount(() => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.stats - .getActiveUsersCount() - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.stats.getActiveUsersCount().then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/stats/active-users') - .reply(500); + nock(API_URL).get('/stats/active-users').reply(500); - this.stats.getActiveUsersCount().catch(function(err) { + this.stats.getActiveUsersCount().catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a GET request to /api/v2/stats/active-users', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/stats/active-users', function (done) { + const { request } = this; - this.stats.getActiveUsersCount().then(function() { + this.stats.getActiveUsersCount().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the token data in the body of the request', function(done) { + it('should pass the token data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/stats/active-users') - .reply(200); + const request = nock(API_URL).get('/stats/active-users').reply(200); - this.stats.getActiveUsersCount().then(function() { + this.stats.getActiveUsersCount().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/stats/active-users') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.stats.getActiveUsersCount().then(function() { + this.stats.getActiveUsersCount().then(() => { expect(request.isDone()).to.be.true; done(); }); diff --git a/test/management/tenant.tests.js b/test/management/tenant.tests.js index 0b541a6a4..4045f3902 100644 --- a/test/management/tenant.tests.js +++ b/test/management/tenant.tests.js @@ -1,91 +1,83 @@ -var expect = require('chai').expect; -var nock = require('nock'); +const { expect } = require('chai'); +const nock = require('nock'); -var SRC_DIR = '../../src'; -var API_URL = 'https://tenants.auth0.com'; +const API_URL = 'https://tenants.auth0.com'; -var TenantManager = require(SRC_DIR + '/management/TenantManager'); -var ArgumentError = require('rest-facade').ArgumentError; +const TenantManager = require(`../../src/management/TenantManager`); +const { ArgumentError } = require('rest-facade'); -describe('TenantManager', function() { - before(function() { +describe('TenantManager', () => { + before(function () { this.token = 'TOKEN'; this.tenant = new TenantManager({ - headers: { authorization: 'Bearer ' + this.token }, - baseUrl: API_URL + headers: { authorization: `Bearer ${this.token}` }, + baseUrl: API_URL, }); }); - describe('instance', function() { - var methods = ['updateSettings', 'getSettings']; + describe('instance', () => { + const methods = ['updateSettings', 'getSettings']; - methods.forEach(function(method) { - it('should have a ' + method + ' method', function() { + methods.forEach((method) => { + it(`should have a ${method} method`, function () { expect(this.tenant[method]).to.exist.to.be.an.instanceOf(Function); }); }); }); - describe('#constructor', function() { - it('should error when no options are provided', function() { - expect(TenantManager).to.throw(ArgumentError, 'Must provide manager options'); + describe('#constructor', () => { + it('should error when no options are provided', () => { + expect(() => { + new TenantManager(); + }).to.throw(ArgumentError, 'Must provide manager options'); }); - it('should throw an error when no base URL is provided', function() { - var manager = TenantManager.bind(null, {}); - - expect(manager).to.throw(ArgumentError, 'Must provide a base URL for the API'); + it('should throw an error when no base URL is provided', () => { + expect(() => { + new TenantManager({}); + }).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); - it('should throw an error when the base URL is invalid', function() { - var manager = TenantManager.bind(null, { baseUrl: '' }); - - expect(manager).to.throw(ArgumentError, 'The provided base URL is invalid'); + it('should throw an error when the base URL is invalid', () => { + expect(() => { + new TenantManager({ baseUrl: '' }); + }).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); - describe('#getSettings', function() { - beforeEach(function() { - this.request = nock(API_URL) - .get('/tenants/settings') - .reply(200); + describe('#getSettings', () => { + beforeEach(function () { + this.request = nock(API_URL).get('/tenants/settings').reply(200); }); - it('should accept a callback', function(done) { - this.tenant.getSettings(function() { + it('should accept a callback', function (done) { + this.tenant.getSettings(() => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.tenant - .getSettings() - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.tenant.getSettings().then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/tenants/settings') - .reply(500); + nock(API_URL).get('/tenants/settings').reply(500); - this.tenant.getSettings().catch(function(err) { + this.tenant.getSettings().catch((err) => { expect(err).to.exist; done(); }); }); - it('should pass the body of the response to the "then" handler', function(done) { + it('should pass the body of the response to the "then" handler', function (done) { nock.cleanAll(); - var data = [{ test: true }]; - var request = nock(API_URL) - .get('/tenants/settings') - .reply(200, data); + const data = [{ test: true }]; + nock(API_URL).get('/tenants/settings').reply(200, data); - this.tenant.getSettings().then(function(blacklistedTokens) { + this.tenant.getSettings().then((blacklistedTokens) => { expect(blacklistedTokens).to.be.an.instanceOf(Array); expect(blacklistedTokens.length).to.equal(data.length); @@ -96,116 +88,107 @@ describe('TenantManager', function() { }); }); - it('should perform a GET request to /api/v2/tenants/settings', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/tenants/settings', function (done) { + const { request } = this; - this.tenant.getSettings().then(function() { + this.tenant.getSettings().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/tenants/settings') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.tenant.getSettings().then(function() { + this.tenant.getSettings().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the parameters in the query-string', function(done) { + it('should pass the parameters in the query-string', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/tenants/settings') .query({ include_fields: true, - fields: 'test' + fields: 'test', }) .reply(200); - this.tenant.getSettings({ include_fields: true, fields: 'test' }).then(function() { + this.tenant.getSettings({ include_fields: true, fields: 'test' }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); }); - describe('#updateSettings', function() { - var data = { - friendly_name: 'Test name' + describe('#updateSettings', () => { + const data = { + friendly_name: 'Test name', }; - beforeEach(function() { - this.request = nock(API_URL) - .patch('/tenants/settings') - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).patch('/tenants/settings').reply(200); }); - it('should accept a callback', function(done) { - this.tenant.updateSettings(data, function() { + it('should accept a callback', function (done) { + this.tenant.updateSettings(data, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.tenant - .updateSettings(data) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.tenant.updateSettings(data).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/tenants/settings') - .reply(500); + nock(API_URL).patch('/tenants/settings').reply(500); - this.tenant.updateSettings(data).catch(function(err) { + this.tenant.updateSettings(data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a PATCH request to /api/v2/tenants/settings', function(done) { - var request = this.request; + it('should perform a PATCH request to /api/v2/tenants/settings', function (done) { + const { request } = this; - this.tenant.updateSettings(data).then(function() { + this.tenant.updateSettings(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the data in the body of the request', function(done) { + it('should pass the data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/tenants/settings', data) - .reply(200); + const request = nock(API_URL).patch('/tenants/settings', data).reply(200); - this.tenant.updateSettings(data).then(function() { + this.tenant.updateSettings(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .patch('/tenants/settings') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.tenant.updateSettings(data).then(function() { + this.tenant.updateSettings(data).then(() => { expect(request.isDone()).to.be.true; done(); }); diff --git a/test/management/tickets.tests.js b/test/management/tickets.tests.js index 072a0fe39..54ba811a0 100644 --- a/test/management/tickets.tests.js +++ b/test/management/tickets.tests.js @@ -1,121 +1,115 @@ -var expect = require('chai').expect; -var nock = require('nock'); +const { expect } = require('chai'); +const nock = require('nock'); -var SRC_DIR = '../../src'; -var API_URL = 'https://tenants.auth0.com'; +const API_URL = 'https://tenants.auth0.com'; -var TicketsManager = require(SRC_DIR + '/management/TicketsManager'); -var ArgumentError = require('rest-facade').ArgumentError; +const TicketsManager = require(`../../src/management/TicketsManager`); +const { ArgumentError } = require('rest-facade'); -describe('TicketsManager', function() { - before(function() { +describe('TicketsManager', () => { + before(function () { this.token = 'TOKEN'; this.tickets = new TicketsManager({ - headers: { authorization: 'Bearer ' + this.token }, - baseUrl: API_URL + headers: { authorization: `Bearer ${this.token}` }, + baseUrl: API_URL, }); }); - describe('instance', function() { - var methods = ['changePassword', 'verifyEmail']; + describe('instance', () => { + const methods = ['changePassword', 'verifyEmail']; - methods.forEach(function(method) { - it('should have a ' + method + ' method', function() { + methods.forEach((method) => { + it(`should have a ${method} method`, function () { expect(this.tickets[method]).to.exist.to.be.an.instanceOf(Function); }); }); }); - describe('#constructor', function() { - it('should error when no options are provided', function() { - expect(TicketsManager).to.throw(ArgumentError, 'Must provide manager options'); + describe('#constructor', () => { + it('should error when no options are provided', () => { + expect(() => { + new TicketsManager(); + }).to.throw(ArgumentError, 'Must provide manager options'); }); - it('should throw an error when no base URL is provided', function() { - var manager = TicketsManager.bind(null, {}); - - expect(manager).to.throw(ArgumentError, 'Must provide a base URL for the API'); + it('should throw an error when no base URL is provided', () => { + expect(() => { + new TicketsManager({}); + }).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); - it('should throw an error when the base URL is invalid', function() { - var manager = TicketsManager.bind(null, { baseUrl: '' }); - - expect(manager).to.throw(ArgumentError, 'The provided base URL is invalid'); + it('should throw an error when the base URL is invalid', () => { + expect(() => { + new TicketsManager({ baseUrl: '' }); + }).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); - describe('#verifyEmail', function() { - var data = { + describe('#verifyEmail', () => { + const data = { result_url: 'http://myapp.com/callback', - user_id: '' + user_id: '', }; - beforeEach(function() { - this.request = nock(API_URL) - .post('/tickets/email-verification') - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).post('/tickets/email-verification').reply(200); }); - it('should accept a callback', function(done) { - this.tickets.verifyEmail(data, function() { + it('should accept a callback', function (done) { + this.tickets.verifyEmail(data, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.tickets - .verifyEmail(data) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.tickets.verifyEmail(data).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('tickets/email-verification') - .reply(500); + nock(API_URL).post('tickets/email-verification').reply(500); - this.tickets.verifyEmail(data).catch(function(err) { + this.tickets.verifyEmail(data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a POST request to /api/v2tickets/email-verification', function(done) { - var request = this.request; + it('should perform a POST request to /api/v2tickets/email-verification', function (done) { + const { request } = this; - this.tickets.verifyEmail(data).then(function() { + this.tickets.verifyEmail(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .post('/tickets/email-verification') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.tickets.verifyEmail({}).then(function() { + this.tickets.verifyEmail({}).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the parameters in the query-string', function(done) { + it('should pass the parameters in the query-string', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .post('/tickets/email-verification', { include_fields: true, - fields: 'test' + fields: 'test', }) .reply(200); - this.tickets.verifyEmail({ include_fields: true, fields: 'test' }).then(function() { + this.tickets.verifyEmail({ include_fields: true, fields: 'test' }).then(() => { expect(request.isDone()).to.be.true; done(); @@ -123,79 +117,70 @@ describe('TicketsManager', function() { }); }); - describe('#changePassword', function() { - var data = { + describe('#changePassword', () => { + const data = { result_url: 'http://myapp.com/callback', user_id: '', new_password: 'secret', connection_id: 'con_0000000000000001', - email: '' + email: '', }; - beforeEach(function() { - this.request = nock(API_URL) - .post('/tickets/password-change') - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).post('/tickets/password-change').reply(200); }); - it('should accept a callback', function(done) { - this.tickets.changePassword(data, function() { + it('should accept a callback', function (done) { + this.tickets.changePassword(data, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.tickets - .changePassword(data) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.tickets.changePassword(data).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/tickets/email-verification') - .reply(500); + nock(API_URL).post('/tickets/email-verification').reply(500); - this.tickets.changePassword(data).catch(function(err) { + this.tickets.changePassword(data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a POST request to /api/v2tickets/email-verification', function(done) { - var request = this.request; + it('should perform a POST request to /api/v2tickets/email-verification', function (done) { + const { request } = this; - this.tickets.changePassword(data).then(function() { + this.tickets.changePassword(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the data in the body of the request', function(done) { + it('should pass the data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/tickets/password-change', data) - .reply(200); + const request = nock(API_URL).post('/tickets/password-change', data).reply(200); - this.tickets.changePassword(data).then(function() { + this.tickets.changePassword(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .post('/tickets/password-change') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.tickets.changePassword(data).then(function() { + this.tickets.changePassword(data).then(() => { expect(request.isDone()).to.be.true; done(); }); diff --git a/test/management/user-blocks.tests.js b/test/management/user-blocks.tests.js index decf9c491..67c6c1843 100644 --- a/test/management/user-blocks.tests.js +++ b/test/management/user-blocks.tests.js @@ -1,100 +1,97 @@ -var expect = require('chai').expect; -var nock = require('nock'); +const { expect } = require('chai'); +const nock = require('nock'); -var SRC_DIR = '../../src'; -var API_URL = 'https://tenants.auth0.com'; +const API_URL = 'https://tenants.auth0.com'; -var UserBlocksManager = require(SRC_DIR + '/management/UserBlocksManager'); -var ArgumentError = require('rest-facade').ArgumentError; +const UserBlocksManager = require(`../../src/management/UserBlocksManager`); +const { ArgumentError } = require('rest-facade'); -describe('UserBlocksManager', function() { - before(function() { +describe('UserBlocksManager', () => { + before(function () { this.token = 'TOKEN'; this.userBlocks = new UserBlocksManager({ - headers: { authorization: 'Bearer ' + this.token }, - baseUrl: API_URL + headers: { authorization: `Bearer ${this.token}` }, + baseUrl: API_URL, }); }); - describe('instance', function() { - var methods = ['get', 'delete', 'getByIdentifier', 'deleteByIdentifier']; + describe('instance', () => { + const methods = ['get', 'delete', 'getByIdentifier', 'deleteByIdentifier']; - methods.forEach(function(method) { - it('should have a ' + method + ' method', function() { + methods.forEach((method) => { + it(`should have a ${method} method`, function () { expect(this.userBlocks[method]).to.exist.to.be.an.instanceOf(Function); }); }); }); - describe('#constructor', function() { - it('should error when no options are provided', function() { - expect(UserBlocksManager).to.throw(ArgumentError, 'Must provide manager options'); + describe('#constructor', () => { + it('should error when no options are provided', () => { + expect(() => { + new UserBlocksManager(); + }).to.throw(ArgumentError, 'Must provide manager options'); }); - it('should throw an error when no base URL is provided', function() { - var manager = UserBlocksManager.bind(null, {}); - - expect(manager).to.throw(ArgumentError, 'Must provide a base URL for the API'); + it('should throw an error when no base URL is provided', () => { + expect(() => { + new UserBlocksManager({}); + }).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); - it('should throw an error when the base URL is invalid', function() { - var manager = UserBlocksManager.bind(null, { baseUrl: '' }); - - expect(manager).to.throw(ArgumentError, 'The provided base URL is invalid'); + it('should throw an error when the base URL is invalid', () => { + expect(() => { + new UserBlocksManager({ baseUrl: '' }); + }).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); - describe('#get', function() { - var id = 'USER_5'; + describe('#get', () => { + const id = 'USER_5'; - beforeEach(function() { - this.request = nock(API_URL) - .get('/user-blocks/' + id) - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).get(`/user-blocks/${id}`).reply(200); }); - afterEach(function() { + afterEach(() => { nock.cleanAll(); }); - it('should throw an error when no id is provided', function() { - var userBlocks = this.userBlocks; + it('should throw an error when no id is provided', function () { + const { userBlocks } = this; - expect(function() { + expect(() => { userBlocks.get({}); }).to.throw(ArgumentError, 'You must provide an user id for the get method'); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.userBlocks.get({ id }, done.bind(null, null)); }); - it('should return a promise when no callback is given', function(done) { + it('should return a promise when no callback is given', function (done) { this.userBlocks.get({ id }).then(done.bind(null, null)); }); - it('should perform a get request to /user-blocks/' + id, function(done) { - var request = this.request; + it(`should perform a get request to /user-blocks/${id}`, function (done) { + const { request } = this; this.userBlocks .get({ id }) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); }) .catch(done); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - nock(API_URL) - .get('/user-blocks/' + id) - .reply(500); + nock(API_URL).get(`/user-blocks/${id}`).reply(500); this.userBlocks .get({ id }) - .catch(function(err) { + .catch((err) => { expect(err).to.exist; done(); @@ -102,17 +99,17 @@ describe('UserBlocksManager', function() { .catch(done); }); - it('should include the token in the authorization header', function(done) { + it('should include the token in the authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/user-blocks/' + id) - .matchHeader('authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .get(`/user-blocks/${id}`) + .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); this.userBlocks .get({ id }) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -121,41 +118,39 @@ describe('UserBlocksManager', function() { }); }); - describe('#delete', function() { - var id = 'USER_5'; + describe('#delete', () => { + const id = 'USER_5'; - beforeEach(function() { - this.request = nock(API_URL) - .delete('/user-blocks/' + id) - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).delete(`/user-blocks/${id}`).reply(200); }); - afterEach(function() { + afterEach(() => { nock.cleanAll(); }); - it('should throw an error when no id is provided', function() { - var userBlocks = this.userBlocks; + it('should throw an error when no id is provided', function () { + const { userBlocks } = this; - expect(function() { + expect(() => { userBlocks.delete({}); }).to.throw(ArgumentError, 'You must provide an user id for the delete method'); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.userBlocks.delete({ id }, done.bind(null, null)); }); - it('should return a promise when no callback is given', function(done) { + it('should return a promise when no callback is given', function (done) { this.userBlocks.delete({ id }).then(done.bind(null, null)); }); - it('should perform a delete request to /user-blocks/' + id, function(done) { - var request = this.request; + it(`should perform a delete request to /user-blocks/${id}`, function (done) { + const { request } = this; this.userBlocks .delete({ id }) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -163,16 +158,14 @@ describe('UserBlocksManager', function() { .catch(done); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - nock(API_URL) - .delete('/user-blocks/' + id) - .reply(500); + nock(API_URL).delete(`/user-blocks/${id}`).reply(500); this.userBlocks .delete({ id }) - .catch(function(err) { + .catch((err) => { expect(err).to.exist; done(); @@ -180,17 +173,17 @@ describe('UserBlocksManager', function() { .catch(done); }); - it('should include the token in the authorization header', function(done) { + it('should include the token in the authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete('/user-blocks/' + id) - .matchHeader('authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .delete(`/user-blocks/${id}`) + .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); this.userBlocks .delete({ id }) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -199,24 +192,21 @@ describe('UserBlocksManager', function() { }); }); - describe('#getByIdentifier', function() { - var identifier = 'USER_5'; + describe('#getByIdentifier', () => { + const identifier = 'USER_5'; - beforeEach(function() { - this.request = nock(API_URL) - .get('/user-blocks') - .query({ identifier }) - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).get('/user-blocks').query({ identifier }).reply(200); }); - afterEach(function() { + afterEach(() => { nock.cleanAll(); }); - it('should throw an error when no identifier is provided', function() { - var userBlocks = this.userBlocks; + it('should throw an error when no identifier is provided', function () { + const { userBlocks } = this; - expect(function() { + expect(() => { userBlocks.getByIdentifier({}); }).to.throw( ArgumentError, @@ -224,20 +214,20 @@ describe('UserBlocksManager', function() { ); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.userBlocks.getByIdentifier({ identifier }, done.bind(null, null)); }); - it('should return a promise when no callback is given', function(done) { + it('should return a promise when no callback is given', function (done) { this.userBlocks.getByIdentifier({ identifier }).then(done.bind(null, null)); }); - it('should perform a get request to /user-blocks', function(done) { - var request = this.request; + it('should perform a get request to /user-blocks', function (done) { + const { request } = this; this.userBlocks .getByIdentifier({ identifier }) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -245,17 +235,14 @@ describe('UserBlocksManager', function() { .catch(done); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - nock(API_URL) - .get('/user-blocks') - .query({ identifier }) - .reply(500); + nock(API_URL).get('/user-blocks').query({ identifier }).reply(500); this.userBlocks .getByIdentifier({ identifier }) - .catch(function(err) { + .catch((err) => { expect(err).to.exist; done(); @@ -263,18 +250,18 @@ describe('UserBlocksManager', function() { .catch(done); }); - it('should include the token in the authorization header', function(done) { + it('should include the token in the authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/user-blocks') .query({ identifier }) - .matchHeader('authorization', 'Bearer ' + this.token) + .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); this.userBlocks .getByIdentifier({ identifier }) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -283,24 +270,21 @@ describe('UserBlocksManager', function() { }); }); - describe('#deleteByIdentifier', function() { - var identifier = 'USER_5'; + describe('#deleteByIdentifier', () => { + const identifier = 'USER_5'; - beforeEach(function() { - this.request = nock(API_URL) - .delete('/user-blocks') - .query({ identifier }) - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).delete('/user-blocks').query({ identifier }).reply(200); }); - afterEach(function() { + afterEach(() => { nock.cleanAll(); }); - it('should throw an error when no identifier is provided', function() { - var userBlocks = this.userBlocks; + it('should throw an error when no identifier is provided', function () { + const { userBlocks } = this; - expect(function() { + expect(() => { userBlocks.deleteByIdentifier({}); }).to.throw( ArgumentError, @@ -308,20 +292,20 @@ describe('UserBlocksManager', function() { ); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.userBlocks.deleteByIdentifier({ identifier }, done.bind(null, null)); }); - it('should return a promise when no callback is given', function(done) { + it('should return a promise when no callback is given', function (done) { this.userBlocks.deleteByIdentifier({ identifier }).then(done.bind(null, null)); }); - it('should perform a delete request to /user-blocks', function(done) { - var request = this.request; + it('should perform a delete request to /user-blocks', function (done) { + const { request } = this; this.userBlocks .deleteByIdentifier({ identifier }) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -329,17 +313,14 @@ describe('UserBlocksManager', function() { .catch(done); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - nock(API_URL) - .delete('/user-blocks') - .query({ identifier }) - .reply(500); + nock(API_URL).delete('/user-blocks').query({ identifier }).reply(500); this.userBlocks .deleteByIdentifier({ identifier }) - .catch(function(err) { + .catch((err) => { expect(err).to.exist; done(); @@ -347,18 +328,18 @@ describe('UserBlocksManager', function() { .catch(done); }); - it('should include the token in the authorization header', function(done) { + it('should include the token in the authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .delete('/user-blocks') .query({ identifier }) - .matchHeader('authorization', 'Bearer ' + this.token) + .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); this.userBlocks .deleteByIdentifier({ identifier }) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); diff --git a/test/management/users.tests.js b/test/management/users.tests.js index 32613b97c..64aceaeef 100644 --- a/test/management/users.tests.js +++ b/test/management/users.tests.js @@ -1,23 +1,22 @@ -var expect = require('chai').expect; -var nock = require('nock'); +const { expect } = require('chai'); +const nock = require('nock'); -var SRC_DIR = '../../src'; -var API_URL = 'https://tenants.auth0.com'; +const API_URL = 'https://tenants.auth0.com'; -var UsersManager = require(SRC_DIR + '/management/UsersManager'); -var ArgumentError = require('rest-facade').ArgumentError; +const UsersManager = require(`../../src/management/UsersManager`); +const { ArgumentError } = require('rest-facade'); -describe('UsersManager', function() { - before(function() { +describe('UsersManager', () => { + before(function () { this.token = 'TOKEN'; this.users = new UsersManager({ - headers: { authorization: 'Bearer ' + this.token }, - baseUrl: API_URL + headers: { authorization: `Bearer ${this.token}` }, + baseUrl: API_URL, }); }); - describe('instance', function() { - var methods = [ + describe('instance', () => { + const methods = [ 'get', 'getAll', 'create', @@ -39,77 +38,70 @@ describe('UsersManager', function() { 'getPermissions', 'assignPermissions', 'removePermissions', - 'getUserOrganizations' + 'getUserOrganizations', ]; - methods.forEach(function(method) { - it('should have a ' + method + ' method', function() { + methods.forEach((method) => { + it(`should have a ${method} method`, function () { expect(this.users[method]).to.exist.to.be.an.instanceOf(Function); }); }); }); - describe('#constructor', function() { - it('should error when no options are provided', function() { - expect(UsersManager).to.throw(ArgumentError, 'Must provide manager options'); + describe('#constructor', () => { + it('should error when no options are provided', () => { + expect(() => { + new UsersManager(); + }).to.throw(ArgumentError, 'Must provide manager options'); }); - it('should throw an error when no base URL is provided', function() { - var manager = UsersManager.bind(null, {}); - - expect(manager).to.throw(ArgumentError, 'Must provide a base URL for the API'); + it('should throw an error when no base URL is provided', () => { + expect(() => { + new UsersManager({}); + }).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); - it('should throw an error when the base URL is invalid', function() { - var manager = UsersManager.bind(null, { baseUrl: '' }); - - expect(manager).to.throw(ArgumentError, 'The provided base URL is invalid'); + it('should throw an error when the base URL is invalid', () => { + expect(() => { + new UsersManager({ baseUrl: '' }); + }).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); - describe('#getAll', function() { - beforeEach(function() { - this.request = nock(API_URL) - .get('/users') - .reply(200); + describe('#getAll', () => { + beforeEach(function () { + this.request = nock(API_URL).get('/users').reply(200); }); - it('should accept a callback', function(done) { - this.users.getAll(function() { + it('should accept a callback', function (done) { + this.users.getAll(() => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.users - .getAll() - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.users.getAll().then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/users') - .reply(500); + nock(API_URL).get('/users').reply(500); - this.users.getAll().catch(function(err) { + this.users.getAll().catch((err) => { expect(err).to.exist; done(); }); }); - it('should pass the body of the response to the "then" handler', function(done) { + it('should pass the body of the response to the "then" handler', function (done) { nock.cleanAll(); - var data = [{ test: true }]; - var request = nock(API_URL) - .get('/users') - .reply(200, data); + const data = [{ test: true }]; + nock(API_URL).get('/users').reply(200, data); - this.users.getAll().then(function(users) { + this.users.getAll().then((users) => { expect(users).to.be.an.instanceOf(Array); expect(users.length).to.equal(data.length); @@ -120,44 +112,41 @@ describe('UsersManager', function() { }); }); - it('should perform a GET request to /api/v2/users', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/users', function (done) { + const { request } = this; - this.users.getAll().then(function() { + this.users.getAll().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/users') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.users.getAll().then(function() { + this.users.getAll().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the parameters in the query-string', function(done) { + it('should pass the parameters in the query-string', function (done) { nock.cleanAll(); - var params = { + const params = { include_fields: true, - fields: 'test' + fields: 'test', }; - var request = nock(API_URL) - .get('/users') - .query(params) - .reply(200); + const request = nock(API_URL).get('/users').query(params).reply(200); - this.users.getAll(params).then(function() { + this.users.getAll(params).then(() => { expect(request.isDone()).to.be.true; done(); @@ -165,49 +154,40 @@ describe('UsersManager', function() { }); }); - describe('#getByEmail', function() { - beforeEach(function() { - this.request = nock(API_URL) - .get('/users-by-email') - .reply(200); + describe('#getByEmail', () => { + beforeEach(function () { + this.request = nock(API_URL).get('/users-by-email').reply(200); }); - it('should accept a callback', function(done) { - this.users.getByEmail('someone@example.com', function() { + it('should accept a callback', function (done) { + this.users.getByEmail('someone@example.com', () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.users - .getByEmail() - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.users.getByEmail().then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/users-by-email') - .reply(500); + nock(API_URL).get('/users-by-email').reply(500); - this.users.getByEmail().catch(function(err) { + this.users.getByEmail().catch((err) => { expect(err).to.exist; done(); }); }); - it('should pass the body of the response to the "then" handler', function(done) { + it('should pass the body of the response to the "then" handler', function (done) { nock.cleanAll(); - var data = [{ test: true }]; - var request = nock(API_URL) - .get('/users-by-email') - .reply(200, data); + const data = [{ test: true }]; + nock(API_URL).get('/users-by-email').reply(200, data); - this.users.getByEmail().then(function(users) { + this.users.getByEmail().then((users) => { expect(users).to.be.an.instanceOf(Array); expect(users.length).to.equal(data.length); @@ -218,67 +198,61 @@ describe('UsersManager', function() { }); }); - it('should perform a GET request to /api/v2/users-by-email', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/users-by-email', function (done) { + const { request } = this; - this.users.getByEmail().then(function() { + this.users.getByEmail().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get('/users-by-email') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.users.getByEmail().then(function() { + this.users.getByEmail().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass an email in as a query string', function(done) { + it('should pass an email in as a query string', function (done) { nock.cleanAll(); - var params = { - email: 'email@example.com' + const params = { + email: 'email@example.com', }; - var request = nock(API_URL) - .get('/users-by-email') - .query(params) - .reply(200); + const request = nock(API_URL).get('/users-by-email').query(params).reply(200); - this.users.getByEmail(params.email).then(function() { + this.users.getByEmail(params.email).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass additional options into the query string', function(done) { + it('should pass additional options into the query string', function (done) { nock.cleanAll(); - var additionalOptions = { + const additionalOptions = { fields: 'user_id, email, email_verified', - include_fields: true + include_fields: true, }; - var params = { + const params = { email: 'email@example.com', - ...additionalOptions + ...additionalOptions, }; - var request = nock(API_URL) - .get('/users-by-email') - .query(params) - .reply(200); + const request = nock(API_URL).get('/users-by-email').query(params).reply(200); - this.users.getByEmail(params.email, additionalOptions).then(function() { + this.users.getByEmail(params.email, additionalOptions).then(() => { expect(request.isDone()).to.be.true; done(); @@ -286,67 +260,60 @@ describe('UsersManager', function() { }); }); - describe('#get', function() { - beforeEach(function() { + describe('#get', () => { + beforeEach(function () { this.data = { id: 5, name: 'Test rule', enabled: true, script: "function (user, contest, callback) { console.log('Test'); }", - stage: 'login_success' + stage: 'login_success', }; - this.request = nock(API_URL) - .get('/users/' + this.data.id) - .reply(200, this.data); + this.request = nock(API_URL).get(`/users/${this.data.id}`).reply(200, this.data); }); - it('should accept a callback', function(done) { - var params = { id: this.data.id }; + it('should accept a callback', function (done) { + const params = { id: this.data.id }; this.users.get(params, done.bind(null, null)); }); - it('should return a promise if no callback is given', function(done) { - this.users - .get({ id: this.data.id }) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.users.get({ id: this.data.id }).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should perform a POST request to /api/v2/users/5', function(done) { - var request = this.request; + it('should perform a POST request to /api/v2/users/5', function (done) { + const { request } = this; - this.users.get({ id: this.data.id }).then(function() { + this.users.get({ id: this.data.id }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/users/' + this.data.id) - .reply(500); + nock(API_URL).get(`/users/${this.data.id}`).reply(500); - this.users.get({ id: this.data.id }).catch(function(err) { + this.users.get({ id: this.data.id }).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/users/' + this.data.id) - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .get(`/users/${this.data.id}`) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.users.get({ id: this.data.id }).then(function() { + this.users.get({ id: this.data.id }).then(() => { expect(request.isDone()).to.be.true; done(); @@ -354,81 +321,72 @@ describe('UsersManager', function() { }); }); - describe('#create', function() { - var data = { + describe('#create', () => { + const data = { id: 5, name: 'Test rule', enabled: true, script: "function (user, contest, callback) { console.log('Test'); }", - stage: 'login_success' + stage: 'login_success', }; - beforeEach(function() { - this.request = nock(API_URL) - .post('/users') - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).post('/users').reply(200); }); - it('should accept a callback', function(done) { - this.users.create(data, function() { + it('should accept a callback', function (done) { + this.users.create(data, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.users - .create(data) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.users.create(data).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/users') - .reply(500); + nock(API_URL).post('/users').reply(500); - this.users.create(data).catch(function(err) { + this.users.create(data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a POST request to /api/v2/users', function(done) { - var request = this.request; + it('should perform a POST request to /api/v2/users', function (done) { + const { request } = this; - this.users.create(data).then(function() { + this.users.create(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the data in the body of the request', function(done) { + it('should pass the data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/users', data) - .reply(200); + const request = nock(API_URL).post('/users', data).reply(200); - this.users.create(data).then(function() { + this.users.create(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .post('/users') - .matchHeader('Authorization', 'Bearer ' + this.token) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.users.create(data).then(function() { + this.users.create(data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -436,58 +394,49 @@ describe('UsersManager', function() { }); }); - describe('#update', function() { - beforeEach(function() { + describe('#update', () => { + beforeEach(function () { this.data = { id: 5 }; - this.request = nock(API_URL) - .patch('/users/' + this.data.id) - .reply(200, this.data); + this.request = nock(API_URL).patch(`/users/${this.data.id}`).reply(200, this.data); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.users.update({ id: 5 }, {}, done.bind(null, null)); }); - it('should return a promise if no callback is given', function(done) { - this.users - .update({ id: 5 }, {}) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.users.update({ id: 5 }, {}).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should perform a PATCH request to /api/v2/users/5', function(done) { - var request = this.request; + it('should perform a PATCH request to /api/v2/users/5', function (done) { + const { request } = this; - this.users.update({ id: 5 }, {}).then(function() { + this.users.update({ id: 5 }, {}).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the new data in the body of the request', function(done) { + it('should include the new data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/users/' + this.data.id, this.data) - .reply(200); + const request = nock(API_URL).patch(`/users/${this.data.id}`, this.data).reply(200); - this.users.update({ id: 5 }, this.data).then(function() { + this.users.update({ id: 5 }, this.data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/users/' + this.data.id) - .reply(500); + nock(API_URL).patch(`/users/${this.data.id}`).reply(500); - this.users.update({ id: this.data.id }, this.data).catch(function(err) { + this.users.update({ id: this.data.id }, this.data).catch((err) => { expect(err).to.exist; done(); @@ -495,56 +444,52 @@ describe('UsersManager', function() { }); }); - describe('#delete', function() { - var id = 'USER_5'; + describe('#delete', () => { + const id = 'USER_5'; - beforeEach(function() { - this.request = nock(API_URL) - .delete('/users/' + id) - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).delete(`/users/${id}`).reply(200); }); - it('should accept a callback', function(done) { - this.users.delete({ id: id }, done.bind(null, null)); + it('should accept a callback', function (done) { + this.users.delete({ id }, done.bind(null, null)); }); - it('should return a promise when no callback is given', function(done) { - this.users.delete({ id: id }).then(done.bind(null, null)); + it('should return a promise when no callback is given', function (done) { + this.users.delete({ id }).then(done.bind(null, null)); }); - it('should perform a delete request to /users/' + id, function(done) { - var request = this.request; + it(`should perform a delete request to /users/${id}`, function (done) { + const { request } = this; - this.users.delete({ id: id }).then(function() { + this.users.delete({ id }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete('/users/' + id) - .reply(500); + nock(API_URL).delete(`/users/${id}`).reply(500); - this.users.delete({ id: id }).catch(function(err) { + this.users.delete({ id }).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the authorization header', function(done) { + it('should include the token in the authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete('/users/' + id) - .matchHeader('authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .delete(`/users/${id}`) + .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); - this.users.delete({ id: id }).then(function() { + this.users.delete({ id }).then(() => { expect(request.isDone()).to.be.true; done(); @@ -552,93 +497,84 @@ describe('UsersManager', function() { }); }); - describe('#link', function() { - var userId = 'USER_ID'; - var data = { + describe('#link', () => { + const userId = 'USER_ID'; + const data = { provider: 'twitter', - user_id: '191919191919191' + user_id: '191919191919191', }; - beforeEach(function() { - this.request = nock(API_URL) - .post('/users/' + userId + '/identities') - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).post(`/users/${userId}/identities`).reply(200); }); - it('should validate empty userId', function() { - var _this = this; - expect(function() { - _this.users.link(null, data, function() {}); + it('should validate empty userId', function () { + const _this = this; + expect(() => { + _this.users.link(null, data, () => {}); }).to.throw('The userId cannot be null or undefined'); }); - it('should validate non-string userId', function() { - var _this = this; - expect(function() { - _this.users.link(123, data, function() {}); + it('should validate non-string userId', function () { + const _this = this; + expect(() => { + _this.users.link(123, data, () => {}); }).to.throw('The userId has to be a string'); }); - it('should accept a callback', function(done) { - this.users.link(userId, data, function() { + it('should accept a callback', function (done) { + this.users.link(userId, data, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { - this.users - .link(userId, data) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', function (done) { + this.users.link(userId, data).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/users/' + userId + '/identities') - .reply(500); + nock(API_URL).post(`/users/${userId}/identities`).reply(500); - this.users.link(userId, data).catch(function(err) { + this.users.link(userId, data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a POST request to /api/v2/users', function(done) { - var request = this.request; + it('should perform a POST request to /api/v2/users', function (done) { + const { request } = this; - this.users.link(userId, data).then(function() { + this.users.link(userId, data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the data in the body of the request', function(done) { + it('should pass the data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/users/' + userId + '/identities', data) - .reply(200); + const request = nock(API_URL).post(`/users/${userId}/identities`, data).reply(200); - this.users.link(userId, data).then(function() { + this.users.link(userId, data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/users/' + userId + '/identities') - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .post(`/users/${userId}/identities`) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.users.link(userId, data).then(function() { + this.users.link(userId, data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -646,61 +582,57 @@ describe('UsersManager', function() { }); }); - describe('#unlink', function() { - var data = { + describe('#unlink', () => { + const data = { id: 'u1', user_id: 'u2', - provider: 'auth0' + provider: 'auth0', }; - var url = '/users/' + data.id + '/identities/' + data.provider + '/' + data.user_id; + const url = `/users/${data.id}/identities/${data.provider}/${data.user_id}`; - beforeEach(function() { - this.request = nock(API_URL) - .delete(url) - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).delete(url).reply(200); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.users.unlink(data, done.bind(null, null)); }); - it('should return a promise when no callback is given', function(done) { + it('should return a promise when no callback is given', function (done) { this.users.unlink(data).then(done.bind(null, null)); }); - it('should perform a DELETE request to ' + url, function(done) { - var request = this.request; + it(`should perform a DELETE request to ${url}`, function (done) { + const { request } = this; - this.users.unlink(data).then(function() { + this.users.unlink(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete(url) - .reply(500); + nock(API_URL).delete(url).reply(500); - this.users.unlink(data).catch(function(err) { + this.users.unlink(data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the authorization header', function(done) { + it('should include the token in the authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .delete(url) - .matchHeader('authorization', 'Bearer ' + this.token) + .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); - this.users.unlink(data).then(function() { + this.users.unlink(data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -708,60 +640,56 @@ describe('UsersManager', function() { }); }); - describe('#deleteMultifactorProvider', function() { - var data = { + describe('#deleteMultifactorProvider', () => { + const data = { id: 'u1', - provider: 'auth0' + provider: 'auth0', }; - var url = '/users/' + data.id + '/multifactor/' + data.provider; + const url = `/users/${data.id}/multifactor/${data.provider}`; - beforeEach(function() { - this.request = nock(API_URL) - .delete(url) - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).delete(url).reply(200); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.users.deleteMultifactorProvider(data, done.bind(null, null)); }); - it('should return a promise when no callback is given', function(done) { + it('should return a promise when no callback is given', function (done) { this.users.deleteMultifactorProvider(data).then(done.bind(null, null)); }); - it('should perform a DELETE request to ' + url, function(done) { - var request = this.request; + it(`should perform a DELETE request to ${url}`, function (done) { + const { request } = this; - this.users.deleteMultifactorProvider(data).then(function() { + this.users.deleteMultifactorProvider(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete(url) - .reply(500); + nock(API_URL).delete(url).reply(500); - this.users.deleteMultifactorProvider(data).catch(function(err) { + this.users.deleteMultifactorProvider(data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the authorization header', function(done) { + it('should include the token in the authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .delete(url) - .matchHeader('authorization', 'Bearer ' + this.token) + .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); - this.users.deleteMultifactorProvider(data).then(function() { + this.users.deleteMultifactorProvider(data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -769,52 +697,50 @@ describe('UsersManager', function() { }); }); - describe('#updateUserMetadata', function() { - beforeEach(function() { + describe('#updateUserMetadata', () => { + beforeEach(function () { this.data = { id: 5, foo: 'bar', - test: 'data' + test: 'data', }; - this.request = nock(API_URL) - .patch('/users/' + this.data.id) - .reply(200, this.data); + this.request = nock(API_URL).patch(`/users/${this.data.id}`).reply(200, this.data); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.users.updateUserMetadata({ id: 5 }, {}, done.bind(null, null)); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.users .updateUserMetadata({ id: 5 }, {}) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should perform a PATCH request to /api/v2/users/5', function(done) { - var request = this.request; + it('should perform a PATCH request to /api/v2/users/5', function (done) { + const { request } = this; - this.users.updateUserMetadata({ id: 5 }, {}).then(function() { + this.users.updateUserMetadata({ id: 5 }, {}).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the metadata in the body of the request', function(done) { + it('should include the metadata in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/users/' + this.data.id, { - user_metadata: this.data + const request = nock(API_URL) + .patch(`/users/${this.data.id}`, { + user_metadata: this.data, }) .reply(200); this.users .updateUserMetadata({ id: 5 }, this.data) - .then(function() { + .then(() => { expect(request.isDone()).to.be.true; done(); @@ -822,14 +748,12 @@ describe('UsersManager', function() { .catch(done); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .patch('/users/' + this.data.id) - .reply(500); + nock(API_URL).patch(`/users/${this.data.id}`).reply(500); - this.users.updateUserMetadata({ id: this.data.id }, this.data).catch(function(err) { + this.users.updateUserMetadata({ id: this.data.id }, this.data).catch((err) => { expect(err).to.exist; done(); @@ -837,74 +761,68 @@ describe('UsersManager', function() { }); }); - describe('#logs', function() { - var data = { - id: 'user_id' + describe('#logs', () => { + const data = { + id: 'user_id', }; - var url = '/users/' + data.id + '/logs'; + const url = `/users/${data.id}/logs`; - beforeEach(function() { - this.request = nock(API_URL) - .get(url) - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).get(url).reply(200); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.users.logs(data, done.bind(null, null)); }); - it('should return a promise when no callback is given', function(done) { + it('should return a promise when no callback is given', function (done) { this.users.logs(data).then(done.bind(null, null)); }); - it('should perform a GET request to ' + url, function(done) { - var request = this.request; + it(`should perform a GET request to ${url}`, function (done) { + const { request } = this; - this.users.logs(data).then(function() { + this.users.logs(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get(url) - .reply(500); + nock(API_URL).get(url).reply(500); - this.users.logs(data).catch(function(err) { + this.users.logs(data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the authorization header', function(done) { + it('should include the token in the authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) + const request = nock(API_URL) .get(url) - .matchHeader('authorization', 'Bearer ' + this.token) + .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); - this.users.logs(data).then(function() { + this.users.logs(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the body of the response to the "then" handler', function(done) { + it('should pass the body of the response to the "then" handler', function (done) { nock.cleanAll(); - var response = [{ test: true }]; - var request = nock(API_URL) - .get(url) - .reply(200, response); + const response = [{ test: true }]; + nock(API_URL).get(url).reply(200, response); - this.users.logs(data).then(function(logs) { + this.users.logs(data).then((logs) => { expect(logs).to.be.an.instanceOf(Array); expect(logs.length).to.equal(response.length); @@ -915,22 +833,19 @@ describe('UsersManager', function() { }); }); - it('should pass the parameters in the query-string', function(done) { + it('should pass the parameters in the query-string', function (done) { nock.cleanAll(); - var params = { + const params = { page: 0, - per_page: 30 + per_page: 30, }; - var request = nock(API_URL) - .get(url) - .query(params) - .reply(200); + const request = nock(API_URL).get(url).query(params).reply(200); data.page = params.page; data.per_page = params.per_page; - this.users.logs(data).then(function() { + this.users.logs(data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -938,58 +853,54 @@ describe('UsersManager', function() { }); }); - describe('#getGuardianEnrollments', function() { - var data = { - id: 5 + describe('#getGuardianEnrollments', () => { + const data = { + id: 5, }; - beforeEach(function() { - this.request = nock(API_URL) - .get('/users/' + data.id + '/enrollments') - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).get(`/users/${data.id}/enrollments`).reply(200); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.users.getGuardianEnrollments(data, done.bind(null, null)); }); - it('should return a promise when no callback is given', function(done) { + it('should return a promise when no callback is given', function (done) { this.users.getGuardianEnrollments(data).then(done.bind(null, null)); }); - it('should perform a GET request to /api/v2/users/5/enrollments', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/users/5/enrollments', function (done) { + const { request } = this; - this.users.getGuardianEnrollments(data).then(function() { + this.users.getGuardianEnrollments(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/users/' + data.id + '/enrollments') - .reply(500); + nock(API_URL).get(`/users/${data.id}/enrollments`).reply(500); - this.users.getGuardianEnrollments(data).catch(function(err) { + this.users.getGuardianEnrollments(data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the authorization header', function(done) { + it('should include the token in the authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/users/' + data.id + '/enrollments') - .matchHeader('authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .get(`/users/${data.id}/enrollments`) + .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); - this.users.getGuardianEnrollments(data).then(function() { + this.users.getGuardianEnrollments(data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -997,70 +908,66 @@ describe('UsersManager', function() { }); }); - describe('#regenerateRecoveryCode', function() { - var data = { - id: 'USER_ID' + describe('#regenerateRecoveryCode', () => { + const data = { + id: 'USER_ID', }; - beforeEach(function() { - this.request = nock(API_URL) - .post('/users/' + data.id + '/recovery-code-regeneration') - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).post(`/users/${data.id}/recovery-code-regeneration`).reply(200); }); - it('should validate empty userId', function() { - var _this = this; - expect(function() { - _this.users.regenerateRecoveryCode(null, function() {}); + it('should validate empty userId', function () { + const _this = this; + expect(() => { + _this.users.regenerateRecoveryCode(null, () => {}); }).to.throw('The userId cannot be null or undefined'); }); - it('should accept a callback', function(done) { - this.users.regenerateRecoveryCode(data, function() { + it('should accept a callback', function (done) { + this.users.regenerateRecoveryCode(data, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.users .regenerateRecoveryCode(data) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/users/' + data.id + '/recovery-code-regeneration') - .reply(500); + nock(API_URL).post(`/users/${data.id}/recovery-code-regeneration`).reply(500); - this.users.regenerateRecoveryCode(data).catch(function(err) { + this.users.regenerateRecoveryCode(data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a POST request to /api/v2/users/:id/recovery-code-regeneration', function(done) { - var request = this.request; + it('should perform a POST request to /api/v2/users/:id/recovery-code-regeneration', function (done) { + const { request } = this; - this.users.regenerateRecoveryCode(data).then(function() { + this.users.regenerateRecoveryCode(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/users/' + data.id + '/recovery-code-regeneration') - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .post(`/users/${data.id}/recovery-code-regeneration`) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.users.regenerateRecoveryCode(data).then(function() { + this.users.regenerateRecoveryCode(data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -1068,70 +975,70 @@ describe('UsersManager', function() { }); }); - describe('#invalidateRememberBrowser', function() { - var data = { - id: 'USER_ID' + describe('#invalidateRememberBrowser', () => { + const data = { + id: 'USER_ID', }; - beforeEach(function() { + beforeEach(function () { this.request = nock(API_URL) - .post('/users/' + data.id + '/multifactor/actions/invalidate-remember-browser') + .post(`/users/${data.id}/multifactor/actions/invalidate-remember-browser`) .reply(204); }); - it('should validate empty userId', function() { - var _this = this; - expect(function() { - _this.users.invalidateRememberBrowser(null, function() {}); + it('should validate empty userId', function () { + const _this = this; + expect(() => { + _this.users.invalidateRememberBrowser(null, () => {}); }).to.throw('The userId cannot be null or undefined'); }); - it('should accept a callback', function(done) { - this.users.invalidateRememberBrowser(data, function() { + it('should accept a callback', function (done) { + this.users.invalidateRememberBrowser(data, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.users .invalidateRememberBrowser(data) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/users/' + data.id + '/multifactor/actions/invalidate-remember-browser') + nock(API_URL) + .post(`/users/${data.id}/multifactor/actions/invalidate-remember-browser`) .reply(500); - this.users.invalidateRememberBrowser(data).catch(function(err) { + this.users.invalidateRememberBrowser(data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a POST request to /api/v2/users/:id/multifactor/actions/invalidate-remember-browser', function(done) { - var request = this.request; + it('should perform a POST request to /api/v2/users/:id/multifactor/actions/invalidate-remember-browser', function (done) { + const { request } = this; - this.users.invalidateRememberBrowser(data).then(function() { + this.users.invalidateRememberBrowser(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/users/' + data.id + '/multifactor/actions/invalidate-remember-browser') - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .post(`/users/${data.id}/multifactor/actions/invalidate-remember-browser`) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.users.invalidateRememberBrowser(data).then(function() { + this.users.invalidateRememberBrowser(data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -1139,58 +1046,54 @@ describe('UsersManager', function() { }); }); - describe('#getRoles', function() { - var data = { - id: 'user_id' + describe('#getRoles', () => { + const data = { + id: 'user_id', }; - beforeEach(function() { - this.request = nock(API_URL) - .get('/users/' + data.id + '/roles') - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).get(`/users/${data.id}/roles`).reply(200); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.users.getRoles(data, done.bind(null, null)); }); - it('should return a promise when no callback is given', function(done) { + it('should return a promise when no callback is given', function (done) { this.users.getRoles(data).then(done.bind(null, null)); }); - it('should perform a GET request to /api/v2/users/user_id/roles', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/users/user_id/roles', function (done) { + const { request } = this; - this.users.getRoles(data).then(function() { + this.users.getRoles(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/users/' + data.id + '/roles') - .reply(500); + nock(API_URL).get(`/users/${data.id}/roles`).reply(500); - this.users.getRoles(data).catch(function(err) { + this.users.getRoles(data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the authorization header', function(done) { + it('should include the token in the authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/users/' + data.id + '/roles') - .matchHeader('authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .get(`/users/${data.id}/roles`) + .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); - this.users.getRoles(data).then(function() { + this.users.getRoles(data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -1198,92 +1101,86 @@ describe('UsersManager', function() { }); }); - describe('#assignRoles', function() { - beforeEach(function() { + describe('#assignRoles', () => { + beforeEach(function () { this.data = { - id: 'user_id' + id: 'user_id', }; this.body = { roles: ['role1', 'role2', 'role3'] }; - this.request = nock(API_URL) - .post('/users/' + this.data.id + '/roles') - .reply(200); + this.request = nock(API_URL).post(`/users/${this.data.id}/roles`).reply(200); }); - it('should validate empty user_id', function() { - var _this = this; - expect(function() { - _this.users.assignRoles({ id: null }, _this.body, function() {}); + it('should validate empty user_id', function () { + const _this = this; + expect(() => { + _this.users.assignRoles({ id: null }, _this.body, () => {}); }).to.throw('The user_id cannot be null or undefined'); }); - it('should validate non-string user_id', function() { - var _this = this; - expect(function() { - _this.users.assignRoles({ id: 127 }, _this.body, function() {}); + it('should validate non-string user_id', function () { + const _this = this; + expect(() => { + _this.users.assignRoles({ id: 127 }, _this.body, () => {}); }).to.throw('The user_id has to be a string'); }); - it('should accept a callback', function(done) { - this.users.assignRoles(this.data, {}, function() { + it('should accept a callback', function (done) { + this.users.assignRoles(this.data, {}, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.users .assignRoles(this.data, {}) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/users/' + this.data.id + '/roles') - .reply(500); + nock(API_URL).post(`/users/${this.data.id}/roles`).reply(500); - this.users.assignRoles(this.data, {}).catch(function(err) { + this.users.assignRoles(this.data, {}).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a POST request to /api/v2/users/user_id/roles', function(done) { - var request = this.request; + it('should perform a POST request to /api/v2/users/user_id/roles', function (done) { + const { request } = this; - this.users.assignRoles(this.data, {}).then(function() { + this.users.assignRoles(this.data, {}).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the data in the body of the request', function(done) { + it('should pass the data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/users/' + this.data.id + '/roles', this.body) - .reply(200); + const request = nock(API_URL).post(`/users/${this.data.id}/roles`, this.body).reply(200); - this.users.assignRoles(this.data, this.body).then(function() { + this.users.assignRoles(this.data, this.body).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/users/' + this.data.id + '/roles') - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .post(`/users/${this.data.id}/roles`) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.users.assignRoles(this.data, {}).then(function() { + this.users.assignRoles(this.data, {}).then(() => { expect(request.isDone()).to.be.true; done(); @@ -1291,92 +1188,86 @@ describe('UsersManager', function() { }); }); - describe('#removeRoles', function() { - beforeEach(function() { + describe('#removeRoles', () => { + beforeEach(function () { this.data = { - id: 'user_id' + id: 'user_id', }; this.body = { roles: ['role1', 'role2', 'role3'] }; - this.request = nock(API_URL) - .delete('/users/' + this.data.id + '/roles', {}) - .reply(200); + this.request = nock(API_URL).delete(`/users/${this.data.id}/roles`, {}).reply(200); }); - it('should validate empty user_id', function() { - var _this = this; - expect(function() { - _this.users.removeRoles({ id: null }, this.body, function() {}); + it('should validate empty user_id', function () { + const _this = this; + expect(function () { + _this.users.removeRoles({ id: null }, this.body, () => {}); }).to.throw('The user_id cannot be null or undefined'); }); - it('should validate non-string user_id', function() { - var _this = this; - expect(function() { - _this.users.removeRoles({ id: 123 }, _this.body, function() {}); + it('should validate non-string user_id', function () { + const _this = this; + expect(() => { + _this.users.removeRoles({ id: 123 }, _this.body, () => {}); }).to.throw('The user_id has to be a string'); }); - it('should accept a callback', function(done) { - this.users.removeRoles(this.data, {}, function() { + it('should accept a callback', function (done) { + this.users.removeRoles(this.data, {}, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.users .removeRoles(this.data, {}) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/users/' + this.data.id + '/roles') - .reply(500); + nock(API_URL).post(`/users/${this.data.id}/roles`).reply(500); - this.users.removeRoles(this.data, {}).catch(function(err) { + this.users.removeRoles(this.data, {}).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a DELETE request to /api/v2/users/user_id/roles', function(done) { - var request = this.request; + it('should perform a DELETE request to /api/v2/users/user_id/roles', function (done) { + const { request } = this; - this.users.removeRoles(this.data, {}).then(function() { + this.users.removeRoles(this.data, {}).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the data in the body of the request', function(done) { + it('should pass the data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete('/users/' + this.data.id + '/roles', this.body) - .reply(200); + const request = nock(API_URL).delete(`/users/${this.data.id}/roles`, this.body).reply(200); - this.users.removeRoles(this.data, this.body).then(function() { + this.users.removeRoles(this.data, this.body).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete('/users/' + this.data.id + '/roles') - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .delete(`/users/${this.data.id}/roles`) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.users.removeRoles(this.data, {}).then(function() { + this.users.removeRoles(this.data, {}).then(() => { expect(request.isDone()).to.be.true; done(); @@ -1384,58 +1275,54 @@ describe('UsersManager', function() { }); }); - describe('#getPermissions', function() { - var data = { - id: 'user_id' + describe('#getPermissions', () => { + const data = { + id: 'user_id', }; - beforeEach(function() { - this.request = nock(API_URL) - .get('/users/' + data.id + '/permissions') - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).get(`/users/${data.id}/permissions`).reply(200); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.users.getPermissions(data, done.bind(null, null)); }); - it('should return a promise when no callback is given', function(done) { + it('should return a promise when no callback is given', function (done) { this.users.getPermissions(data).then(done.bind(null, null)); }); - it('should perform a GET request to /api/v2/users/user_id/permissions', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/users/user_id/permissions', function (done) { + const { request } = this; - this.users.getPermissions(data).then(function() { + this.users.getPermissions(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/users/' + data.id + '/permissions') - .reply(500); + nock(API_URL).get(`/users/${data.id}/permissions`).reply(500); - this.users.getPermissions(data).catch(function(err) { + this.users.getPermissions(data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the authorization header', function(done) { + it('should include the token in the authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/users/' + data.id + '/permissions') - .matchHeader('authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .get(`/users/${data.id}/permissions`) + .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); - this.users.getPermissions(data).then(function() { + this.users.getPermissions(data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -1443,92 +1330,88 @@ describe('UsersManager', function() { }); }); - describe('#assignPermissions', function() { - beforeEach(function() { + describe('#assignPermissions', () => { + beforeEach(function () { this.data = { - id: 'user_id' + id: 'user_id', }; this.body = { permission_name: 'My Permission', resource_server_identifier: 'test123' }; - this.request = nock(API_URL) - .post('/users/' + this.data.id + '/permissions') - .reply(200); + this.request = nock(API_URL).post(`/users/${this.data.id}/permissions`).reply(200); }); - it('should validate empty user_id', function() { - var _this = this; - expect(function() { - _this.users.assignPermissions({ id: null }, this.body, function() {}); + it('should validate empty user_id', function () { + const _this = this; + expect(function () { + _this.users.assignPermissions({ id: null }, this.body, () => {}); }).to.throw('The user_id cannot be null or undefined'); }); - it('should validate non-string user_id', function() { - var _this = this; - expect(function() { - _this.users.assignPermissions({ id: 123 }, _this.body, function() {}); + it('should validate non-string user_id', function () { + const _this = this; + expect(() => { + _this.users.assignPermissions({ id: 123 }, _this.body, () => {}); }).to.throw('The user_id has to be a string'); }); - it('should accept a callback', function(done) { - this.users.assignPermissions(this.data, {}, function() { + it('should accept a callback', function (done) { + this.users.assignPermissions(this.data, {}, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.users .assignPermissions(this.data, {}) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/users/' + this.data.id + '/permissions') - .reply(500); + nock(API_URL).post(`/users/${this.data.id}/permissions`).reply(500); - this.users.assignPermissions(this.data, {}).catch(function(err) { + this.users.assignPermissions(this.data, {}).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a POST request to /api/v2/users/user_id/permissions', function(done) { - var request = this.request; + it('should perform a POST request to /api/v2/users/user_id/permissions', function (done) { + const { request } = this; - this.users.assignPermissions(this.data, {}).then(function() { + this.users.assignPermissions(this.data, {}).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the data in the body of the request', function(done) { + it('should pass the data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/users/' + this.data.id + '/permissions', this.body) + const request = nock(API_URL) + .post(`/users/${this.data.id}/permissions`, this.body) .reply(200); - this.users.assignPermissions(this.data, this.body).then(function() { + this.users.assignPermissions(this.data, this.body).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/users/' + this.data.id + '/permissions') - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .post(`/users/${this.data.id}/permissions`) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.users.assignPermissions(this.data, {}).then(function() { + this.users.assignPermissions(this.data, {}).then(() => { expect(request.isDone()).to.be.true; done(); @@ -1536,92 +1419,88 @@ describe('UsersManager', function() { }); }); - describe('#removePermissions', function() { - beforeEach(function() { + describe('#removePermissions', () => { + beforeEach(function () { this.data = { - id: 'user_id' + id: 'user_id', }; this.body = { permission_name: 'My Permission', resource_server_identifier: 'test123' }; - this.request = nock(API_URL) - .delete('/users/' + this.data.id + '/permissions', {}) - .reply(200); + this.request = nock(API_URL).delete(`/users/${this.data.id}/permissions`, {}).reply(200); }); - it('should validate empty user_id', function() { - var _this = this; - expect(function() { - _this.users.removePermissions({ id: null }, this.body, function() {}); + it('should validate empty user_id', function () { + const _this = this; + expect(function () { + _this.users.removePermissions({ id: null }, this.body, () => {}); }).to.throw('The user_id cannot be null or undefined'); }); - it('should validate non-string user_id', function() { - var _this = this; - expect(function() { - _this.users.removePermissions({ id: 123 }, _this.body, function() {}); + it('should validate non-string user_id', function () { + const _this = this; + expect(() => { + _this.users.removePermissions({ id: 123 }, _this.body, () => {}); }).to.throw('The user_id has to be a string'); }); - it('should accept a callback', function(done) { - this.users.removePermissions(this.data, {}, function() { + it('should accept a callback', function (done) { + this.users.removePermissions(this.data, {}, () => { done(); }); }); - it('should return a promise if no callback is given', function(done) { + it('should return a promise if no callback is given', function (done) { this.users .removePermissions(this.data, {}) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .post('/users/' + this.data.id + '/permissions') - .reply(500); + nock(API_URL).post(`/users/${this.data.id}/permissions`).reply(500); - this.users.removePermissions(this.data, {}).catch(function(err) { + this.users.removePermissions(this.data, {}).catch((err) => { expect(err).to.exist; done(); }); }); - it('should perform a DELETE request to /api/v2/users/user_id/permissions', function(done) { - var request = this.request; + it('should perform a DELETE request to /api/v2/users/user_id/permissions', function (done) { + const { request } = this; - this.users.removePermissions(this.data, {}).then(function() { + this.users.removePermissions(this.data, {}).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the data in the body of the request', function(done) { + it('should pass the data in the body of the request', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete('/users/' + this.data.id + '/permissions', this.body) + const request = nock(API_URL) + .delete(`/users/${this.data.id}/permissions`, this.body) .reply(200); - this.users.removePermissions(this.data, this.body).then(function() { + this.users.removePermissions(this.data, this.body).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function(done) { + it('should include the token in the Authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .delete('/users/' + this.data.id + '/permissions') - .matchHeader('Authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .delete(`/users/${this.data.id}/permissions`) + .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.users.removePermissions(this.data, {}).then(function() { + this.users.removePermissions(this.data, {}).then(() => { expect(request.isDone()).to.be.true; done(); @@ -1629,58 +1508,54 @@ describe('UsersManager', function() { }); }); - describe('#getUserOrganizations', function() { - var data = { - id: 'user_id' + describe('#getUserOrganizations', () => { + const data = { + id: 'user_id', }; - beforeEach(function() { - this.request = nock(API_URL) - .get('/users/' + data.id + '/organizations') - .reply(200); + beforeEach(function () { + this.request = nock(API_URL).get(`/users/${data.id}/organizations`).reply(200); }); - it('should accept a callback', function(done) { + it('should accept a callback', function (done) { this.users.getUserOrganizations(data, done.bind(null, null)); }); - it('should return a promise when no callback is given', function(done) { + it('should return a promise when no callback is given', function (done) { this.users.getUserOrganizations(data).then(done.bind(null, null)); }); - it('should perform a GET request to /api/v2/users/user_id/organizations', function(done) { - var request = this.request; + it('should perform a GET request to /api/v2/users/user_id/organizations', function (done) { + const { request } = this; - this.users.getUserOrganizations(data).then(function() { + this.users.getUserOrganizations(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function(done) { + it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/users/' + data.id + '/organizations') - .reply(500); + nock(API_URL).get(`/users/${data.id}/organizations`).reply(500); - this.users.getUserOrganizations(data).catch(function(err) { + this.users.getUserOrganizations(data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the authorization header', function(done) { + it('should include the token in the authorization header', function (done) { nock.cleanAll(); - var request = nock(API_URL) - .get('/users/' + data.id + '/organizations') - .matchHeader('authorization', 'Bearer ' + this.token) + const request = nock(API_URL) + .get(`/users/${data.id}/organizations`) + .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); - this.users.getUserOrganizations(data).then(function() { + this.users.getUserOrganizations(data).then(() => { expect(request.isDone()).to.be.true; done(); diff --git a/test/retry-rest-client.tests.js b/test/retry-rest-client.tests.js index 90b874ffc..01f4ee7ab 100644 --- a/test/retry-rest-client.tests.js +++ b/test/retry-rest-client.tests.js @@ -1,131 +1,123 @@ -var expect = require('chai').expect; -var sinon = require('sinon'); -var nock = require('nock'); +const { expect } = require('chai'); +const sinon = require('sinon'); +const nock = require('nock'); -var ArgumentError = require('rest-facade').ArgumentError; -var RestClient = require('rest-facade').Client; -var RetryRestClient = require('../src/RetryRestClient'); +const { ArgumentError } = require('rest-facade'); +const RestClient = require('rest-facade').Client; +const RetryRestClient = require('../src/RetryRestClient'); -var API_URL = 'https://tenant.auth0.com'; +const API_URL = 'https://tenant.auth0.com'; -describe('RetryRestClient', function() { - before(function() { +describe('RetryRestClient', () => { + before(function () { this.restClient = new RestClient(API_URL); }); - it('should raise an error when no RestClient is provided', function() { - expect(RetryRestClient).to.throw(ArgumentError, 'Must provide RestClient'); + it('should raise an error when no RestClient is provided', () => { + expect(() => { + new RetryRestClient(); + }).to.throw(ArgumentError, 'Must provide RestClient'); }); - it('should raise an error when enabled is not of type boolean', function() { - var options = { enabled: {} }; - var client = RetryRestClient.bind(null, {}, options); - expect(client).to.throw(ArgumentError, 'Must provide enabled boolean value'); + it('should raise an error when enabled is not of type boolean', () => { + const options = { enabled: {} }; + expect(() => { + new RetryRestClient({}, options); + }).to.throw(ArgumentError, 'Must provide enabled boolean value'); }); - it('should raise an error when maxRetries is negative', function() { - var options = { maxRetries: -1 }; - var client = RetryRestClient.bind(null, {}, options); - expect(client).to.throw(ArgumentError, 'Must provide maxRetries as a positive number'); + it('should raise an error when maxRetries is negative', () => { + const options = { maxRetries: -1 }; + expect(() => { + new RetryRestClient({}, options); + }).to.throw(ArgumentError, 'Must provide maxRetries as a positive number'); }); - describe('instance', function() { - var client = new RetryRestClient(new RestClient(API_URL)); - var methods = ['getAll', 'get', 'create', 'update', 'delete']; + describe('instance', () => { + const client = new RetryRestClient(new RestClient(API_URL)); + const methods = ['getAll', 'get', 'create', 'update', 'delete']; - methods.forEach(function(method) { - it('should have a ' + method + ' method', function() { + methods.forEach((method) => { + it(`should have a ${method} method`, () => { expect(client[method]).to.exist.to.be.an.instanceOf(Function); }); }); }); - it('should pass data to callback when provided', function(done) { - nock(API_URL) - .get('/') - .reply(200, { success: true }); + it('should pass data to callback when provided', function (done) { + nock(API_URL).get('/').reply(200, { success: true }); - var client = new RetryRestClient(this.restClient); - client.getAll(function(err, data) { + const client = new RetryRestClient(this.restClient); + client.getAll((err, data) => { expect(err).to.null; expect(data.success).to.be.true; done(); }); }); - it('should return promise for successful request when no callback is provided', function(done) { - nock(API_URL) - .get('/') - .reply(200, { success: true }); + it('should return promise for successful request when no callback is provided', function (done) { + nock(API_URL).get('/').reply(200, { success: true }); - var client = new RetryRestClient(this.restClient); - client.getAll().then(function(data) { + const client = new RetryRestClient(this.restClient); + client.getAll().then((data) => { expect(data.success).to.be.true; done(); }); }); - it('should pass err to callback when provided', function(done) { - nock(API_URL) - .get('/') - .reply(500); + it('should pass err to callback when provided', function (done) { + nock(API_URL).get('/').reply(500); - var client = new RetryRestClient(this.restClient); - client.getAll(function(err) { + const client = new RetryRestClient(this.restClient); + client.getAll((err) => { expect(err).to.not.null; expect(err.statusCode).to.be.equal(500); done(); }); }); - it('should return promise for failed request when no callback is provided', function(done) { - nock(API_URL) - .get('/') - .reply(500); + it('should return promise for failed request when no callback is provided', function (done) { + nock(API_URL).get('/').reply(500); - var client = new RetryRestClient(this.restClient); - client.getAll().catch(function(err) { + const client = new RetryRestClient(this.restClient); + client.getAll().catch((err) => { expect(err).to.not.null; expect(err.statusCode).to.be.equal(500); done(); }); }); - it('should retry once when an error is returned', function(done) { - var self = this; - var timesCalled = 0; - var restClientSpy = { - getAll: function() { + it('should retry once when an error is returned', function (done) { + const self = this; + let timesCalled = 0; + const restClientSpy = { + getAll(...args) { timesCalled += 1; - return self.restClient.getAll(arguments); - } + return self.restClient.getAll(args); + }, }; - nock(API_URL) - .get('/') - .reply(429, { success: false }) - .get('/') - .reply(200, { success: true }); + nock(API_URL).get('/').reply(429, { success: false }).get('/').reply(200, { success: true }); - var client = new RetryRestClient(restClientSpy); - client.getAll().then(function(data) { + const client = new RetryRestClient(restClientSpy); + client.getAll().then((data) => { expect(data.success).to.be.true; expect(timesCalled).to.be.equal(2); done(); }); }); - it('should try 4 times when request fails 3 times', function(done) { - var self = this; - var clock = sinon.useFakeTimers(); - var timesCalled = 0; - var restClientSpy = { - getAll: function() { + it('should try 4 times when request fails 3 times', function (done) { + const self = this; + const clock = sinon.useFakeTimers(); + let timesCalled = 0; + const restClientSpy = { + getAll(...args) { timesCalled += 1; - return self.restClient.getAll(arguments).finally(() => { + return self.restClient.getAll(...args).finally(() => { clock.runAllAsync(); }); - } + }, }; nock(API_URL) @@ -135,8 +127,8 @@ describe('RetryRestClient', function() { .get('/') .reply(200, { success: true }); - var client = new RetryRestClient(restClientSpy); - client.getAll().then(function(data) { + const client = new RetryRestClient(restClientSpy); + client.getAll().then((data) => { clock.restore(); expect(data.success).to.be.true; expect(timesCalled).to.be.equal(4); @@ -144,26 +136,23 @@ describe('RetryRestClient', function() { }); }); - it('should retry 2 times and fail when maxRetries is exceeded', function(done) { - var self = this; - var clock = sinon.useFakeTimers(); - var timesCalled = 0; - var restClientSpy = { - getAll: function() { + it('should retry 2 times and fail when maxRetries is exceeded', function (done) { + const self = this; + const clock = sinon.useFakeTimers(); + let timesCalled = 0; + const restClientSpy = { + getAll(...args) { timesCalled += 1; - return self.restClient.getAll(arguments).finally(() => { + return self.restClient.getAll(...args).finally(() => { clock.runAllAsync(); }); - } + }, }; - nock(API_URL) - .get('/') - .times(4) - .reply(429, { success: false }); + nock(API_URL).get('/').times(4).reply(429, { success: false }); - var client = new RetryRestClient(restClientSpy, { maxRetries: 3 }); - client.getAll().catch(function(err) { + const client = new RetryRestClient(restClientSpy, { maxRetries: 3 }); + client.getAll().catch((err) => { clock.restore(); expect(err).to.not.null; expect(timesCalled).to.be.equal(4); // Initial call + 3 retires. @@ -171,33 +160,31 @@ describe('RetryRestClient', function() { }); }); - it('should not retry when status code is not 429', function(done) { - nock(API_URL) - .get('/') - .reply(500); + it('should not retry when status code is not 429', function (done) { + nock(API_URL).get('/').reply(500); - var client = new RetryRestClient(this.restClient); - client.getAll().catch(function(err) { + const client = new RetryRestClient(this.restClient); + client.getAll().catch((err) => { expect(err).to.not.null; expect(err.statusCode).to.be.equal(500); done(); }); }); - it('should delay the retry using exponential backoff and succeed after retry', function(done) { - var self = this; - var clock = sinon.useFakeTimers(); - var backoffs = []; - var prev = 0; - var restClientSpy = { - getAll: function() { - var now = new Date().getTime(); + it('should delay the retry using exponential backoff and succeed after retry', function (done) { + const self = this; + const clock = sinon.useFakeTimers(); + const backoffs = []; + let prev = 0; + const restClientSpy = { + getAll(...args) { + const now = new Date().getTime(); backoffs.push(now - prev); prev = now; - return self.restClient.getAll(arguments).finally(() => { + return self.restClient.getAll(...args).finally(() => { clock.runAllAsync(); }); - } + }, }; nock(API_URL) @@ -207,41 +194,39 @@ describe('RetryRestClient', function() { .get('/') .reply(200, { success: true }); - var client = new RetryRestClient(restClientSpy, { maxRetries: 10 }); + const client = new RetryRestClient(restClientSpy, { maxRetries: 10 }); - client.getAll().then(function(data) { + client.getAll().then((data) => { clock.restore(); expect(data.success).to.be.true; expect(backoffs.length).to.be.equal(10); expect(backoffs.shift()).to.be.equal(0, 'first request should happen immediately'); - for (var i = 0; i < backoffs.length; i++) { + for (let i = 0; i < backoffs.length; i++) { expect(backoffs[i] / 1000).to.be.within( Math.pow(2, i), 2 * Math.pow(2, i), - 'attempt ' + (i + 1) + ' in secs' + `attempt ${i + 1} in secs` ); } done(); }); }); - it('should not retry when retry functionality is disabled', function(done) { - var self = this; - var timesCalled = 0; - var restClientSpy = { - getAll: function() { + it('should not retry when retry functionality is disabled', function (done) { + const self = this; + let timesCalled = 0; + const restClientSpy = { + getAll(...args) { timesCalled += 1; - return self.restClient.getAll(arguments); - } + return self.restClient.getAll(...args); + }, }; - nock(API_URL) - .get('/') - .reply(429, { success: false }); + nock(API_URL).get('/').reply(429, { success: false }); - var client = new RetryRestClient(restClientSpy, { enabled: false }); - client.getAll().catch(function(err) { + const client = new RetryRestClient(restClientSpy, { enabled: false }); + client.getAll().catch((err) => { expect(err).to.not.null; expect(err.statusCode).to.be.equal(429); expect(timesCalled).to.be.equal(1); @@ -249,64 +234,58 @@ describe('RetryRestClient', function() { }); }); - it('should remove callback from arguments object if data is passed', function(done) { - var self = this; - var restClientSpy = { - create: function() { + it('should remove callback from arguments object if data is passed', (done) => { + const restClientSpy = { + create() { expect(arguments.length).to.be.equal(1); done(); return Promise.resolve(); - } + }, }; - var client = new RetryRestClient(restClientSpy, { enabled: false }); - client.create({ data: 'foobar' }, function() {}); + const client = new RetryRestClient(restClientSpy, { enabled: false }); + client.create({ data: 'foobar' }, () => {}); }); - it('should remove callback from arguments object if urlParams and data is passed', function(done) { - var self = this; - var restClientSpy = { - create: function() { + it('should remove callback from arguments object if urlParams and data is passed', (done) => { + const restClientSpy = { + create() { expect(arguments.length).to.be.equal(2); done(); return Promise.resolve(); - } + }, }; - var client = new RetryRestClient(restClientSpy, { enabled: false }); - var urlParams = { id: '123' }; - var data = { data: 'foobar' }; - client.create('/:id', data, function() {}); + const client = new RetryRestClient(restClientSpy, { enabled: false }); + const data = { data: 'foobar' }; + client.create('/:id', data, () => {}); }); - it('should not remove data object when no callback is passed', function(done) { - var self = this; - var restClientSpy = { - create: function() { + it('should not remove data object when no callback is passed', (done) => { + const restClientSpy = { + create() { expect(arguments.length).to.be.equal(1); done(); return Promise.resolve(); - } + }, }; - var client = new RetryRestClient(restClientSpy, { enabled: false }); - var data = { data: 'foobar' }; + const client = new RetryRestClient(restClientSpy, { enabled: false }); + const data = { data: 'foobar' }; client.create(data); }); - it('should not remove data object when urlParams is passed and no callback is passed', function(done) { - var self = this; - var restClientSpy = { - create: function() { + it('should not remove data object when urlParams is passed and no callback is passed', (done) => { + const restClientSpy = { + create() { expect(arguments.length).to.be.equal(2); done(); return Promise.resolve(); - } + }, }; - var client = new RetryRestClient(restClientSpy, { enabled: false }); - var urlParams = { id: '123' }; - var data = { data: 'foobar' }; + const client = new RetryRestClient(restClientSpy, { enabled: false }); + const data = { data: 'foobar' }; client.create('/:id', data); }); }); diff --git a/test/utils.tests.js b/test/utils.tests.js index 5fcbaf17f..c733653a9 100644 --- a/test/utils.tests.js +++ b/test/utils.tests.js @@ -1,15 +1,15 @@ -var expect = require('chai').expect; -var utils = require('../src/utils.js'); +const { expect } = require('chai'); +const utils = require('../src/utils.js'); -describe('Utils', function() { - describe('client info', function() { - it('should generate default telemetry value', function() { - var pkgVersion = require('../package.json').version; - var nodeVersion = process.version.replace('v', ''); +describe('Utils', () => { + describe('client info', () => { + it('should generate default telemetry value', () => { + const pkgVersion = require('../package.json').version; + const nodeVersion = process.version.replace('v', ''); expect(utils.generateClientInfo()).to.deep.equal({ name: 'node-auth0', version: pkgVersion, - env: { node: nodeVersion } + env: { node: nodeVersion }, }); }); }); diff --git a/test/utils/ensureMethod.js b/test/utils/ensureMethod.js index 1efd07cec..56ecc6c4a 100644 --- a/test/utils/ensureMethod.js +++ b/test/utils/ensureMethod.js @@ -1,7 +1,7 @@ -var expect = require('chai').expect; +const { expect } = require('chai'); -module.exports = function(obj, name) { - return function() { +module.exports = function (obj, name) { + return function () { expect(obj[name]).to.exist.to.be.an.instanceOf(Function); }; }; diff --git a/test/utils/ensureProperty.js b/test/utils/ensureProperty.js index bfdde1474..e7b8b2309 100644 --- a/test/utils/ensureProperty.js +++ b/test/utils/ensureProperty.js @@ -1,7 +1,7 @@ -var expect = require('chai').expect; +const { expect } = require('chai'); -module.exports = function(obj, name, cls) { - return function() { +module.exports = function (obj, name, cls) { + return function () { expect(obj[name]).to.exist.to.be.an.instanceOf(cls); }; }; diff --git a/test/utils/extractParts.js b/test/utils/extractParts.js index 2a09fe95f..0ad320016 100644 --- a/test/utils/extractParts.js +++ b/test/utils/extractParts.js @@ -1,15 +1,13 @@ -module.exports = function(body, boundary) { - var partRegexp = new RegExp(boundary + '[-]{2}|' + boundary, 'g'); - var parts = {}; - var name; - var value; +module.exports = function (body, boundary) { + const partRegexp = new RegExp(`${boundary}[-]{2}|${boundary}`, 'g'); + const parts = {}; - body.split(partRegexp).forEach(function(part) { + body.split(partRegexp).forEach((part) => { // Ignore empty strings in the array. if (part.trim().length === 0) return; - name = part.match(/name="([^"]*)"/)[1]; - value = part.split('"' + name + '"')[1]; + const [, name] = part.match(/name="([^"]*)"/); + const [, value] = part.split(`"${name}"`); parts[name] = value.trim(); }); diff --git a/test/utils/index.js b/test/utils/index.js index 763766fc2..6882fef14 100644 --- a/test/utils/index.js +++ b/test/utils/index.js @@ -1,5 +1,5 @@ module.exports = { extractParts: require('./extractParts'), ensureProperty: require('./ensureProperty'), - ensureMethod: require('./ensureMethod') + ensureMethod: require('./ensureMethod'), }; diff --git a/webpack.config.js b/webpack.config.js index 2f71c79fe..7bf56604b 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -1,26 +1,26 @@ -var Webpack = require('webpack'); -var pkg = require('./package.json'); +const Webpack = require('webpack'); +const pkg = require('./package.json'); -var StringReplacePlugin = require('string-replace-webpack-plugin'); +const StringReplacePlugin = require('string-replace-webpack-plugin'); module.exports = { entry: './src/index.js', output: { path: './build', - filename: pkg.name + '-' + pkg.version + '.min.js', + filename: `${pkg.name}-${pkg.version}.min.js`, library: 'Auth0', - libraryTarget: 'umd' + libraryTarget: 'umd', }, node: { Buffer: true, process: true, - url: true + url: true, }, module: { loaders: [ { test: /\.json$/, - loader: 'json' + loader: 'json', }, { test: /\.js$/, @@ -29,27 +29,25 @@ module.exports = { { // Remove User-Agent for browser version pattern: /'User-Agent': 'node\.js/gim, - replacement: function(match, p1, offset, string) { - return "// 'User-Agent': 'node.js"; - }.bind(this) - } - ] - }) - } - ] + replacement: () => "// 'User-Agent': 'node.js", + }, + ], + }), + }, + ], }, plugins: [ new StringReplacePlugin(), new Webpack.optimize.DedupePlugin(), new Webpack.optimize.UglifyJsPlugin({ compress: { - warnings: false - } - }) + warnings: false, + }, + }), ], resolve: { modulesDirectories: ['node_modules'], root: __dirname, - alias: {} - } + alias: {}, + }, }; diff --git a/yarn.lock b/yarn.lock index 5e3120363..de1749edd 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2,6 +2,13 @@ # yarn lockfile v1 +"@babel/code-frame@7.12.11": + version "7.12.11" + resolved "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.12.11.tgz" + integrity sha512-Zt1yodBx1UcyiePMSkWnU4hPqhwq7hGi2nFL1LeA3EUl+q2LQx16MISgJ0+z7dnmgvP9QtIleuETGOiOH1RcIw== + dependencies: + "@babel/highlight" "^7.10.4" + "@babel/code-frame@^7.0.0", "@babel/code-frame@^7.10.4": version "7.10.4" resolved "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.10.4.tgz" @@ -93,32 +100,62 @@ lodash "^4.17.19" to-fast-properties "^2.0.0" -"@sinonjs/commons@^1", "@sinonjs/commons@^1.6.0", "@sinonjs/commons@^1.7.0", "@sinonjs/commons@^1.8.1": - version "1.8.1" - resolved "https://registry.npmjs.org/@sinonjs/commons/-/commons-1.8.1.tgz" - integrity sha512-892K+kWUUi3cl+LlqEWIDrhvLgdL79tECi8JZUyq6IviKy/DNhuzCRlbHUjxK89f4ypPMMaFnFuR9Ie6DoIMsw== +"@es-joy/jsdoccomment@0.10.8": + version "0.10.8" + resolved "https://registry.yarnpkg.com/@es-joy/jsdoccomment/-/jsdoccomment-0.10.8.tgz#b3152887e25246410ed4ea569a55926ec13b2b05" + integrity sha512-3P1JiGL4xaR9PoTKUHa2N/LKwa2/eUdRqGwijMWWgBqbFEqJUVpmaOi2TcjcemrsRMgFLBzQCK4ToPhrSVDiFQ== dependencies: - type-detect "4.0.8" + comment-parser "1.2.4" + esquery "^1.4.0" + jsdoc-type-pratt-parser "1.1.1" -"@sinonjs/fake-timers@^6.0.0", "@sinonjs/fake-timers@^6.0.1": - version "6.0.1" - resolved "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-6.0.1.tgz" - integrity sha512-MZPUxrmFubI36XS1DI3qmI0YdN1gks62JtFZvxR67ljjSNCeK6U08Zx4msEWOXuofgqUt6zPHSi1H9fbjR/NRA== +"@eslint/eslintrc@^0.4.3": + version "0.4.3" + resolved "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-0.4.3.tgz" + integrity sha512-J6KFFz5QCYUJq3pf0mjEcCJVERbzv71PUIDczuh9JkwGEzced6CO5ADLHB1rbf/+oPBtoPfMYNOpGDzCANlbXw== dependencies: - "@sinonjs/commons" "^1.7.0" + ajv "^6.12.4" + debug "^4.1.1" + espree "^7.3.0" + globals "^13.9.0" + ignore "^4.0.6" + import-fresh "^3.2.1" + js-yaml "^3.13.1" + minimatch "^3.0.4" + strip-json-comments "^3.1.1" -"@sinonjs/formatio@^5.0.1": - version "5.0.1" - resolved "https://registry.npmjs.org/@sinonjs/formatio/-/formatio-5.0.1.tgz" - integrity sha512-KaiQ5pBf1MpS09MuA0kp6KBQt2JUOQycqVG1NZXvzeaXe5LGFqAKueIS0bw4w0P9r7KuBSVdUk5QjXsUdu2CxQ== +"@humanwhocodes/config-array@^0.5.0": + version "0.5.0" + resolved "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.5.0.tgz" + integrity sha512-FagtKFz74XrTl7y6HCzQpwDfXP0yhxe9lHLD1UZxjvZIcbyRz8zTFF/yYNfSfzU414eDwZ1SrO0Qvtyf+wFMQg== + dependencies: + "@humanwhocodes/object-schema" "^1.2.0" + debug "^4.1.1" + minimatch "^3.0.4" + +"@humanwhocodes/object-schema@^1.2.0": + version "1.2.0" + resolved "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-1.2.0.tgz" + integrity sha512-wdppn25U8z/2yiaT6YGquE6X8sSv7hNMWSXYSSU1jGv/yd6XqjXgTDJ8KP4NgjTXfJ3GbRjeeb8RTV7a/VpM+w== + +"@sinonjs/commons@^1.6.0", "@sinonjs/commons@^1.7.0", "@sinonjs/commons@^1.8.3": + version "1.8.3" + resolved "https://registry.npmjs.org/@sinonjs/commons/-/commons-1.8.3.tgz" + integrity sha512-xkNcLAn/wZaX14RPlwizcKicDk9G3F8m2nU3L7Ukm5zBgTwiT0wsoFAHx9Jq56fJA1z/7uKGtCRu16sOUCLIHQ== + dependencies: + type-detect "4.0.8" + +"@sinonjs/fake-timers@^7.0.4", "@sinonjs/fake-timers@^7.1.2": + version "7.1.2" + resolved "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-7.1.2.tgz" + integrity sha512-iQADsW4LBMISqZ6Ci1dupJL9pprqwcVFTcOsEmQOEhW+KLCVn/Y4Jrvg2k19fIHCp+iFprriYPTdRcQR8NbUPg== dependencies: - "@sinonjs/commons" "^1" - "@sinonjs/samsam" "^5.0.2" + "@sinonjs/commons" "^1.7.0" -"@sinonjs/samsam@^5.0.2", "@sinonjs/samsam@^5.2.0": - version "5.3.0" - resolved "https://registry.npmjs.org/@sinonjs/samsam/-/samsam-5.3.0.tgz" - integrity sha512-hXpcfx3aq+ETVBwPlRFICld5EnrkexXuXDwqUNhDdr5L8VjvMeSRwyOa0qL7XFmR+jVWR4rUZtnxlG7RX72sBg== +"@sinonjs/samsam@^6.0.2": + version "6.0.2" + resolved "https://registry.npmjs.org/@sinonjs/samsam/-/samsam-6.0.2.tgz" + integrity sha512-jxPRPp9n93ci7b8hMfJOFDPRLFYadN6FSpeROFTR4UNF4i5b+EK6m4QXPO46BDhFgRy1JuS87zAnFOzCUwMJcQ== dependencies: "@sinonjs/commons" "^1.6.0" lodash.get "^4.4.2" @@ -216,6 +253,11 @@ "@types/mime" "^1" "@types/node" "*" +"@ungap/promise-all-settled@1.1.2": + version "1.1.2" + resolved "https://registry.yarnpkg.com/@ungap/promise-all-settled/-/promise-all-settled-1.1.2.tgz#aa58042711d6e3275dd37dc597e5d31e8c290a44" + integrity sha512-sL/cEvJWAnClXw0wHk85/2L0G6Sj8UB0Ctc1TEMbKSsmpRosqhwj9gWgFRZSrBr2f9tiXISwNhCPmlfqUqyb9Q== + "@webassemblyjs/ast@1.9.0": version "1.9.0" resolved "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.9.0.tgz" @@ -371,11 +413,21 @@ resolved "https://registry.npmjs.org/@xtuc/long/-/long-4.2.2.tgz" integrity sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ== +acorn-jsx@^5.3.1: + version "5.3.2" + resolved "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz" + integrity sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ== + acorn@^6.4.1: version "6.4.2" resolved "https://registry.npmjs.org/acorn/-/acorn-6.4.2.tgz" integrity sha512-XtGIhXwF8YM8bJhGxG5kXgjkEuNGLTkoYqVE+KMR+aspr4KGYmKYg7yUe3KghyQ9yheNwLnjmzh/7+gfDBmHCQ== +acorn@^7.4.0: + version "7.4.1" + resolved "https://registry.npmjs.org/acorn/-/acorn-7.4.1.tgz" + integrity sha512-nQyp0o1/mNdbTO1PO6kHkwSrmgZ0MT/jCCpNiwbUjGoRN4dlBhqJtoQuCnEOKzgTVwg0ZWiCoQy6SxMebQVh8A== + agent-base@5: version "5.1.1" resolved "https://registry.npmjs.org/agent-base/-/agent-base-5.1.1.tgz" @@ -398,7 +450,7 @@ ajv-keywords@^3.1.0, ajv-keywords@^3.4.1: resolved "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-3.5.2.tgz" integrity sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ== -ajv@^6.1.0, ajv@^6.10.2: +ajv@^6.1.0, ajv@^6.10.0, ajv@^6.10.2, ajv@^6.12.4: version "6.12.6" resolved "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz" integrity sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g== @@ -408,15 +460,25 @@ ajv@^6.1.0, ajv@^6.10.2: json-schema-traverse "^0.4.1" uri-js "^4.2.2" +ajv@^8.0.1: + version "8.6.3" + resolved "https://registry.npmjs.org/ajv/-/ajv-8.6.3.tgz" + integrity sha512-SMJOdDP6LqTkD0Uq8qLi+gMwSt0imXLSV080qFVwJCpH9U6Mb+SUGHAXM0KNbcBPguytWyvFxcHgMLe2D2XSpw== + dependencies: + fast-deep-equal "^3.1.1" + json-schema-traverse "^1.0.0" + require-from-string "^2.0.2" + uri-js "^4.2.2" + amdefine@>=0.0.4: version "1.0.1" resolved "https://registry.npmjs.org/amdefine/-/amdefine-1.0.1.tgz" integrity sha1-SlKCrBZHKek2Gbz9OtFR+BfOkfU= -ansi-colors@3.2.3: - version "3.2.3" - resolved "https://registry.npmjs.org/ansi-colors/-/ansi-colors-3.2.3.tgz" - integrity sha512-LEHHyuhlPY3TmuUYMh2oz89lTShfvgbmzaBcxve9t/9Wuy7Dwf4yoAKcND7KFT1HAQfqZ12qtc+DUrBMeKF9nw== +ansi-colors@4.1.1, ansi-colors@^4.1.1: + version "4.1.1" + resolved "https://registry.npmjs.org/ansi-colors/-/ansi-colors-4.1.1.tgz" + integrity sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA== ansi-regex@^3.0.0: version "3.0.0" @@ -428,6 +490,11 @@ ansi-regex@^4.1.0: resolved "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz" integrity sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg== +ansi-regex@^5.0.1: + version "5.0.1" + resolved "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz" + integrity sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ== + ansi-styles@^3.2.0, ansi-styles@^3.2.1: version "3.2.1" resolved "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz" @@ -435,6 +502,13 @@ ansi-styles@^3.2.0, ansi-styles@^3.2.1: dependencies: color-convert "^1.9.0" +ansi-styles@^4.0.0, ansi-styles@^4.1.0: + version "4.3.0" + resolved "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz" + integrity sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg== + dependencies: + color-convert "^2.0.1" + anymatch@^2.0.0: version "2.0.0" resolved "https://registry.npmjs.org/anymatch/-/anymatch-2.0.0.tgz" @@ -451,6 +525,14 @@ anymatch@~3.1.1: normalize-path "^3.0.0" picomatch "^2.0.4" +anymatch@~3.1.2: + version "3.1.2" + resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-3.1.2.tgz#c0557c096af32f106198f4f4e2a383537e378716" + integrity sha512-P43ePfOAIupkguHUycrc4qJ9kz8ZiuOUijaETwX7THt0Y/GNK7v0aa8rY816xWjZ7rJdA5XdMcpVFTKMq+RvWg== + dependencies: + normalize-path "^3.0.0" + picomatch "^2.0.4" + append-transform@^1.0.0: version "1.0.0" resolved "https://registry.npmjs.org/append-transform/-/append-transform-1.0.0.tgz" @@ -475,6 +557,11 @@ argparse@^1.0.7: dependencies: sprintf-js "~1.0.2" +argparse@^2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/argparse/-/argparse-2.0.1.tgz#246f50f3ca78a3240f6c997e8a9bd1eac49e4b38" + integrity sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q== + argv@0.0.2: version "0.0.2" resolved "https://registry.npmjs.org/argv/-/argv-0.0.2.tgz" @@ -557,6 +644,11 @@ ast-types@^0.13.2: dependencies: tslib "^2.0.1" +astral-regex@^2.0.0: + version "2.0.0" + resolved "https://registry.npmjs.org/astral-regex/-/astral-regex-2.0.0.tgz" + integrity sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ== + async-each@^1.0.1: version "1.0.3" resolved "https://registry.npmjs.org/async-each/-/async-each-1.0.3.tgz" @@ -586,7 +678,7 @@ axios@^0.21.1: axios@^0.21.4: version "0.21.4" - resolved "https://registry.yarnpkg.com/axios/-/axios-0.21.4.tgz#c67b90dc0568e5c1cf2b0b858c43ba28e2eda575" + resolved "https://registry.npmjs.org/axios/-/axios-0.21.4.tgz" integrity sha512-ut5vewkiu8jjGBdqpM44XxjuCjq9LAKeHVmoVfHVzy8eHgxxq8SbAVQNovDA8mVi05kP0Ea/n/UzcSHcTJQfNg== dependencies: follow-redirects "^1.14.0" @@ -636,7 +728,7 @@ binary-extensions@^2.0.0: bindings@^1.5.0: version "1.5.0" - resolved "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz" + resolved "https://registry.yarnpkg.com/bindings/-/bindings-1.5.0.tgz#10353c9e945334bc0511a6d90b38fbc7c9c504df" integrity sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ== dependencies: file-uri-to-path "1.0.0" @@ -873,6 +965,11 @@ callsites@^2.0.0: resolved "https://registry.npmjs.org/callsites/-/callsites-2.0.0.tgz" integrity sha1-BuuE8A7qQT2oav/vrL/7Ngk7PFA= +callsites@^3.0.0: + version "3.1.0" + resolved "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz" + integrity sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ== + camel-case@^1.1.1: version "1.2.2" resolved "https://registry.npmjs.org/camel-case/-/camel-case-1.2.2.tgz" @@ -886,6 +983,11 @@ camelcase@^5.0.0: resolved "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz" integrity sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg== +camelcase@^6.0.0: + version "6.2.0" + resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-6.2.0.tgz#924af881c9d525ac9d87f40d964e5cea982a1809" + integrity sha512-c7wVvbw3f37nuobQNtgsgG9POC9qMbNuMQmTCqZv23b6MIz0fcYpBiOlv9gEN/hdLdnZTDQhg6e9Dq5M1vKvfg== + catharsis@^0.9.0: version "0.9.0" resolved "https://registry.npmjs.org/catharsis/-/catharsis-0.9.0.tgz" @@ -905,7 +1007,7 @@ chai@^4.1.2, chai@^4.2.0: pathval "^1.1.0" type-detect "^4.0.5" -chalk@^2.0.0, chalk@^2.0.1, chalk@^2.3.0, chalk@^2.4.2: +chalk@^2.0.0, chalk@^2.3.0, chalk@^2.4.2: version "2.4.2" resolved "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz" integrity sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ== @@ -914,6 +1016,14 @@ chalk@^2.0.0, chalk@^2.0.1, chalk@^2.3.0, chalk@^2.4.2: escape-string-regexp "^1.0.5" supports-color "^5.3.0" +chalk@^4.0.0, chalk@^4.1.0: + version "4.1.2" + resolved "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz" + integrity sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA== + dependencies: + ansi-styles "^4.1.0" + supports-color "^7.1.0" + change-case@^2.3.0: version "2.3.1" resolved "https://registry.npmjs.org/change-case/-/change-case-2.3.1.tgz" @@ -946,6 +1056,21 @@ check-error@^1.0.2: resolved "https://registry.npmjs.org/check-error/-/check-error-1.0.2.tgz" integrity sha1-V00xLt2Iu13YkS6Sht1sCu1KrII= +chokidar@3.5.2: + version "3.5.2" + resolved "https://registry.yarnpkg.com/chokidar/-/chokidar-3.5.2.tgz#dba3976fcadb016f66fd365021d91600d01c1e75" + integrity sha512-ekGhOnNVPgT77r4K/U3GDhu+FQ2S8TnK/s2KbIGXi0SZWuwkZ2QNyfWdZW+TVfn84DpEP7rLeCt2UI6bJ8GwbQ== + dependencies: + anymatch "~3.1.2" + braces "~3.0.2" + glob-parent "~5.1.2" + is-binary-path "~2.1.0" + is-glob "~4.0.1" + normalize-path "~3.0.0" + readdirp "~3.6.0" + optionalDependencies: + fsevents "~2.3.2" + chokidar@^2.1.8: version "2.1.8" resolved "https://registry.npmjs.org/chokidar/-/chokidar-2.1.8.tgz" @@ -1024,6 +1149,15 @@ cliui@^5.0.0: strip-ansi "^5.2.0" wrap-ansi "^5.1.0" +cliui@^7.0.2: + version "7.0.4" + resolved "https://registry.yarnpkg.com/cliui/-/cliui-7.0.4.tgz#a0265ee655476fc807aea9df3df8df7783808b4f" + integrity sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ== + dependencies: + string-width "^4.2.0" + strip-ansi "^6.0.0" + wrap-ansi "^7.0.0" + codecov@^3.7.2: version "3.8.1" resolved "https://registry.npmjs.org/codecov/-/codecov-3.8.1.tgz" @@ -1050,11 +1184,23 @@ color-convert@^1.9.0: dependencies: color-name "1.1.3" +color-convert@^2.0.1: + version "2.0.1" + resolved "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz" + integrity sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ== + dependencies: + color-name "~1.1.4" + color-name@1.1.3: version "1.1.3" resolved "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz" integrity sha1-p9BVi9icQveV3UIyj3QIMcpTvCU= +color-name@~1.1.4: + version "1.1.4" + resolved "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz" + integrity sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA== + combined-stream@^1.0.8: version "1.0.8" resolved "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz" @@ -1067,6 +1213,11 @@ commander@^2.20.0: resolved "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz" integrity sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ== +comment-parser@1.2.4: + version "1.2.4" + resolved "https://registry.yarnpkg.com/comment-parser/-/comment-parser-1.2.4.tgz#489f3ee55dfd184a6e4bffb31baba284453cb760" + integrity sha512-pm0b+qv+CkWNriSTMsfnjChF9kH0kxz55y44Wo5le9qLxMj5xDQAaEd9ZN1ovSuk9CsrncWaFwgpOMg7ClJwkw== + commondir@^1.0.1: version "1.0.1" resolved "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz" @@ -1231,6 +1382,15 @@ cross-spawn@^6.0.0, cross-spawn@^6.0.5: shebang-command "^1.2.0" which "^1.2.9" +cross-spawn@^7.0.2: + version "7.0.3" + resolved "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz" + integrity sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w== + dependencies: + path-key "^3.1.0" + shebang-command "^2.0.0" + which "^2.0.1" + crypt@0.0.2: version "0.0.2" resolved "https://registry.npmjs.org/crypt/-/crypt-0.0.2.tgz" @@ -1277,13 +1437,6 @@ data-uri-to-buffer@3: resolved "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-3.0.1.tgz" integrity sha512-WboRycPNsVw3B3TL559F7kuBUM4d8CgMEvk6xEJlOp7OBPjt6G7z8WMWlD2rOFZLk6OYfFIUGsCOWzcQH9K2og== -debug@3.2.6: - version "3.2.6" - resolved "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz" - integrity sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ== - dependencies: - ms "^2.1.1" - debug@4, debug@^4.1.0, debug@^4.1.1: version "4.3.1" resolved "https://registry.npmjs.org/debug/-/debug-4.3.1.tgz" @@ -1291,6 +1444,13 @@ debug@4, debug@^4.1.0, debug@^4.1.1: dependencies: ms "2.1.2" +debug@4.3.2, debug@^4.0.1, debug@^4.3.2: + version "4.3.2" + resolved "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz" + integrity sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw== + dependencies: + ms "2.1.2" + debug@^2.2.0, debug@^2.3.3: version "2.6.9" resolved "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz" @@ -1298,18 +1458,16 @@ debug@^2.2.0, debug@^2.3.3: dependencies: ms "2.0.0" -debug@^4.3.2: - version "4.3.2" - resolved "https://registry.yarnpkg.com/debug/-/debug-4.3.2.tgz#f0a49c18ac8779e31d4a0c6029dfb76873c7428b" - integrity sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw== - dependencies: - ms "2.1.2" - decamelize@^1.2.0: version "1.2.0" resolved "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz" integrity sha1-9lNNFRSCabIDUue+4m9QH5oZEpA= +decamelize@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/decamelize/-/decamelize-4.0.0.tgz#aa472d7bf660eb15f3494efd531cab7f2a709837" + integrity sha512-9iE1PgSik9HeIIw2JO94IidnE3eBoQrFJ3w7sFuzSX4DpmZ3v5sZpUiV5Swcf6mQEF+Y0ru8Neo+p+nyh2J+hQ== + decode-uri-component@^0.2.0: version "0.2.0" resolved "https://registry.npmjs.org/decode-uri-component/-/decode-uri-component-0.2.0.tgz" @@ -1334,6 +1492,11 @@ deep-equal@^1.0.0: object-keys "^1.1.1" regexp.prototype.flags "^1.2.0" +deep-is@^0.1.3: + version "0.1.4" + resolved "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz" + integrity sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ== + deep-is@~0.1.3: version "0.1.3" resolved "https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz" @@ -1351,7 +1514,7 @@ default-require-extensions@^2.0.0: dependencies: strip-bom "^3.0.0" -define-properties@^1.1.2, define-properties@^1.1.3: +define-properties@^1.1.3: version "1.1.3" resolved "https://registry.npmjs.org/define-properties/-/define-properties-1.1.3.tgz" integrity sha512-3MqfYKj2lLzdMSf8ZIZE/V+Zuy+BgD6f164e8K2w7dgnpKArBDerGYpM46IYYcjnkdPNMjPk9A6VFB8+3SKlXQ== @@ -1382,7 +1545,7 @@ define-property@^2.0.2: degenerator@^3.0.1: version "3.0.1" - resolved "https://registry.yarnpkg.com/degenerator/-/degenerator-3.0.1.tgz#7ef78ec0c8577a544477308ddf1d2d6e88d51f5b" + resolved "https://registry.npmjs.org/degenerator/-/degenerator-3.0.1.tgz" integrity sha512-LFsIFEeLPlKvAKXu7j3ssIG6RT0TbI7/GhsqrI0DnHASEQjXQ0LUSYcjJteGgRGmZbl1TnMSxpNQIAiJ7Du5TQ== dependencies: ast-types "^0.13.2" @@ -1408,15 +1571,10 @@ des.js@^1.0.0: inherits "^2.0.1" minimalistic-assert "^1.0.0" -diff@3.5.0: - version "3.5.0" - resolved "https://registry.npmjs.org/diff/-/diff-3.5.0.tgz" - integrity sha512-A46qtFgd+g7pDZinpnwiRJtxbC1hpgf0uzP3iG89scHk0AUC7A1TGxf5OiiOUv/JMZR8GOt8hL900hV0bOy5xA== - -diff@^4.0.2: - version "4.0.2" - resolved "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz" - integrity sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A== +diff@5.0.0, diff@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/diff/-/diff-5.0.0.tgz#7ed6ad76d859d030787ec35855f5b1daf31d852b" + integrity sha512-/VTCrvm5Z0JGty/BWHljh+BAiw3IK+2j87NGMu8Nwc/f48WoDAC395uomO9ZD117ZOBaHmkX1oyLvkVM/aIT3w== diffie-hellman@^5.0.0: version "5.0.3" @@ -1427,6 +1585,13 @@ diffie-hellman@^5.0.0: miller-rabin "^4.0.0" randombytes "^2.0.0" +doctrine@^3.0.0: + version "3.0.0" + resolved "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz" + integrity sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w== + dependencies: + esutils "^2.0.2" + domain-browser@^1.1.1: version "1.2.0" resolved "https://registry.npmjs.org/domain-browser/-/domain-browser-1.2.0.tgz" @@ -1474,6 +1639,11 @@ emoji-regex@^7.0.1: resolved "https://registry.npmjs.org/emoji-regex/-/emoji-regex-7.0.3.tgz" integrity sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA== +emoji-regex@^8.0.0: + version "8.0.0" + resolved "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz" + integrity sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A== + emojis-list@^2.0.0: version "2.1.0" resolved "https://registry.npmjs.org/emojis-list/-/emojis-list-2.1.0.tgz" @@ -1500,6 +1670,13 @@ enhanced-resolve@^4.3.0: memory-fs "^0.5.0" tapable "^1.0.0" +enquirer@^2.3.5: + version "2.3.6" + resolved "https://registry.npmjs.org/enquirer/-/enquirer-2.3.6.tgz" + integrity sha512-yjNnPr315/FjS4zIsUxYguYUPP2e1NK4d7E7ZOLiyYCcbFBiTMyID+2wvm2w6+pZ/odMA7cRkjhsPbltwBOrLg== + dependencies: + ansi-colors "^4.1.1" + entities@~2.0.0: version "2.0.3" resolved "https://registry.npmjs.org/entities/-/entities-2.0.3.tgz" @@ -1519,33 +1696,6 @@ error-ex@^1.3.1: dependencies: is-arrayish "^0.2.1" -es-abstract@^1.18.0-next.1: - version "1.18.0-next.1" - resolved "https://registry.npmjs.org/es-abstract/-/es-abstract-1.18.0-next.1.tgz" - integrity sha512-I4UGspA0wpZXWENrdA0uHbnhte683t3qT/1VFH9aX2dA5PPSf6QW5HHXf5HImaqPmjXaVeVk4RGWnaylmV7uAA== - dependencies: - es-to-primitive "^1.2.1" - function-bind "^1.1.1" - has "^1.0.3" - has-symbols "^1.0.1" - is-callable "^1.2.2" - is-negative-zero "^2.0.0" - is-regex "^1.1.1" - object-inspect "^1.8.0" - object-keys "^1.1.1" - object.assign "^4.1.1" - string.prototype.trimend "^1.0.1" - string.prototype.trimstart "^1.0.1" - -es-to-primitive@^1.2.1: - version "1.2.1" - resolved "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.1.tgz" - integrity sha512-QCOllgZJtaUo9miYBcLChTUaHNjJF3PYs1VidD7AwiEj1kYxKeQTctLAezAOH5ZKRH0g2IgPn6KwB4IT8iRpvA== - dependencies: - is-callable "^1.1.4" - is-date-object "^1.0.1" - is-symbol "^1.0.2" - es6-error@^4.0.1: version "4.1.1" resolved "https://registry.npmjs.org/es6-error/-/es6-error-4.1.1.tgz" @@ -1556,7 +1706,17 @@ es6-promisify@^6.0.0, es6-promisify@^6.1.1: resolved "https://registry.npmjs.org/es6-promisify/-/es6-promisify-6.1.1.tgz" integrity sha512-HBL8I3mIki5C1Cc9QjKUenHtnG0A5/xA8Q/AllRcfiwl2CZFXGK7ddBiCoRwAix4i2KxcQfjtIVcrVbB3vbmwg== -escape-string-regexp@1.0.5, escape-string-regexp@^1.0.5: +escalade@^3.1.1: + version "3.1.1" + resolved "https://registry.yarnpkg.com/escalade/-/escalade-3.1.1.tgz#d8cfdc7000965c5a0174b4a82eaa5c0552742e40" + integrity sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw== + +escape-string-regexp@4.0.0, escape-string-regexp@^4.0.0: + version "4.0.0" + resolved "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz" + integrity sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA== + +escape-string-regexp@^1.0.5: version "1.0.5" resolved "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz" integrity sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ= @@ -1578,6 +1738,53 @@ escodegen@^1.8.1: optionalDependencies: source-map "~0.6.1" +eslint-config-prettier@^8.3.0: + version "8.3.0" + resolved "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-8.3.0.tgz" + integrity sha512-BgZuLUSeKzvlL/VUjx/Yb787VQ26RU3gGjA3iiFvdsp/2bMfVIWUVP7tjxtjS0e+HP409cPlPvNkQloz8C91ew== + +eslint-plugin-es@^3.0.0: + version "3.0.1" + resolved "https://registry.yarnpkg.com/eslint-plugin-es/-/eslint-plugin-es-3.0.1.tgz#75a7cdfdccddc0589934aeeb384175f221c57893" + integrity sha512-GUmAsJaN4Fc7Gbtl8uOBlayo2DqhwWvEzykMHSCZHU3XdJ+NSzzZcVhXh3VxX5icqQ+oQdIEawXX8xkR3mIFmQ== + dependencies: + eslint-utils "^2.0.0" + regexpp "^3.0.0" + +eslint-plugin-jsdoc@^36.1.0: + version "36.1.0" + resolved "https://registry.yarnpkg.com/eslint-plugin-jsdoc/-/eslint-plugin-jsdoc-36.1.0.tgz#8dfe5f27edfb6aa3812e6d86ccaea849ddc86b03" + integrity sha512-Qpied2AJCQcScxfzTObLKRiP5QgLXjMU/ITjBagEV5p2Q/HpumD1EQtazdRYdjDSwPmXhwOl2yquwOGQ4HOJNw== + dependencies: + "@es-joy/jsdoccomment" "0.10.8" + comment-parser "1.2.4" + debug "^4.3.2" + esquery "^1.4.0" + jsdoc-type-pratt-parser "^1.1.1" + lodash "^4.17.21" + regextras "^0.8.0" + semver "^7.3.5" + spdx-expression-parse "^3.0.1" + +eslint-plugin-node@^11.1.0: + version "11.1.0" + resolved "https://registry.yarnpkg.com/eslint-plugin-node/-/eslint-plugin-node-11.1.0.tgz#c95544416ee4ada26740a30474eefc5402dc671d" + integrity sha512-oUwtPJ1W0SKD0Tr+wqu92c5xuCeQqB3hSCHasn/ZgjFdA9iDGNkNf2Zi9ztY7X+hNuMib23LNGRm6+uN+KLE3g== + dependencies: + eslint-plugin-es "^3.0.0" + eslint-utils "^2.0.0" + ignore "^5.1.1" + minimatch "^3.0.4" + resolve "^1.10.1" + semver "^6.1.0" + +eslint-plugin-prettier@^4.0.0: + version "4.0.0" + resolved "https://registry.npmjs.org/eslint-plugin-prettier/-/eslint-plugin-prettier-4.0.0.tgz" + integrity sha512-98MqmCJ7vJodoQK359bqQWaxOE0CS8paAz/GgjaZLyex4TTk3g9HugoO89EqWCrFiOqn9EVvcoo7gZzONCWVwQ== + dependencies: + prettier-linter-helpers "^1.0.0" + eslint-scope@^4.0.3: version "4.0.3" resolved "https://registry.npmjs.org/eslint-scope/-/eslint-scope-4.0.3.tgz" @@ -1586,12 +1793,99 @@ eslint-scope@^4.0.3: esrecurse "^4.1.0" estraverse "^4.1.1" +eslint-scope@^5.1.1: + version "5.1.1" + resolved "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz" + integrity sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw== + dependencies: + esrecurse "^4.3.0" + estraverse "^4.1.1" + +eslint-utils@^2.0.0, eslint-utils@^2.1.0: + version "2.1.0" + resolved "https://registry.npmjs.org/eslint-utils/-/eslint-utils-2.1.0.tgz" + integrity sha512-w94dQYoauyvlDc43XnGB8lU3Zt713vNChgt4EWwhXAP2XkBvndfxF0AgIqKOOasjPIPzj9JqgwkwbCYD0/V3Zg== + dependencies: + eslint-visitor-keys "^1.1.0" + +eslint-visitor-keys@^1.1.0, eslint-visitor-keys@^1.3.0: + version "1.3.0" + resolved "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz" + integrity sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ== + +eslint-visitor-keys@^2.0.0: + version "2.1.0" + resolved "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-2.1.0.tgz" + integrity sha512-0rSmRBzXgDzIsD6mGdJgevzgezI534Cer5L/vyMX0kHzT/jiB43jRhd9YUlMGYLQy2zprNmoT8qasCGtY+QaKw== + +eslint@^7.32.0: + version "7.32.0" + resolved "https://registry.npmjs.org/eslint/-/eslint-7.32.0.tgz" + integrity sha512-VHZ8gX+EDfz+97jGcgyGCyRia/dPOd6Xh9yPv8Bl1+SoaIwD+a/vlrOmGRUyOYu7MwUhc7CxqeaDZU13S4+EpA== + dependencies: + "@babel/code-frame" "7.12.11" + "@eslint/eslintrc" "^0.4.3" + "@humanwhocodes/config-array" "^0.5.0" + ajv "^6.10.0" + chalk "^4.0.0" + cross-spawn "^7.0.2" + debug "^4.0.1" + doctrine "^3.0.0" + enquirer "^2.3.5" + escape-string-regexp "^4.0.0" + eslint-scope "^5.1.1" + eslint-utils "^2.1.0" + eslint-visitor-keys "^2.0.0" + espree "^7.3.1" + esquery "^1.4.0" + esutils "^2.0.2" + fast-deep-equal "^3.1.3" + file-entry-cache "^6.0.1" + functional-red-black-tree "^1.0.1" + glob-parent "^5.1.2" + globals "^13.6.0" + ignore "^4.0.6" + import-fresh "^3.0.0" + imurmurhash "^0.1.4" + is-glob "^4.0.0" + js-yaml "^3.13.1" + json-stable-stringify-without-jsonify "^1.0.1" + levn "^0.4.1" + lodash.merge "^4.6.2" + minimatch "^3.0.4" + natural-compare "^1.4.0" + optionator "^0.9.1" + progress "^2.0.0" + regexpp "^3.1.0" + semver "^7.2.1" + strip-ansi "^6.0.0" + strip-json-comments "^3.1.0" + table "^6.0.9" + text-table "^0.2.0" + v8-compile-cache "^2.0.3" + +espree@^7.3.0, espree@^7.3.1: + version "7.3.1" + resolved "https://registry.npmjs.org/espree/-/espree-7.3.1.tgz" + integrity sha512-v3JCNCE64umkFpmkFGqzVKsOT0tN1Zr+ueqLZfpV1Ob8e+CEgPWa+OxCoGH3tnhimMKIaBm4m/vaRpJ/krRz2g== + dependencies: + acorn "^7.4.0" + acorn-jsx "^5.3.1" + eslint-visitor-keys "^1.3.0" + esprima@^4.0.0, esprima@^4.0.1: version "4.0.1" resolved "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz" integrity sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A== -esrecurse@^4.1.0: +esquery@^1.4.0: + version "1.4.0" + resolved "https://registry.npmjs.org/esquery/-/esquery-1.4.0.tgz" + integrity sha512-cCDispWt5vHHtwMY2YrAQ4ibFkAL8RbH5YGBnZBc90MolvvfkkQcJro/aZiAQUlQ3qgrYS6D6v8Gc5G5CQsc9w== + dependencies: + estraverse "^5.1.0" + +esrecurse@^4.1.0, esrecurse@^4.3.0: version "4.3.0" resolved "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz" integrity sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag== @@ -1603,7 +1897,7 @@ estraverse@^4.1.1, estraverse@^4.2.0: resolved "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz" integrity sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw== -estraverse@^5.2.0: +estraverse@^5.1.0, estraverse@^5.2.0: version "5.2.0" resolved "https://registry.npmjs.org/estraverse/-/estraverse-5.2.0.tgz" integrity sha512-BxbNGGNm0RyRYvUdHpIwv9IWzeM9XClbOxwoATuFdOE7ZE6wHL+HQ5T8hoPM+zHvmKzzsEqhgy0GrQ5X13afiQ== @@ -1694,17 +1988,22 @@ extglob@^2.0.4: snapdragon "^0.8.1" to-regex "^3.0.1" -fast-deep-equal@^3.1.1: +fast-deep-equal@^3.1.1, fast-deep-equal@^3.1.3: version "3.1.3" resolved "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz" integrity sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q== +fast-diff@^1.1.2: + version "1.2.0" + resolved "https://registry.npmjs.org/fast-diff/-/fast-diff-1.2.0.tgz" + integrity sha512-xJuoT5+L99XlZ8twedaRf6Ax2TgQVxvgZOYoPKqZufmJib0tL2tegPBOZb1pVNgIhlqDlA0eO0c3wBvQcmzx4w== + fast-json-stable-stringify@^2.0.0: version "2.1.0" resolved "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz" integrity sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw== -fast-levenshtein@~2.0.6: +fast-levenshtein@^2.0.6, fast-levenshtein@~2.0.6: version "2.0.6" resolved "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz" integrity sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc= @@ -1719,6 +2018,13 @@ figgy-pudding@^3.5.1: resolved "https://registry.npmjs.org/figgy-pudding/-/figgy-pudding-3.5.2.tgz" integrity sha512-0btnI/H8f2pavGMN8w40mlSKOfTK2SVJmBfBeVIj3kNw0swwgzyRq0d5TJVOwodFmtvpPeWPN/MCcfuWF0Ezbw== +file-entry-cache@^6.0.1: + version "6.0.1" + resolved "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-6.0.1.tgz" + integrity sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg== + dependencies: + flat-cache "^3.0.4" + file-loader@^0.8.1: version "0.8.5" resolved "https://registry.npmjs.org/file-loader/-/file-loader-0.8.5.tgz" @@ -1728,7 +2034,7 @@ file-loader@^0.8.1: file-uri-to-path@1.0.0: version "1.0.0" - resolved "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz" + resolved "https://registry.yarnpkg.com/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz#553a7b8446ff6f684359c445f1e37a05dacc33dd" integrity sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw== file-uri-to-path@2: @@ -1770,12 +2076,13 @@ find-cache-dir@^2.1.0: make-dir "^2.0.0" pkg-dir "^3.0.0" -find-up@3.0.0, find-up@^3.0.0: - version "3.0.0" - resolved "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz" - integrity sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg== +find-up@5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/find-up/-/find-up-5.0.0.tgz#4c92819ecb7083561e4f4a240a86be5198f536fc" + integrity sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng== dependencies: - locate-path "^3.0.0" + locate-path "^6.0.0" + path-exists "^4.0.0" find-up@^2.1.0: version "2.1.0" @@ -1784,6 +2091,13 @@ find-up@^2.1.0: dependencies: locate-path "^2.0.0" +find-up@^3.0.0: + version "3.0.0" + resolved "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz" + integrity sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg== + dependencies: + locate-path "^3.0.0" + find-up@^4.0.0: version "4.1.0" resolved "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz" @@ -1792,12 +2106,23 @@ find-up@^4.0.0: locate-path "^5.0.0" path-exists "^4.0.0" -flat@^4.1.0: - version "4.1.1" - resolved "https://registry.npmjs.org/flat/-/flat-4.1.1.tgz" - integrity sha512-FmTtBsHskrU6FJ2VxCnsDb84wu9zhmO3cUX2kGFb5tuwhfXxGciiT0oRY+cck35QmG+NmGh5eLz6lLCpWTqwpA== +flat-cache@^3.0.4: + version "3.0.4" + resolved "https://registry.npmjs.org/flat-cache/-/flat-cache-3.0.4.tgz" + integrity sha512-dm9s5Pw7Jc0GvMYbshN6zchCA9RgQlzzEZX3vylR9IqFfS8XciblUXOKfW6SiuJ0e13eDYZoZV5wdrev7P3Nwg== dependencies: - is-buffer "~2.0.3" + flatted "^3.1.0" + rimraf "^3.0.2" + +flat@^5.0.2: + version "5.0.2" + resolved "https://registry.yarnpkg.com/flat/-/flat-5.0.2.tgz#8ca6fe332069ffa9d324c327198c598259ceb241" + integrity sha512-b6suED+5/3rTpUBdG1gupIl8MPFCAMA0QXwmljLhvCUKcUvdE4gWky9zpuGCcXHOsz4J9wPGNWq6OKpmIzz3hQ== + +flatted@^3.1.0: + version "3.2.2" + resolved "https://registry.npmjs.org/flatted/-/flatted-3.2.2.tgz" + integrity sha512-JaTY/wtrcSyvXJl4IMFHPKyFur1sE9AUqc0QnhOaJ0CxHtAoIV8pYDzeEfAaNEtGkOfq4gr3LBFmdXW5mOQFnA== flush-write-stream@^1.0.0: version "1.1.1" @@ -1814,7 +2139,7 @@ follow-redirects@^1.10.0: follow-redirects@^1.14.0: version "1.14.3" - resolved "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.14.3.tgz#6ada78118d8d24caee595595accdc0ac6abd022e" + resolved "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.14.3.tgz" integrity sha512-3MkHxknWMUtb23apkgz/83fDoe+y+qr0TdgacGIA7bew+QLBo3vdgEN2xEsuXNivpFy4CyDhBBZnNZOtalmenw== for-in@^1.0.2: @@ -1841,7 +2166,7 @@ form-data@^3.0.0: form-data@^3.0.1: version "3.0.1" - resolved "https://registry.yarnpkg.com/form-data/-/form-data-3.0.1.tgz#ebd53791b78356a99af9a300d4282c4d5eb9755f" + resolved "https://registry.npmjs.org/form-data/-/form-data-3.0.1.tgz" integrity sha512-RHkBKtLWUVwd7SqRIvCZMEvAMoGUp0XU+seQiZejj0COz3RI3hWP4sCv3gZWWLjJTd7rGwcsF5eKZGii0r/hbg== dependencies: asynckit "^0.4.0" @@ -1894,7 +2219,7 @@ fs.realpath@^1.0.0: fsevents@^1.2.7: version "1.2.13" - resolved "https://registry.npmjs.org/fsevents/-/fsevents-1.2.13.tgz" + resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-1.2.13.tgz#f325cb0455592428bcf11b383370ef70e3bfcc38" integrity sha512-oWb1Z6mkHIskLzEJ/XWX0srkpkTQ7vaopMQkyaEIoq0fmtFVxOthb8cCxeT+p3ynTdkk/RZwbgG4brR5BeWECw== dependencies: bindings "^1.5.0" @@ -1902,9 +2227,14 @@ fsevents@^1.2.7: fsevents@~2.1.2: version "2.1.3" - resolved "https://registry.npmjs.org/fsevents/-/fsevents-2.1.3.tgz" + resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-2.1.3.tgz#fb738703ae8d2f9fe900c33836ddebee8b97f23e" integrity sha512-Auw9a4AxqWpa9GUfj370BMPzzyncfBABW8Mab7BGWBYDj4Isgq+cDKtx0i6u9jcX9pQDnswsaaOTgTmA5pEjuQ== +fsevents@~2.3.2: + version "2.3.2" + resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-2.3.2.tgz#8a526f78b8fdf4623b709e0b975c52c24c02fd1a" + integrity sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA== + ftp@^0.3.10: version "0.3.10" resolved "https://registry.npmjs.org/ftp/-/ftp-0.3.10.tgz" @@ -1918,9 +2248,14 @@ function-bind@^1.1.1: resolved "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz" integrity sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A== -get-caller-file@^2.0.1: +functional-red-black-tree@^1.0.1: + version "1.0.1" + resolved "https://registry.npmjs.org/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz" + integrity sha1-GwqzvVU7Kg1jmdKcDj6gslIHgyc= + +get-caller-file@^2.0.1, get-caller-file@^2.0.5: version "2.0.5" - resolved "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz" + resolved "https://registry.yarnpkg.com/get-caller-file/-/get-caller-file-2.0.5.tgz#4f94412a82db32f36e3b0b9741f8a97feb031f7e" integrity sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg== get-func-name@^2.0.0: @@ -1988,6 +2323,13 @@ glob-parent@^3.1.0: is-glob "^3.1.0" path-dirname "^1.0.0" +glob-parent@^5.1.2, glob-parent@~5.1.2: + version "5.1.2" + resolved "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz" + integrity sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow== + dependencies: + is-glob "^4.0.1" + glob-parent@~5.1.0: version "5.1.1" resolved "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.1.tgz" @@ -1995,7 +2337,19 @@ glob-parent@~5.1.0: dependencies: is-glob "^4.0.1" -glob@7.1.3, glob@^7.1.3: +glob@7.1.7: + version "7.1.7" + resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.7.tgz#3b193e9233f01d42d0b3f78294bbeeb418f94a90" + integrity sha512-OvD9ENzPLbegENnYP5UUfJIirTg4+XwMWGaQfQTY0JenxNvvIKP3U3/tAQSPIu/lHxXYSZmpXlUHeqAIdKzBLQ== + dependencies: + fs.realpath "^1.0.0" + inflight "^1.0.4" + inherits "2" + minimatch "^3.0.4" + once "^1.3.0" + path-is-absolute "^1.0.0" + +glob@^7.1.3: version "7.1.3" resolved "https://registry.npmjs.org/glob/-/glob-7.1.3.tgz" integrity sha512-vcfuiIxogLV4DlGBHIUOwI0IbrJ8HWPc4MU7HzviGeNho/UJDfi6B5p3sHeWIQ0KGIU0Jpxi5ZHxemQfLkkAwQ== @@ -2024,6 +2378,13 @@ globals@^11.1.0: resolved "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz" integrity sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA== +globals@^13.6.0, globals@^13.9.0: + version "13.11.0" + resolved "https://registry.npmjs.org/globals/-/globals-13.11.0.tgz" + integrity sha512-08/xrJ7wQjK9kkkRoI3OFUBbLx4f+6x3SGwcPvQ0QH6goFDrOU2oyAWrmh3dJezu65buo+HBMzAMQy6rovVC3g== + dependencies: + type-fest "^0.20.2" + graceful-fs@^4.1.11, graceful-fs@^4.1.15, graceful-fs@^4.1.2, graceful-fs@^4.1.6, graceful-fs@^4.1.9, graceful-fs@^4.2.0: version "4.2.4" resolved "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.4.tgz" @@ -2044,7 +2405,7 @@ has-flag@^4.0.0: resolved "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz" integrity sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ== -has-symbols@^1.0.0, has-symbols@^1.0.1: +has-symbols@^1.0.1: version "1.0.1" resolved "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.1.tgz" integrity sha512-PLcsoqu++dmEIZB+6totNFKq/7Do+Z0u4oT0zKOJNl3lYK6vGwwu2hjHs+68OEZbTjiUE9bgOABXbP/GvrS0Kg== @@ -2222,6 +2583,16 @@ ignore@^3.3.7: resolved "https://registry.npmjs.org/ignore/-/ignore-3.3.10.tgz" integrity sha512-Pgs951kaMm5GXP7MOvxERINe3gsaVjUWFm+UZPSq9xYriQAksyhg0csnS0KXSNRD5NmNdapXEpjxG49+AKh/ug== +ignore@^4.0.6: + version "4.0.6" + resolved "https://registry.npmjs.org/ignore/-/ignore-4.0.6.tgz" + integrity sha512-cyFDKrqc/YdcWFniJhzI42+AzS+gNwmUzOSFcRCQYwySuBBBy/KjuxWLZ/FHEH6Moq1NizMOBWyTcv8O4OZIMg== + +ignore@^5.1.1: + version "5.1.8" + resolved "https://registry.yarnpkg.com/ignore/-/ignore-5.1.8.tgz#f150a8b50a34289b33e22f5889abd4d8016f0e57" + integrity sha512-BMpfD7PpiETpBl/A6S498BaIJ6Y/ABT93ETbby2fP00v4EbvPBXWEoaR1UBPKs3iR53pJY7EtZk5KACI57i1Uw== + import-fresh@^2.0.0: version "2.0.0" resolved "https://registry.npmjs.org/import-fresh/-/import-fresh-2.0.0.tgz" @@ -2230,6 +2601,14 @@ import-fresh@^2.0.0: caller-path "^2.0.0" resolve-from "^3.0.0" +import-fresh@^3.0.0, import-fresh@^3.2.1: + version "3.3.0" + resolved "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.0.tgz" + integrity sha512-veYYhQa+D1QBKznvhUHxb8faxlrwUnxseDAbAp457E0wLNio2bOSKnjYDhMj+YiAq61xrMGhQk9iXVk5FzgQMw== + dependencies: + parent-module "^1.0.0" + resolve-from "^4.0.0" + imurmurhash@^0.1.4: version "0.1.4" resolved "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz" @@ -2313,16 +2692,6 @@ is-buffer@^1.1.5, is-buffer@~1.1.6: resolved "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz" integrity sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w== -is-buffer@~2.0.3: - version "2.0.5" - resolved "https://registry.npmjs.org/is-buffer/-/is-buffer-2.0.5.tgz" - integrity sha512-i2R6zNFDwgEHJyQUtJEk0XFi1i0dPFn/oqjK3/vPCcDeJvW5NQ83V8QbicfF1SupOaB0h8ntgBC2YiE7dfyctQ== - -is-callable@^1.1.4, is-callable@^1.2.2: - version "1.2.2" - resolved "https://registry.npmjs.org/is-callable/-/is-callable-1.2.2.tgz" - integrity sha512-dnMqspv5nU3LoewK2N/y7KLtxtakvTuaCsU9FU50/QDmdbHNy/4/JuRtMHqRU22o3q+W89YQndQEeCVwK+3qrA== - is-core-module@^2.1.0: version "2.2.0" resolved "https://registry.npmjs.org/is-core-module/-/is-core-module-2.2.0.tgz" @@ -2330,6 +2699,13 @@ is-core-module@^2.1.0: dependencies: has "^1.0.3" +is-core-module@^2.2.0: + version "2.7.0" + resolved "https://registry.yarnpkg.com/is-core-module/-/is-core-module-2.7.0.tgz#3c0ef7d31b4acfc574f80c58409d568a836848e3" + integrity sha512-ByY+tjCciCr+9nLryBYcSD50EOGWt95c7tIsKTG1J2ixKKXPvF7Ej3AVd+UfDydAJom3biBGDBALaO79ktwgEQ== + dependencies: + has "^1.0.3" + is-data-descriptor@^0.1.4: version "0.1.4" resolved "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz" @@ -2394,6 +2770,11 @@ is-fullwidth-code-point@^2.0.0: resolved "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz" integrity sha1-o7MKXE8ZkYMWeqq5O+764937ZU8= +is-fullwidth-code-point@^3.0.0: + version "3.0.0" + resolved "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz" + integrity sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg== + is-glob@^3.1.0: version "3.1.0" resolved "https://registry.npmjs.org/is-glob/-/is-glob-3.1.0.tgz" @@ -2415,11 +2796,6 @@ is-lower-case@^1.1.0: dependencies: lower-case "^1.1.0" -is-negative-zero@^2.0.0: - version "2.0.1" - resolved "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.1.tgz" - integrity sha512-2z6JzQvZRa9A2Y7xC6dQQm4FSTSTNWjKIYYTt4246eMTJmIo0Q+ZyOsU66X8lxK1AbB92dFeglPLrhwpeRKO6w== - is-number@^3.0.0: version "3.0.0" resolved "https://registry.npmjs.org/is-number/-/is-number-3.0.0.tgz" @@ -2437,6 +2813,11 @@ is-object@~1.0.1: resolved "https://registry.npmjs.org/is-object/-/is-object-1.0.2.tgz" integrity sha512-2rRIahhZr2UWb45fIOuvZGpFtz0TyOZLf32KxBbSoUCeZR495zCKlWUKKUByk3geS2eAs7ZAABt0Y/Rx0GiQGA== +is-plain-obj@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/is-plain-obj/-/is-plain-obj-2.1.0.tgz#45e42e37fccf1f40da8e5f76ee21515840c09287" + integrity sha512-YWnfyRwxL/+SsrWYfOpUtz5b3YD+nyfkHvjbcanzk8zgyO4ASD67uVMRt8k5bM4lLMDnXfriRhOpemw+NfT1eA== + is-plain-object@^2.0.3, is-plain-object@^2.0.4: version "2.0.4" resolved "https://registry.npmjs.org/is-plain-object/-/is-plain-object-2.0.4.tgz" @@ -2444,7 +2825,7 @@ is-plain-object@^2.0.3, is-plain-object@^2.0.4: dependencies: isobject "^3.0.1" -is-regex@^1.0.4, is-regex@^1.1.1: +is-regex@^1.0.4: version "1.1.1" resolved "https://registry.npmjs.org/is-regex/-/is-regex-1.1.1.tgz" integrity sha512-1+QkEcxiLlB7VEyFtyBg94e08OAsvq7FUBgApTq/w2ymCLyKJgDPsybBENVtA7XCQEgEXxKPonG+mvYRxh/LIg== @@ -2456,12 +2837,10 @@ is-stream@^1.0.1, is-stream@^1.1.0: resolved "https://registry.npmjs.org/is-stream/-/is-stream-1.1.0.tgz" integrity sha1-EtSj3U5o4Lec6428hBc66A2RykQ= -is-symbol@^1.0.2: - version "1.0.3" - resolved "https://registry.npmjs.org/is-symbol/-/is-symbol-1.0.3.tgz" - integrity sha512-OwijhaRSgqvhm/0ZdAcXNZt9lYdKFpcRDT5ULUuYXPoT794UNOdU+gpT6Rzo7b4V2HUl/op6GqY894AZwv9faQ== - dependencies: - has-symbols "^1.0.1" +is-unicode-supported@^0.1.0: + version "0.1.0" + resolved "https://registry.yarnpkg.com/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz#3f26c76a809593b52bfa2ecb5710ed2779b522a7" + integrity sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw== is-upper-case@^1.1.0: version "1.1.2" @@ -2564,14 +2943,6 @@ js-tokens@^4.0.0: resolved "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz" integrity sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ== -js-yaml@3.13.1: - version "3.13.1" - resolved "https://registry.npmjs.org/js-yaml/-/js-yaml-3.13.1.tgz" - integrity sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw== - dependencies: - argparse "^1.0.7" - esprima "^4.0.0" - js-yaml@3.14.0, js-yaml@^3.13.1: version "3.14.0" resolved "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.0.tgz" @@ -2580,6 +2951,13 @@ js-yaml@3.14.0, js-yaml@^3.13.1: argparse "^1.0.7" esprima "^4.0.0" +js-yaml@4.1.0: + version "4.1.0" + resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-4.1.0.tgz#c1fb65f8f5017901cdd2c951864ba18458a10602" + integrity sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA== + dependencies: + argparse "^2.0.1" + js2xmlparser@^4.0.1: version "4.0.1" resolved "https://registry.npmjs.org/js2xmlparser/-/js2xmlparser-4.0.1.tgz" @@ -2587,6 +2965,16 @@ js2xmlparser@^4.0.1: dependencies: xmlcreate "^2.0.3" +jsdoc-type-pratt-parser@1.1.1: + version "1.1.1" + resolved "https://registry.yarnpkg.com/jsdoc-type-pratt-parser/-/jsdoc-type-pratt-parser-1.1.1.tgz#10fe5e409ba38de22a48b555598955a26ff0160f" + integrity sha512-uelRmpghNwPBuZScwgBG/OzodaFk5RbO5xaivBdsAY70icWfShwZ7PCMO0x1zSkOa8T1FzHThmrdoyg/0AwV5g== + +jsdoc-type-pratt-parser@^1.1.1: + version "1.2.0" + resolved "https://registry.yarnpkg.com/jsdoc-type-pratt-parser/-/jsdoc-type-pratt-parser-1.2.0.tgz#3482a3833b74a88c95a6ba7253f0c0de3b77b9f5" + integrity sha512-4STjeF14jp4bqha44nKMY1OUI6d2/g6uclHWUCZ7B4DoLzaB5bmpTkQrpqU+vSVzMD0LsKAOskcnI3I3VfIpmg== + jsdoc@^3.6.3: version "3.6.7" resolved "https://registry.npmjs.org/jsdoc/-/jsdoc-3.6.7.tgz" @@ -2632,6 +3020,16 @@ json-schema-traverse@^0.4.1: resolved "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz" integrity sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg== +json-schema-traverse@^1.0.0: + version "1.0.0" + resolved "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz" + integrity sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug== + +json-stable-stringify-without-jsonify@^1.0.1: + version "1.0.1" + resolved "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz" + integrity sha1-nbe1lJatPzz+8wp1FC0tkwrXJlE= + json-stringify-safe@^5.0.1: version "5.0.1" resolved "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz" @@ -2673,9 +3071,9 @@ jsonwebtoken@^8.5.1: semver "^5.6.0" just-extend@^4.0.2: - version "4.1.1" - resolved "https://registry.npmjs.org/just-extend/-/just-extend-4.1.1.tgz" - integrity sha512-aWgeGFW67BP3e5181Ep1Fv2v8z//iBJfrvyTnq8wG86vEESwmonn1zPBJ0VfmT9CJq2FIT0VsETtrNFm2a+SHA== + version "4.2.1" + resolved "https://registry.npmjs.org/just-extend/-/just-extend-4.2.1.tgz" + integrity sha512-g3UB796vUFIY90VIv/WX3L2c8CS2MdWUww3CNrYmqza1Fg0DURc2K/O4YrnklBdQarSJ/y8JnJYDGc+1iumQjg== jwa@^1.4.1: version "1.4.1" @@ -2741,6 +3139,14 @@ klaw@^3.0.0: dependencies: graceful-fs "^4.1.9" +levn@^0.4.1: + version "0.4.1" + resolved "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz" + integrity sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ== + dependencies: + prelude-ls "^1.2.1" + type-check "~0.4.0" + levn@~0.3.0: version "0.3.0" resolved "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz" @@ -2823,6 +3229,13 @@ locate-path@^5.0.0: dependencies: p-locate "^4.1.0" +locate-path@^6.0.0: + version "6.0.0" + resolved "https://registry.yarnpkg.com/locate-path/-/locate-path-6.0.0.tgz#55321eb309febbc59c4801d931a72452a681d286" + integrity sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw== + dependencies: + p-locate "^5.0.0" + lodash.clonedeep@^4.5.0: version "4.5.0" resolved "https://registry.npmjs.org/lodash.clonedeep/-/lodash.clonedeep-4.5.0.tgz" @@ -2868,22 +3281,33 @@ lodash.isstring@^4.0.1: resolved "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz" integrity sha1-1SfftUVuynzJu5XV2ur4i6VKVFE= +lodash.merge@^4.6.2: + version "4.6.2" + resolved "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz" + integrity sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ== + lodash.once@^4.0.0: version "4.1.1" resolved "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz" integrity sha1-DdOXEhPHxW34gJd9UEyI+0cal6w= -lodash@^4.17.14, lodash@^4.17.15, lodash@^4.17.19, lodash@^4.17.5: +lodash.truncate@^4.4.2: + version "4.4.2" + resolved "https://registry.npmjs.org/lodash.truncate/-/lodash.truncate-4.4.2.tgz" + integrity sha1-WjUNoLERO4N+z//VgSy+WNbq4ZM= + +lodash@^4.17.14, lodash@^4.17.15, lodash@^4.17.19, lodash@^4.17.21, lodash@^4.17.5: version "4.17.21" resolved "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz" integrity sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg== -log-symbols@2.2.0: - version "2.2.0" - resolved "https://registry.npmjs.org/log-symbols/-/log-symbols-2.2.0.tgz" - integrity sha512-VeIAFslyIerEJLXHziedo2basKbMKtTw3vfn5IzG0XTjhAVEJyNHnL2p7vc+wBDSdQuUpNw3M2u6xb9QsAY5Eg== +log-symbols@4.1.0: + version "4.1.0" + resolved "https://registry.yarnpkg.com/log-symbols/-/log-symbols-4.1.0.tgz#3fbdbb95b4683ac9fc785111e792e558d4abd503" + integrity sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg== dependencies: - chalk "^2.0.1" + chalk "^4.1.0" + is-unicode-supported "^0.1.0" lower-case-first@^1.0.0: version "1.0.2" @@ -2929,7 +3353,7 @@ lru-memoizer@^2.1.2: lru-memoizer@^2.1.4: version "2.1.4" - resolved "https://registry.yarnpkg.com/lru-memoizer/-/lru-memoizer-2.1.4.tgz#b864d92b557f00b1eeb322156a0409cb06dafac6" + resolved "https://registry.npmjs.org/lru-memoizer/-/lru-memoizer-2.1.4.tgz" integrity sha512-IXAq50s4qwrOBrXJklY+KhgZF+5y98PDaNo0gi/v2KQBFLyWr+JyFvijZXkGKjQj/h9c0OwoE+JZbwUXce76hQ== dependencies: lodash.clonedeep "^4.5.0" @@ -3127,13 +3551,6 @@ mixin-deep@^1.2.0: for-in "^1.0.2" is-extendable "^1.0.1" -mkdirp@0.5.4: - version "0.5.4" - resolved "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.4.tgz" - integrity sha512-iG9AK/dJLtJ0XNgTuDbSyNS3zECqDlAhnQW4CsNxBG3LQJBbHmRX1egw39DmtOdCAqY+dKXV+sgPgilNWUKMVw== - dependencies: - minimist "^1.2.5" - mkdirp@^0.5.0, mkdirp@^0.5.1, mkdirp@^0.5.3, mkdirp@~0.5.1: version "0.5.5" resolved "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.5.tgz" @@ -3146,10 +3563,10 @@ mkdirp@^1.0.4: resolved "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz" integrity sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw== -mocha-junit-reporter@^1.23.1: - version "1.23.3" - resolved "https://registry.npmjs.org/mocha-junit-reporter/-/mocha-junit-reporter-1.23.3.tgz" - integrity sha512-ed8LqbRj1RxZfjt/oC9t12sfrWsjZ3gNnbhV1nuj9R/Jb5/P3Xb4duv2eCfCDMYH+fEu0mqca7m4wsiVjsxsvA== +mocha-junit-reporter@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/mocha-junit-reporter/-/mocha-junit-reporter-2.0.0.tgz#3bf990fce7a42c0d2b718f188553a25d9f24b9a2" + integrity sha512-20HoWh2HEfhqmigfXOKUhZQyX23JImskc37ZOhIjBKoBEsb+4cAFRJpAVhFpnvsztLklW/gFVzsrobjLwmX4lA== dependencies: debug "^2.2.0" md5 "^2.1.0" @@ -3157,45 +3574,41 @@ mocha-junit-reporter@^1.23.1: strip-ansi "^4.0.0" xml "^1.0.0" -mocha@^6.2.0: - version "6.2.3" - resolved "https://registry.npmjs.org/mocha/-/mocha-6.2.3.tgz" - integrity sha512-0R/3FvjIGH3eEuG17ccFPk117XL2rWxatr81a57D+r/x2uTYZRbdZ4oVidEUMh2W2TJDa7MdAb12Lm2/qrKajg== +mocha@^9.1.2: + version "9.1.2" + resolved "https://registry.yarnpkg.com/mocha/-/mocha-9.1.2.tgz#93f53175b0f0dc4014bd2d612218fccfcf3534d3" + integrity sha512-ta3LtJ+63RIBP03VBjMGtSqbe6cWXRejF9SyM9Zyli1CKZJZ+vfCTj3oW24V7wAphMJdpOFLoMI3hjJ1LWbs0w== dependencies: - ansi-colors "3.2.3" + "@ungap/promise-all-settled" "1.1.2" + ansi-colors "4.1.1" browser-stdout "1.3.1" - debug "3.2.6" - diff "3.5.0" - escape-string-regexp "1.0.5" - find-up "3.0.0" - glob "7.1.3" + chokidar "3.5.2" + debug "4.3.2" + diff "5.0.0" + escape-string-regexp "4.0.0" + find-up "5.0.0" + glob "7.1.7" growl "1.10.5" he "1.2.0" - js-yaml "3.13.1" - log-symbols "2.2.0" + js-yaml "4.1.0" + log-symbols "4.1.0" minimatch "3.0.4" - mkdirp "0.5.4" - ms "2.1.1" - node-environment-flags "1.0.5" - object.assign "4.1.0" - strip-json-comments "2.0.1" - supports-color "6.0.0" - which "1.3.1" - wide-align "1.1.3" - yargs "13.3.2" - yargs-parser "13.1.2" - yargs-unparser "1.6.0" + ms "2.1.3" + nanoid "3.1.25" + serialize-javascript "6.0.0" + strip-json-comments "3.1.1" + supports-color "8.1.1" + which "2.0.2" + workerpool "6.1.5" + yargs "16.2.0" + yargs-parser "20.2.4" + yargs-unparser "2.0.0" module-not-found-error@^1.0.1: version "1.0.1" resolved "https://registry.npmjs.org/module-not-found-error/-/module-not-found-error-1.0.1.tgz" integrity sha1-z4tP9PKWQGdNbN0CsOO8UjwrvcA= -moment@^2.24.0: - version "2.29.1" - resolved "https://registry.npmjs.org/moment/-/moment-2.29.1.tgz" - integrity sha512-kHmoybcPV8Sqy59DwNDY3Jefr64lK/by/da0ViFcuA4DH0vQg5Q6Ze5VimxkfQNSC+Mls/Kx53s7TjP1RhFEDQ== - move-concurrently@^1.0.1: version "1.0.1" resolved "https://registry.npmjs.org/move-concurrently/-/move-concurrently-1.0.1.tgz" @@ -3218,17 +3631,12 @@ ms@2.0.0: resolved "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz" integrity sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g= -ms@2.1.1: - version "2.1.1" - resolved "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz" - integrity sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg== - ms@2.1.2, ms@^2.1.1: version "2.1.2" resolved "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz" integrity sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w== -ms@^2.1.2: +ms@2.1.3, ms@^2.1.2: version "2.1.3" resolved "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz" integrity sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA== @@ -3244,9 +3652,14 @@ multimatch@^3.0.0: minimatch "^3.0.4" nan@^2.12.1: - version "2.14.2" - resolved "https://registry.npmjs.org/nan/-/nan-2.14.2.tgz" - integrity sha512-M2ufzIiINKCuDfBSAUr1vWQ+vuVcA9kqx8JJUsbQi6yf1uGRyb7HfpdfUr5qLXf3B/t8dPvcjhKMmlfnP47EzQ== + version "2.15.0" + resolved "https://registry.yarnpkg.com/nan/-/nan-2.15.0.tgz#3f34a473ff18e15c1b5626b62903b5ad6e665fee" + integrity sha512-8ZtvEnA2c5aYCZYd1cvgdnU6cqwixRoYg70xPLWUws5ORTa/lnw+u4amixRS/Ac5U5mQVgp9pnlSUnbNWFaWZQ== + +nanoid@3.1.25: + version "3.1.25" + resolved "https://registry.yarnpkg.com/nanoid/-/nanoid-3.1.25.tgz#09ca32747c0e543f0e1814b7d3793477f9c8e152" + integrity sha512-rdwtIXaXCLFAQbnfqDRnI6jaRHp9fTcYBjtFKE8eezcZ7LuLjhUaQGNeMXf1HmRoCH32CLz6XwX0TtxEOS/A3Q== nanomatch@^1.2.9: version "1.2.13" @@ -3265,6 +3678,11 @@ nanomatch@^1.2.9: snapdragon "^0.8.1" to-regex "^3.0.1" +natural-compare@^1.4.0: + version "1.4.0" + resolved "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz" + integrity sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc= + neo-async@^2.5.0, neo-async@^2.6.1: version "2.6.2" resolved "https://registry.npmjs.org/neo-async/-/neo-async-2.6.2.tgz" @@ -3285,13 +3703,13 @@ nice-try@^1.0.4: resolved "https://registry.npmjs.org/nice-try/-/nice-try-1.0.5.tgz" integrity sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ== -nise@^4.0.4: - version "4.0.4" - resolved "https://registry.npmjs.org/nise/-/nise-4.0.4.tgz" - integrity sha512-bTTRUNlemx6deJa+ZyoCUTRvH3liK5+N6VQZ4NIw90AgDXY6iPnsqplNFf6STcj+ePk0H/xqxnP75Lr0J0Fq3A== +nise@^5.1.0: + version "5.1.0" + resolved "https://registry.npmjs.org/nise/-/nise-5.1.0.tgz" + integrity sha512-W5WlHu+wvo3PaKLsJJkgPup2LrsXCcm7AWwyNZkUnn5rwPkuPBi3Iwk5SQtN0mv+K65k7nKKjwNQ30wg3wLAQQ== dependencies: "@sinonjs/commons" "^1.7.0" - "@sinonjs/fake-timers" "^6.0.0" + "@sinonjs/fake-timers" "^7.0.4" "@sinonjs/text-encoding" "^0.7.1" just-extend "^4.0.2" path-to-regexp "^1.7.0" @@ -3311,14 +3729,6 @@ nock@^10.0.6: qs "^6.5.1" semver "^5.5.0" -node-environment-flags@1.0.5: - version "1.0.5" - resolved "https://registry.npmjs.org/node-environment-flags/-/node-environment-flags-1.0.5.tgz" - integrity sha512-VNYPRfGfmZLx0Ye20jWzHUjyTW/c+6Wq+iLhDzUI4XmhrDd9l/FozXV3F2xOaXjvp0co0+v1YSR3CMP6g+VvLQ== - dependencies: - object.getownpropertydescriptors "^2.0.3" - semver "^5.7.0" - node-fetch@^2.2.0: version "2.6.1" resolved "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.1.tgz" @@ -3427,11 +3837,6 @@ object-copy@^0.1.0: define-property "^0.2.5" kind-of "^3.0.3" -object-inspect@^1.8.0: - version "1.9.0" - resolved "https://registry.npmjs.org/object-inspect/-/object-inspect-1.9.0.tgz" - integrity sha512-i3Bp9iTqwhaLZBxGkRfo5ZbE07BQRT7MGu8+nNgwW9ItGp1TzCTw2DLEoWwjClxBjOFI/hWljTAmYGCEwmtnOw== - object-is@^1.0.1: version "1.1.5" resolved "https://registry.npmjs.org/object-is/-/object-is-1.1.5.tgz" @@ -3440,7 +3845,7 @@ object-is@^1.0.1: call-bind "^1.0.2" define-properties "^1.1.3" -object-keys@^1.0.11, object-keys@^1.0.12, object-keys@^1.1.1: +object-keys@^1.0.12, object-keys@^1.1.1: version "1.1.1" resolved "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz" integrity sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA== @@ -3452,35 +3857,6 @@ object-visit@^1.0.0: dependencies: isobject "^3.0.0" -object.assign@4.1.0: - version "4.1.0" - resolved "https://registry.npmjs.org/object.assign/-/object.assign-4.1.0.tgz" - integrity sha512-exHJeq6kBKj58mqGyTQ9DFvrZC/eR6OwxzoM9YRoGBqrXYonaFyGiFMuc9VZrXf7DarreEwMpurG3dd+CNyW5w== - dependencies: - define-properties "^1.1.2" - function-bind "^1.1.1" - has-symbols "^1.0.0" - object-keys "^1.0.11" - -object.assign@^4.1.1: - version "4.1.2" - resolved "https://registry.npmjs.org/object.assign/-/object.assign-4.1.2.tgz" - integrity sha512-ixT2L5THXsApyiUPYKmW+2EHpXXe5Ii3M+f4e+aJFAHao5amFRW6J0OO6c/LU8Be47utCx2GL89hxGB6XSmKuQ== - dependencies: - call-bind "^1.0.0" - define-properties "^1.1.3" - has-symbols "^1.0.1" - object-keys "^1.1.1" - -object.getownpropertydescriptors@^2.0.3: - version "2.1.1" - resolved "https://registry.npmjs.org/object.getownpropertydescriptors/-/object.getownpropertydescriptors-2.1.1.tgz" - integrity sha512-6DtXgZ/lIZ9hqx4GtZETobXLR/ZLaa0aqV0kzbn80Rf8Z2e/XFnhA0I7p07N2wH8bBBltr2xQPi6sbKWAY2Eng== - dependencies: - call-bind "^1.0.0" - define-properties "^1.1.3" - es-abstract "^1.18.0-next.1" - object.pick@^1.3.0: version "1.3.0" resolved "https://registry.npmjs.org/object.pick/-/object.pick-1.3.0.tgz" @@ -3512,6 +3888,18 @@ optionator@^0.8.1: type-check "~0.3.2" word-wrap "~1.2.3" +optionator@^0.9.1: + version "0.9.1" + resolved "https://registry.npmjs.org/optionator/-/optionator-0.9.1.tgz" + integrity sha512-74RlY5FCnhq4jRxVUPKDaRwrVNXMqsGsiW6AJw4XK8hmtm10wC0ypZBLw5IIp85NZMr91+qd1RvvENwg7jjRFw== + dependencies: + deep-is "^0.1.3" + fast-levenshtein "^2.0.6" + levn "^0.4.1" + prelude-ls "^1.2.1" + type-check "^0.4.0" + word-wrap "^1.2.3" + os-browserify@^0.3.0: version "0.3.0" resolved "https://registry.npmjs.org/os-browserify/-/os-browserify-0.3.0.tgz" @@ -3546,6 +3934,13 @@ p-limit@^2.0.0, p-limit@^2.2.0: dependencies: p-try "^2.0.0" +p-limit@^3.0.2: + version "3.1.0" + resolved "https://registry.yarnpkg.com/p-limit/-/p-limit-3.1.0.tgz#e1daccbe78d0d1388ca18c64fea38e3e57e3706b" + integrity sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ== + dependencies: + yocto-queue "^0.1.0" + p-locate@^2.0.0: version "2.0.0" resolved "https://registry.npmjs.org/p-locate/-/p-locate-2.0.0.tgz" @@ -3567,6 +3962,13 @@ p-locate@^4.1.0: dependencies: p-limit "^2.2.0" +p-locate@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/p-locate/-/p-locate-5.0.0.tgz#83c8315c6785005e3bd021839411c9e110e6d834" + integrity sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw== + dependencies: + p-limit "^3.0.2" + p-try@^1.0.0: version "1.0.0" resolved "https://registry.npmjs.org/p-try/-/p-try-1.0.0.tgz" @@ -3579,7 +3981,7 @@ p-try@^2.0.0: pac-proxy-agent@^5.0.0: version "5.0.0" - resolved "https://registry.yarnpkg.com/pac-proxy-agent/-/pac-proxy-agent-5.0.0.tgz#b718f76475a6a5415c2efbe256c1c971c84f635e" + resolved "https://registry.npmjs.org/pac-proxy-agent/-/pac-proxy-agent-5.0.0.tgz" integrity sha512-CcFG3ZtnxO8McDigozwE3AqAw15zDvGH+OjXO4kzf7IkEKkQ4gxQ+3sdF50WmhQ4P/bVusXcqNE2S3XrNURwzQ== dependencies: "@tootallnate/once" "1" @@ -3594,7 +3996,7 @@ pac-proxy-agent@^5.0.0: pac-resolver@^5.0.0: version "5.0.0" - resolved "https://registry.yarnpkg.com/pac-resolver/-/pac-resolver-5.0.0.tgz#1d717a127b3d7a9407a16d6e1b012b13b9ba8dc0" + resolved "https://registry.npmjs.org/pac-resolver/-/pac-resolver-5.0.0.tgz" integrity sha512-H+/A6KitiHNNW+bxBKREk2MCGSxljfqRX76NjummWEYIat7ldVXRU3dhRIE3iXZ0nvGBk6smv3nntxKkzRL8NA== dependencies: degenerator "^3.0.1" @@ -3632,6 +4034,13 @@ param-case@^1.1.0: dependencies: sentence-case "^1.1.2" +parent-module@^1.0.0: + version "1.0.1" + resolved "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz" + integrity sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g== + dependencies: + callsites "^3.0.0" + parse-asn1@^5.0.0, parse-asn1@^5.1.5: version "5.1.6" resolved "https://registry.npmjs.org/parse-asn1/-/parse-asn1-5.1.6.tgz" @@ -3711,9 +4120,14 @@ path-key@^2.0.0, path-key@^2.0.1: resolved "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz" integrity sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A= +path-key@^3.1.0: + version "3.1.1" + resolved "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz" + integrity sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q== + path-parse@^1.0.6: version "1.0.7" - resolved "https://registry.yarnpkg.com/path-parse/-/path-parse-1.0.7.tgz#fbc114b60ca42b30d9daf5858e4bd68bbedb6735" + resolved "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz" integrity sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw== path-to-regexp@^1.7.0: @@ -3797,15 +4211,27 @@ posix-character-classes@^0.1.0: resolved "https://registry.npmjs.org/posix-character-classes/-/posix-character-classes-0.1.1.tgz" integrity sha1-AerA/jta9xoqbAL+q7jB/vfgDqs= +prelude-ls@^1.2.1: + version "1.2.1" + resolved "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz" + integrity sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g== + prelude-ls@~1.1.2: version "1.1.2" resolved "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz" integrity sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ= -prettier@^1.18.2: - version "1.19.1" - resolved "https://registry.npmjs.org/prettier/-/prettier-1.19.1.tgz" - integrity sha512-s7PoyDv/II1ObgQunCbB9PdLmUcBZcnWOcxDh7O0N/UwDEsHyqkW+Qh28jW+mVuCdx7gLB0BotYI1Y6uI9iyew== +prettier-linter-helpers@^1.0.0: + version "1.0.0" + resolved "https://registry.npmjs.org/prettier-linter-helpers/-/prettier-linter-helpers-1.0.0.tgz" + integrity sha512-GbK2cP9nraSSUF9N2XwUwqfzlAFlMNYYl+ShE/V+H8a9uNl/oUqB1w2EL54Jh0OlyRSd8RfWYJ3coVS4TROP2w== + dependencies: + fast-diff "^1.1.2" + +prettier@2.4.1: + version "2.4.1" + resolved "https://registry.yarnpkg.com/prettier/-/prettier-2.4.1.tgz#671e11c89c14a4cfc876ce564106c4a6726c9f5c" + integrity sha512-9fbDAXSBcc6Bs1mZrDYb3XKzDLm4EXXL9sC1LqKP5rZkT6KRr/rf9amVUcODVXgguK/isJz0d0hP72WeaKWsvA== pretty-quick@^1.11.1: version "1.11.1" @@ -3829,6 +4255,11 @@ process@^0.11.10: resolved "https://registry.npmjs.org/process/-/process-0.11.10.tgz" integrity sha1-czIwDoQBYb2j5podHZGn1LwW8YI= +progress@^2.0.0: + version "2.0.3" + resolved "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz" + integrity sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA== + promise-inflight@^1.0.1: version "1.0.1" resolved "https://registry.npmjs.org/promise-inflight/-/promise-inflight-1.0.1.tgz" @@ -3841,7 +4272,7 @@ propagate@^1.0.0: proxy-agent@^5.0.0: version "5.0.0" - resolved "https://registry.yarnpkg.com/proxy-agent/-/proxy-agent-5.0.0.tgz#d31405c10d6e8431fde96cba7a0c027ce01d633b" + resolved "https://registry.npmjs.org/proxy-agent/-/proxy-agent-5.0.0.tgz" integrity sha512-gkH7BkvLVkSfX9Dk27W6TyNOWWZWRilRfk1XxGNWOYJ2TuedAv1yFpCaU9QSBmBe716XOTNpYNOzhysyw8xn7g== dependencies: agent-base "^6.0.0" @@ -3858,9 +4289,9 @@ proxy-from-env@^1.0.0, proxy-from-env@^1.1.0: resolved "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz" integrity sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg== -proxyquire@^2.1.1: +proxyquire@^2.1.3: version "2.1.3" - resolved "https://registry.npmjs.org/proxyquire/-/proxyquire-2.1.3.tgz" + resolved "https://registry.yarnpkg.com/proxyquire/-/proxyquire-2.1.3.tgz#2049a7eefa10a9a953346a18e54aab2b4268df39" integrity sha512-BQWfCqYM+QINd+yawJz23tbBM40VIGXOdDw3X344KcclI/gtBbdWF6SlQ4nK/bYhF9d27KYug9WzljHC6B9Ysg== dependencies: fill-keys "^1.0.2" @@ -4044,6 +4475,13 @@ readdirp@~3.5.0: dependencies: picomatch "^2.2.1" +readdirp@~3.6.0: + version "3.6.0" + resolved "https://registry.yarnpkg.com/readdirp/-/readdirp-3.6.0.tgz#74a370bd857116e245b29cc97340cd431a02a6c7" + integrity sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA== + dependencies: + picomatch "^2.2.1" + regex-not@^1.0.0, regex-not@^1.0.2: version "1.0.2" resolved "https://registry.npmjs.org/regex-not/-/regex-not-1.0.2.tgz" @@ -4060,6 +4498,16 @@ regexp.prototype.flags@^1.2.0: call-bind "^1.0.2" define-properties "^1.1.3" +regexpp@^3.0.0, regexpp@^3.1.0: + version "3.2.0" + resolved "https://registry.npmjs.org/regexpp/-/regexpp-3.2.0.tgz" + integrity sha512-pq2bWo9mVD43nbts2wGv17XLiNLya+GklZ8kaDLV2Z08gDCsGpnKn9BFMepvWuHCbyVvY7J5o5+BVvoQbmlJLg== + +regextras@^0.8.0: + version "0.8.0" + resolved "https://registry.yarnpkg.com/regextras/-/regextras-0.8.0.tgz#ec0f99853d4912839321172f608b544814b02217" + integrity sha512-k519uI04Z3SaY0fLX843MRXnDeG2+vHOFsyhiPZvNLe7r8rD2YNRjq4BQLZZ0oAr2NrtvZlICsXysGNFPGa3CQ== + release-zalgo@^1.0.0: version "1.0.0" resolved "https://registry.npmjs.org/release-zalgo/-/release-zalgo-1.0.0.tgz" @@ -4087,6 +4535,11 @@ require-directory@^2.1.1: resolved "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz" integrity sha1-jGStX9MNqxyXbiNE/+f3kqam30I= +require-from-string@^2.0.2: + version "2.0.2" + resolved "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz" + integrity sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw== + require-main-filename@^2.0.0: version "2.0.0" resolved "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz" @@ -4122,9 +4575,17 @@ resolve@^1.10.0, resolve@^1.11.1: is-core-module "^2.1.0" path-parse "^1.0.6" +resolve@^1.10.1: + version "1.20.0" + resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.20.0.tgz#629a013fb3f70755d6f0b7935cc1c2c5378b1975" + integrity sha512-wENBPt4ySzg4ybFQW2TT1zMQucPK95HSh/nq2CFTZVOGut2+pQvSsgtda4d26YrYcr067wjbmzOG8byDPBX63A== + dependencies: + is-core-module "^2.2.0" + path-parse "^1.0.6" + rest-facade@^1.13.1: version "1.13.1" - resolved "https://registry.yarnpkg.com/rest-facade/-/rest-facade-1.13.1.tgz#b0746011f6f4987eb3fe1f3ace3bfb7505288878" + resolved "https://registry.npmjs.org/rest-facade/-/rest-facade-1.13.1.tgz" integrity sha512-BrN31iNzBPuUmWvYntVbaKRx1CWen5q7FiDpOXd0i4LaP3aWyAc4FO3CztAFvNeDMQbWRzbmVZDsmlvk+Kbe2g== dependencies: change-case "^2.3.0" @@ -4140,7 +4601,7 @@ ret@~0.1.10: retry@^0.13.1: version "0.13.1" - resolved "https://registry.yarnpkg.com/retry/-/retry-0.13.1.tgz#185b1587acf67919d63b357349e03537b2484658" + resolved "https://registry.npmjs.org/retry/-/retry-0.13.1.tgz" integrity sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg== rimraf@^2.5.4, rimraf@^2.6.2, rimraf@^2.6.3: @@ -4150,6 +4611,13 @@ rimraf@^2.5.4, rimraf@^2.6.2, rimraf@^2.6.3: dependencies: glob "^7.1.3" +rimraf@^3.0.2: + version "3.0.2" + resolved "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz" + integrity sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA== + dependencies: + glob "^7.1.3" + ripemd160@^2.0.0, ripemd160@^2.0.1: version "2.0.2" resolved "https://registry.npmjs.org/ripemd160/-/ripemd160-2.0.2.tgz" @@ -4206,16 +4674,23 @@ semver-compare@^1.0.0: resolved "https://registry.npmjs.org/semver-compare/-/semver-compare-1.0.0.tgz" integrity sha1-De4hahyUGrN+nvsXiPavxf9VN/w= -"semver@2 || 3 || 4 || 5", semver@^5.5.0, semver@^5.6.0, semver@^5.7.0: +"semver@2 || 3 || 4 || 5", semver@^5.5.0, semver@^5.6.0: version "5.7.1" resolved "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz" integrity sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ== -semver@^6.0.0: +semver@^6.0.0, semver@^6.1.0: version "6.3.0" resolved "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz" integrity sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw== +semver@^7.2.1, semver@^7.3.5: + version "7.3.5" + resolved "https://registry.npmjs.org/semver/-/semver-7.3.5.tgz" + integrity sha512-PoeGJYh8HK4BTO/a9Tf6ZG3veo/A7ZVsYrSA6J8ny9nb3B1VrpkuN+z9OE5wfE5p6H4LchYZsegiQgbJD94ZFQ== + dependencies: + lru-cache "^6.0.0" + semver@^7.3.2: version "7.3.4" resolved "https://registry.npmjs.org/semver/-/semver-7.3.4.tgz" @@ -4230,6 +4705,13 @@ sentence-case@^1.1.1, sentence-case@^1.1.2: dependencies: lower-case "^1.1.1" +serialize-javascript@6.0.0: + version "6.0.0" + resolved "https://registry.yarnpkg.com/serialize-javascript/-/serialize-javascript-6.0.0.tgz#efae5d88f45d7924141da8b5c3a7a7e663fefeb8" + integrity sha512-Qr3TosvguFt8ePWqsvRfrKyQXIiW+nGbYpy8XK24NQHE83caxWt+mIymTT19DGFbNWNLfEwsrkSmN64lVWB9ag== + dependencies: + randombytes "^2.1.0" + serialize-javascript@^4.0.0: version "4.0.0" resolved "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-4.0.0.tgz" @@ -4277,34 +4759,54 @@ shebang-command@^1.2.0: dependencies: shebang-regex "^1.0.0" +shebang-command@^2.0.0: + version "2.0.0" + resolved "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz" + integrity sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA== + dependencies: + shebang-regex "^3.0.0" + shebang-regex@^1.0.0: version "1.0.0" resolved "https://registry.npmjs.org/shebang-regex/-/shebang-regex-1.0.0.tgz" integrity sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM= +shebang-regex@^3.0.0: + version "3.0.0" + resolved "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz" + integrity sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A== + signal-exit@^3.0.0, signal-exit@^3.0.2: version "3.0.3" resolved "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.3.tgz" integrity sha512-VUJ49FC8U1OxwZLxIbTTrDvLnf/6TDgxZcK8wxR8zs13xpx7xbG60ndBlhNrFi2EMuFRoeDoJO7wthSLq42EjA== -sinon@^9.0.3: - version "9.2.1" - resolved "https://registry.npmjs.org/sinon/-/sinon-9.2.1.tgz" - integrity sha512-naPfsamB5KEE1aiioaoqJ6MEhdUs/2vtI5w1hPAXX/UwvoPjXcwh1m5HiKx0HGgKR8lQSoFIgY5jM6KK8VrS9w== - dependencies: - "@sinonjs/commons" "^1.8.1" - "@sinonjs/fake-timers" "^6.0.1" - "@sinonjs/formatio" "^5.0.1" - "@sinonjs/samsam" "^5.2.0" - diff "^4.0.2" - nise "^4.0.4" - supports-color "^7.1.0" +sinon@^11.1.2: + version "11.1.2" + resolved "https://registry.npmjs.org/sinon/-/sinon-11.1.2.tgz" + integrity sha512-59237HChms4kg7/sXhiRcUzdSkKuydDeTiamT/jesUVHshBgL8XAmhgFo0GfK6RruMDM/iRSij1EybmMog9cJw== + dependencies: + "@sinonjs/commons" "^1.8.3" + "@sinonjs/fake-timers" "^7.1.2" + "@sinonjs/samsam" "^6.0.2" + diff "^5.0.0" + nise "^5.1.0" + supports-color "^7.2.0" slash@^3.0.0: version "3.0.0" resolved "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz" integrity sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q== +slice-ansi@^4.0.0: + version "4.0.0" + resolved "https://registry.npmjs.org/slice-ansi/-/slice-ansi-4.0.0.tgz" + integrity sha512-qMCMfhY040cVHT43K9BFygqYbUPFZKHOg7K73mtTWJRb8pyP3fzf4Ixd5SzdEJQ6MRUg/WBnOLxghZtKKurENQ== + dependencies: + ansi-styles "^4.0.0" + astral-regex "^2.0.0" + is-fullwidth-code-point "^3.0.0" + smart-buffer@^4.1.0: version "4.1.0" resolved "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.1.0.tgz" @@ -4435,7 +4937,7 @@ spdx-exceptions@^2.1.0: resolved "https://registry.npmjs.org/spdx-exceptions/-/spdx-exceptions-2.3.0.tgz" integrity sha512-/tTrYOC7PPI1nUAgx34hUpqXuyJG+DTHJTnIULG4rDygi4xu/tfgmq1e1cIRwRzwZgo4NLySi+ricLkZkw4i5A== -spdx-expression-parse@^3.0.0: +spdx-expression-parse@^3.0.0, spdx-expression-parse@^3.0.1: version "3.0.1" resolved "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-3.0.1.tgz" integrity sha512-cbqHunsQWnJNE6KhVSMsMeH5H/L9EpymbzqTQ3uLwNCLZ1Q481oWaofqH7nO6V07xlXwY6PhQdQ2IedWx/ZK4Q== @@ -4531,14 +5033,6 @@ string-replace-webpack-plugin@0.1.3: file-loader "^0.8.1" style-loader "^0.8.3" -"string-width@^1.0.2 || 2": - version "2.1.1" - resolved "https://registry.npmjs.org/string-width/-/string-width-2.1.1.tgz" - integrity sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw== - dependencies: - is-fullwidth-code-point "^2.0.0" - strip-ansi "^4.0.0" - string-width@^3.0.0, string-width@^3.1.0: version "3.1.0" resolved "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz" @@ -4548,21 +5042,14 @@ string-width@^3.0.0, string-width@^3.1.0: is-fullwidth-code-point "^2.0.0" strip-ansi "^5.1.0" -string.prototype.trimend@^1.0.1: - version "1.0.3" - resolved "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.3.tgz" - integrity sha512-ayH0pB+uf0U28CtjlLvL7NaohvR1amUvVZk+y3DYb0Ey2PUV5zPkkKy9+U1ndVEIXO8hNg18eIv9Jntbii+dKw== - dependencies: - call-bind "^1.0.0" - define-properties "^1.1.3" - -string.prototype.trimstart@^1.0.1: - version "1.0.3" - resolved "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.3.tgz" - integrity sha512-oBIBUy5lea5tt0ovtOFiEQaBkoBBkyJhZXzJYrSmDo5IUUqbOPvVezuRs/agBIdZ2p2Eo1FD6bD9USyBLfl3xg== +string-width@^4.1.0, string-width@^4.2.0, string-width@^4.2.3: + version "4.2.3" + resolved "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz" + integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g== dependencies: - call-bind "^1.0.0" - define-properties "^1.1.3" + emoji-regex "^8.0.0" + is-fullwidth-code-point "^3.0.0" + strip-ansi "^6.0.1" string_decoder@^1.0.0, string_decoder@^1.1.1: version "1.3.0" @@ -4597,6 +5084,13 @@ strip-ansi@^5.0.0, strip-ansi@^5.1.0, strip-ansi@^5.2.0: dependencies: ansi-regex "^4.1.0" +strip-ansi@^6.0.0, strip-ansi@^6.0.1: + version "6.0.1" + resolved "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz" + integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A== + dependencies: + ansi-regex "^5.0.1" + strip-bom@^3.0.0: version "3.0.0" resolved "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz" @@ -4607,12 +5101,7 @@ strip-eof@^1.0.0: resolved "https://registry.npmjs.org/strip-eof/-/strip-eof-1.0.0.tgz" integrity sha1-u0P/VZim6wXYm1n80SnJgzE2Br8= -strip-json-comments@2.0.1: - version "2.0.1" - resolved "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz" - integrity sha1-PFMZQukIwml8DsNEhYwobHygpgo= - -strip-json-comments@^3.1.0: +strip-json-comments@3.1.1, strip-json-comments@^3.1.0, strip-json-comments@^3.1.1: version "3.1.1" resolved "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz" integrity sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig== @@ -4631,7 +5120,7 @@ style-loader@^0.8.3: superagent-proxy@^3.0.0: version "3.0.0" - resolved "https://registry.yarnpkg.com/superagent-proxy/-/superagent-proxy-3.0.0.tgz#e1a17ccba25883599e18d2974020fe83ee7d95d1" + resolved "https://registry.npmjs.org/superagent-proxy/-/superagent-proxy-3.0.0.tgz" integrity sha512-wAlRInOeDFyd9pyonrkJspdRAxdLrcsZ6aSnS+8+nu4x1aXbz6FWSTT9M6Ibze+eG60szlL7JA8wEIV7bPWuyQ== dependencies: debug "^4.3.2" @@ -4654,12 +5143,12 @@ superagent@^5.1.1: readable-stream "^3.6.0" semver "^7.3.2" -supports-color@6.0.0: - version "6.0.0" - resolved "https://registry.npmjs.org/supports-color/-/supports-color-6.0.0.tgz" - integrity sha512-on9Kwidc1IUQo+bQdhi8+Tijpo0e1SS6RoGo2guUwn5vdaxw8RXOF9Vb2ws+ihWOmh4JnCJOvaziZWP1VABaLg== +supports-color@8.1.1: + version "8.1.1" + resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-8.1.1.tgz#cd6fc17e28500cff56c1b86c0a7fd4a54a73005c" + integrity sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q== dependencies: - has-flag "^3.0.0" + has-flag "^4.0.0" supports-color@^5.3.0: version "5.5.0" @@ -4675,7 +5164,7 @@ supports-color@^6.1.0: dependencies: has-flag "^3.0.0" -supports-color@^7.1.0: +supports-color@^7.1.0, supports-color@^7.2.0: version "7.2.0" resolved "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz" integrity sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw== @@ -4690,6 +5179,18 @@ swap-case@^1.1.0: lower-case "^1.1.1" upper-case "^1.1.1" +table@^6.0.9: + version "6.7.2" + resolved "https://registry.npmjs.org/table/-/table-6.7.2.tgz" + integrity sha512-UFZK67uvyNivLeQbVtkiUs8Uuuxv24aSL4/Vil2PJVtMgU8Lx0CYkP12uCGa3kjyQzOSgV1+z9Wkb82fCGsO0g== + dependencies: + ajv "^8.0.1" + lodash.clonedeep "^4.5.0" + lodash.truncate "^4.4.2" + slice-ansi "^4.0.0" + string-width "^4.2.3" + strip-ansi "^6.0.1" + taffydb@2.6.2: version "2.6.2" resolved "https://registry.npmjs.org/taffydb/-/taffydb-2.6.2.tgz" @@ -4745,6 +5246,11 @@ test-exclude@^5.2.3: read-pkg-up "^4.0.0" require-main-filename "^2.0.0" +text-table@^0.2.0: + version "0.2.0" + resolved "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz" + integrity sha1-f17oI66AUgfACvLfSoTsP8+lcLQ= + through2@^2.0.0: version "2.0.5" resolved "https://registry.npmjs.org/through2/-/through2-2.0.5.tgz" @@ -4830,6 +5336,13 @@ tty-browserify@0.0.0: resolved "https://registry.npmjs.org/tty-browserify/-/tty-browserify-0.0.0.tgz" integrity sha1-oVe6QC2iTpv5V/mqadUk7tQpAaY= +type-check@^0.4.0, type-check@~0.4.0: + version "0.4.0" + resolved "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz" + integrity sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew== + dependencies: + prelude-ls "^1.2.1" + type-check@~0.3.2: version "0.3.2" resolved "https://registry.npmjs.org/type-check/-/type-check-0.3.2.tgz" @@ -4842,6 +5355,11 @@ type-detect@4.0.8, type-detect@^4.0.0, type-detect@^4.0.5, type-detect@^4.0.8: resolved "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz" integrity sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g== +type-fest@^0.20.2: + version "0.20.2" + resolved "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz" + integrity sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ== + type-fest@^0.6.0: version "0.6.0" resolved "https://registry.npmjs.org/type-fest/-/type-fest-0.6.0.tgz" @@ -4975,6 +5493,11 @@ uuid@^3.3.2: resolved "https://registry.npmjs.org/uuid/-/uuid-3.4.0.tgz" integrity sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A== +v8-compile-cache@^2.0.3: + version "2.3.0" + resolved "https://registry.npmjs.org/v8-compile-cache/-/v8-compile-cache-2.3.0.tgz" + integrity sha512-l8lCEmLcLYZh4nbunNZvQCJc5pv7+RCwa8q/LdUx8u7lsWvPDKmpodJAJNwkAhJC//dFY48KuIEmjtd4RViDrA== + validate-npm-package-license@^3.0.1: version "3.0.4" resolved "https://registry.npmjs.org/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz" @@ -4990,7 +5513,7 @@ vm-browserify@^1.0.1: vm2@^3.9.3: version "3.9.3" - resolved "https://registry.yarnpkg.com/vm2/-/vm2-3.9.3.tgz#29917f6cc081cc43a3f580c26c5b553fd3c91f40" + resolved "https://registry.npmjs.org/vm2/-/vm2-3.9.3.tgz" integrity sha512-smLS+18RjXYMl9joyJxMNI9l4w7biW8ilSDaVRvFBDwOH8P0BK1ognFQTpg0wyQ6wIKLTblHJvROW692L/E53Q== watchpack-chokidar2@^2.0.1: @@ -5053,28 +5576,21 @@ which-module@^2.0.0: resolved "https://registry.npmjs.org/which-module/-/which-module-2.0.0.tgz" integrity sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho= -which@1.3.1, which@^1.2.9, which@^1.3.0: - version "1.3.1" - resolved "https://registry.npmjs.org/which/-/which-1.3.1.tgz" - integrity sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ== - dependencies: - isexe "^2.0.0" - -which@^2.0.2: +which@2.0.2, which@^2.0.1, which@^2.0.2: version "2.0.2" resolved "https://registry.npmjs.org/which/-/which-2.0.2.tgz" integrity sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA== dependencies: isexe "^2.0.0" -wide-align@1.1.3: - version "1.1.3" - resolved "https://registry.npmjs.org/wide-align/-/wide-align-1.1.3.tgz" - integrity sha512-QGkOQc8XL6Bt5PwnsExKBPuMKBxnGxWWW3fU55Xt4feHozMUhdUMaBCk290qpm/wG5u/RSKzwdAC4i51YigihA== +which@^1.2.9, which@^1.3.0: + version "1.3.1" + resolved "https://registry.npmjs.org/which/-/which-1.3.1.tgz" + integrity sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ== dependencies: - string-width "^1.0.2 || 2" + isexe "^2.0.0" -word-wrap@~1.2.3: +word-wrap@^1.2.3, word-wrap@~1.2.3: version "1.2.3" resolved "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.3.tgz" integrity sha512-Hz/mrNwitNRh/HUAtM/VT/5VH+ygD6DV7mYKZAtHOrbs8U7lvPS6xf7EJKMF0uW1KJCl0H701g3ZGus+muE5vQ== @@ -5086,6 +5602,11 @@ worker-farm@^1.7.0: dependencies: errno "~0.1.7" +workerpool@6.1.5: + version "6.1.5" + resolved "https://registry.yarnpkg.com/workerpool/-/workerpool-6.1.5.tgz#0f7cf076b6215fd7e1da903ff6f22ddd1886b581" + integrity sha512-XdKkCK0Zqc6w3iTxLckiuJ81tiD/o5rBE/m+nXpRCB+/Sq4DqkfXZ/x0jW02DG1tGsfUGXbTJyZDP+eu67haSw== + wrap-ansi@^5.1.0: version "5.1.0" resolved "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-5.1.0.tgz" @@ -5095,6 +5616,15 @@ wrap-ansi@^5.1.0: string-width "^3.0.0" strip-ansi "^5.0.0" +wrap-ansi@^7.0.0: + version "7.0.0" + resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-7.0.0.tgz#67e145cff510a6a6984bdf1152911d69d2eb9e43" + integrity sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q== + dependencies: + ansi-styles "^4.0.0" + string-width "^4.1.0" + strip-ansi "^6.0.0" + wrappy@1: version "1.0.2" resolved "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz" @@ -5134,6 +5664,11 @@ y18n@^4.0.0: resolved "https://registry.npmjs.org/y18n/-/y18n-4.0.1.tgz" integrity sha512-wNcy4NvjMYL8gogWWYAO7ZFWFfHcbdbE57tZO8e4cbpj8tfUcwrwqSl3ad8HxpYWCdXcJUCeKKZS62Av1affwQ== +y18n@^5.0.5: + version "5.0.8" + resolved "https://registry.yarnpkg.com/y18n/-/y18n-5.0.8.tgz#7f4934d0f7ca8c56f95314939ddcd2dd91ce1d55" + integrity sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA== + yallist@^2.0.0: version "2.1.2" resolved "https://registry.npmjs.org/yallist/-/yallist-2.1.2.tgz" @@ -5149,7 +5684,12 @@ yallist@^4.0.0: resolved "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz" integrity sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A== -yargs-parser@13.1.2, yargs-parser@^13.0.0, yargs-parser@^13.1.2: +yargs-parser@20.2.4: + version "20.2.4" + resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-20.2.4.tgz#b42890f14566796f85ae8e3a25290d205f154a54" + integrity sha512-WOkpgNhPTlE73h4VFAFsOnomJVaovO8VqLDzy5saChRBFQFBoMYirowyW+Q9HB4HFF4Z7VZTiG3iSzJJA29yRA== + +yargs-parser@^13.0.0, yargs-parser@^13.1.2: version "13.1.2" resolved "https://registry.npmjs.org/yargs-parser/-/yargs-parser-13.1.2.tgz" integrity sha512-3lbsNRf/j+A4QuSZfDRA7HRSfWrzO0YjqTJd5kjAq37Zep1CEgaYmrH9Q3GwPiB9cHyd1Y1UwggGhJGoxipbzg== @@ -5157,16 +5697,35 @@ yargs-parser@13.1.2, yargs-parser@^13.0.0, yargs-parser@^13.1.2: camelcase "^5.0.0" decamelize "^1.2.0" -yargs-unparser@1.6.0: - version "1.6.0" - resolved "https://registry.npmjs.org/yargs-unparser/-/yargs-unparser-1.6.0.tgz" - integrity sha512-W9tKgmSn0DpSatfri0nx52Joq5hVXgeLiqR/5G0sZNDoLZFOr/xjBUDcShCOGNsBnEMNo1KAMBkTej1Hm62HTw== - dependencies: - flat "^4.1.0" - lodash "^4.17.15" - yargs "^13.3.0" +yargs-parser@^20.2.2: + version "20.2.9" + resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-20.2.9.tgz#2eb7dc3b0289718fc295f362753845c41a0c94ee" + integrity sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w== + +yargs-unparser@2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/yargs-unparser/-/yargs-unparser-2.0.0.tgz#f131f9226911ae5d9ad38c432fe809366c2325eb" + integrity sha512-7pRTIA9Qc1caZ0bZ6RYRGbHJthJWuakf+WmHK0rVeLkNrrGhfoabBNdue6kdINI6r4if7ocq9aD/n7xwKOdzOA== + dependencies: + camelcase "^6.0.0" + decamelize "^4.0.0" + flat "^5.0.2" + is-plain-obj "^2.1.0" + +yargs@16.2.0: + version "16.2.0" + resolved "https://registry.yarnpkg.com/yargs/-/yargs-16.2.0.tgz#1c82bf0f6b6a66eafce7ef30e376f49a12477f66" + integrity sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw== + dependencies: + cliui "^7.0.2" + escalade "^3.1.1" + get-caller-file "^2.0.5" + require-directory "^2.1.1" + string-width "^4.2.0" + y18n "^5.0.5" + yargs-parser "^20.2.2" -yargs@13.3.2, yargs@^13.2.2, yargs@^13.3.0: +yargs@^13.2.2: version "13.3.2" resolved "https://registry.npmjs.org/yargs/-/yargs-13.3.2.tgz" integrity sha512-AX3Zw5iPruN5ie6xGRIDgqkT+ZhnRlZMLMHAs8tg7nRruy2Nb+i5o9bwghAogtM08q1dpr2LVoS8KSTMYpWXUw== @@ -5181,3 +5740,8 @@ yargs@13.3.2, yargs@^13.2.2, yargs@^13.3.0: which-module "^2.0.0" y18n "^4.0.0" yargs-parser "^13.1.2" + +yocto-queue@^0.1.0: + version "0.1.0" + resolved "https://registry.yarnpkg.com/yocto-queue/-/yocto-queue-0.1.0.tgz#0294eb3dee05028d31ee1a5fa2c556a6aaf10a1b" + integrity sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q== From 54f8c97ec341f462ba7ec808b19dd13ed14e5ad6 Mon Sep 17 00:00:00 2001 From: hornta Date: Mon, 4 Oct 2021 16:18:39 +0200 Subject: [PATCH 02/22] Refactored ConnectionsManager to class --- src/management/ConnectionsManager.js | 408 +++++++++++++++------------ test/management/connections.tests.js | 61 +++- 2 files changed, 280 insertions(+), 189 deletions(-) diff --git a/src/management/ConnectionsManager.js b/src/management/ConnectionsManager.js index f486bbc69..d157aa216 100644 --- a/src/management/ConnectionsManager.js +++ b/src/management/ConnectionsManager.js @@ -1,214 +1,258 @@ const { ArgumentError } = require('rest-facade'); -const utils = require('../utils'); const Auth0RestClient = require('../Auth0RestClient'); const RetryRestClient = require('../RetryRestClient'); /** - * @class ConnectionsManager * Represents the relationship between Auth0 and an Identity provider. - * @class - * @memberof module:management - * @param {object} options The client options. - * @param {string} options.baseUrl The URL of the API. - * @param {object} [options.headers] Headers to be included in all requests. - * @param {object} [options.retry] Retry Policy Config */ -const ConnectionsManager = function (options) { - if (options === null || typeof options !== 'object') { - throw new ArgumentError('Must provide client options'); - } +class ConnectionsManager { + /** + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config + */ + constructor(options) { + if (options === null || typeof options !== 'object') { + throw new ArgumentError('Must provide client options'); + } - if (options.baseUrl === null || options.baseUrl === undefined) { - throw new ArgumentError('Must provide a base URL for the API'); - } + if (options.baseUrl === null || options.baseUrl === undefined) { + throw new ArgumentError('Must provide a base URL for the API'); + } + + if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { + throw new ArgumentError('The provided base URL is invalid'); + } + + /** + * Options object for the Rest Client instance. + * + * @type {object} + */ + const clientOptions = { + headers: options.headers, + query: { repeatParams: false }, + }; + + /** + * Provides an abstraction layer for performing CRUD operations on + * {@link https://auth0.com/docs/api/v2#!/ConnectionsManagers Auth0 + * Connections}. + * + * @type {external:RestClient} + */ + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/connections/:id `, + clientOptions, + options.tokenProvider + ); + this.resource = new RetryRestClient(auth0RestClient, options.retry); - if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { - throw new ArgumentError('The provided base URL is invalid'); + const statusClient = new Auth0RestClient( + `${options.baseUrl}/connections/:id/status`, + clientOptions, + options.tokenProvider + ); + this.status = new RetryRestClient(statusClient, options.retry); + + /** + * Provides an abstraction layer for consuming the + * {@link https://auth0.com/docs/api/management/v2#!/Connections/delete_users_by_email + * endpoint}. + * + * @type {external:RestClient} + */ + const userAuth0RestClient = new Auth0RestClient( + `${options.baseUrl}/connections/:id/users`, + clientOptions, + options.tokenProvider + ); + this.user = new RetryRestClient(userAuth0RestClient, options.retry); } /** - * Options object for the Rest Client instance. + * Create a new connection. + * + * @function create + * @memberof module:management.ConnectionsManager.prototype + * @example + * management.connections.create(data, function (err) { + * if (err) { + * // Handle error. + * } * - * @type {object} + * // Connection created. + * }); + * @param {object} data Connection data object. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const clientOptions = { - headers: options.headers, - query: { repeatParams: false }, - }; + create(...args) { + return this.resource.create(...args); + } /** - * Provides an abstraction layer for performing CRUD operations on - * {@link https://auth0.com/docs/api/v2#!/ConnectionsManagers Auth0 - * Connections}. + * Get all connections. * - * @type {external:RestClient} + * @function getAll + * @memberof module:management.ConnectionsManager.prototype + * @example + * This method takes an optional object as first argument that may be used to + * specify pagination settings. If pagination options are not present, + * the first page of a limited number of results will be returned. + * + * + * // Pagination settings. + * var params = { + * per_page: 10, + * page: 0 + * }; + * + * management.connections.getAll(params, function (err, connections) { + * console.log(connections.length); + * }); + * @param {object} [params] Connections params. + * @param {number} [params.per_page] Number of results per page. + * @param {number} [params.page] Page number, zero indexed. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const auth0RestClient = new Auth0RestClient( - `${options.baseUrl}/connections/:id `, - clientOptions, - options.tokenProvider - ); - this.resource = new RetryRestClient(auth0RestClient, options.retry); + getAll(...args) { + return this.resource.getAll(...args); + } /** - * Provides an abstraction layer for consuming the - * {@link https://auth0.com/docs/api/management/v2#!/Connections/delete_users_by_email - * endpoint}. + * Get an Auth0 connection. * - * @type {external:RestClient} + * @function get + * @memberof module:management.ConnectionsManager.prototype + * @example + * management.connections.get({ id: CONNECTION_ID }, function (err, connection) { + * if (err) { + * // Handle error. + * } + * + * console.log(connection); + * }); + * @param {object} params Connection parameters. + * @param {string} params.id Connection ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const userAuth0RestClient = new Auth0RestClient( - `${options.baseUrl}/connections/:id/users`, - clientOptions, - options.tokenProvider - ); - this.user = new RetryRestClient(userAuth0RestClient, options.retry); -}; - -/** - * Create a new connection. - * - * @function create - * @memberof module:management.ConnectionsManager.prototype - * @example - * management.connections.create(data, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Connection created. - * }); - * @param {object} data Connection data object. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ConnectionsManager, 'create', 'resource.create'); + get(...args) { + return this.resource.get(...args); + } -/** - * Get all connections. - * - * @function getAll - * @memberof module:management.ConnectionsManager.prototype - * @example - * This method takes an optional object as first argument that may be used to - * specify pagination settings. If pagination options are not present, - * the first page of a limited number of results will be returned. - * - * - * // Pagination settings. - * var params = { - * per_page: 10, - * page: 0 - * }; - * - * management.connections.getAll(params, function (err, connections) { - * console.log(connections.length); - * }); - * @param {object} [params] Connections params. - * @param {number} [params.per_page] Number of results per page. - * @param {number} [params.page] Page number, zero indexed. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ConnectionsManager, 'getAll', 'resource.getAll'); + /** + * Update an existing connection. + * + * @function update + * @memberof module:management.ConnectionsManager.prototype + * @example + * var data = { name: 'newConnectionName' }; + * var params = { id: CONNECTION_ID }; + * + * management.connections.update(params, data, function (err, connection) { + * if (err) { + * // Handle error. + * } + * + * console.log(connection.name); // 'newConnectionName' + * }); + * @param {object} params Connection parameters. + * @param {string} params.id Connection ID. + * @param {object} data Updated connection data. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + update(...args) { + return this.resource.patch(...args); + } -/** - * Get an Auth0 connection. - * - * @function get - * @memberof module:management.ConnectionsManager.prototype - * @example - * management.connections.get({ id: CONNECTION_ID }, function (err, connection) { - * if (err) { - * // Handle error. - * } - * - * console.log(connection); - * }); - * @param {object} params Connection parameters. - * @param {string} params.id Connection ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ConnectionsManager, 'get', 'resource.get'); + /** + * Delete an existing connection. + * + * @function delete + * @memberof module:management.ConnectionsManager.prototype + * @example + * management.connections.delete({ id: CONNECTION_ID }, function (err) { + * if (err) { + * // Handle error. + * } + * + * // Connection deleted. + * }); + * @param {object} params Connection parameters. + * @param {string} params.id Connection ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + delete(...args) { + return this.resource.delete(...args); + } -/** - * Update an existing connection. - * - * @function update - * @memberof module:management.ConnectionsManager.prototype - * @example - * var data = { name: 'newConnectionName' }; - * var params = { id: CONNECTION_ID }; - * - * management.connections.update(params, data, function (err, connection) { - * if (err) { - * // Handle error. - * } - * - * console.log(connection.name); // 'newConnectionName' - * }); - * @param {object} params Connection parameters. - * @param {string} params.id Connection ID. - * @param {object} data Updated connection data. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ConnectionsManager, 'update', 'resource.patch'); + /** + * Checks the status of an ad/ldap connection referenced by its ID. + * + * @function checkStatus + * @memberOf module:management.OrganizationsManager.prototype + * @example + * var params = {id : 'CONNECTION_ID'} + * @example + * This methods takes the connection ID and returns the status when online, or an error when offline. + * + * + * management.connections.checkStatus( {id : 'CONNECTION_ID'}, function (err, status) { + * if (err) { + * console.log('OFFLINE', err); + * } else { + * console.log('ONLINE', status); + * } + * }); + * @param {object} params Connection parameters + * @param {string} params.id ID of the Connection. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + checkStatus(...args) { + return this.status.get(...args); + } -/** - * Delete an existing connection. - * - * @function delete - * @memberof module:management.ConnectionsManager.prototype - * @example - * management.connections.delete({ id: CONNECTION_ID }, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Connection deleted. - * }); - * @param {object} params Connection parameters. - * @param {string} params.id Connection ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ConnectionsManager, 'delete', 'resource.delete'); + /** + * Delete a connection user by email. + * + * @function delete + * @memberof module:management.ConnectionsManager.prototype + * @example + * management.connections.deleteUserByEmail({ id: CONNECTION_ID, email:USER_EMAIL }, function (err) { + * if (err) { + * // Handle error. + * } + * + * // User deleted. + * }); + * @param {object} params Connection parameters. + * @param {string} params.id Connection ID. + * @param {string} params.email User Email. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + deleteUserByEmail(params, cb) { + if (typeof params !== 'object' || typeof params.email !== 'string' || params.email.length < 1) { + throw new ArgumentError('You must provide an email for the deleteUserByEmail method'); + } -/** - * Delete a connection user by email. - * - * @function delete - * @memberof module:management.ConnectionsManager.prototype - * @example - * management.connections.deleteUserByEmail({ id: CONNECTION_ID, email:USER_EMAIL }, function (err) { - * if (err) { - * // Handle error. - * } - * - * // User deleted. - * }); - * @param {object} params Connection parameters. - * @param {string} params.id Connection ID. - * @param {string} params.email User Email. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -ConnectionsManager.prototype.deleteUserByEmail = function (params, cb) { - if (typeof params !== 'object' || typeof params.email !== 'string' || params.email.length < 1) { - throw new ArgumentError('You must provide an email for the deleteUserByEmail method'); - } + if (!params.id) { + throw new ArgumentError('The connection id cannot be null or undefined'); + } - if (!params.id) { - throw new ArgumentError('The connection id cannot be null or undefined'); - } + if (cb && cb instanceof Function) { + return this.user.delete(params, {}, cb); + } - if (cb && cb instanceof Function) { - return this.user.delete(params, {}, cb); + return this.user.delete(params, {}); } - - return this.user.delete(params, {}); -}; +} module.exports = ConnectionsManager; diff --git a/test/management/connections.tests.js b/test/management/connections.tests.js index 0a6b497be..39234304a 100644 --- a/test/management/connections.tests.js +++ b/test/management/connections.tests.js @@ -27,19 +27,21 @@ describe('ConnectionsManager', () => { describe('#constructor', () => { it('should error when no options are provided', () => { - expect(ConnectionsManager).to.throw(ArgumentError, 'Must provide client options'); + expect(() => { + new ConnectionsManager(); + }).to.throw(ArgumentError, 'Must provide client options'); }); it('should throw an error when no base URL is provided', () => { - const client = ConnectionsManager.bind(null, {}); - - expect(client).to.throw(ArgumentError, 'Must provide a base URL for the API'); + expect(() => { + new ConnectionsManager({}); + }).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); it('should throw an error when the base URL is invalid', () => { - const client = ConnectionsManager.bind(null, { baseUrl: '' }); - - expect(client).to.throw(ArgumentError, 'The provided base URL is invalid'); + expect(() => { + new ConnectionsManager({ baseUrl: '' }); + }).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); @@ -417,6 +419,51 @@ describe('ConnectionsManager', () => { }); }); + describe('#checkStatus', () => { + const params = { id: 5 }; + const data = { + id: params.id, + name: 'Test connection', + }; + + beforeEach(function () { + this.request = nock(API_URL).get(`/connections/${data.id}/status`).reply(200); + }); + + it('should accept a callback', function (done) { + this.connections.checkStatus(params, () => { + done(); + }); + }); + + it('should return a promise if no callback is given', function (done) { + this.connections.checkStatus(params).then(done.bind(null, null)).catch(done.bind(null, null)); + }); + + it('should report success', function (done) { + nock.cleanAll(); + + nock(API_URL).get(`/connections/${params.id}/status`).reply(200); + + this.connections.checkStatus(params).then((response) => { + expect(response).to.exist; + done(); + }); + }); + + it('should report failure', function (done) { + nock.cleanAll(); + + nock(API_URL).get(`/connections/${params.id}/status`).reply(500); + + this.connections.checkStatus(params).catch((err) => { + expect(err).to.exist; + + done(); + }); + }); + }); + describe('#delete user', () => { const id = 5; const email = 'user@domain.com'; From 3da4f1c7087849a4ea881be5d22cff9ff5294c3e Mon Sep 17 00:00:00 2001 From: hornta Date: Mon, 4 Oct 2021 17:56:38 +0200 Subject: [PATCH 03/22] Got rid of dependency on es6-promisify by using the native Promise object. --- package.json | 1 - yarn.lock | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/package.json b/package.json index 27c14d820..176de67ae 100644 --- a/package.json +++ b/package.json @@ -34,7 +34,6 @@ "homepage": "https://github.com/auth0/node-auth0", "dependencies": { "axios": "^0.21.4", - "es6-promisify": "^6.1.1", "form-data": "^3.0.1", "jsonwebtoken": "^8.5.1", "jwks-rsa": "^1.12.1", diff --git a/yarn.lock b/yarn.lock index de1749edd..cf56cd3c2 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1701,7 +1701,7 @@ es6-error@^4.0.1: resolved "https://registry.npmjs.org/es6-error/-/es6-error-4.1.1.tgz" integrity sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg== -es6-promisify@^6.0.0, es6-promisify@^6.1.1: +es6-promisify@^6.0.0: version "6.1.1" resolved "https://registry.npmjs.org/es6-promisify/-/es6-promisify-6.1.1.tgz" integrity sha512-HBL8I3mIki5C1Cc9QjKUenHtnG0A5/xA8Q/AllRcfiwl2CZFXGK7ddBiCoRwAix4i2KxcQfjtIVcrVbB3vbmwg== From 6befd385d838f06278e94f5343c55abbf37d45cc Mon Sep 17 00:00:00 2001 From: hornta Date: Tue, 5 Oct 2021 01:10:49 +0200 Subject: [PATCH 04/22] Upgrade docker node image to 12 --- .circleci/config.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 3e5a2c46b..5cb1ce065 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -4,7 +4,7 @@ orbs: jobs: build-and-test: docker: - - image: circleci/node:10 + - image: circleci/node:12 environment: LANG: en_US.UTF-8 steps: @@ -14,6 +14,9 @@ jobs: command: 'sudo npm update -g yarn' - ship/node-install-packages: pkg-manager: yarn + - run: + name: ESLint + command: yarn lint - run: name: Check command: yarn check From b1c1639b6603ad3761ea25ea11f55d3e913fda5d Mon Sep 17 00:00:00 2001 From: hornta Date: Tue, 5 Oct 2021 01:11:24 +0200 Subject: [PATCH 05/22] Add some linting to aid in working with promises --- .eslintrc.js | 1 + package.json | 4 +++- yarn.lock | 5 +++++ 3 files changed, 9 insertions(+), 1 deletion(-) diff --git a/.eslintrc.js b/.eslintrc.js index 6a2bf37af..a57542893 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -9,6 +9,7 @@ module.exports = { 'eslint:recommended', 'plugin:jsdoc/recommended', 'plugin:node/recommended', + 'plugin:promise/recommended', 'plugin:prettier/recommended', ], plugins: ['jsdoc'], diff --git a/package.json b/package.json index 176de67ae..b62bfaf7d 100644 --- a/package.json +++ b/package.json @@ -16,7 +16,8 @@ "test:coverage": "codecov", "test:watch": "cross-env NODE_ENV=test mocha --timeout 5000 ./test/**/*.tests.js ./test/*.tests.js --watch", "jsdoc:generate": "jsdoc --configure .jsdoc.json --verbose", - "precommit": "pretty-quick --staged" + "precommit": "pretty-quick --staged", + "lint": "eslint ." }, "repository": { "type": "git", @@ -50,6 +51,7 @@ "eslint-plugin-jsdoc": "^36.1.0", "eslint-plugin-node": "^11.1.0", "eslint-plugin-prettier": "^4.0.0", + "eslint-plugin-promise": "^5.1.0", "husky": "^3.0.1", "jsdoc": "^3.6.3", "json-loader": "^0.5.7", diff --git a/yarn.lock b/yarn.lock index cf56cd3c2..d8b402005 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1785,6 +1785,11 @@ eslint-plugin-prettier@^4.0.0: dependencies: prettier-linter-helpers "^1.0.0" +eslint-plugin-promise@^5.1.0: + version "5.1.0" + resolved "https://registry.yarnpkg.com/eslint-plugin-promise/-/eslint-plugin-promise-5.1.0.tgz#fb2188fb734e4557993733b41aa1a688f46c6f24" + integrity sha512-NGmI6BH5L12pl7ScQHbg7tvtk4wPxxj8yPHH47NvSmMtFneC077PSeY3huFj06ZWZvtbfxSPt3RuOQD5XcR4ng== + eslint-scope@^4.0.3: version "4.0.3" resolved "https://registry.npmjs.org/eslint-scope/-/eslint-scope-4.0.3.tgz" From e222f3296e7ad1b06ce129ad3934072dd49859a2 Mon Sep 17 00:00:00 2001 From: hornta Date: Tue, 5 Oct 2021 10:39:44 +0200 Subject: [PATCH 06/22] Converted the remaining prototypes to classes --- .eslintrc.js | 1 + src/auth/DatabaseAuthenticator.js | 9 - src/auth/OAUthWithIDTokenValidation.js | 164 +- src/auth/OAuthAuthenticator.js | 11 - src/auth/PasswordlessAuthenticator.js | 6 - src/auth/TokensManager.js | 6 - src/auth/UsersManager.js | 4 - src/auth/index.js | 1021 ++- src/index.js | 2 +- src/management/ActionsManager.js | 39 - src/management/BlacklistedTokensManager.js | 4 - src/management/BrandingManager.js | 287 +- src/management/ClientGrantsManager.js | 257 +- src/management/ClientsManager.js | 284 +- src/management/ConnectionsManager.js | 14 - src/management/CustomDomainsManager.js | 276 +- src/management/DeviceCredentialsManager.js | 191 +- src/management/EmailProviderManager.js | 221 +- src/management/EmailTemplatesManager.js | 193 +- src/management/GrantsManager.js | 181 +- src/management/GuardianManager.js | 779 +-- src/management/HooksManager.js | 577 +- src/management/JobsManager.js | 640 +- src/management/LogStreamsManager.js | 278 +- src/management/LogsManager.js | 178 +- src/management/MigrationsManager.js | 159 +- src/management/OrganizationsManager.js | 1413 ++-- src/management/PromptsManager.js | 325 +- src/management/ResourceServersManager.js | 281 +- src/management/RolesManager.js | 661 +- src/management/RulesConfigsManager.js | 189 +- src/management/RulesManager.js | 309 +- src/management/StatsManager.js | 178 +- src/management/TenantManager.js | 4 - src/management/UserBlocksManager.js | 15 - src/management/UsersManager.js | 2 +- src/management/index.js | 6223 ++++++++--------- src/utils.js | 23 - test/auth/authentication-client.tests.js | 13 +- .../oauth-with-idtoken-validation.tests.js | 4 +- test/management/branding.tests.js | 16 +- test/management/client-grants.tests.js | 16 +- test/management/client.tests.js | 16 +- test/management/custom-domains.tests.js | 16 +- test/management/device-credentials.tests.js | 16 +- test/management/email-provider.tests.js | 16 +- test/management/email-templates.tests.js | 16 +- test/management/grants.tests.js | 16 +- test/management/guardian.tests.js | 16 +- test/management/hooks.tests.js | 16 +- test/management/jobs.tests.js | 16 +- test/management/log-streams.tests.js | 16 +- test/management/logs.tests.js | 16 +- test/management/management-client.tests.js | 52 +- .../management-token-provider.tests.js | 74 +- test/management/migrations.tests.js | 16 +- test/management/organizations.tests.js | 539 +- test/management/prompts.tests.js | 16 +- test/management/resource-servers.tests.js | 19 +- test/management/roles.tests.js | 16 +- test/management/rules-configs.tests.js | 16 +- test/management/rules.tests.js | 16 +- test/management/stats.tests.js | 16 +- test/management/users.tests.js | 1452 ++-- test/retry-rest-client.tests.js | 130 +- 65 files changed, 8767 insertions(+), 9225 deletions(-) diff --git a/.eslintrc.js b/.eslintrc.js index a57542893..88e4502bd 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -55,5 +55,6 @@ module.exports = { 'jsdoc/require-returns-description': 'off', 'jsdoc/no-undefined-types': 'off', 'jsdoc/require-param': 'off', + 'jsdoc/check-param-names': 'off', }, }; diff --git a/src/auth/DatabaseAuthenticator.js b/src/auth/DatabaseAuthenticator.js index 82fb5c853..cebb038a8 100644 --- a/src/auth/DatabaseAuthenticator.js +++ b/src/auth/DatabaseAuthenticator.js @@ -7,7 +7,6 @@ const RestClient = require('rest-facade').Client; */ class DatabaseAuthenticator { /** - * @memberof module:auth * @param {object} options Authenticator options. * @param {string} options.baseUrl The auth0 account URL. * @param {string} [options.clientId] Default client ID. @@ -40,8 +39,6 @@ class DatabaseAuthenticator { /** * Sign in using a database or active directory service. * - * @function signIn - * @memberof module:auth.DatabaseAuthenticator.prototype * @example * Given the user credentials and the connection specified, it will do the * authentication on the provider and return a JSON with the `access_token` @@ -94,8 +91,6 @@ class DatabaseAuthenticator { /** * Sign up using a database or active directory service. * - * @function signUp - * @memberof module:auth.DatabaseAuthenticator.prototype * @example * Given the user credentials, the connection specified and (optionally) the * client ID, it will create a new user. Find more information in the @@ -159,8 +154,6 @@ class DatabaseAuthenticator { /** * Change password using a database or active directory service. * - * @function changePassword - * @memberof module:auth.DatabaseAuthenticator.prototype * @example * Given the user email, the connection specified and the new password to * use, Auth0 will send a forgot password email. Once the user clicks on the @@ -226,8 +219,6 @@ class DatabaseAuthenticator { /** * Request a change password email using a database or active directory service. * - * @function requestChangePasswordEmail - * @memberof module:auth.DatabaseAuthenticator.prototype * @example * Given the user email, the connection specified, Auth0 will send a change * password email. once the user clicks on the confirm password change link, diff --git a/src/auth/OAUthWithIDTokenValidation.js b/src/auth/OAUthWithIDTokenValidation.js index 59caf7521..26913dddf 100644 --- a/src/auth/OAUthWithIDTokenValidation.js +++ b/src/auth/OAUthWithIDTokenValidation.js @@ -8,56 +8,52 @@ const HS256_IGNORE_VALIDATION_MESSAGE = /** * Abstracts the `oauth.create` method with additional id_token validation - * - * @param {object} oauth An instance of @type {OAuthAuthenticator} - * @param {object} options Authenticator options. - * @param {string} options.domain AuthenticationClient server domain - * @param {string} [options.clientId] Default client ID. - * @param {string} [options.clientSecret] Default client Secret. - * @param {string} [options.supportedAlgorithms] Algorithms that your application expects to receive - * @param {boolean} [options.__bypassIdTokenValidation] Whether the id_token should be validated or not - * @param {Function} [options.jwksClient] Dependency injected `jwks-rsa` */ -const OAUthWithIDTokenValidation = function (oauth, options) { - if (!oauth) { - throw new ArgumentError('Missing OAuthAuthenticator param'); - } +class OAUthWithIDTokenValidation { + /** + * @param {object} oauth An instance of @type {OAuthAuthenticator} + * @param {object} options Authenticator options. + * @param {string} options.domain AuthenticationClient server domain + * @param {string} [options.clientId] Default client ID. + * @param {string} [options.clientSecret] Default client Secret. + * @param {string} [options.supportedAlgorithms] Algorithms that your application expects to receive + * @param {boolean} [options.__bypassIdTokenValidation] Whether the id_token should be validated or not + * @param {Function} [options.jwksClient] Dependency injected `jwks-rsa` + */ + constructor(oauth, options) { + if (!oauth) { + throw new ArgumentError('Missing OAuthAuthenticator param'); + } - if (!options) { - throw new ArgumentError('Missing authenticator options'); - } + if (!options) { + throw new ArgumentError('Missing authenticator options'); + } - if (typeof options !== 'object') { - throw new ArgumentError('The authenticator options must be an object'); - } + if (typeof options !== 'object') { + throw new ArgumentError('The authenticator options must be an object'); + } - this.oauth = oauth; - this.__bypassIdTokenValidation = options.__bypassIdTokenValidation; - this.clientId = options.clientId; - this.clientSecret = options.clientSecret; - this.domain = options.domain; - this.supportedAlgorithms = options.supportedAlgorithms || ['HS256', 'RS256']; - this._jwksClient = (options.jwksClient || jwksClient)({ - jwksUri: `https://${options.domain}/.well-known/jwks.json`, - }); -}; + this.oauth = oauth; + this.__bypassIdTokenValidation = options.__bypassIdTokenValidation; + this.clientId = options.clientId; + this.clientSecret = options.clientSecret; + this.domain = options.domain; + this.supportedAlgorithms = options.supportedAlgorithms || ['HS256', 'RS256']; + this._jwksClient = (options.jwksClient || jwksClient)({ + jwksUri: `https://${options.domain}/.well-known/jwks.json`, + }); + } -/** - * Creates an oauth request and validates the id_token (if any) - * - * @function create - * @memberof module:auth.OAuthWithIDTokenValidation.prototype - * @param {object} params OAuth parameters that are passed through - * @param {object} data Custom parameters sent to the OAuth endpoint - * @param {Function} [cb] Callback function - * @returns {Promise|undefined} - */ -OAUthWithIDTokenValidation.prototype.create = function (params, data, cb) { - const _this = this; - const createAndValidate = this.oauth.create(params, data).then((r) => { - if (_this.__bypassIdTokenValidation) { - return r; - } + /** + * Creates an oauth request and validates the id_token (if any) + * + * @param {object} params OAuth parameters that are passed through + * @param {object} data Custom parameters sent to the OAuth endpoint + * @param {Function} [cb] Callback function + * @returns {Promise|undefined} + */ + create(params, data, cb) { + const _this = this; function getKey(header, callback) { if (header.alg === 'HS256') { if (!_this.clientSecret) { @@ -73,51 +69,57 @@ OAUthWithIDTokenValidation.prototype.create = function (params, data, cb) { return callback(null, signingKey); }); } - if (r.id_token) { - return new Promise((res, rej) => { - const options = { - algorithms: this.supportedAlgorithms, - audience: this.clientId, - issuer: `https://${this.domain}/`, - }; - - if (data.organization) { - options.organization = data.organization; - } + const createAndValidate = this.oauth.create(params, data).then((r) => { + if (_this.__bypassIdTokenValidation) { + return r; + } - if (data.nonce) { - options.nonce = data.nonce; - } + if (r.id_token) { + return new Promise((resolve, reject) => { + const options = { + algorithms: this.supportedAlgorithms, + audience: this.clientId, + issuer: `https://${this.domain}/`, + }; - if (data.maxAge) { - options.maxAge = data.maxAge; - } + if (data.organization) { + options.organization = data.organization; + } - jwt.verify(r.id_token, getKey, options, (err) => { - if (err) { - if (err.message && err.message.includes(HS256_IGNORE_VALIDATION_MESSAGE)) { - console.warn(HS256_IGNORE_VALIDATION_MESSAGE); - } else { - return rej(err); - } + if (data.nonce) { + options.nonce = data.nonce; } - try { - validateIdToken(r.id_token, options); - } catch (idTokenError) { - return rej(idTokenError); + if (data.maxAge) { + options.maxAge = data.maxAge; } - return res(r); + jwt.verify(r.id_token, getKey, options, (err) => { + if (err) { + if (err.message && err.message.includes(HS256_IGNORE_VALIDATION_MESSAGE)) { + console.warn(HS256_IGNORE_VALIDATION_MESSAGE); + } else { + return reject(err); + } + } + + try { + validateIdToken(r.id_token, options); + } catch (idTokenError) { + return reject(idTokenError); + } + + return resolve(r); + }); }); - }); + } + return r; + }); + if (!cb) { + return createAndValidate; } - return r; - }); - if (!cb) { - return createAndValidate; + createAndValidate.then((r) => cb(null, r)).catch((e) => cb(e)); } - createAndValidate.then((r) => cb(null, r)).catch((e) => cb(e)); -}; +} module.exports = OAUthWithIDTokenValidation; diff --git a/src/auth/OAuthAuthenticator.js b/src/auth/OAuthAuthenticator.js index 8a1414a9b..f3f981003 100644 --- a/src/auth/OAuthAuthenticator.js +++ b/src/auth/OAuthAuthenticator.js @@ -26,7 +26,6 @@ function getParamsFromOptions(options) { */ class OAuthAuthenticator { /** - * @memberof module:auth * @param {object} options Authenticator options. * @param {string} options.baseUrl The Auth0 account URL. * @param {string} options.domain AuthenticationClient server domain @@ -63,8 +62,6 @@ class OAuthAuthenticator { /** * Sign in using a username and password. * - * @function signIn - * @memberof module:auth.OAuthAuthenticator.prototype * @example * Given the user's credentials and the connection specified, it * will return a JSON with the access_token and id_token. @@ -134,8 +131,6 @@ class OAuthAuthenticator { /** * Sign in using a username and password * - * @function passwordGrant - * @memberof module:auth.OAuthAuthenticator.prototype * @example * Given the user's credentials perform the OAuth password grant * or Password Realm grant if a realm is provided, @@ -212,8 +207,6 @@ class OAuthAuthenticator { /** * Exchange a refresh token * - * @function refreshToken - * @memberof module:auth.OAuthAuthenticator.prototype * @example * Given a refresh token from a previous authentication request * it will return a JSON with the access_token and id_token if @@ -269,8 +262,6 @@ class OAuthAuthenticator { /** * Sign in using a social provider access token. * - * @function socialSignIn - * @memberof module:auth.OAuthAuthenticator.prototype * @param {object} data User credentials object. * @param {string} data.access_token User access token. * @param {string} data.connection Identity provider. @@ -335,8 +326,6 @@ class OAuthAuthenticator { /** * Sign in using an authorization code * - * @function authorizationCodeGrant - * @memberof module:auth.OAuthAuthenticator.prototype * @example * Given the code returned in the URL params after the redirect * from successful authentication, exchange the code for auth0 diff --git a/src/auth/PasswordlessAuthenticator.js b/src/auth/PasswordlessAuthenticator.js index 03c120739..c380e08ff 100644 --- a/src/auth/PasswordlessAuthenticator.js +++ b/src/auth/PasswordlessAuthenticator.js @@ -55,8 +55,6 @@ class PasswordlessAuthenticator { /** * Sign in with the given user credentials. * - * @function signIn - * @memberof module:auth.PasswordlessAuthenticator.prototype * @example * Once you have a verification code, use this endpoint to login * the user with their phone number/email and verification code. @@ -159,8 +157,6 @@ class PasswordlessAuthenticator { /** * Start passwordless flow sending an email. * - * @function sendEmail - * @memberof module:auth.PasswordlessAuthenticator.prototype * @example * Given the user `email` address, it will send an email with: * @@ -235,8 +231,6 @@ class PasswordlessAuthenticator { /** * Start passwordless flow sending an SMS. * - * @function sendSMS - * @memberof module:auth.PasswordlessAuthenticator.prototype * @example * Given the user `phone_number`, it will send a SMS message with a * verification code. You can then authenticate with this user using the diff --git a/src/auth/TokensManager.js b/src/auth/TokensManager.js index e554e718e..b7f4164ba 100644 --- a/src/auth/TokensManager.js +++ b/src/auth/TokensManager.js @@ -30,8 +30,6 @@ class TokensManager { /** * Given an ID token get the user profile linked to it. * - * @function getInfo - * @memberof module:auth.TokensManager.prototype * @example * Validates a JSON Web Token (signature and expiration) and returns the user * information associated with the user id (sub property) of the token. Find @@ -82,8 +80,6 @@ class TokensManager { * Exchange the token of the logged in user with a token that is valid to call * the API (signed with the API secret). * - * @function getDelegationToken - * @memberof module:auth.TokensManager.prototype * @example * Given an existing token, this endpoint will generate a new token signed * with the target client secret. This is used to flow the identity of the @@ -170,8 +166,6 @@ class TokensManager { /** * Proactively revoke an issued refresh token. * - * @function revokeRefreshToken - * @memberof module:auth.TokensManager.prototype * @example * Given an existing refresh token, this endpoint will revoke it in order * to prevent unauthorized silently user authentication tokens refresh. diff --git a/src/auth/UsersManager.js b/src/auth/UsersManager.js index d730ee661..2d2393b4d 100644 --- a/src/auth/UsersManager.js +++ b/src/auth/UsersManager.js @@ -29,8 +29,6 @@ class UsersManager { /** * Given an access token get the user profile linked to it. * - * @function getInfo - * @memberof module:auth.UsersManager.prototype * @example * Get the user information based on the Auth0 access token (obtained during * login). Find more information in the @@ -82,8 +80,6 @@ class UsersManager { /** * Impersonate the user with the given user ID. * - * @function impersonate - * @memberof module:auth.UsersManager.prototype * @example * Gets a link that can be used once to log in as a specific user. Useful for * troubleshooting. Find more information in the diff --git a/src/auth/index.js b/src/auth/index.js index cb726682c..8a174ce56 100644 --- a/src/auth/index.js +++ b/src/auth/index.js @@ -15,13 +15,10 @@ const TokensManager = require('./TokensManager'); const BASE_URL_FORMAT = 'https://%s'; /** - * @class * Authentication API SDK. * - * This client must used to access Auth0's - * Authentication API. - * @class - * @memberof module:auth + * This client must used to access Auth0's {@link https://auth0.com/docs/auth-api Authentication API}. + * * @example * The AuthenticationClient constructor takes an optional client * ID, if specified it will be used as default value for all endpoints that @@ -33,554 +30,538 @@ const BASE_URL_FORMAT = 'https://%s'; * domain: '{YOUR_ACCOUNT}.auth0.com', * clientId: '{OPTIONAL_CLIENT_ID}' * }); - * @param {object} options Options for the Authentication Client SDK. - * @param {string} options.domain AuthenticationClient server domain. - * @param {string} [options.clientId] Default client ID. - * @param {string} [options.clientSecret] Default client Secret. - * @param {string} [options.supportedAlgorithms] Algorithms that your application expects to receive - * @param {boolean} [options.__bypassIdTokenValidation] Whether the id_token should be validated or not - * @param {object} [options.headers] Additional headers that will be added to the outgoing requests. */ -const AuthenticationClient = function (options) { - if (!options || typeof options !== 'object') { - throw new ArgumentError('Authentication Client SDK options must be an object'); - } +class AuthenticationClient { + /** + * @param {object} options Options for the Authentication Client SDK. + * @param {string} options.domain AuthenticationClient server domain. + * @param {string} [options.clientId] Default client ID. + * @param {string} [options.clientSecret] Default client Secret. + * @param {string} [options.supportedAlgorithms] Algorithms that your application expects to receive + * @param {boolean} [options.__bypassIdTokenValidation] Whether the id_token should be validated or not + * @param {object} [options.headers] Additional headers that will be added to the outgoing requests. + */ + constructor(options) { + if (!options || typeof options !== 'object') { + throw new ArgumentError('Authentication Client SDK options must be an object'); + } - if (!options.domain || options.domain.length === 0) { - throw new ArgumentError('Must provide a domain'); - } + if (!options.domain || options.domain.length === 0) { + throw new ArgumentError('Must provide a domain'); + } - const defaultHeaders = { - 'User-Agent': `node.js/${process.version.replace('v', '')}`, - 'Content-Type': 'application/json', - }; - - const managerOptions = { - clientId: options.clientId, - domain: options.domain, - clientSecret: options.clientSecret, - headers: Object.assign(defaultHeaders, options.headers || {}), - baseUrl: util.format(BASE_URL_FORMAT, options.domain), - supportedAlgorithms: options.supportedAlgorithms, - __bypassIdTokenValidation: options.__bypassIdTokenValidation, - }; - - if (options.telemetry !== false) { - const clientInfo = options.clientInfo || utils.generateClientInfo(); - if ('string' === typeof clientInfo.name && clientInfo.name) { - const telemetry = jsonToBase64(clientInfo); - managerOptions.headers['Auth0-Client'] = telemetry; + const defaultHeaders = { + 'User-Agent': `node.js/${process.version.replace('v', '')}`, + 'Content-Type': 'application/json', + }; + + const managerOptions = { + clientId: options.clientId, + domain: options.domain, + clientSecret: options.clientSecret, + headers: Object.assign(defaultHeaders, options.headers || {}), + baseUrl: util.format(BASE_URL_FORMAT, options.domain), + supportedAlgorithms: options.supportedAlgorithms, + __bypassIdTokenValidation: options.__bypassIdTokenValidation, + }; + + if (options.telemetry !== false) { + const clientInfo = options.clientInfo || utils.generateClientInfo(); + if ('string' === typeof clientInfo.name && clientInfo.name) { + const telemetry = jsonToBase64(clientInfo); + managerOptions.headers['Auth0-Client'] = telemetry; + } } + + /** + * OAuth authenticator. + * + * @type {OAuthAuthenticator} + */ + this.oauth = new OAuthAuthenticator(managerOptions); + + /** + * Database authenticator. + * + * @type {DatabaseAuthenticator} + */ + this.database = new DatabaseAuthenticator(managerOptions, this.oauth); + + /** + * Passwordless authenticator. + * + * @type {PasswordlessAuthenticator} + */ + this.passwordless = new PasswordlessAuthenticator(managerOptions, this.oauth); + + /** + * Users manager. + * + * @type {UsersManager} + */ + this.users = new UsersManager(managerOptions); + + /** + * Tokens manager. + * + * @type {TokensManager} + */ + this.tokens = new TokensManager(managerOptions); } /** - * OAuth authenticator. + * Start passwordless flow sending an email. + * + * @example + * Given the user `email` address, it will send an email with a link. You can + * then authenticate with this user opening the link and he will be + * automatically logged in to the application. Optionally, you can + * append/override parameters to the link (like `scope`, `redirect_uri`, + * `protocol`, `response_type`, etc.) using `authParams` object. + * + * Find more information in the + * API Docs + * * - * @type {OAuthAuthenticator} + * var data = { + * email: '{EMAIL}', + * authParams: {} // Optional auth params. + * }; + * + * auth0.requestMagicLink(data, function (err) { + * if (err) { + * // Handle error. + * } + * }; + * @param {object} data User data object. + * @param {string} data.email User email address. + * @param {object} [data.authParams] Authentication parameters. + * @param {Function} [cb] Method callback. + * @returns {Promise|undefined} */ - this.oauth = new OAuthAuthenticator(managerOptions); + requestMagicLink(data, cb) { + data.send = 'link'; + + return this.passwordless.sendEmail(data, cb); + } /** - * Database authenticator. + * Start passwordless flow sending an email. * - * @type {DatabaseAuthenticator} + * @example + * Given the user `email` address, it will send an email with a verification + * code. You can then authenticate with this user using the `/oauth/ro` + * endpoint using the email as username and the code as password. + * + * Find more information in the + * API Docs + * + * + * var data = { + * email: '{EMAIL}', + * authParams: {} // Optional auth params. + * }; + * + * auth0.requestEmailCode(data, function (err) { + * if (err) { + * // Handle error. + * } + * }; + * @param {object} data User data object. + * @param {string} data.email User email address. + * @param {object} [data.authParams] Authentication parameters. + * @param {Function} [cb] Method callback. + * @returns {Promise|undefined} */ - this.database = new DatabaseAuthenticator(managerOptions, this.oauth); + requestEmailCode(data, cb) { + data.send = 'code'; + + return this.passwordless.sendEmail(data, cb); + } /** - * Passwordless authenticator. + * Verify the given OTP which was sent on the given email. + * + * @example + * Given the user credentials (`email` and `otp`), authenticates + * with the provider using the `/oauth/token` endpoint. Upon successful + * authentication, returns a JSON object containing the `access_token` and + * `id_token`. + * + * + * var data = { + * email: '{EMAIL}', + * otp: '{VERIFICATION_CODE}' + * }; * - * @type {PasswordlessAuthenticator} + * auth0.verifyEmailCode(data, function (err) { + * if (err) { + * // Handle error. + * } + * }); + * @example + * The user data object has the following structure. + * + * + * { + * id_token: String, + * access_token: String, + * token_type: String + * } + * @param {object} data Credentials object. + * @param {string} data.email Email. + * @param {string} data.otp Verification code. + * @param {Function} [cb] Method callback. + * @returns {Promise|undefined} */ - this.passwordless = new PasswordlessAuthenticator(managerOptions, this.oauth); + verifyEmailCode(data, cb) { + const translatedData = { + username: data.email, + realm: 'email', + otp: data.otp, + }; + + return this.passwordless.signIn(translatedData, cb); + } /** - * Users manager. + * Start passwordless flow sending an SMS. + * + * @example + * Given the user `phone_number`, it will send a SMS message with a + * verification code. You can then authenticate with this user using the + * `/oauth/ro` endpoint specifying `phone_number` as `username` and `code` as + * `password`: + * * - * @type {UsersManager} + * var data = { + * phone_number: '{PHONE}' + * }; + * + * auth0.requestSMSCode(data, function (err) { + * if (err) { + * // Handle error. + * } + * + * }); + * @param {object} data User data object. + * @param {string} data.phone_number The user phone number. + * @param {Function} [cb] Method callback. + * @returns {Promise|undefined} */ - this.users = new UsersManager(managerOptions); + requestSMSCode(data, cb) { + const translatedData = { + phone_number: data.phoneNumber || data.phone_number, + }; + + return this.passwordless.sendSMS(translatedData, cb); + } /** - * Tokens manager. + * Sign in with the given user credentials. + * + * @example + * Given the user credentials (`phone_number` and `otp`), authenticates + * with the provider using the `/oauth/token` endpoint. Upon successful + * authentication, returns a JSON object containing the `access_token` and + * `id_token`. + * + * + * var data = { + * username: '{PHONE_NUMBER}' + * otp: '{VERIFICATION_CODE}' + * }; + * + * auth0.verifySMSCode(data, function (err) { + * if (err) { + * // Handle error. + * } + * }); + * @example + * Given the user credentials (`phone_number` and `password`), authenticates + * with the provider using the deprecated `/oauth/ro` endpoint. Upon successful + * authentication, returns a JSON object containing the `access_token` and + * `id_token`. + * * - * @type {TokensManager} + * var data = { + * username: '{PHONE_NUMBER}', + * password: '{VERIFICATION_CODE}' + * }; + * + * auth0.verifySMSCode(data, function (err) { + * if (err) { + * // Handle error. + * } + * }); + * @example + * The user data object has the following structure. + * + * + * { + * id_token: String, + * access_token: String, + * token_type: String + * } + * @param {object} data Credentials object. + * @param {string} data.username Phone number. + * @param {string} data.otp Verification code. Use this instead of `password` to use the `/oauth/token` endpoint. + * @param {string} data.password Verification code. Use this instead of `otp` to use the `/oauth/ro` endpoint. + * @param {Function} [cb] Method callback. + * @returns {Promise|undefined} */ - this.tokens = new TokensManager(managerOptions); -}; - -/** - * Start passwordless flow sending an email. - * - * @function requestMagicLink - * @memberof module:auth.AuthenticationClient.prototype - * @example - * Given the user `email` address, it will send an email with a link. You can - * then authenticate with this user opening the link and he will be - * automatically logged in to the application. Optionally, you can - * append/override parameters to the link (like `scope`, `redirect_uri`, - * `protocol`, `response_type`, etc.) using `authParams` object. - * - * Find more information in the - * API Docs - * - * - * var data = { - * email: '{EMAIL}', - * authParams: {} // Optional auth params. - * }; - * - * auth0.requestMagicLink(data, function (err) { - * if (err) { - * // Handle error. - * } - * }; - * @param {object} data User data object. - * @param {string} data.email User email address. - * @param {object} [data.authParams] Authentication parameters. - * @param {Function} [cb] Method callback. - * @returns {Promise|undefined} - */ -AuthenticationClient.prototype.requestMagicLink = function (data, cb) { - data.send = 'link'; - - return this.passwordless.sendEmail(data, cb); -}; - -/** - * Start passwordless flow sending an email. - * - * @function requestEmailCode - * @memberof module:auth.AuthenticationClient.prototype - * @example - * Given the user `email` address, it will send an email with a verification - * code. You can then authenticate with this user using the `/oauth/ro` - * endpoint using the email as username and the code as password. - * - * Find more information in the - * API Docs - * - * - * var data = { - * email: '{EMAIL}', - * authParams: {} // Optional auth params. - * }; - * - * auth0.requestEmailCode(data, function (err) { - * if (err) { - * // Handle error. - * } - * }; - * @param {object} data User data object. - * @param {string} data.email User email address. - * @param {object} [data.authParams] Authentication parameters. - * @param {Function} [cb] Method callback. - * @returns {Promise|undefined} - */ -AuthenticationClient.prototype.requestEmailCode = function (data, cb) { - data.send = 'code'; - - return this.passwordless.sendEmail(data, cb); -}; - -/** - * Verify the given OTP which was sent on the given email. - * - * @function verifyEmailCode - * @memberof module:auth.AuthenticationClient.prototype - * @example - * Given the user credentials (`email` and `otp`), authenticates - * with the provider using the `/oauth/token` endpoint. Upon successful - * authentication, returns a JSON object containing the `access_token` and - * `id_token`. - * - * - * var data = { - * email: '{EMAIL}', - * otp: '{VERIFICATION_CODE}' - * }; - * - * auth0.verifyEmailCode(data, function (err) { - * if (err) { - * // Handle error. - * } - * }); - * @example - * The user data object has the following structure. - * - * - * { - * id_token: String, - * access_token: String, - * token_type: String - * } - * @param {object} data Credentials object. - * @param {string} data.email Email. - * @param {string} data.otp Verification code. - * @param {Function} [cb] Method callback. - * @returns {Promise|undefined} - */ -AuthenticationClient.prototype.verifyEmailCode = function (data, cb) { - const translatedData = { - username: data.email, - realm: 'email', - otp: data.otp, - }; - - return this.passwordless.signIn(translatedData, cb); -}; - -/** - * Start passwordless flow sending an SMS. - * - * @function requestSMSCode - * @memberof module:auth.AuthenticationClient.prototype - * @example - * Given the user `phone_number`, it will send a SMS message with a - * verification code. You can then authenticate with this user using the - * `/oauth/ro` endpoint specifying `phone_number` as `username` and `code` as - * `password`: - * - * - * var data = { - * phone_number: '{PHONE}' - * }; - * - * auth0.requestSMSCode(data, function (err) { - * if (err) { - * // Handle error. - * } - * - * }); - * @param {object} data User data object. - * @param {string} data.phone_number The user phone number. - * @param {Function} [cb] Method callback. - * @returns {Promise|undefined} - */ -AuthenticationClient.prototype.requestSMSCode = function (data, cb) { - const translatedData = { - phone_number: data.phoneNumber || data.phone_number, - }; - - return this.passwordless.sendSMS(translatedData, cb); -}; + verifySMSCode(data, cb) { + const translatedData = { + username: data.phoneNumber || data.phone_number || data.username, + }; + + if (data.otp) { + translatedData.otp = data.otp; + } else { + translatedData.password = data.code || data.password; + } -/** - * Sign in with the given user credentials. - * - * @function verifySMSCode - * @memberof module:auth.AuthenticationClient.prototype - * @example - * Given the user credentials (`phone_number` and `otp`), authenticates - * with the provider using the `/oauth/token` endpoint. Upon successful - * authentication, returns a JSON object containing the `access_token` and - * `id_token`. - * - * - * var data = { - * username: '{PHONE_NUMBER}' - * otp: '{VERIFICATION_CODE}' - * }; - * - * auth0.verifySMSCode(data, function (err) { - * if (err) { - * // Handle error. - * } - * }); - * @example - * Given the user credentials (`phone_number` and `password`), authenticates - * with the provider using the deprecated `/oauth/ro` endpoint. Upon successful - * authentication, returns a JSON object containing the `access_token` and - * `id_token`. - * - * - * var data = { - * username: '{PHONE_NUMBER}', - * password: '{VERIFICATION_CODE}' - * }; - * - * auth0.verifySMSCode(data, function (err) { - * if (err) { - * // Handle error. - * } - * }); - * @example - * The user data object has the following structure. - * - * - * { - * id_token: String, - * access_token: String, - * token_type: String - * } - * @param {object} data Credentials object. - * @param {string} data.username Phone number. - * @param {string} data.otp Verification code. Use this instead of `password` to use the `/oauth/token` endpoint. - * @param {string} data.password Verification code. Use this instead of `otp` to use the `/oauth/ro` endpoint. - * @param {Function} [cb] Method callback. - * @returns {Promise|undefined} - */ -AuthenticationClient.prototype.verifySMSCode = function (data, cb) { - const translatedData = { - username: data.phoneNumber || data.phone_number || data.username, - }; - - if (data.otp) { - translatedData.otp = data.otp; - } else { - translatedData.password = data.code || data.password; + return this.passwordless.signIn(translatedData, cb); } - return this.passwordless.signIn(translatedData, cb); -}; - -/** - * Exchange the token of the logged in user with a token that is valid to call - * the API (signed with the API secret). - * - * @function getDelegationToken - * @memberof module:auth.AuthenticationClient.prototype - * @example - * Given an existing token, this endpoint will generate a new token signed - * with the target client secret. This is used to flow the identity of the - * user from the application to an API or across different APIs that are - * protected with different secrets. Find more information in the - * API Docs. - * - * - * var data = { - * id_token: '{ID_TOKEN}', - * api_type: 'app', - * target: '{TARGET}', - * grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer' - * }; - * - * auth0.getDelegationToken(data, function (err, token) { - * if (err) { - * // Handle error. - * } - * - * console.log(token); - * }); - * @param {object} data Token data object. - * @param {string} data.id_token The user ID token. - * @param {string} data.api_type The API type (aws, firebase, etc). - * @param {string} data.target The target client ID. - * @param {string} data.grant_type The grant type. - * @param {Function} [cb] Method callback. - * @returns {Promise|undefined} - */ -AuthenticationClient.prototype.getDelegationToken = function (data, cb) { - const translatedData = { - id_token: data.id_token, - api_type: data.api || data.api_type, - scope: data.scope, - target: data.targetClientId || data.target, - grant_type: data.grant_type, - }; - - return this.tokens.getDelegationToken(translatedData, cb); -}; + /** + * Exchange the token of the logged in user with a token that is valid to call + * the API (signed with the API secret). + * + * @example + * Given an existing token, this endpoint will generate a new token signed + * with the target client secret. This is used to flow the identity of the + * user from the application to an API or across different APIs that are + * protected with different secrets. Find more information in the + * API Docs. + * + * + * var data = { + * id_token: '{ID_TOKEN}', + * api_type: 'app', + * target: '{TARGET}', + * grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer' + * }; + * + * auth0.getDelegationToken(data, function (err, token) { + * if (err) { + * // Handle error. + * } + * + * console.log(token); + * }); + * @param {object} data Token data object. + * @param {string} data.id_token The user ID token. + * @param {string} data.api_type The API type (aws, firebase, etc). + * @param {string} data.target The target client ID. + * @param {string} data.grant_type The grant type. + * @param {Function} [cb] Method callback. + * @returns {Promise|undefined} + */ + getDelegationToken(data, cb) { + const translatedData = { + id_token: data.id_token, + api_type: data.api || data.api_type, + scope: data.scope, + target: data.targetClientId || data.target, + grant_type: data.grant_type, + }; + + return this.tokens.getDelegationToken(translatedData, cb); + } -/** - * Change password using a database or active directory service. - * - * @function changePassword - * @memberof module:auth.AuthenticationClient.prototype - * @example - * Given the user email, the connection specified and the new password to - * use, Auth0 will send a forgot password email. Once the user clicks on the - * confirm password change link, the new password specified in this POST will - * be set to this user. Find more information in the - * - * API Docs. - * - * - * var data = { - * email: '{EMAIL}', - * password: '{PASSWORD}', - * connection: 'Username-Password-Authentication' - * }; - * - * auth0.changePassword(data, function (err, message) { - * if (err) { - * // Handle error. - * } - * - * console.log(message); - * }); - * @param {object} data User data object. - * @param {string} data.email User email. - * @param {string} data.password User password. - * @param {string} data.connection Identity provider for the user. - * @param {Function} [cb] Method callback. - * @returns {Promise|undefined} - */ -AuthenticationClient.prototype.changePassword = function (data, cb) { - return this.database.changePassword(data, cb); -}; + /** + * Change password using a database or active directory service. + * + * @example + * Given the user email, the connection specified and the new password to + * use, Auth0 will send a forgot password email. Once the user clicks on the + * confirm password change link, the new password specified in this POST will + * be set to this user. Find more information in the + * + * API Docs. + * + * + * var data = { + * email: '{EMAIL}', + * password: '{PASSWORD}', + * connection: 'Username-Password-Authentication' + * }; + * + * auth0.changePassword(data, function (err, message) { + * if (err) { + * // Handle error. + * } + * + * console.log(message); + * }); + * @param {object} data User data object. + * @param {string} data.email User email. + * @param {string} data.password User password. + * @param {string} data.connection Identity provider for the user. + * @param {Function} [cb] Method callback. + * @returns {Promise|undefined} + */ + changePassword(data, cb) { + return this.database.changePassword(data, cb); + } -/** - * Request a change password email using a database or active directory service. - * - * @function requestChangePasswordEmail - * @memberof module:auth.AuthenticationClient.prototype - * @example - * Given the user email, the connection specified, Auth0 will send a change - * password email. once the user clicks on the confirm password change link, - * the new password specified in this POST will be set to this user. Find more - * information in the + * API Docs. + * + * + * var data = { + * email: '{EMAIL}', + * connection: 'Username-Password-Authentication', + * client_id: 'OS1VzKTVjizL0VCc9Hx2ae2aTPXWy6BD' + * }; + * + * auth0.requestChangePasswordEmail(data, function (err, message) { + * if (err) { + * // Handle error. + * } + * + * console.log(message); + * }); + * @param {object} data User data object. + * @param {string} data.email User email. + * @param {string} data.connection Identity provider for the user. + * @param {string} data.client_id Client ID of the Application requesting the password change, to be included in the email template. + * @param {Function} [cb] Method callback. + * @returns {Promise|undefined} + */ + requestChangePasswordEmail(data, cb) { + return this.database.requestChangePasswordEmail(data, cb); + } -/** - * Given an access token get the user profile linked to it. - * - * @function getProfile - * @memberof module:auth.AuthenticationClient.prototype - * @example - * Get the user information based on the Auth0 access token (obtained during - * login). Find more information in the - * API Docs. - * - * - * auth0.getProfile(data, function (err, userInfo) { - * if (err) { - * // Handle error. - * } - * - * console.log(userInfo); - * }); - * @param {string} accessToken The user access token. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(AuthenticationClient, 'getProfile', 'users.getInfo'); + /** + * Given an access token get the user profile linked to it. + * + * @example + * Get the user information based on the Auth0 access token (obtained during + * login). Find more information in the + * API Docs. + * + * + * auth0.getProfile(data, function (err, userInfo) { + * if (err) { + * // Handle error. + * } + * + * console.log(userInfo); + * }); + * @param {string} accessToken The user access token. + * @returns {Promise|undefined} + */ + getProfile(...args) { + return this.users.getInfo(...args); + } -/** - * Gets an access token using the client credentials grant flow. - * - * @function clientCredentialsGrant - * @memberof module:auth.AuthenticationClient.prototype - * @example - * Gets an access token using the client credentials grant flow. Find more information in the - * API Docs. - * - * - * auth0.clientCredentialsGrant({ - * audience: 'https://tenant.auth0.com/api/v2/', - * scope: 'read:users update:users' - * }, function (err, response) { - * if (err) { - * // Handle error. - * } - * - * console.log(response); - * }); - * @param {object} options - * @param {string} [options.scope] scopes to request to be added to the returned access token - * @param {string} [options.audience] audience or identifier of the API where the access token will be used, e.g. Auth0 Management API - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod( - AuthenticationClient, - 'clientCredentialsGrant', - 'oauth.clientCredentialsGrant' -); + /** + * Gets an access token using the client credentials grant flow. + * + * @example + * Gets an access token using the client credentials grant flow. Find more information in the + * API Docs. + * + * + * auth0.clientCredentialsGrant({ + * audience: 'https://tenant.auth0.com/api/v2/', + * scope: 'read:users update:users' + * }, function (err, response) { + * if (err) { + * // Handle error. + * } + * + * console.log(response); + * }); + * @param {object} options + * @param {string} [options.scope] scopes to request to be added to the returned access token + * @param {string} [options.audience] audience or identifier of the API where the access token will be used, e.g. Auth0 Management API + * @returns {Promise|undefined} + */ + clientCredentialsGrant(...args) { + return this.oauth.clientCredentialsGrant(...args); + } -/** - * Sign in using a username and password - * - * @function passwordGrant - * @memberof module:auth.AuthenticationClient.prototype - * @example - * Given the user's credentials perform the OAuth password grant - * or Password Realm grant if a realm is provided, - * it will return a JSON with the access_token and id_token. - * More information in the - * - * API Docs - * . - * - * - * var data = { - * client_id: '{CLIENT_ID}', // Optional field. - * username: '{USERNAME}', - * password: '{PASSWORD}' - * realm: '{CONNECTION_NAME}', // Optional field. - * scope: 'openid' // Optional field. - * }; - * - * auth0.passwordGrant(data, function (err, userData) { - * if (err) { - * // Handle error. - * } - * - * console.log(userData); - * }); - * @param {object} userData User credentials object. - * @param {string} userData.username Username. - * @param {string} userData.password User password. - * @param {string} [userData.realm] Name of the realm to use to authenticate or the connection name - * @param {object} [options] Additional options. - * @param {string} [options.forwardedFor] Value to be used for auth0-forwarded-for header - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(AuthenticationClient, 'passwordGrant', 'oauth.passwordGrant'); + /** + * Sign in using a username and password + * + * @example + * Given the user's credentials perform the OAuth password grant + * or Password Realm grant if a realm is provided, + * it will return a JSON with the access_token and id_token. + * More information in the + * + * API Docs + * . + * + * + * var data = { + * client_id: '{CLIENT_ID}', // Optional field. + * username: '{USERNAME}', + * password: '{PASSWORD}' + * realm: '{CONNECTION_NAME}', // Optional field. + * scope: 'openid' // Optional field. + * }; + * + * auth0.passwordGrant(data, function (err, userData) { + * if (err) { + * // Handle error. + * } + * + * console.log(userData); + * }); + * @param {object} userData User credentials object. + * @param {string} userData.username Username. + * @param {string} userData.password User password. + * @param {string} [userData.realm] Name of the realm to use to authenticate or the connection name + * @param {object} [options] Additional options. + * @param {string} [options.forwardedFor] Value to be used for auth0-forwarded-for header + * @returns {Promise|undefined} + */ + passwordGrant(...args) { + return this.oauth.passwordGrant(...args); + } -/** - * Sign in using a refresh token - * - * @function refreshToken - * @memberof module:auth.AuthenticationClient.prototype - * @example - * Given a refresh token from a previous authentication request, - * it will return a JSON with the access_token and id_token. - * More information in the - * - * API Docs - * . - * - * - * var data = { - * client_id: '{CLIENT_ID}', // Optional field. - * refresh_token: '{REFRESH_TOKEN}', - * }; - * - * auth0.refreshToken(data, function (err, userData) { - * if (err) { - * // Handle error. - * } - * - * console.log(userData); - * }); - * @param {object} userData User credentials object. - * @param {string} userData.refresh_token Refresh token. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(AuthenticationClient, 'refreshToken', 'oauth.refreshToken'); + /** + * Sign in using a refresh token + * + * @example + * Given a refresh token from a previous authentication request, + * it will return a JSON with the access_token and id_token. + * More information in the + * + * API Docs + * . + * + * + * var data = { + * client_id: '{CLIENT_ID}', // Optional field. + * refresh_token: '{REFRESH_TOKEN}', + * }; + * + * auth0.refreshToken(data, function (err, userData) { + * if (err) { + * // Handle error. + * } + * + * console.log(userData); + * }); + * @param {object} userData User credentials object. + * @param {string} userData.refresh_token Refresh token. + * @returns {Promise|undefined} + */ + refreshToken(...args) { + return this.oauth.refreshToken(...args); + } +} module.exports = AuthenticationClient; diff --git a/src/index.js b/src/index.js index e2a7d9c61..ad3d0e4ca 100644 --- a/src/index.js +++ b/src/index.js @@ -2,7 +2,7 @@ * Simple facade for consuming a REST API endpoint. * * @external RestClient - * @see https://github.com/ngonzalvez/rest-facade + * {@link https://github.com/ngonzalvez/rest-facade} */ module.exports = { diff --git a/src/management/ActionsManager.js b/src/management/ActionsManager.js index aacf6254b..218419419 100644 --- a/src/management/ActionsManager.js +++ b/src/management/ActionsManager.js @@ -2,13 +2,6 @@ const { ArgumentError } = require('rest-facade'); const Auth0RestClient = require('../Auth0RestClient'); const RetryRestClient = require('../RetryRestClient'); -/** - * Simple facade for consuming a REST API endpoint. - * - * @external RestClient - * {@link https://github.com/ngonzalvez/rest-facade} - */ - /** * {@link https://auth0.com/docs/api/v2#!/Actions/get_actions Actions} provide a way to extend * Auth0 flows with custom logic. @@ -16,8 +9,6 @@ const RetryRestClient = require('../RetryRestClient'); */ class ActionsManager { /** - * @class - * @memberof module:management * @param {object} options The client options. * @param {string} options.baseUrl The URL of the API. * @param {object} [options.headers] Headers to be included in all requests. @@ -113,8 +104,6 @@ class ActionsManager { /** * Get all Triggers. * - * @function getAllTriggers - * @memberof module:management.ActionsManager.prototype * @example * This method takes an optional object as first argument that may be used to * specify pagination settings. If pagination options are not present, @@ -148,8 +137,6 @@ class ActionsManager { /** * Update the actions bound to a trigger . * - * @function updateTriggerBindings - * @memberof module:management.ActionsManager.prototype * @example * var data = { bindings: [{ id_type: "action_id", id_value: ACTION_ID1},{id_type: "action_name", id_value: ACTION_NAME2}]; * var params = { trigger_id: TRIGGER_ID }; @@ -181,8 +168,6 @@ class ActionsManager { /** * Get the actions bound to a trigger . * - * @function getTriggerBindings - * @memberof module:management.ActionsManager.prototype * @example * var params = { trigger_id: TRIGGER_ID }; * @@ -212,8 +197,6 @@ class ActionsManager { /** * Create a new Action. * - * @function create - * @memberof module:management.ActionsManager.prototype * @example * management.actions.create(data, function (err) { * if (err) { @@ -233,8 +216,6 @@ class ActionsManager { /** * Get all actions. * - * @function getAll - * @memberof module:management.ActionsManager.prototype * @example * This method takes an optional object as first argument that may be used to * specify pagination settings. If pagination options are not present, @@ -266,8 +247,6 @@ class ActionsManager { /** * Get an Auth0 action. * - * @function get - * @memberof module:management.ActionsManager.prototype * @example * management.actions.get({ id: ACTION_ID }, function (err, action) { * if (err) { @@ -299,8 +278,6 @@ class ActionsManager { /** * Update an existing action. * - * @function update - * @memberof module:management.ActionsManager.prototype * @example * var data = { name: 'new-name' }; * var params = { id: ACTION_ID }; @@ -346,8 +323,6 @@ class ActionsManager { /** * Delete an existing action. Deleting an Action deletes all the action's versions * - * @function delete - * @memberof module:management.ActionsManager.prototype * @example * management.actions.delete({ id: ACTION_ID }, function (err) { * if (err) { @@ -379,8 +354,6 @@ class ActionsManager { /** * test an Action. * - * @function test - * @memberof module:management.ActionsManager.prototype * @example * var params = { id: ACTION_ID}; * management.actions.test(params, payload, function (err) { @@ -414,8 +387,6 @@ class ActionsManager { * deploy an Action. * The action must be in a state of 'built' before it can be deployed. * - * @function deploy - * @memberof module:management.ActionsManager.prototype * @example * var params = { id: ACTION_ID}; * mangement.actions.deploy(params, function (err, actionVersion) { @@ -446,8 +417,6 @@ class ActionsManager { /** * Get all action versions * - * @function getVersions - * @memberof module:management.ActionsManager.prototype * @example * This method takes an optional object as first argument that may be used to * specify pagination settings. If pagination options are not present, @@ -487,8 +456,6 @@ class ActionsManager { /** * Get an Action Version. * - * @function getVersion - * @memberof module:management.ActionsManager.prototype * @example * var params = { id: ACTION_ID, version_id: VERSION_ID }; * management.actions.getVersion(params, function (err, actionVersion) { @@ -523,8 +490,6 @@ class ActionsManager { * this operation is supported as a way of creating versions without * updating the action's code (which can be useful in some CI/CD scenarios). * - * @function createVersion - * @memberof module:management.ActionsManager.prototype * @example * var params = { id: ACTION_ID }; * management.actions.createActionVersion(params, data, function (err, actionVersion) { @@ -556,8 +521,6 @@ class ActionsManager { /** * deploy an Action Version to roll back to a previous version. * - * @function deployVersion - * @memberof module:management.ActionsManager.prototype * @example * var params = { id: ACTION_ID, version_id: VERSION_ID }; * management.actions.deployVersion(params, function (err, actionVersion) { @@ -589,8 +552,6 @@ class ActionsManager { /** * Get an execution by ID. * - * @function getExecution - * @memberof module:management.ActionExecutionsManager.prototype * @example * management.actions.getExecution({ execution_id: EXECUTION_ID }, function (err, action) { * if (err) { diff --git a/src/management/BlacklistedTokensManager.js b/src/management/BlacklistedTokensManager.js index 7d3e6da9d..a1a8d4eb9 100644 --- a/src/management/BlacklistedTokensManager.js +++ b/src/management/BlacklistedTokensManager.js @@ -54,8 +54,6 @@ class BlacklistedTokensManager { /** * Blacklist a new token. * - * @function add - * @memberof module:management.BlacklistedTokensManager.prototype * @example * var token = { * aud: 'aud', @@ -82,8 +80,6 @@ class BlacklistedTokensManager { /** * Get all blacklisted tokens. * - * @function getAll - * @memberof module:management.BlacklistedTokensManager.prototype * @example * management.blacklistedTokens.getAll(function (err, tokens) { * console.log(tokens.length); diff --git a/src/management/BrandingManager.js b/src/management/BrandingManager.js index 5c12d5dc8..58c6955f1 100644 --- a/src/management/BrandingManager.js +++ b/src/management/BrandingManager.js @@ -1,172 +1,161 @@ const { ArgumentError } = require('rest-facade'); -const utils = require('../utils'); const Auth0RestClient = require('../Auth0RestClient'); const RetryRestClient = require('../RetryRestClient'); /** - * Simple facade for consuming a REST API endpoint. - * - * @external RestClient - * @see https://github.com/ngonzalvez/rest-facade - */ - -/** - * @class BrandingManager * Manages settings related to branding. - * @class - * @memberof module:management - * @param {object} options The client options. - * @param {string} options.baseUrl The URL of the API. - * @param {object} [options.headers] Headers to be included in all requests. - * @param {object} [options.retry] Retry Policy Config */ -const BrandingManager = function (options) { - if (options === null || typeof options !== 'object') { - throw new ArgumentError('Must provide manager options'); - } +class BrandingManager { + /** + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config + */ + constructor(options) { + if (options === null || typeof options !== 'object') { + throw new ArgumentError('Must provide manager options'); + } - if (options.baseUrl === null || options.baseUrl === undefined) { - throw new ArgumentError('Must provide a base URL for the API'); - } + if (options.baseUrl === null || options.baseUrl === undefined) { + throw new ArgumentError('Must provide a base URL for the API'); + } - if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { - throw new ArgumentError('The provided base URL is invalid'); - } + if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { + throw new ArgumentError('The provided base URL is invalid'); + } + + const clientOptions = { + errorFormatter: { message: 'message', name: 'error' }, + headers: options.headers, + query: { repeatParams: false }, + }; + + /** + * Provides an abstraction layer for consuming the + * {@link https://auth0.com/docs/api/management/v2#!/Branding Branding endpoint}. + * + * @type {external:RestClient} + */ + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/branding`, + clientOptions, + options.tokenProvider + ); + this.resource = new RetryRestClient(auth0RestClient, options.retry); - const clientOptions = { - errorFormatter: { message: 'message', name: 'error' }, - headers: options.headers, - query: { repeatParams: false }, - }; + /** + * Provides an abstraction layer for consuming the + * {@link https://auth0.com/docs/api/management/v2#!/Branding/get_universal_login Branding new universal login template endpoint}. + * + * @type {external:RestClient} + */ + const brandingTemplateAuth0RestClient = new Auth0RestClient( + `${options.baseUrl}/branding/templates/universal-login`, + clientOptions, + options.tokenProvider + ); + this.brandingTemplates = new RetryRestClient(brandingTemplateAuth0RestClient, options.retry); + } /** - * Provides an abstraction layer for consuming the - * {@link https://auth0.com/docs/api/management/v2#!/Branding Branding endpoint}. + * Update the branding settings. + * + * @example + * management.branding.updateSettings(params, data, function (err, branding) { + * if (err) { + * // Handle error. + * } * - * @type {external:RestClient} + * // Updated branding + * console.log(branding); + * }); + * @param {object} params Branding parameters (leavy empty). + * @param {object} data Updated branding data. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const auth0RestClient = new Auth0RestClient( - `${options.baseUrl}/branding`, - clientOptions, - options.tokenProvider - ); - this.resource = new RetryRestClient(auth0RestClient, options.retry); + updateSettings(...args) { + return this.resource.patch(...args); + } /** - * Provides an abstraction layer for consuming the - * {@link https://auth0.com/docs/api/management/v2#!/Branding/get_universal_login Branding new universal login template endpoint}. + * Get the branding settings.. * - * @type {external:RestClient} + * @example + * management.branding.getSettings(data, function (err, branding) { + * if (err) { + * // Handle error. + * } + * + * // Branding + * console.log(branding); + * }); + * @param {object} params Branding parameters. + * @param {object} data Branding data. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const brandingTemplateAuth0RestClient = new Auth0RestClient( - `${options.baseUrl}/branding/templates/universal-login`, - clientOptions, - options.tokenProvider - ); - this.brandingTemplates = new RetryRestClient(brandingTemplateAuth0RestClient, options.retry); -}; - -/** - * Update the branding settings. - * - * @function updateSettings - * @memberof module:management.BrandingManager.prototype - * @example - * management.branding.updateSettings(params, data, function (err, branding) { - * if (err) { - * // Handle error. - * } - * - * // Updated branding - * console.log(branding); - * }); - * @param {object} params Branding parameters (leavy empty). - * @param {object} data Updated branding data. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(BrandingManager, 'updateSettings', 'resource.patch'); - -/** - * Get the branding settings.. - * - * @function getSettings - * @memberof module:management.BrandingManager.prototype - * @example - * management.branding.getSettings(data, function (err, branding) { - * if (err) { - * // Handle error. - * } - * - * // Branding - * console.log(branding); - * }); - * @param {object} params Branding parameters. - * @param {object} data Branding data. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(BrandingManager, 'getSettings', 'resource.get'); + getSettings(...args) { + return this.resource.get(...args); + } -/** - * Get the new universal login template. - * - * @function getUniversalLoginTemplate - * @memberof module:management.BrandingManager.prototype - * @example - * management.branding.getUniversalLoginTemplate(data, function (err, template) { - * if (err) { - * // Handle error. - * } - * - * // Branding - * console.log(template); - * }); - * @param {object} params Branding parameters (leave empty). - * @param {object} data Branding data (leave empty). - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(BrandingManager, 'getUniversalLoginTemplate', 'brandingTemplates.get'); + /** + * Get the new universal login template. + * + * @example + * management.branding.getUniversalLoginTemplate(data, function (err, template) { + * if (err) { + * // Handle error. + * } + * + * // Branding + * console.log(template); + * }); + * @param {object} params Branding parameters (leave empty). + * @param {object} data Branding data (leave empty). + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getUniversalLoginTemplate(...args) { + return this.brandingTemplates.get(...args); + } -/** - * Set the new universal login template. - * - * @function setUniversalLoginTemplate - * @memberof module:management.BrandingManager.prototype - * @example - * management.branding.setUniversalLoginTemplate(params, data, function (err) { - * if (err) { - * // Handle error. - * } - * }); - * @param {object} params Branding parameters (leavy empty). - * @param {object} data Branding data (object with template field). - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(BrandingManager, 'setUniversalLoginTemplate', 'brandingTemplates.update'); + /** + * Set the new universal login template. + * + * @example + * management.branding.setUniversalLoginTemplate(params, data, function (err) { + * if (err) { + * // Handle error. + * } + * }); + * @param {object} params Branding parameters (leavy empty). + * @param {object} data Branding data (object with template field). + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + setUniversalLoginTemplate(...args) { + return this.brandingTemplates.update(...args); + } -/** - * Delete the new universal login template (revert to default). - * - * @function deleteUniversalLoginTemplate - * @memberof module:management.BrandingManager.prototype - * @example - * management.branding.deleteUniversalLoginTemplate(data, function (err) { - * if (err) { - * // Handle error. - * } - * }); - * @param {object} params Branding parameters (leavy empty). - * @param {object} data Branding data (leave empty). - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod( - BrandingManager, - 'deleteUniversalLoginTemplate', - 'brandingTemplates.delete' -); + /** + * Delete the new universal login template (revert to default). + * + * @example + * management.branding.deleteUniversalLoginTemplate(data, function (err) { + * if (err) { + * // Handle error. + * } + * }); + * @param {object} params Branding parameters (leavy empty). + * @param {object} data Branding data (leave empty). + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + deleteUniversalLoginTemplate(...args) { + return this.brandingTemplates.delete(...args); + } +} module.exports = BrandingManager; diff --git a/src/management/ClientGrantsManager.js b/src/management/ClientGrantsManager.js index 76829d7b2..6ddd50202 100644 --- a/src/management/ClientGrantsManager.js +++ b/src/management/ClientGrantsManager.js @@ -1,151 +1,152 @@ const { ArgumentError } = require('rest-facade'); -const utils = require('../utils'); const Auth0RestClient = require('../Auth0RestClient'); const RetryRestClient = require('../RetryRestClient'); + /** - * @class ClientGrantsManager * Auth0 Client Grants Manager. * * See {@link https://auth0.com/docs/api/v2#!/Client_Grants Client Grants} - * @class - * @memberof module:management - * @param {object} options The client options. - * @param {string} options.baseUrl The URL of the API. - * @param {object} [options.headers] Headers to be included in all requests. - * @param {object} [options.retry] Retry Policy Config */ -const ClientGrantsManager = function (options) { - if (options === null || typeof options !== 'object') { - throw new ArgumentError('Must provide client options'); - } +class ClientGrantsManager { + /** + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config + */ + constructor(options) { + if (options === null || typeof options !== 'object') { + throw new ArgumentError('Must provide client options'); + } - if (options.baseUrl === null || options.baseUrl === undefined) { - throw new ArgumentError('Must provide a base URL for the API'); - } + if (options.baseUrl === null || options.baseUrl === undefined) { + throw new ArgumentError('Must provide a base URL for the API'); + } + + if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { + throw new ArgumentError('The provided base URL is invalid'); + } - if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { - throw new ArgumentError('The provided base URL is invalid'); + /** + * Options object for the Rest Client instance. + * + * @type {object} + */ + const clientOptions = { + errorFormatter: { message: 'message', name: 'error' }, + headers: options.headers, + query: { repeatParams: false }, + }; + + /** + * Provides an abstraction layer for consuming the + * {@link https://auth0.com/docs/api/v2#!/Client_Grants Auth0 Client Grants endpoint}. + * + * @type {external:RestClient} + */ + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/client-grants/:id`, + clientOptions, + options.tokenProvider + ); + this.resource = new RetryRestClient(auth0RestClient, options.retry); } /** - * Options object for the Rest Client instance. + * Create an Auth0 client grant. + * + * @example + * management.clientGrants.create(data, function (err) { + * if (err) { + * // Handle error. + * } * - * @type {object} + * // Client grant created. + * }); + * @param {object} data The client data object. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const clientOptions = { - errorFormatter: { message: 'message', name: 'error' }, - headers: options.headers, - query: { repeatParams: false }, - }; + create(...args) { + return this.resource.create(...args); + } /** - * Provides an abstraction layer for consuming the - * {@link https://auth0.com/docs/api/v2#!/Client_Grants Auth0 Client Grants endpoint}. + * Get all Auth0 Client Grants. + * + * @example + * This method takes an optional object as first argument that may be used to + * specify pagination settings. If pagination options are not present, + * the first page of a limited number of results will be returned. + * + * + * // Pagination settings. + * var params = { + * per_page: 10, + * page: 0 + * }; + * * - * @type {external:RestClient} + * management.clientGrants.getAll(params, function (err, grants) { + * console.log(grants.length); + * }); + * @param {object} [params] Client Grants parameters. + * @param {number} [params.per_page] Number of results per page. + * @param {number} [params.page] Page number, zero indexed. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const auth0RestClient = new Auth0RestClient( - `${options.baseUrl}/client-grants/:id`, - clientOptions, - options.tokenProvider - ); - this.resource = new RetryRestClient(auth0RestClient, options.retry); -}; - -/** - * Create an Auth0 client grant. - * - * @function create - * @memberof module:management.ClientGrantsManager.prototype - * @example - * management.clientGrants.create(data, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Client grant created. - * }); - * @param {object} data The client data object. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ClientGrantsManager, 'create', 'resource.create'); - -/** - * Get all Auth0 Client Grants. - * - * @function getAll - * @memberof module:management.ClientGrantsManager.prototype - * @example - * This method takes an optional object as first argument that may be used to - * specify pagination settings. If pagination options are not present, - * the first page of a limited number of results will be returned. - * - * - * // Pagination settings. - * var params = { - * per_page: 10, - * page: 0 - * }; - * - * - * management.clientGrants.getAll(params, function (err, grants) { - * console.log(grants.length); - * }); - * @param {object} [params] Client Grants parameters. - * @param {number} [params.per_page] Number of results per page. - * @param {number} [params.page] Page number, zero indexed. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ClientGrantsManager, 'getAll', 'resource.getAll'); + getAll(...args) { + return this.resource.getAll(...args); + } -/** - * Update an Auth0 client grant. - * - * @function update - * @memberof module:management.ClientGrantsManager.prototype - * @example - * var data = { - * client_id: CLIENT_ID, - * audience: AUDIENCE, - * scope: [] - * }; - * var params = { id: CLIENT_GRANT_ID }; - * - * management.clientGrants.update(params, data, function (err, grant) { - * if (err) { - * // Handle error. - * } - * - * console.log(grant.id); - * }); - * @param {object} params Client parameters. - * @param {string} params.id Client grant ID. - * @param {object} data Updated client data. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ClientGrantsManager, 'update', 'resource.patch'); + /** + * Update an Auth0 client grant. + * + * @example + * var data = { + * client_id: CLIENT_ID, + * audience: AUDIENCE, + * scope: [] + * }; + * var params = { id: CLIENT_GRANT_ID }; + * + * management.clientGrants.update(params, data, function (err, grant) { + * if (err) { + * // Handle error. + * } + * + * console.log(grant.id); + * }); + * @param {object} params Client parameters. + * @param {string} params.id Client grant ID. + * @param {object} data Updated client data. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + update(...args) { + return this.resource.patch(...args); + } -/** - * Delete an Auth0 client grant. - * - * @function delete - * @memberof module:management.ClientGrantsManager.prototype - * @example - * management.clientGrants.delete({ id: GRANT_ID }, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Grant deleted. - * }); - * @param {object} params Client parameters. - * @param {string} params.id Client grant ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ClientGrantsManager, 'delete', 'resource.delete'); + /** + * Delete an Auth0 client grant. + * + * @example + * management.clientGrants.delete({ id: GRANT_ID }, function (err) { + * if (err) { + * // Handle error. + * } + * + * // Grant deleted. + * }); + * @param {object} params Client parameters. + * @param {string} params.id Client grant ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + delete(...args) { + return this.resource.delete(...args); + } +} module.exports = ClientGrantsManager; diff --git a/src/management/ClientsManager.js b/src/management/ClientsManager.js index 9abd3da37..bf66e1970 100644 --- a/src/management/ClientsManager.js +++ b/src/management/ClientsManager.js @@ -1,10 +1,8 @@ const { ArgumentError } = require('rest-facade'); -const utils = require('../utils'); const Auth0RestClient = require('../Auth0RestClient'); const RetryRestClient = require('../RetryRestClient'); /** - * @class ClientsManager * Auth0 Clients Manager. * * {@link https://auth0.com/docs/api/v2#!/Clients Clients} represent @@ -12,160 +10,162 @@ const RetryRestClient = require('../RetryRestClient'); * You can learn more about this in the * {@link https://auth0.com/docs/applications Applications} section of the * documentation. - * @class - * @memberof module:management - * @param {object} options The client options. - * @param {string} options.baseUrl The URL of the API. - * @param {object} [options.headers] Headers to be included in all requests. - * @param {object} [options.retry] Retry Policy Config */ -const ClientsManager = function (options) { - if (options === null || typeof options !== 'object') { - throw new ArgumentError('Must provide client options'); - } +class ClientsManager { + /** + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config + */ + constructor(options) { + if (options === null || typeof options !== 'object') { + throw new ArgumentError('Must provide client options'); + } - if (options.baseUrl === null || options.baseUrl === undefined) { - throw new ArgumentError('Must provide a base URL for the API'); - } + if (options.baseUrl === null || options.baseUrl === undefined) { + throw new ArgumentError('Must provide a base URL for the API'); + } - if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { - throw new ArgumentError('The provided base URL is invalid'); + if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { + throw new ArgumentError('The provided base URL is invalid'); + } + + /** + * Options object for the Rest Client instance. + * + * @type {object} + */ + const clientOptions = { + errorFormatter: { message: 'message', name: 'error' }, + headers: options.headers, + query: { repeatParams: false }, + }; + + /** + * Provides an abstraction layer for consuming the + * {@link https://auth0.com/docs/api/v2#!/Clients Auth0 Clients endpoint}. + * + * @type {external:RestClient} + */ + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/clients/:client_id`, + clientOptions, + options.tokenProvider + ); + this.resource = new RetryRestClient(auth0RestClient, options.retry); } /** - * Options object for the Rest Client instance. + * Create an Auth0 client. + * + * @example + * management.clients.create(data, function (err) { + * if (err) { + * // Handle error. + * } * - * @type {object} + * // Client created. + * }); + * @param {object} data The client data object. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const clientOptions = { - errorFormatter: { message: 'message', name: 'error' }, - headers: options.headers, - query: { repeatParams: false }, - }; + create(...args) { + return this.resource.create(...args); + } /** - * Provides an abstraction layer for consuming the - * {@link https://auth0.com/docs/api/v2#!/Clients Auth0 Clients endpoint}. + * Get all Auth0 clients. + * + * @example + * This method takes an optional object as first argument that may be used to + * specify pagination settings. If pagination options are not present, + * the first page of a limited number of results will be returned. + * + * + * // Pagination settings. + * var params = { + * per_page: 10, + * page: 0 + * }; * - * @type {external:RestClient} + * management.clients.getAll(params, function (err, clients) { + * console.log(clients.length); + * }); + * @param {object} [params] Clients parameters. + * @param {number} [params.per_page] Number of results per page. + * @param {number} [params.page] Page number, zero indexed. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const auth0RestClient = new Auth0RestClient( - `${options.baseUrl}/clients/:client_id`, - clientOptions, - options.tokenProvider - ); - this.resource = new RetryRestClient(auth0RestClient, options.retry); -}; - -/** - * Create an Auth0 client. - * - * @function create - * @memberof module:management.ClientsManager.prototype - * @example - * management.clients.create(data, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Client created. - * }); - * @param {object} data The client data object. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ClientsManager, 'create', 'resource.create'); - -/** - * Get all Auth0 clients. - * - * @function getAll - * @memberof module:management.ClientsManager.prototype - * @example - * This method takes an optional object as first argument that may be used to - * specify pagination settings. If pagination options are not present, - * the first page of a limited number of results will be returned. - * - * - * // Pagination settings. - * var params = { - * per_page: 10, - * page: 0 - * }; - * - * management.clients.getAll(params, function (err, clients) { - * console.log(clients.length); - * }); - * @param {object} [params] Clients parameters. - * @param {number} [params.per_page] Number of results per page. - * @param {number} [params.page] Page number, zero indexed. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ClientsManager, 'getAll', 'resource.getAll'); + getAll(...args) { + return this.resource.getAll(...args); + } -/** - * Get an Auth0 client. - * - * @function get - * @memberof module:management.ClientsManager.prototype - * @example - * management.clients.get({ client_id: CLIENT_ID }, function (err, client) { - * if (err) { - * // Handle error. - * } - * - * console.log(client); - * }); - * @param {object} params Client parameters. - * @param {string} params.client_id Application client ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ClientsManager, 'get', 'resource.get'); + /** + * Get an Auth0 client. + * + * @example + * management.clients.get({ client_id: CLIENT_ID }, function (err, client) { + * if (err) { + * // Handle error. + * } + * + * console.log(client); + * }); + * @param {object} params Client parameters. + * @param {string} params.client_id Application client ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + get(...args) { + return this.resource.get(...args); + } -/** - * Update an Auth0 client. - * - * @function update - * @memberof module:management.ClientsManager.prototype - * @example - * var data = { name: 'newClientName' }; - * var params = { client_id: CLIENT_ID }; - * - * management.clients.update(params, data, function (err, client) { - * if (err) { - * // Handle error. - * } - * - * console.log(client.name); // 'newClientName' - * }); - * @param {object} params Client parameters. - * @param {string} params.client_id Application client ID. - * @param {object} data Updated client data. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ClientsManager, 'update', 'resource.patch'); + /** + * Update an Auth0 client. + * + * @example + * var data = { name: 'newClientName' }; + * var params = { client_id: CLIENT_ID }; + * + * management.clients.update(params, data, function (err, client) { + * if (err) { + * // Handle error. + * } + * + * console.log(client.name); // 'newClientName' + * }); + * @param {object} params Client parameters. + * @param {string} params.client_id Application client ID. + * @param {object} data Updated client data. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + update(...args) { + return this.resource.patch(...args); + } -/** - * Delete an Auth0 client. - * - * @function delete - * @memberof module:management.ClientsManager.prototype - * @example - * management.clients.delete({ client_id: CLIENT_ID }, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Client deleted. - * }); - * @param {object} params Client parameters. - * @param {string} params.client_id Application client ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ClientsManager, 'delete', 'resource.delete'); + /** + * Delete an Auth0 client. + * + * @example + * management.clients.delete({ client_id: CLIENT_ID }, function (err) { + * if (err) { + * // Handle error. + * } + * + * // Client deleted. + * }); + * @param {object} params Client parameters. + * @param {string} params.client_id Application client ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + delete(...args) { + return this.resource.delete(...args); + } +} module.exports = ClientsManager; diff --git a/src/management/ConnectionsManager.js b/src/management/ConnectionsManager.js index d157aa216..42650da5d 100644 --- a/src/management/ConnectionsManager.js +++ b/src/management/ConnectionsManager.js @@ -74,8 +74,6 @@ class ConnectionsManager { /** * Create a new connection. * - * @function create - * @memberof module:management.ConnectionsManager.prototype * @example * management.connections.create(data, function (err) { * if (err) { @@ -95,8 +93,6 @@ class ConnectionsManager { /** * Get all connections. * - * @function getAll - * @memberof module:management.ConnectionsManager.prototype * @example * This method takes an optional object as first argument that may be used to * specify pagination settings. If pagination options are not present, @@ -125,8 +121,6 @@ class ConnectionsManager { /** * Get an Auth0 connection. * - * @function get - * @memberof module:management.ConnectionsManager.prototype * @example * management.connections.get({ id: CONNECTION_ID }, function (err, connection) { * if (err) { @@ -147,8 +141,6 @@ class ConnectionsManager { /** * Update an existing connection. * - * @function update - * @memberof module:management.ConnectionsManager.prototype * @example * var data = { name: 'newConnectionName' }; * var params = { id: CONNECTION_ID }; @@ -173,8 +165,6 @@ class ConnectionsManager { /** * Delete an existing connection. * - * @function delete - * @memberof module:management.ConnectionsManager.prototype * @example * management.connections.delete({ id: CONNECTION_ID }, function (err) { * if (err) { @@ -195,8 +185,6 @@ class ConnectionsManager { /** * Checks the status of an ad/ldap connection referenced by its ID. * - * @function checkStatus - * @memberOf module:management.OrganizationsManager.prototype * @example * var params = {id : 'CONNECTION_ID'} * @example @@ -222,8 +210,6 @@ class ConnectionsManager { /** * Delete a connection user by email. * - * @function delete - * @memberof module:management.ConnectionsManager.prototype * @example * management.connections.deleteUserByEmail({ id: CONNECTION_ID, email:USER_EMAIL }, function (err) { * if (err) { diff --git a/src/management/CustomDomainsManager.js b/src/management/CustomDomainsManager.js index 75d3f483a..296ed61aa 100644 --- a/src/management/CustomDomainsManager.js +++ b/src/management/CustomDomainsManager.js @@ -1,10 +1,8 @@ const { ArgumentError } = require('rest-facade'); -const utils = require('../utils'); const Auth0RestClient = require('../Auth0RestClient'); const RetryRestClient = require('../RetryRestClient'); /** - * @class CustomDomainsManager * Auth0 Custom Domains Manager. * * {@link https://auth0.com/docs/api/management/v2#!/Custom_Domains/get_custom_domains CustomDomains} represent @@ -12,164 +10,164 @@ const RetryRestClient = require('../RetryRestClient'); * You can learn more about this in the * {@link https://auth0.com/docs/custom-domains CustomDomains} section of the * documentation. - * @class - * @memberof module:management - * @param {object} options The client options. - * @param {string} options.baseUrl The URL of the API. - * @param {object} [options.headers] Headers to be included in all requests. - * @param {object} [options.retry] Retry Policy Config */ -const CustomDomainsManager = function (options) { - if (options === null || typeof options !== 'object') { - throw new ArgumentError('Must provide manager options'); - } +class CustomDomainsManager { + /** + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config + */ + constructor(options) { + if (options === null || typeof options !== 'object') { + throw new ArgumentError('Must provide manager options'); + } - if (options.baseUrl === null || options.baseUrl === undefined) { - throw new ArgumentError('Must provide a base URL for the API'); - } + if (options.baseUrl === null || options.baseUrl === undefined) { + throw new ArgumentError('Must provide a base URL for the API'); + } + + if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { + throw new ArgumentError('The provided base URL is invalid'); + } + + /** + * Options object for the Rest Client instance. + * + * @type {object} + */ + const clientOptions = { + errorFormatter: { message: 'message', name: 'error' }, + headers: options.headers, + query: { repeatParams: false }, + }; - if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { - throw new ArgumentError('The provided base URL is invalid'); + /** + * Provides an abstraction layer for consuming the + * {@link https://auth0.com/docs/api/v2#!/Custom_Domains Auth0 Custom Domains endpoint}. + * + * @type {external:RestClient} + */ + const auth0CustomDomainsRestClient = new Auth0RestClient( + `${options.baseUrl}/custom-domains/:id`, + clientOptions, + options.tokenProvider + ); + this.resource = new RetryRestClient(auth0CustomDomainsRestClient, options.retry); + + /** + * Provides an abstraction layer for consuming the + * {@link https://auth0.com/docs/api/v2#!/Custom_Domains Auth0 Custom Domains Verify endpoint}. + * + * @type {external:RestClient} + */ + const auth0VerifyRestClient = new Auth0RestClient( + `${options.baseUrl}/custom-domains/:id/verify`, + clientOptions, + options.tokenProvider + ); + this.vefifyResource = new RetryRestClient(auth0VerifyRestClient, options.retry); } /** - * Options object for the Rest Client instance. + * Create an Auth0 Custom Domain. + * + * @example + * management.customDomains.create(data, function (err) { + * if (err) { + * // Handle error. + * } * - * @type {object} + * // CustomDomain created. + * }); + * @param {object} data The custom domain data object. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const clientOptions = { - errorFormatter: { message: 'message', name: 'error' }, - headers: options.headers, - query: { repeatParams: false }, - }; + create(...args) { + return this.resource.create(...args); + } /** - * Provides an abstraction layer for consuming the - * {@link https://auth0.com/docs/api/v2#!/Custom_Domains Auth0 Custom Domains endpoint}. + * Get all Auth0 CustomDomains. * - * @type {external:RestClient} + * @example + * management.customDomains.getAll(function (err, customDomains) { + * console.log(customDomains.length); + * }); + * @returns {Promise|undefined} */ - const auth0CustomDomainsRestClient = new Auth0RestClient( - `${options.baseUrl}/custom-domains/:id`, - clientOptions, - options.tokenProvider - ); - this.resource = new RetryRestClient(auth0CustomDomainsRestClient, options.retry); + getAll(...args) { + return this.resource.getAll(...args); + } /** - * Provides an abstraction layer for consuming the - * {@link https://auth0.com/docs/api/v2#!/Custom_Domains Auth0 Custom Domains Verify endpoint}. + * Get a Custom Domain. + * + * @example + * management.customDomains.get({ id: CUSTOM_DOMAIN_ID }, function (err, customDomain) { + * if (err) { + * // Handle error. + * } * - * @type {external:RestClient} + * console.log(customDomain); + * }); + * @param {object} params Custom Domain parameters. + * @param {string} params.id Custom Domain ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const auth0VerifyRestClient = new Auth0RestClient( - `${options.baseUrl}/custom-domains/:id/verify`, - clientOptions, - options.tokenProvider - ); - this.vefifyResource = new RetryRestClient(auth0VerifyRestClient, options.retry); -}; - -/** - * Create an Auth0 Custom Domain. - * - * @function create - * @memberof module:management.CustomDomainsManager.prototype - * @example - * management.customDomains.create(data, function (err) { - * if (err) { - * // Handle error. - * } - * - * // CustomDomain created. - * }); - * @param {object} data The custom domain data object. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(CustomDomainsManager, 'create', 'resource.create'); + get(...args) { + return this.resource.get(...args); + } -/** - * Get all Auth0 CustomDomains. - * - * @function getAll - * @memberof module:management.CustomDomainsManager.prototype - * @example - * management.customDomains.getAll(function (err, customDomains) { - * console.log(customDomains.length); - * }); - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(CustomDomainsManager, 'getAll', 'resource.getAll'); + /** + * Verify a Custom Domain. + * + * @example + * management.customDomains.verify({ id: CUSTOM_DOMAIN_ID }, function (err, customDomain) { + * if (err) { + * // Handle error. + * } + * + * console.log(customDomain); + * }); + * @param {object} params Custom Domain parameters. + * @param {string} params.id Custom Domain ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + verify(params, cb) { + if (!params || !params.id) { + throw new ArgumentError('The custom domain id cannot be null or undefined'); + } -/** - * Get a Custom Domain. - * - * @function get - * @memberof module:management.CustomDomainsManager.prototype - * @example - * management.customDomains.get({ id: CUSTOM_DOMAIN_ID }, function (err, customDomain) { - * if (err) { - * // Handle error. - * } - * - * console.log(customDomain); - * }); - * @param {object} params Custom Domain parameters. - * @param {string} params.id Custom Domain ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(CustomDomainsManager, 'get', 'resource.get'); + if (cb && cb instanceof Function) { + return this.vefifyResource.create(params, {}, cb); + } -/** - * Verify a Custom Domain. - * - * @function verify - * @memberof module:management.CustomDomainsManager.prototype - * @example - * management.customDomains.verify({ id: CUSTOM_DOMAIN_ID }, function (err, customDomain) { - * if (err) { - * // Handle error. - * } - * - * console.log(customDomain); - * }); - * @param {object} params Custom Domain parameters. - * @param {string} params.id Custom Domain ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -CustomDomainsManager.prototype.verify = function (params, cb) { - if (!params || !params.id) { - throw new ArgumentError('The custom domain id cannot be null or undefined'); + return this.vefifyResource.create(params, {}); } - if (cb && cb instanceof Function) { - return this.vefifyResource.create(params, {}, cb); + /** + * Delete a Custom Domain. + * + * @example + * management.customDomains.delete({ id: CUSTOM_DOMAIN_ID }, function (err) { + * if (err) { + * // Handle error. + * } + * + * // CustomDomain deleted. + * }); + * @param {object} params Custom Domain parameters. + * @param {string} params.id Custom Domain ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + delete(...args) { + return this.resource.delete(...args); } - - return this.vefifyResource.create(params, {}); -}; - -/** - * Delete a Custom Domain. - * - * @function delete - * @memberof module:management.CustomDomainsManager.prototype - * @example - * management.customDomains.delete({ id: CUSTOM_DOMAIN_ID }, function (err) { - * if (err) { - * // Handle error. - * } - * - * // CustomDomain deleted. - * }); - * @param {object} params Custom Domain parameters. - * @param {string} params.id Custom Domain ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(CustomDomainsManager, 'delete', 'resource.delete'); +} module.exports = CustomDomainsManager; diff --git a/src/management/DeviceCredentialsManager.js b/src/management/DeviceCredentialsManager.js index aaa5b51b6..0143059a8 100644 --- a/src/management/DeviceCredentialsManager.js +++ b/src/management/DeviceCredentialsManager.js @@ -1,120 +1,113 @@ const { ArgumentError } = require('rest-facade'); -const utils = require('../utils'); const Auth0RestClient = require('../Auth0RestClient'); const RetryRestClient = require('../RetryRestClient'); /** - * Simple facade for consuming a REST API endpoint. - * - * @external RestClient - * @see https://github.com/ngonzalvez/rest-facade - */ - -/** - * @class DeviceCredentialsManager * Manages Auth0 Device Credentials. - * @class - * @memberof module:management - * @param {object} options The client options. - * @param {string} options.baseUrl The URL of the API. - * @param {object} [options.headers] Headers to be included in all requests. - * @param {object} [options.retry] Retry Policy Config */ -const DeviceCredentialsManager = function (options) { - if (options === null || typeof options !== 'object') { - throw new ArgumentError('Must provide manager options'); - } +class DeviceCredentialsManager { + /** + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config + */ + constructor(options) { + if (options === null || typeof options !== 'object') { + throw new ArgumentError('Must provide manager options'); + } - if (options.baseUrl === null || options.baseUrl === undefined) { - throw new ArgumentError('Must provide a base URL for the API'); - } + if (options.baseUrl === null || options.baseUrl === undefined) { + throw new ArgumentError('Must provide a base URL for the API'); + } - if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { - throw new ArgumentError('The provided base URL is invalid'); + if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { + throw new ArgumentError('The provided base URL is invalid'); + } + + /** + * Options object for the RestClient instance. + * + * @type {object} + */ + const clientOptions = { + errorFormatter: { message: 'message', name: 'error' }, + headers: options.headers, + query: { repeatParams: false }, + }; + + /** + * Provides an abstraction layer for consuming the + * {@link https://auth0.com/docs/api/v2#!/Device_Credentials + * Auth0 DeviceCredentialsManagers endpoint}. + * + * @type {external:RestClient} + */ + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/device-credentials/:id`, + clientOptions, + options.tokenProvider + ); + this.resource = new RetryRestClient(auth0RestClient, options.retry); } /** - * Options object for the RestClient instance. + * Create an Auth0 credential. * - * @type {object} + * @example + * management.deviceCredentials.create(data, function (err) { + * if (err) { + * // Handle error. + * } + * + * // Credential created. + * }); + * @param {object} data The device credential data object. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const clientOptions = { - errorFormatter: { message: 'message', name: 'error' }, - headers: options.headers, - query: { repeatParams: false }, - }; + createPublicKey(...args) { + return this.resource.create(...args); + } /** - * Provides an abstraction layer for consuming the - * {@link https://auth0.com/docs/api/v2#!/Device_Credentials - * Auth0 DeviceCredentialsManagers endpoint}. + * Get all Auth0 credentials. * - * @type {external:RestClient} + * @example + * var params = {user_id: "USER_ID"}; + * + * management.deviceCredentials.getAll(params, function (err, credentials) { + * console.log(credentials.length); + * }); + * @param {object} params Credential parameters. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const auth0RestClient = new Auth0RestClient( - `${options.baseUrl}/device-credentials/:id`, - clientOptions, - options.tokenProvider - ); - this.resource = new RetryRestClient(auth0RestClient, options.retry); -}; - -/** - * Create an Auth0 credential. - * - * @function create - * @memberof module:management.DeviceCredentialsManager.prototype - * @example - * management.deviceCredentials.create(data, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Credential created. - * }); - * @param {object} data The device credential data object. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(DeviceCredentialsManager, 'createPublicKey', 'resource.create'); - -/** - * Get all Auth0 credentials. - * - * @function getAll - * @memberof module:management.DeviceCredentialsManager.prototype - * @example - * var params = {user_id: "USER_ID"}; - * - * management.deviceCredentials.getAll(params, function (err, credentials) { - * console.log(credentials.length); - * }); - * @param {object} params Credential parameters. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(DeviceCredentialsManager, 'getAll', 'resource.getAll'); + getAll(...args) { + return this.resource.getAll(...args); + } -/** - * Delete an Auth0 device credential. - * - * @function delete - * @memberof module:management.DeviceCredentialsManager.prototype - * @example - * var params = { id: CREDENTIAL_ID }; - * - * management.deviceCredentials.delete(params, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Credential deleted. - * }); - * @param {object} params Credential parameters. - * @param {string} params.id Device credential ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(DeviceCredentialsManager, 'delete', 'resource.delete'); + /** + * Delete an Auth0 device credential. + * + * @example + * var params = { id: CREDENTIAL_ID }; + * + * management.deviceCredentials.delete(params, function (err) { + * if (err) { + * // Handle error. + * } + * + * // Credential deleted. + * }); + * @param {object} params Credential parameters. + * @param {string} params.id Device credential ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + delete(...args) { + return this.resource.delete(...args); + } +} module.exports = DeviceCredentialsManager; diff --git a/src/management/EmailProviderManager.js b/src/management/EmailProviderManager.js index 45849124d..2905b0d9f 100644 --- a/src/management/EmailProviderManager.js +++ b/src/management/EmailProviderManager.js @@ -1,136 +1,129 @@ const { ArgumentError } = require('rest-facade'); -const utils = require('../utils'); const Auth0RestClient = require('../Auth0RestClient'); const RetryRestClient = require('../RetryRestClient'); /** - * Simple facade for consuming a REST API endpoint. - * - * @external RestClient - * @see https://github.com/ngonzalvez/rest-facade - */ - -/** - * @class EmailProviderManager * Auth0 Email Provider. - * @class - * @memberof module:management - * @param {object} options The client options. - * @param {string} options.baseUrl The URL of the API. - * @param {object} [options.headers] Headers to be included in all requests. - * @param {object} [options.retry] Retry Policy Config */ -const EmailProviderManager = function (options) { - if (options === null || typeof options !== 'object') { - throw new ArgumentError('Must provide client options'); - } +class EmailProviderManager { + /** + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config + */ + constructor(options) { + if (options === null || typeof options !== 'object') { + throw new ArgumentError('Must provide client options'); + } - if (options.baseUrl === null || options.baseUrl === undefined) { - throw new ArgumentError('Must provide a base URL for the API'); - } + if (options.baseUrl === null || options.baseUrl === undefined) { + throw new ArgumentError('Must provide a base URL for the API'); + } + + if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { + throw new ArgumentError('The provided base URL is invalid'); + } - if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { - throw new ArgumentError('The provided base URL is invalid'); + /** + * Options object for the Rest Client instance. + * + * @type {object} + */ + const clientOptions = { + errorFormatter: { message: 'message', name: 'error' }, + headers: options.headers, + query: { repeatParams: false }, + }; + + /** + * Provides an abstraction layer for consuming the + * [Auth0 Clients endpoint]{@link https://auth0.com/docs/api/v2#!/Clients}. + * + * @type {external:RestClient} + */ + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/emails/provider`, + clientOptions, + options.tokenProvider + ); + this.resource = new RetryRestClient(auth0RestClient, options.retry); } /** - * Options object for the Rest Client instance. + * Configure the email provider. + * + * @example + * management.emailProvider.configure(data, function (err) { + * if (err) { + * // Handle error. + * } * - * @type {object} + * // Email provider configured. + * }); + * @param {object} data The email provider data object. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const clientOptions = { - errorFormatter: { message: 'message', name: 'error' }, - headers: options.headers, - query: { repeatParams: false }, - }; + configure(...args) { + return this.resource.create(...args); + } /** - * Provides an abstraction layer for consuming the - * [Auth0 Clients endpoint]{@link https://auth0.com/docs/api/v2#!/Clients}. + * Get the email provider. * - * @type {external:RestClient} + * @example + * management.emailProvider.get(function (err, provider) { + * console.log(provider); + * }); + * @param {Function} [cb] Callback function. + * @param {object} [params] Clients parameters. + * @param {number} [params.fields] A comma separated list of fields to include or exclude (depending on include_fields) from the result, empty to retrieve: name, enabled, settings fields. + * @param {number} [params.include_fields] true if the fields specified are to be excluded from the result, false otherwise (defaults to true) + * @returns {Promise|undefined} */ - const auth0RestClient = new Auth0RestClient( - `${options.baseUrl}/emails/provider`, - clientOptions, - options.tokenProvider - ); - this.resource = new RetryRestClient(auth0RestClient, options.retry); -}; - -/** - * Configure the email provider. - * - * @function configure - * @memberof module:management.EmailProviderManager.prototype - * @example - * management.emailProvider.configure(data, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Email provider configured. - * }); - * @param {object} data The email provider data object. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(EmailProviderManager, 'configure', 'resource.create'); - -/** - * Get the email provider. - * - * @function get - * @memberof module:management.EmailProviderManager.prototype - * @example - * management.emailProvider.get(function (err, provider) { - * console.log(provider); - * }); - * @param {Function} [cb] Callback function. - * @param {object} [params] Clients parameters. - * @param {number} [params.fields] A comma separated list of fields to include or exclude (depending on include_fields) from the result, empty to retrieve: name, enabled, settings fields. - * @param {number} [params.include_fields] true if the fields specified are to be excluded from the result, false otherwise (defaults to true) - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(EmailProviderManager, 'get', 'resource.getAll'); + get(...args) { + return this.resource.getAll(...args); + } -/** - * Update the email provider. - * - * @function update - * @memberof module:management.EmailProviderManager.prototype - * @example - * management.emailProvider.update(params, data, function (err, provider) { - * if (err) { - * // Handle error. - * } - * - * // Updated email provider. - * console.log(provider); - * }); - * @param {object} params Email provider parameters. - * @param {object} data Updated email provider data. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(EmailProviderManager, 'update', 'resource.patch'); + /** + * Update the email provider. + * + * @example + * management.emailProvider.update(params, data, function (err, provider) { + * if (err) { + * // Handle error. + * } + * + * // Updated email provider. + * console.log(provider); + * }); + * @param {object} params Email provider parameters. + * @param {object} data Updated email provider data. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + update(...args) { + return this.resource.patch(...args); + } -/** - * Delete email provider. - * - * @function delete - * @memberof module:management.EmailProviderManager.prototype - * @example - * management.emailProvider.delete(function (err) { - * if (err) { - * // Handle error. - * } - * - * // Email provider configured. - * }); - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(EmailProviderManager, 'delete', 'resource.delete'); + /** + * Delete email provider. + * + * @example + * management.emailProvider.delete(function (err) { + * if (err) { + * // Handle error. + * } + * + * // Email provider configured. + * }); + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + delete(...args) { + return this.resource.delete(...args); + } +} module.exports = EmailProviderManager; diff --git a/src/management/EmailTemplatesManager.js b/src/management/EmailTemplatesManager.js index 7607c901f..3ff1cd1c7 100644 --- a/src/management/EmailTemplatesManager.js +++ b/src/management/EmailTemplatesManager.js @@ -1,120 +1,113 @@ const { ArgumentError } = require('rest-facade'); -const utils = require('../utils'); const Auth0RestClient = require('../Auth0RestClient'); const RetryRestClient = require('../RetryRestClient'); /** - * Simple facade for consuming a REST API endpoint. - * - * @external RestClient - * @see https://github.com/ngonzalvez/rest-facade - */ - -/** - * @class EmailTemplatesManager * This class provides a simple abstraction for performing CRUD operations - * on Auth0's Email Templates. {@see https://auth0.com/docs/api/management/v2#!/Email_Templates/get_email_templates_by_templateName} - * @class - * @memberof module:management - * @param {object} options The client options. - * @param {string} options.baseUrl The URL of the API. - * @param {object} [options.headers] Headers to be included in all requests. - * @param {object} [options.retry] Retry Policy Config + * on Auth0's Email Templates. {@link https://auth0.com/docs/api/management/v2#!/Email_Templates/get_email_templates_by_templateName} */ -const EmailTemplatesManager = function (options) { - if (!options || 'object' !== typeof options) { - throw new ArgumentError('Must provide manager options'); - } +class EmailTemplatesManager { + /** + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config + */ + constructor(options) { + if (!options || 'object' !== typeof options) { + throw new ArgumentError('Must provide manager options'); + } + + if (!options.baseUrl || 'string' !== typeof options.baseUrl) { + throw new ArgumentError('Must provide a valid string as base URL for the API'); + } - if (!options.baseUrl || 'string' !== typeof options.baseUrl) { - throw new ArgumentError('Must provide a valid string as base URL for the API'); + /** + * Options object for the Rest Client instance. + * + * @type {object} + */ + const clientOptions = { + headers: options.headers, + query: { repeatParams: false }, + }; + + /** + * Provides an abstraction layer for performing CRUD operations on + * {@link https://auth0.com/docs/api/management/v2#!/Email_Templates/get_email_templates_by_templateName Auth0's Email Templates}. + * + * @type {external:RestClient} + */ + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/email-templates/:name`, + clientOptions, + options.tokenProvider + ); + this.resource = new RetryRestClient(auth0RestClient, options.retry); } /** - * Options object for the Rest Client instance. + * Create a new Email Template. + * + * @example + * management.emailTemplates.create(data, function (err) { + * if (err) { + * // Handle error. + * } * - * @type {object} + * // Email Template created. + * }); + * @param {object} data Email Template data object. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const clientOptions = { - headers: options.headers, - query: { repeatParams: false }, - }; + create(...args) { + return this.resource.create(...args); + } /** - * Provides an abstraction layer for performing CRUD operations on - * {@link https://auth0.com/docs/api/management/v2#!/Email_Templates/get_email_templates_by_templateName Auth0's Email Templates}. + * Get an Auth0 Email Template. * - * @type {external:RestClient} + * @example + * management.emailTemplates.get({ name: EMAIL_TEMPLATE_NAME }, function (err, emailTemplate) { + * if (err) { + * // Handle error. + * } + * + * console.log(emailTemplate); + * }); + * @param {object} params Email Template parameters. + * @param {string} params.name Template Name + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const auth0RestClient = new Auth0RestClient( - `${options.baseUrl}/email-templates/:name`, - clientOptions, - options.tokenProvider - ); - this.resource = new RetryRestClient(auth0RestClient, options.retry); -}; - -/** - * Create a new Email Template. - * - * @function create - * @memberof module:management.EmailTemplatesManager.prototype - * @example - * management.emailTemplates.create(data, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Email Template created. - * }); - * @param {object} data Email Template data object. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(EmailTemplatesManager, 'create', 'resource.create'); - -/** - * Get an Auth0 Email Template. - * - * @function get - * @memberof module:management.EmailTemplatesManager.prototype - * @example - * management.emailTemplates.get({ name: EMAIL_TEMPLATE_NAME }, function (err, emailTemplate) { - * if (err) { - * // Handle error. - * } - * - * console.log(emailTemplate); - * }); - * @param {object} params Email Template parameters. - * @param {string} params.name Template Name - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(EmailTemplatesManager, 'get', 'resource.get'); + get(...args) { + return this.resource.get(...args); + } -/** - * Update an existing Email Template. - * - * @function update - * @memberof module:management.EmailTemplatesManager.prototype - * @example - * var data = { from: 'new@email.com' }; - * var params = { name: EMAIL_TEMPLATE_NAME }; - * - * management.emailTemplates.update(params, data, function (err, emailTemplate) { - * if (err) { - * // Handle error. - * } - * - * console.log(emailTemplate.from); // 'new@email.com' - * }); - * @param {object} params Email Template parameters. - * @param {string} params.name Template Name - * @param {object} data Updated Email Template data. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(EmailTemplatesManager, 'update', 'resource.patch'); + /** + * Update an existing Email Template. + * + * @example + * var data = { from: 'new@email.com' }; + * var params = { name: EMAIL_TEMPLATE_NAME }; + * + * management.emailTemplates.update(params, data, function (err, emailTemplate) { + * if (err) { + * // Handle error. + * } + * + * console.log(emailTemplate.from); // 'new@email.com' + * }); + * @param {object} params Email Template parameters. + * @param {string} params.name Template Name + * @param {object} data Updated Email Template data. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + update(...args) { + return this.resource.patch(...args); + } +} module.exports = EmailTemplatesManager; diff --git a/src/management/GrantsManager.js b/src/management/GrantsManager.js index f2a281ea0..bc5d3f2d2 100644 --- a/src/management/GrantsManager.js +++ b/src/management/GrantsManager.js @@ -1,111 +1,112 @@ const { ArgumentError } = require('rest-facade'); -const utils = require('../utils'); const Auth0RestClient = require('../Auth0RestClient'); const RetryRestClient = require('../RetryRestClient'); + /** - * @class GrantsManager * Auth0 Grants Manager. * * See {@link https://auth0.com/docs/api/v2#!/Grants Grants} - * @class - * @memberof module:management - * @param {object} options The client options. - * @param {string} options.baseUrl The URL of the API. - * @param {object} [options.headers] Headers to be included in all requests. - * @param {object} [options.retry] Retry Policy Config */ -const GrantsManager = function (options) { - if (options === null || typeof options !== 'object') { - throw new ArgumentError('Must provide client options'); - } +class GrantsManager { + /** + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config + */ + constructor(options) { + if (options === null || typeof options !== 'object') { + throw new ArgumentError('Must provide client options'); + } - if (options.baseUrl === null || options.baseUrl === undefined) { - throw new ArgumentError('Must provide a base URL for the API'); - } + if (options.baseUrl === null || options.baseUrl === undefined) { + throw new ArgumentError('Must provide a base URL for the API'); + } + + if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { + throw new ArgumentError('The provided base URL is invalid'); + } - if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { - throw new ArgumentError('The provided base URL is invalid'); + /** + * Options object for the Rest Client instance. + * + * @type {object} + */ + const clientOptions = { + errorFormatter: { message: 'message', name: 'error' }, + headers: options.headers, + query: { repeatParams: false }, + }; + + /** + * Provides an abstraction layer for consuming the + * {@link https://auth0.com/docs/api/v2#!/Grants Auth0 Grants endpoint}. + * + * @type {external:RestClient} + */ + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/grants/:id`, + clientOptions, + options.tokenProvider + ); + this.resource = new RetryRestClient(auth0RestClient, options.retry); } /** - * Options object for the Rest Client instance. + * Get all Auth0 Grants. + * + * @example + * var params = { + * per_page: 10, + * page: 0, + * include_totals: true, + * user_id: 'USER_ID', + * client_id: 'CLIENT_ID', + * audience: 'AUDIENCE' + * }; * - * @type {object} + * management.getGrants(params, function (err, grants) { + * console.log(grants.length); + * }); + * @param {object} params Grants parameters. + * @param {number} params.per_page Number of results per page. + * @param {number} params.page Page number, zero indexed. + * @param {boolean} params.include_totals true if a query summary must be included in the result, false otherwise. Default false; + * @param {string} params.user_id The user_id of the grants to retrieve. + * @param {string} params.client_id The client_id of the grants to retrieve. + * @param {string} params.audience The audience of the grants to retrieve. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const clientOptions = { - errorFormatter: { message: 'message', name: 'error' }, - headers: options.headers, - query: { repeatParams: false }, - }; + getAll(...args) { + return this.resource.getAll(...args); + } /** - * Provides an abstraction layer for consuming the - * {@link https://auth0.com/docs/api/v2#!/Grants Auth0 Grants endpoint}. + * Delete an Auth0 grant. * - * @type {external:RestClient} + * @example + * var params = { + * id: 'GRANT_ID', + * user_id: 'USER_ID' + * }; + * + * management.deleteGrant(params, function (err) { + * if (err) { + * // Handle error. + * } + * + * // Grant deleted. + * }); + * @param {object} params Grant parameters. + * @param {string} params.id Grant ID. + * @param {string} params.user_id The user_id of the grants to delete. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const auth0RestClient = new Auth0RestClient( - `${options.baseUrl}/grants/:id`, - clientOptions, - options.tokenProvider - ); - this.resource = new RetryRestClient(auth0RestClient, options.retry); -}; - -/** - * Get all Auth0 Grants. - * - * @function getAll - * @memberof module:management.GrantsManager.prototype - * @example - * var params = { - * per_page: 10, - * page: 0, - * include_totals: true, - * user_id: 'USER_ID', - * client_id: 'CLIENT_ID', - * audience: 'AUDIENCE' - * }; - * - * management.getGrants(params, function (err, grants) { - * console.log(grants.length); - * }); - * @param {object} params Grants parameters. - * @param {number} params.per_page Number of results per page. - * @param {number} params.page Page number, zero indexed. - * @param {boolean} params.include_totals true if a query summary must be included in the result, false otherwise. Default false; - * @param {string} params.user_id The user_id of the grants to retrieve. - * @param {string} params.client_id The client_id of the grants to retrieve. - * @param {string} params.audience The audience of the grants to retrieve. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(GrantsManager, 'getAll', 'resource.getAll'); - -/** - * Delete an Auth0 grant. - * - * @function delete - * @memberof module:management.GrantsManager.prototype - * @example - * var params = { - * id: 'GRANT_ID', - * user_id: 'USER_ID' - * }; - * - * management.deleteGrant(params, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Grant deleted. - * }); - * @param {object} params Grant parameters. - * @param {string} params.id Grant ID. - * @param {string} params.user_id The user_id of the grants to delete. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(GrantsManager, 'delete', 'resource.delete'); + delete(...args) { + return this.resource.delete(...args); + } +} module.exports = GrantsManager; diff --git a/src/management/GuardianManager.js b/src/management/GuardianManager.js index 157b62e14..89d7de5a5 100644 --- a/src/management/GuardianManager.js +++ b/src/management/GuardianManager.js @@ -1,457 +1,434 @@ const { ArgumentError } = require('rest-facade'); -const utils = require('../utils'); const Auth0RestClient = require('../Auth0RestClient'); const RetryRestClient = require('../RetryRestClient'); /** - * Simple facade for consuming a REST API endpoint. - * - * @external RestClient - * @see https://github.com/ngonzalvez/rest-facade - */ - -/** - * @class * Abstracts interaction with the Guardian endpoint. - * @class - * @memberof module:management - * @param {object} options The client options. - * @param {string} options.baseUrl The URL of the API. - * @param {object} [options.headers] Headers to be included in all requests. - * @param {object} [options.retry] Retry Policy Config */ -const GuardianManager = function (options) { - if (options === null || typeof options !== 'object') { - throw new ArgumentError('Must provide manager options'); +class GuardianManager { + /** + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config + */ + constructor(options) { + if (options === null || typeof options !== 'object') { + throw new ArgumentError('Must provide manager options'); + } + + if (options.baseUrl === null || options.baseUrl === undefined) { + throw new ArgumentError('Must provide a base URL for the API'); + } + + if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { + throw new ArgumentError('The provided base URL is invalid'); + } + + const clientOptions = { + errorFormatter: { message: 'message', name: 'error' }, + headers: options.headers, + query: { repeatParams: false }, + }; + + /** + * Provides an abstraction layer for retrieving Guardian enrollments. + * + * @type {external:RestClient} + */ + const guardianEnrollmentsAuth0RestClient = new Auth0RestClient( + `${options.baseUrl}/guardian/enrollments/:id`, + clientOptions, + options.tokenProvider + ); + this.enrollments = new RetryRestClient(guardianEnrollmentsAuth0RestClient, options.retry); + + /** + * Provides an abstraction layer for retrieving Guardian tickets. + * + * @type {external:RestClient} + */ + const guardianTicketsAuth0RestClient = new Auth0RestClient( + `${options.baseUrl}/guardian/enrollments/ticket`, + clientOptions, + options.tokenProvider + ); + this.tickets = new RetryRestClient(guardianTicketsAuth0RestClient, options.retry); + + /** + * Provides an abstraction layer for retrieving Guardian factors. + * + * @type {external:RestClient} + */ + const guardianFactorsAuth0RestClient = new Auth0RestClient( + `${options.baseUrl}/guardian/factors/:name`, + clientOptions, + options.tokenProvider + ); + this.factors = new RetryRestClient(guardianFactorsAuth0RestClient, options.retry); + + /** + * Provides an abstraction layer for configuring Factor settings + * + * @type {external:RestClient} + */ + const guardianFactorSettingsAuth0RestClient = new Auth0RestClient( + `${options.baseUrl}/guardian/factors/:name/settings`, + clientOptions, + options.tokenProvider + ); + this.factorSettings = new RetryRestClient(guardianFactorSettingsAuth0RestClient, options.retry); + + /** + * Provides an abstraction layer for retrieving Guardian factor templates. + * + * @type {external:RestClient} + */ + const guardianFactorsTemplatesAuth0RestClient = new Auth0RestClient( + `${options.baseUrl}/guardian/factors/:name/templates`, + clientOptions, + options.tokenProvider + ); + this.factorsTemplates = new RetryRestClient( + guardianFactorsTemplatesAuth0RestClient, + options.retry + ); + + /** + * Provides an abstraction layer for retrieving Guardian factor providers. + * + * @type {external:RestClient} + */ + const guardianFactorsProvidersAuth0RestClient = new Auth0RestClient( + `${options.baseUrl}/guardian/factors/:name/providers/:provider`, + clientOptions, + options.tokenProvider + ); + this.factorsProviders = new RetryRestClient( + guardianFactorsProvidersAuth0RestClient, + options.retry + ); + + /** + * Provides an abstraction layer for retrieving Guardian policies. + * + * @type {external:RestClient} + */ + const guardianPoliciesAuth0RestClient = new Auth0RestClient( + `${options.baseUrl}/guardian/policies`, + clientOptions, + options.tokenProvider + ); + this.policies = new RetryRestClient(guardianPoliciesAuth0RestClient, options.retry); + + /** + * Provides an abstraction layer for retrieving Guardian phone factor selected provider. + * + * @type {external:RestClient} + */ + const guardianFactorsPhoneSelectedProviderAuth0RestClient = new Auth0RestClient( + `${options.baseUrl}/guardian/factors/sms/selected-provider`, + clientOptions, + options.tokenProvider + ); + this.factorsPhoneSelectedProvider = new RetryRestClient( + guardianFactorsPhoneSelectedProviderAuth0RestClient, + options.retry + ); + + /** + * Provides an abstraction layer for retrieving Guardian phone factor message types. + * + * @type {external:RestClient} + */ + const guardianFactorsPhoneMessageTypesAuth0RestClient = new Auth0RestClient( + `${options.baseUrl}/guardian/factors/phone/message-types`, + clientOptions, + options.tokenProvider + ); + this.factorsPhoneMessageTypes = new RetryRestClient( + guardianFactorsPhoneMessageTypesAuth0RestClient, + options.retry + ); } - if (options.baseUrl === null || options.baseUrl === undefined) { - throw new ArgumentError('Must provide a base URL for the API'); + /** + * Get a single Guardian enrollment. + * + * @example + * management.guardian.getGuardianEnrollment({ id: ENROLLMENT_ID }, function (err, enrollment) { + * console.log(enrollment); + * }); + * @param {object} data The user data object. + * @param {string} data.id The user id. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getGuardianEnrollment(...args) { + return this.enrollments.get(...args); } - if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { - throw new ArgumentError('The provided base URL is invalid'); + /** + * Delete a Guardian enrollment. + * + * @example + * management.guardian.deleteGuardianEnrollment({ id: ENROLLMENT_ID }, function (err, enrollments) { + * console.log(enrollments); + * }); + * @param {object} data The user data object. + * @param {string} data.id The user id. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + deleteGuardianEnrollment(...args) { + return this.enrollments.delete(...args); } - const clientOptions = { - errorFormatter: { message: 'message', name: 'error' }, - headers: options.headers, - query: { repeatParams: false }, - }; - /** - * Provides an abstraction layer for retrieving Guardian enrollments. + * Create a Guardian enrollment ticket. * - * @type {external:RestClient} + * @example + * management.guardian.createEnrollmentTicket(function (err, ticket) { + * console.log(ticket); + * }); + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const guardianEnrollmentsAuth0RestClient = new Auth0RestClient( - `${options.baseUrl}/guardian/enrollments/:id`, - clientOptions, - options.tokenProvider - ); - this.enrollments = new RetryRestClient(guardianEnrollmentsAuth0RestClient, options.retry); + createEnrollmentTicket(...args) { + return this.tickets.create(...args); + } /** - * Provides an abstraction layer for retrieving Guardian tickets. + * Get a list of factors and statuses. * - * @type {external:RestClient} + * @example + * management.guardian.getFactors(function (err, factors) { + * console.log(factors.length); + * }); + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const guardianTicketsAuth0RestClient = new Auth0RestClient( - `${options.baseUrl}/guardian/enrollments/ticket`, - clientOptions, - options.tokenProvider - ); - this.tickets = new RetryRestClient(guardianTicketsAuth0RestClient, options.retry); + getFactors(...args) { + return this.factors.getAll(...args); + } /** - * Provides an abstraction layer for retrieving Guardian factors. + * Get Guardian factor configuration * - * @type {external:RestClient} + * @example + * management.guardian.getFactorSettings({ name: 'webauthn-roaming' }, function (err, settings) { + * console.log(settings); + * }); + * @param {object} params Factor parameters. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const guardianFactorsAuth0RestClient = new Auth0RestClient( - `${options.baseUrl}/guardian/factors/:name`, - clientOptions, - options.tokenProvider - ); - this.factors = new RetryRestClient(guardianFactorsAuth0RestClient, options.retry); + getFactorSettings(...args) { + return this.factorSettings.get(...args); + } /** - * Provides an abstraction layer for configuring Factor settings + * Update Guardian factor configuration * - * @type {external:RestClient} + * @example + * management.guardian.updateFactorSettings( + * { name: 'webauthn-roaming' }, + * { userVerification: 'discouraged', overrideRelyingParty: false }, + * function (err, settings) { + * console.log(settings); + * }); + * @param {object} params Factor parameters. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const guardianFactorSettingsAuth0RestClient = new Auth0RestClient( - `${options.baseUrl}/guardian/factors/:name/settings`, - clientOptions, - options.tokenProvider - ); - this.factorSettings = new RetryRestClient(guardianFactorSettingsAuth0RestClient, options.retry); + updateFactorSettings(...args) { + return this.factorSettings.update(...args); + } /** - * Provides an abstraction layer for retrieving Guardian factor templates. + * Get Guardian factor provider configuration * - * @type {external:RestClient} + * @example + * management.guardian.getFactorProvider({ name: 'sms', provider: 'twilio'}, function (err, provider) { + * console.log(provider); + * }); + * @param {object} params Factor provider parameters. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const guardianFactorsTemplatesAuth0RestClient = new Auth0RestClient( - `${options.baseUrl}/guardian/factors/:name/templates`, - clientOptions, - options.tokenProvider - ); - this.factorsTemplates = new RetryRestClient( - guardianFactorsTemplatesAuth0RestClient, - options.retry - ); + getFactorProvider(...args) { + return this.factorsProviders.get(...args); + } /** - * Provides an abstraction layer for retrieving Guardian factor providers. + * Update Guardian's factor provider * - * @type {external:RestClient} + * @example + * management.guardian.updateFactorProvider({ name: 'sms', provider: 'twilio' }, { + * messaging_service_sid: 'XXXXXXXXXXXXXX', + * auth_token: 'XXXXXXXXXXXXXX', + * sid: 'XXXXXXXXXXXXXX' + * }, function (err, provider) { + * console.log(provider); + * }); + * @param {object} params Factor provider parameters. + * @param {object} data Updated Factor provider data. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const guardianFactorsProvidersAuth0RestClient = new Auth0RestClient( - `${options.baseUrl}/guardian/factors/:name/providers/:provider`, - clientOptions, - options.tokenProvider - ); - this.factorsProviders = new RetryRestClient( - guardianFactorsProvidersAuth0RestClient, - options.retry - ); + updateFactorProvider(...args) { + return this.factorsProviders.update(...args); + } /** - * Provides an abstraction layer for retrieving Guardian policies. + * Get Guardian enrollment and verification factor templates * - * @type {external:RestClient} + * @example + * management.guardian.getFactorTemplates({ name: 'sms' }, function (err, templates) { + * console.log(templates); + * }); + * @param {object} params Factor parameters. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const guardianPoliciesAuth0RestClient = new Auth0RestClient( - `${options.baseUrl}/guardian/policies`, - clientOptions, - options.tokenProvider - ); - this.policies = new RetryRestClient(guardianPoliciesAuth0RestClient, options.retry); + getFactorTemplates(...args) { + return this.factorsTemplates.get(...args); + } /** - * Provides an abstraction layer for retrieving Guardian phone factor selected provider. + * Update Guardian enrollment and verification factor templates * - * @type {external:RestClient} + * @example + * management.guardian.updateFactorProvider({ name: 'sms' }, { + * enrollment_message: "{{code}} is your verification code for {{tenant.friendly_name}}. Please enter this code to verify your enrollment.", + * verification_message: "{{code}} is your verification code for {{tenant.friendly_name}}" + * }, function (err, templates) { + * console.log(templates); + * }); + * @param {object} params Factor parameters. + * @param {object} data Updated factor templates data. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const guardianFactorsPhoneSelectedProviderAuth0RestClient = new Auth0RestClient( - `${options.baseUrl}/guardian/factors/sms/selected-provider`, - clientOptions, - options.tokenProvider - ); - this.factorsPhoneSelectedProvider = new RetryRestClient( - guardianFactorsPhoneSelectedProviderAuth0RestClient, - options.retry - ); + updateFactorTemplates(...args) { + return this.factorsTemplates.update(...args); + } /** - * Provides an abstraction layer for retrieving Guardian phone factor message types. + * Update Guardian Factor * - * @type {external:RestClient} + * @example + * management.guardian.updateFactor({ name: 'sms' }, { + * enabled: true + * }, function (err, factor) { + * console.log(factor); + * }); + * @param {object} params Factor parameters. + * @param {object} data Updated factor data. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const guardianFactorsPhoneMessageTypesAuth0RestClient = new Auth0RestClient( - `${options.baseUrl}/guardian/factors/phone/message-types`, - clientOptions, - options.tokenProvider - ); - this.factorsPhoneMessageTypes = new RetryRestClient( - guardianFactorsPhoneMessageTypesAuth0RestClient, - options.retry - ); -}; - -/** - * Get a single Guardian enrollment. - * - * @function getGuardianEnrollment - * @memberof module:management.GuardianManager.prototype - * @example - * management.guardian.getGuardianEnrollment({ id: ENROLLMENT_ID }, function (err, enrollment) { - * console.log(enrollment); - * }); - * @param {object} data The user data object. - * @param {string} data.id The user id. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(GuardianManager, 'getGuardianEnrollment', 'enrollments.get'); - -/** - * Delete a Guardian enrollment. - * - * @function deleteGuardianEnrollment - * @memberof module:management.GuardianManager.prototype - * @example - * management.guardian.deleteGuardianEnrollment({ id: ENROLLMENT_ID }, function (err, enrollments) { - * console.log(enrollments); - * }); - * @param {object} data The user data object. - * @param {string} data.id The user id. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(GuardianManager, 'deleteGuardianEnrollment', 'enrollments.delete'); - -/** - * Create a Guardian enrollment ticket. - * - * @function createEnrollmentTicket - * @memberof module:management.GuardianManager.prototype - * @example - * management.guardian.createEnrollmentTicket(function (err, ticket) { - * console.log(ticket); - * }); - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(GuardianManager, 'createEnrollmentTicket', 'tickets.create'); - -/** - * Get a list of factors and statuses. - * - * @function getFactors - * @memberof module:management.GuardianManager.prototype - * @example - * management.guardian.getFactors(function (err, factors) { - * console.log(factors.length); - * }); - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(GuardianManager, 'getFactors', 'factors.getAll'); - -/** - * Get Guardian factor configuration - * - * @function getFactorSettings - * @memberof module:management.GuardianManager.prototype - * @example - * management.guardian.getFactorSettings({ name: 'webauthn-roaming' }, function (err, settings) { - * console.log(settings); - * }); - * @param {object} params Factor parameters. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(GuardianManager, 'getFactorSettings', 'factorSettings.get'); - -/** - * Update Guardian factor configuration - * - * @function updateFactorSettings - * @memberof module:management.GuardianManager.prototype - * @example - * management.guardian.updateFactorSettings( - * { name: 'webauthn-roaming' }, - * { userVerification: 'discouraged', overrideRelyingParty: false }, - * function (err, settings) { - * console.log(settings); - * }); - * @param {object} params Factor parameters. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(GuardianManager, 'updateFactorSettings', 'factorSettings.update'); - -/** - * Get Guardian factor provider configuration - * - * @function getFactorProvider - * @memberof module:management.GuardianManager.prototype - * @example - * management.guardian.getFactorProvider({ name: 'sms', provider: 'twilio'}, function (err, provider) { - * console.log(provider); - * }); - * @param {object} params Factor provider parameters. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(GuardianManager, 'getFactorProvider', 'factorsProviders.get'); - -/** - * Update Guardian's factor provider - * - * @function updateFactorProvider - * @memberof module:management.GuardianManager.prototype - * @example - * management.guardian.updateFactorProvider({ name: 'sms', provider: 'twilio' }, { - * messaging_service_sid: 'XXXXXXXXXXXXXX', - * auth_token: 'XXXXXXXXXXXXXX', - * sid: 'XXXXXXXXXXXXXX' - * }, function (err, provider) { - * console.log(provider); - * }); - * @param {object} params Factor provider parameters. - * @param {object} data Updated Factor provider data. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(GuardianManager, 'updateFactorProvider', 'factorsProviders.update'); - -/** - * Get Guardian enrollment and verification factor templates - * - * @function getFactorTemplates - * @memberof module:management.GuardianManager.prototype - * @example - * management.guardian.getFactorTemplates({ name: 'sms' }, function (err, templates) { - * console.log(templates); - * }); - * @param {object} params Factor parameters. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(GuardianManager, 'getFactorTemplates', 'factorsTemplates.get'); - -/** - * Update Guardian enrollment and verification factor templates - * - * @function updateFactorTemplates - * @memberof module:management.GuardianManager.prototype - * @example - * management.guardian.updateFactorProvider({ name: 'sms' }, { - * enrollment_message: "{{code}} is your verification code for {{tenant.friendly_name}}. Please enter this code to verify your enrollment.", - * verification_message: "{{code}} is your verification code for {{tenant.friendly_name}}" - * }, function (err, templates) { - * console.log(templates); - * }); - * @param {object} params Factor parameters. - * @param {object} data Updated factor templates data. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(GuardianManager, 'updateFactorTemplates', 'factorsTemplates.update'); - -/** - * Update Guardian Factor - * - * @function updateFactor - * @memberof module:management.GuardianManager.prototype - * @example - * management.guardian.updateFactor({ name: 'sms' }, { - * enabled: true - * }, function (err, factor) { - * console.log(factor); - * }); - * @param {object} params Factor parameters. - * @param {object} data Updated factor data. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(GuardianManager, 'updateFactor', 'factors.update'); + updateFactor(...args) { + return this.factors.update(...args); + } -/** - * Get enabled Guardian policies - * - * @function getPolicies - * @memberof module:management.GuardianManager.prototype - * @example - * management.guardian.getPolicies(function (err, policies) { - * console.log(policies); - * }); - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(GuardianManager, 'getPolicies', 'policies.get'); + /** + * Get enabled Guardian policies + * + * @example + * management.guardian.getPolicies(function (err, policies) { + * console.log(policies); + * }); + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getPolicies(...args) { + return this.policies.get(...args); + } -/** - * Update enabled Guardian policies - * - * @function updatePolicies - * @memberof module:management.GuardianManager.prototype - * @example - * management.guardian.updatePolicies({}, [ - * 'all-applications' - * ], function (err, policies) { - * console.log(policies); - * }); - * @param {object} params Parameters. - * @param {string[]} data Policies to enable. Empty array disables all policies. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(GuardianManager, 'updatePolicies', 'policies.update'); + /** + * Update enabled Guardian policies + * + * @example + * management.guardian.updatePolicies({}, [ + * 'all-applications' + * ], function (err, policies) { + * console.log(policies); + * }); + * @param {object} params Parameters. + * @param {string[]} data Policies to enable. Empty array disables all policies. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + updatePolicies(...args) { + return this.policies.update(...args); + } -/** - * Get the Guardian phone factor's selected provider - * - * @function getPhoneFactorSelectedProvider - * @memberof module:management.GuardianManager.prototype - * @example - * management.guardian.getPhoneFactorSelectedProvider(function (err, selectedProvider) { - * console.log(selectedProvider); - * }); - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod( - GuardianManager, - 'getPhoneFactorSelectedProvider', - 'factorsPhoneSelectedProvider.get' -); + /** + * Get the Guardian phone factor's selected provider + * + * @example + * management.guardian.getPhoneFactorSelectedProvider(function (err, selectedProvider) { + * console.log(selectedProvider); + * }); + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getPhoneFactorSelectedProvider(...args) { + return this.factorsPhoneSelectedProvider.get(...args); + } -/** - * Update the Guardian phone factor's selected provider - * - * @function updatePhoneFactorSelectedProvider - * @memberof module:management.GuardianManager.prototype - * @example - * management.guardian.updatePhoneFactorSelectedProvider({}, { - * provider: 'twilio' - * }, function (err, factor) { - * console.log(factor); - * }); - * @param {object} params Parameters. - * @param {object} data Updated selected provider data. - * @param {string} data.provider Name of the selected provider - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod( - GuardianManager, - 'updatePhoneFactorSelectedProvider', - 'factorsPhoneSelectedProvider.update' -); + /** + * Update the Guardian phone factor's selected provider + * + * @example + * management.guardian.updatePhoneFactorSelectedProvider({}, { + * provider: 'twilio' + * }, function (err, factor) { + * console.log(factor); + * }); + * @param {object} params Parameters. + * @param {object} data Updated selected provider data. + * @param {string} data.provider Name of the selected provider + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + updatePhoneFactorSelectedProvider(...args) { + return this.factorsPhoneSelectedProvider.update(...args); + } -/** - * Get the Guardian phone factor's message types - * - * @function getPhoneFactorMessageTypes - * @memberof module:management.GuardianManager.prototype - * @example - * management.guardian.getPhoneFactorMessageTypes(function (err, messageTypes) { - * console.log(messageTypes); - * }); - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod( - GuardianManager, - 'getPhoneFactorMessageTypes', - 'factorsPhoneMessageTypes.get' -); + /** + * Get the Guardian phone factor's message types + * + * @example + * management.guardian.getPhoneFactorMessageTypes(function (err, messageTypes) { + * console.log(messageTypes); + * }); + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getPhoneFactorMessageTypes(...args) { + return this.factorsPhoneMessageTypes.get(...args); + } -/** - * Update the Guardian phone factor's message types - * - * @function updatePhoneFactorMessageTypes - * @memberof module:management.GuardianManager.prototype - * @example - * management.guardian.updatePhoneFactorMessageTypes({}, { - * message_types: ['sms', 'voice'] - * }, function (err, factor) { - * console.log(factor); - * }); - * @param {object} params Parameters. - * @param {object} data Updated selected provider data. - * @param {string[]} data.message_types Message types (only `"sms"` and `"voice"` are supported). - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod( - GuardianManager, - 'updatePhoneFactorMessageTypes', - 'factorsPhoneMessageTypes.update' -); + /** + * Update the Guardian phone factor's message types + * + * @example + * management.guardian.updatePhoneFactorMessageTypes({}, { + * message_types: ['sms', 'voice'] + * }, function (err, factor) { + * console.log(factor); + * }); + * @param {object} params Parameters. + * @param {object} data Updated selected provider data. + * @param {string[]} data.message_types Message types (only `"sms"` and `"voice"` are supported). + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + updatePhoneFactorMessageTypes(...args) { + return this.factorsPhoneMessageTypes.update(...args); + } +} module.exports = GuardianManager; diff --git a/src/management/HooksManager.js b/src/management/HooksManager.js index 729acf894..1d40910ee 100644 --- a/src/management/HooksManager.js +++ b/src/management/HooksManager.js @@ -1,342 +1,327 @@ const { ArgumentError } = require('rest-facade'); -const utils = require('../utils'); const Auth0RestClient = require('../Auth0RestClient'); const RetryRestClient = require('../RetryRestClient'); /** - * Simple facade for consuming a REST API endpoint. - * - * @external RestClient - * @see https://github.com/ngonzalvez/rest-facade - */ - -/** - * @class HooksManager * The hooks manager class provides a simple abstraction for performing CRUD operations * on Auth0 HooksManagers. - * @class - * @memberof module:management - * @param {object} options The client options. - * @param {string} options.baseUrl The URL of the API. - * @param {object} [options.headers] Headers to be included in all requests. - * @param {object} [options.retry] Retry Policy Config */ -const HooksManager = function (options) { - if (options === null || typeof options !== 'object') { - throw new ArgumentError('Must provide manager options'); +class HooksManager { + /** + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config + */ + constructor(options) { + if (options === null || typeof options !== 'object') { + throw new ArgumentError('Must provide manager options'); + } + + if (options.baseUrl === null || options.baseUrl === undefined) { + throw new ArgumentError('Must provide a base URL for the API'); + } + + if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { + throw new ArgumentError('The provided base URL is invalid'); + } + + /** + * Options object for the Rest Client instance. + * + * @type {object} + */ + const clientOptions = { + headers: options.headers, + query: { repeatParams: false }, + }; + + /** + * Provides an abstraction layer for performing CRUD operations on + * {@link https://auth0.com/docs/api/v2#!/HooksManagers Auth0 HooksManagers}. + * + * @type {external:RestClient} + */ + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/hooks/:id`, + clientOptions, + options.tokenProvider + ); + this.resource = new RetryRestClient(auth0RestClient, options.retry); + + const hookSecretsClient = new Auth0RestClient( + `${options.baseUrl}/hooks/:id/secrets`, + clientOptions, + options.tokenProvider + ); + this.secrets = new RetryRestClient(hookSecretsClient, options.retry); } - if (options.baseUrl === null || options.baseUrl === undefined) { - throw new ArgumentError('Must provide a base URL for the API'); + /** + * Create a new hook. + * + * @example + * management.hooks.create(data, function (err) { + * if (err) { + * // Handle error. + * } + * + * // Hook created. + * }); + * @param {object} data Hook data object. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + create(...args) { + return this.resource.create(...args); } - if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { - throw new ArgumentError('The provided base URL is invalid'); + /** + * Get all hooks. + * + * @example + * This method takes an optional object as first argument that may be used to + * specify pagination settings. If pagination options are not present, + * the first page of a limited number of results will be returned. + * + * + * // Pagination settings. + * var params = { + * per_page: 10, + * page: 0 + * }; + * + * management.hooks.getAll(params, function (err, hooks) { + * console.log(hooks.length); + * }); + * @param {object} [params] Hooks parameters. + * @param {number} [params.per_page] Number of results per page. + * @param {number} [params.page] Page number, zero indexed. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getAll(...args) { + return this.resource.getAll(...args); } /** - * Options object for the Rest Client instance. + * Get an Auth0 hook. + * + * @example + * management.hooks.get({ id: HOOK_ID }, function (err, hook) { + * if (err) { + * // Handle error. + * } * - * @type {object} + * console.log(hook); + * }); + * @param {object} params Hook parameters. + * @param {string} params.id Hook ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const clientOptions = { - headers: options.headers, - query: { repeatParams: false }, - }; + get(...args) { + return this.resource.get(...args); + } /** - * Provides an abstraction layer for performing CRUD operations on - * {@link https://auth0.com/docs/api/v2#!/HooksManagers Auth0 HooksManagers}. + * Update an existing hook. + * + * @example + * var data = { name: 'New name' }; + * var params = { id: HOOK_ID }; + * + * // Using auth0 instance. + * management.updateHook(params, data, function (err, hook) { + * if (err) { + * // Handle error. + * } + * + * console.log(hook.name); // 'New name' + * }); * - * @type {external:RestClient} + * // Using the hooks manager directly. + * management.hooks.update(params, data, function (err, hook) { + * if (err) { + * // Handle error. + * } + * + * console.log(hook.name); // 'New name' + * }); + * @param {object} params Hook parameters. + * @param {string} params.id Hook ID. + * @param {object} data Updated hook data. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const auth0RestClient = new Auth0RestClient( - `${options.baseUrl}/hooks/:id`, - clientOptions, - options.tokenProvider - ); - this.resource = new RetryRestClient(auth0RestClient, options.retry); - - const hookSecretsClient = new Auth0RestClient( - `${options.baseUrl}/hooks/:id/secrets`, - clientOptions, - options.tokenProvider - ); - this.secrets = new RetryRestClient(hookSecretsClient, options.retry); -}; - -/** - * Create a new hook. - * - * @function create - * @memberof module:management.HooksManager.prototype - * @example - * management.hooks.create(data, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Hook created. - * }); - * @param {object} data Hook data object. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(HooksManager, 'create', 'resource.create'); - -/** - * Get all hooks. - * - * @function getAll - * @memberof module:management.HooksManager.prototype - * @example - * This method takes an optional object as first argument that may be used to - * specify pagination settings. If pagination options are not present, - * the first page of a limited number of results will be returned. - * - * - * // Pagination settings. - * var params = { - * per_page: 10, - * page: 0 - * }; - * - * management.hooks.getAll(params, function (err, hooks) { - * console.log(hooks.length); - * }); - * @param {object} [params] Hooks parameters. - * @param {number} [params.per_page] Number of results per page. - * @param {number} [params.page] Page number, zero indexed. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(HooksManager, 'getAll', 'resource.getAll'); - -/** - * Get an Auth0 hook. - * - * @function get - * @memberof module:management.HooksManager.prototype - * @example - * management.hooks.get({ id: HOOK_ID }, function (err, hook) { - * if (err) { - * // Handle error. - * } - * - * console.log(hook); - * }); - * @param {object} params Hook parameters. - * @param {string} params.id Hook ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(HooksManager, 'get', 'resource.get'); + update(...args) { + return this.resource.patch(...args); + } -/** - * Update an existing hook. - * - * @function update - * @memberof module:management.HooksManager.prototype - * @example - * var data = { name: 'New name' }; - * var params = { id: HOOK_ID }; - * - * // Using auth0 instance. - * management.updateHook(params, data, function (err, hook) { - * if (err) { - * // Handle error. - * } - * - * console.log(hook.name); // 'New name' - * }); - * - * // Using the hooks manager directly. - * management.hooks.update(params, data, function (err, hook) { - * if (err) { - * // Handle error. - * } - * - * console.log(hook.name); // 'New name' - * }); - * @param {object} params Hook parameters. - * @param {string} params.id Hook ID. - * @param {object} data Updated hook data. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(HooksManager, 'update', 'resource.patch'); + /** + * Delete an existing hook. + * + * @example + * management.hooks.delete({ id: HOOK_ID }, function (err) { + * if (err) { + * // Handle error. + * } + * + * // Hook deleted. + * }); + * @param {object} params Hook parameters. + * @param {string} params.id Hook ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + delete(...args) { + return this.resource.delete(...args); + } -/** - * Delete an existing hook. - * - * @function delete - * @memberof module:management.HooksManager.prototype - * @example - * management.hooks.delete({ id: HOOK_ID }, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Hook deleted. - * }); - * @param {object} params Hook parameters. - * @param {string} params.id Hook ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(HooksManager, 'delete', 'resource.delete'); + /** + * Get Hook secrets + * + * @example + * @param callback + * var params = {id : 'HOOK_ID'} + * @example + * This method takes a first argument as the hookId and returns the secrets for the hook. The secret values will be hidden. + * + * + * management.hooks.getSecrets( {id : 'HOOK_ID'}, function (err, secrets) { + * console.log(secrets); + * }); + * @param {object} params Hook parameters. + * @param {string} params.id ID of the Hook. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getSecrets(params, callback) { + return this.secrets.getAll(params, callback); + } -/** - * Get Hook secrets - * - * @function getSecrets - * @memberof module:management.HooksManager.prototype - * @example - * @param callback - * var params = {id : 'HOOK_ID'} - * @example - * This method takes a first argument as the hookId and returns the secrets for the hook. The secret values will be hidden. - * - * - * management.hooks.getSecrets( {id : 'HOOK_ID'}, function (err, secrets) { - * console.log(secrets); - * }); - * @param {object} params Hook parameters. - * @param {string} params.id ID of the Hook. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -HooksManager.prototype.getSecrets = function (params, callback) { - return this.secrets.getAll(params, callback); -}; + /** + * Add secrets in a hook + * + * @example + * var params = { id :'HOOK_ID'}; + * var data = { "DB_USER" : "jdoe", "DB_PASS": "password123!"}; + * + * management.hooks.addSecrets(params, data, function (err, secrets) { + * if (err) { + * // Handle error. + * } + * + * // secrets added. + * }); + * @param {object} params Hook parameters. + * @param {string} params.id ID of the Hook. + * @param {object} data object containing secrets as key/value pairs + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ -/** - * Add secrets in a hook - * - * @function addSecrets - * @memberof module:management.HooksManager.prototype - * @example - * var params = { id :'HOOK_ID'}; - * var data = { "DB_USER" : "jdoe", "DB_PASS": "password123!"}; - * - * management.hooks.addSecrets(params, data, function (err, secrets) { - * if (err) { - * // Handle error. - * } - * - * // secrets added. - * }); - * @param {object} params Hook parameters. - * @param {string} params.id ID of the Hook. - * @param {object} data object containing secrets as key/value pairs - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ + addSecrets(params, data, cb) { + params = params || {}; + data = data || {}; -HooksManager.prototype.addSecrets = function (params, data, cb) { - params = params || {}; - data = data || {}; + // Require an ID. + if (!params.id) { + throw new ArgumentError('The id passed in params cannot be null or undefined'); + } - // Require an ID. - if (!params.id) { - throw new ArgumentError('The id passed in params cannot be null or undefined'); - } + if (typeof params.id !== 'string') { + throw new ArgumentError('The hook Id has to be a string'); + } - if (typeof params.id !== 'string') { - throw new ArgumentError('The hook Id has to be a string'); - } + if (cb && cb instanceof Function) { + return this.secrets.create(params, data, cb); + } - if (cb && cb instanceof Function) { - return this.secrets.create(params, data, cb); + return this.secrets.create(params, data); } - return this.secrets.create(params, data); -}; + /** + * Update secrets in a hook + * + * @example + * var params = { id :'HOOK_ID'}; + * var data = { "DB_USER" : "jdoe", "DB_PASS": "password123!"}; + * + * management.hooks.updateSecrets(params, data, function (err, secrets) { + * if (err) { + * // Handle error. + * } + * + * // secrets updated. + * }); + * @param {object} params Hook parameters. + * @param {string} params.id ID of the Hook. + * @param {object} data object containing secrets as key/value pairs + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ -/** - * Update secrets in a hook - * - * @function updateSecrets - * @memberof module:management.HooksManager.prototype - * @example - * var params = { id :'HOOK_ID'}; - * var data = { "DB_USER" : "jdoe", "DB_PASS": "password123!"}; - * - * management.hooks.updateSecrets(params, data, function (err, secrets) { - * if (err) { - * // Handle error. - * } - * - * // secrets updated. - * }); - * @param {object} params Hook parameters. - * @param {string} params.id ID of the Hook. - * @param {object} data object containing secrets as key/value pairs - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ + updateSecrets(params, data, cb) { + params = params || {}; + data = data || {}; -HooksManager.prototype.updateSecrets = function (params, data, cb) { - params = params || {}; - data = data || {}; + // Require an ID. + if (!params.id) { + throw new ArgumentError('The id passed in params cannot be null or undefined'); + } - // Require an ID. - if (!params.id) { - throw new ArgumentError('The id passed in params cannot be null or undefined'); - } + if (typeof params.id !== 'string') { + throw new ArgumentError('The hook Id has to be a string'); + } - if (typeof params.id !== 'string') { - throw new ArgumentError('The hook Id has to be a string'); - } + if (cb && cb instanceof Function) { + return this.secrets.patch(params, data, cb); + } - if (cb && cb instanceof Function) { - return this.secrets.patch(params, data, cb); + return this.secrets.patch(params, data); } - return this.secrets.patch(params, data); -}; + /** + * Remove secrets from a hook + * + * @example + * var params = { id :'HOOK_ID'}; + * var data =["DB_PASS"]; + * + * management.hooks.removeSecrets(params, data, function (err, hook) { + * if (err) { + * // Handle error. + * } + * + * // secrets added. + * }); + * @param {object} params Hook parameters. + * @param {string} params.id ID of the Hook. + * @param {object} data Array of secret names + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ -/** - * Remove secrets from a hook - * - * @function removeSecrets - * @memberof module:management.HooksManager.prototype - * @example - * var params = { id :'HOOK_ID'}; - * var data =["DB_PASS"]; - * - * management.hooks.removeSecrets(params, data, function (err, hook) { - * if (err) { - * // Handle error. - * } - * - * // secrets added. - * }); - * @param {object} params Hook parameters. - * @param {string} params.id ID of the Hook. - * @param {object} data Array of secret names - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ + removeSecrets(params, data, cb) { + params = params || {}; + data = data || {}; -HooksManager.prototype.removeSecrets = function (params, data, cb) { - params = params || {}; - data = data || {}; + // Require an ID. + if (!params.id) { + throw new ArgumentError('The id passed in params cannot be null or undefined'); + } - // Require an ID. - if (!params.id) { - throw new ArgumentError('The id passed in params cannot be null or undefined'); - } + if (typeof params.id !== 'string') { + throw new ArgumentError('The hook Id has to be a string'); + } - if (typeof params.id !== 'string') { - throw new ArgumentError('The hook Id has to be a string'); - } + if (cb && cb instanceof Function) { + return this.secrets.delete(params, data, cb); + } - if (cb && cb instanceof Function) { - return this.secrets.delete(params, data, cb); + return this.secrets.delete(params, data); } - - return this.secrets.delete(params, data); -}; +} module.exports = HooksManager; diff --git a/src/management/JobsManager.js b/src/management/JobsManager.js index 8a8f52d07..cfa684792 100644 --- a/src/management/JobsManager.js +++ b/src/management/JobsManager.js @@ -7,364 +7,348 @@ const Auth0RestClient = require('../Auth0RestClient'); const RetryRestClient = require('../RetryRestClient'); /** - * Simple facade for consuming a REST API endpoint. - * - * @external RestClient - * @see https://github.com/ngonzalvez/rest-facade - */ - -/** - * @class * Abstract the creation as well as the retrieval of async jobs. - * @class - * @memberof module:management - * @param {object} options The client options. - * @param {string} options.baseUrl The URL of the API. - * @param {object} [options.headers] Headers to be included in all requests. - * @param {object} [options.retry] Retry Policy Config */ -const JobsManager = function (options) { - if (options === null || typeof options !== 'object') { - throw new ArgumentError('Must provide client options'); - } - - if (options.baseUrl === null || options.baseUrl === undefined) { - throw new ArgumentError('Must provide a base URL for the API'); - } - - if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { - throw new ArgumentError('The provided base URL is invalid'); - } - - const clientOptions = { - errorFormatter: { message: 'message', name: 'error' }, - headers: options.headers, - query: { repeatParams: false }, - }; - - this.options = options; - +class JobsManager { /** - * Provides an abstraction layer for consuming the - * {@link https://auth0.com/docs/api/v2#!/Jobs Jobs endpoint}. - * - * @type {external:RestClient} + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config */ - const auth0RestClient = new Auth0RestClient( - `${options.baseUrl}/jobs/:id`, - clientOptions, - options.tokenProvider - ); - this.jobs = new RetryRestClient(auth0RestClient, options.retry); + constructor(options) { + if (options === null || typeof options !== 'object') { + throw new ArgumentError('Must provide client options'); + } + + if (options.baseUrl === null || options.baseUrl === undefined) { + throw new ArgumentError('Must provide a base URL for the API'); + } + + if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { + throw new ArgumentError('The provided base URL is invalid'); + } + + const clientOptions = { + errorFormatter: { message: 'message', name: 'error' }, + headers: options.headers, + query: { repeatParams: false }, + }; + + this.options = options; + + /** + * Provides an abstraction layer for consuming the + * {@link https://auth0.com/docs/api/v2#!/Jobs Jobs endpoint}. + * + * @type {external:RestClient} + */ + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/jobs/:id`, + clientOptions, + options.tokenProvider + ); + this.jobs = new RetryRestClient(auth0RestClient, options.retry); + + /** + * Provides an abstraction layer for consuming the + * {@link https://auth0.com/docs/api/v2#!/Jobs/:id/errors Errors endpoint}. + * + * @type {external:RestClient} + */ + const jobErrorsRestClient = new Auth0RestClient( + `${options.baseUrl}/jobs/:id/errors`, + clientOptions, + options.tokenProvider + ); + this.jobErrors = new RetryRestClient(jobErrorsRestClient, options.retry); + + /** + * Provides an abstraction layer for consuming the + * {@link https://auth0.com/docs/api/v2#!/Jobs/post_users_exports Create job to export users endpoint} + * + * @type {external:RestClient} + */ + const usersExportsRestClient = new Auth0RestClient( + `${options.baseUrl}/jobs/users-exports`, + clientOptions, + options.tokenProvider + ); + this.usersExports = new RetryRestClient(usersExportsRestClient, options.retry); + } /** - * Provides an abstraction layer for consuming the - * {@link https://auth0.com/docs/api/v2#!/Jobs/:id/errors Errors endpoint}. + * Get a job by its ID. * - * @type {external:RestClient} - */ - const jobErrorsRestClient = new Auth0RestClient( - `${options.baseUrl}/jobs/:id/errors`, - clientOptions, - options.tokenProvider - ); - this.jobErrors = new RetryRestClient(jobErrorsRestClient, options.retry); - - /** - * Provides an abstraction layer for consuming the - * {@link https://auth0.com/docs/api/v2#!/Jobs/post_users_exports Create job to export users endpoint} + * @example + * var params = { + * id: '{JOB_ID}' + * }; * - * @type {external:RestClient} + * management.jobs.get(params, function (err, job) { + * if (err) { + * // Handle error. + * } + * + * // Retrieved job. + * console.log(job); + * }); + * @param {object} params Job parameters. + * @param {string} params.id Job ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const usersExportsRestClient = new Auth0RestClient( - `${options.baseUrl}/jobs/users-exports`, - clientOptions, - options.tokenProvider - ); - this.usersExports = new RetryRestClient(usersExportsRestClient, options.retry); -}; + get(params, cb) { + if (!params.id || typeof params.id !== 'string') { + throw new ArgumentError('The id parameter must be a valid job id'); + } -/** - * Get a job by its ID. - * - * @function get - * @memberof module:management.JobsManager.prototype - * @example - * var params = { - * id: '{JOB_ID}' - * }; - * - * management.jobs.get(params, function (err, job) { - * if (err) { - * // Handle error. - * } - * - * // Retrieved job. - * console.log(job); - * }); - * @param {object} params Job parameters. - * @param {string} params.id Job ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -JobsManager.prototype.get = function (params, cb) { - if (!params.id || typeof params.id !== 'string') { - throw new ArgumentError('The id parameter must be a valid job id'); - } + if (cb && cb instanceof Function) { + return this.jobs.get(params, cb); + } - if (cb && cb instanceof Function) { - return this.jobs.get(params, cb); + // Return a promise. + return this.jobs.get(params); } - // Return a promise. - return this.jobs.get(params); -}; - -JobsManager.prototype._importUsers = function (data, cb) { - const { options } = this; - const url = `${options.baseUrl}/jobs/users-imports`; - const userData = data.users_json ? Buffer.from(data.users_json) : fs.createReadStream(data.users); - const userFilename = data.users_json ? 'users.json' : data.users; - - const form = new FormData(); - form.append('users', userData, userFilename); - form.append('connection_id', data.connection_id); - form.append('upsert', data.upsert === true ? 'true' : 'false'); - form.append('send_completion_email', data.send_completion_email === false ? 'false' : 'true'); - - const headers = { ...options.headers, ...form.getHeaders() }; - headers['Content-Type'] = 'multipart/form-data'; - - const promise = options.tokenProvider.getAccessToken().then((access_token) => - axios - .post(url, form, { headers: { ...headers, Authorization: `Bearer ${access_token}` } }) - .catch((err) => { - if (!err.response) { - return Promise.reject(err); - } - - const res = err.response; - // `superagent` uses the error parameter in callback on http errors. - // the following code is intended to keep that behaviour (https://github.com/visionmedia/superagent/blob/master/lib/node/response.js#L170) - const error = new Error(`${'cannot POST' + ' '}${url} (${res.status})`); - error.status = res.status; - error.method = 'POST'; - error.text = res.data.message || res.statusText || error.message; - return Promise.reject(error); - }) - ); - - // Don't return a promise if a callback was given. - if (cb && cb instanceof Function) { - promise.then(cb.bind(null, null)).catch(cb); - - return; + _importUsers(data, cb) { + const { options } = this; + const url = `${options.baseUrl}/jobs/users-imports`; + const userData = data.users_json + ? Buffer.from(data.users_json) + : fs.createReadStream(data.users); + const userFilename = data.users_json ? 'users.json' : data.users; + + const form = new FormData(); + form.append('users', userData, userFilename); + form.append('connection_id', data.connection_id); + form.append('upsert', data.upsert === true ? 'true' : 'false'); + form.append('send_completion_email', data.send_completion_email === false ? 'false' : 'true'); + + const headers = { ...options.headers, ...form.getHeaders() }; + headers['Content-Type'] = 'multipart/form-data'; + + const promise = options.tokenProvider.getAccessToken().then((access_token) => + axios + .post(url, form, { headers: { ...headers, Authorization: `Bearer ${access_token}` } }) + .catch((err) => { + if (!err.response) { + return Promise.reject(err); + } + + const res = err.response; + // `superagent` uses the error parameter in callback on http errors. + // the following code is intended to keep that behaviour (https://github.com/visionmedia/superagent/blob/master/lib/node/response.js#L170) + const error = new Error(`${'cannot POST' + ' '}${url} (${res.status})`); + error.status = res.status; + error.method = 'POST'; + error.text = res.data.message || res.statusText || error.message; + return Promise.reject(error); + }) + ); + + // Don't return a promise if a callback was given. + if (cb && cb instanceof Function) { + promise.then(cb.bind(null, null)).catch(cb); + + return; + } + + return promise; } - return promise; -}; + /** + * Given a path to a file and a connection id, create a new job that imports the + * users contained in the file or JSON string and associate them with the given + * connection. + * + * @deprecated since version 2.26. It will be deleted in version 3.0. + * @example + * var params = { + * connection_id: '{CONNECTION_ID}', + * users: '{PATH_TO_USERS_FILE}' // or users_json: '{USERS_JSON_STRING}' + * }; + * + * management.jobs.importUsers(params, function (err) { + * if (err) { + * // Handle error. + * } + * }); + * @param {object} data Users import data. + * @param {string} data.connection_id connection_id of the connection to which users will be imported. + * @param {string} [data.users] Path to the users data file. Either users or users_json is mandatory. + * @param {string} [data.users_json] JSON data for the users. + * @param {boolean} [data.upsert] Whether to update users if they already exist (true) or to ignore them (false). + * @param {boolean} [data.send_completion_email] Whether to send a completion email to all tenant owners when the job is finished (true) or not (false). + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + importUsers(data, cb) { + console.warn( + '"importUsers" has been deprecated as it was inconsistent with the API. Please, use "importUsersJob" which returns the response data directly.' + ); + return this._importUsers(data, cb); + } -/** - * Given a path to a file and a connection id, create a new job that imports the - * users contained in the file or JSON string and associate them with the given - * connection. - * - * @deprecated since version 2.26. It will be deleted in version 3.0. - * @function importUsers - * @memberof module:management.JobsManager.prototype - * @example - * var params = { - * connection_id: '{CONNECTION_ID}', - * users: '{PATH_TO_USERS_FILE}' // or users_json: '{USERS_JSON_STRING}' - * }; - * - * management.jobs.importUsers(params, function (err) { - * if (err) { - * // Handle error. - * } - * }); - * @param {object} data Users import data. - * @param {string} data.connection_id connection_id of the connection to which users will be imported. - * @param {string} [data.users] Path to the users data file. Either users or users_json is mandatory. - * @param {string} [data.users_json] JSON data for the users. - * @param {boolean} [data.upsert] Whether to update users if they already exist (true) or to ignore them (false). - * @param {boolean} [data.send_completion_email] Whether to send a completion email to all tenant owners when the job is finished (true) or not (false). - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -JobsManager.prototype.importUsers = function (data, cb) { - console.warn( - '"importUsers" has been deprecated as it was inconsistent with the API. Please, use "importUsersJob" which returns the response data directly.' - ); - return this._importUsers(data, cb); -}; + /** + * Given a path to a file and a connection id, create a new job that imports the + * users contained in the file or JSON string and associate them with the given + * connection. + * + * @example + * var params = { + * connection_id: '{CONNECTION_ID}', + * users: '{PATH_TO_USERS_FILE}' // or users_json: '{USERS_JSON_STRING}' + * }; + * + * management.jobs.importUsers(params, function (err) { + * if (err) { + * // Handle error. + * } + * }); + * @param {object} data Users import data. + * @param {string} data.connection_id connection_id of the connection to which users will be imported. + * @param {string} [data.users] Path to the users data file. Either users or users_json is mandatory. + * @param {string} [data.users_json] JSON data for the users. + * @param {boolean} [data.upsert] Whether to update users if they already exist (true) or to ignore them (false). + * @param {boolean} [data.send_completion_email] Whether to send a completion email to all tenant owners when the job is finished (true) or not (false). + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + importUsersJob(data, cb) { + const promise = this._importUsers(data).then((response) => response.data); -/** - * Given a path to a file and a connection id, create a new job that imports the - * users contained in the file or JSON string and associate them with the given - * connection. - * - * @function importUsersJob - * @memberof module:management.JobsManager.prototype - * @example - * var params = { - * connection_id: '{CONNECTION_ID}', - * users: '{PATH_TO_USERS_FILE}' // or users_json: '{USERS_JSON_STRING}' - * }; - * - * management.jobs.importUsers(params, function (err) { - * if (err) { - * // Handle error. - * } - * }); - * @param {object} data Users import data. - * @param {string} data.connection_id connection_id of the connection to which users will be imported. - * @param {string} [data.users] Path to the users data file. Either users or users_json is mandatory. - * @param {string} [data.users_json] JSON data for the users. - * @param {boolean} [data.upsert] Whether to update users if they already exist (true) or to ignore them (false). - * @param {boolean} [data.send_completion_email] Whether to send a completion email to all tenant owners when the job is finished (true) or not (false). - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -JobsManager.prototype.importUsersJob = function (data, cb) { - const promise = this._importUsers(data).then((response) => response.data); + // Don't return a promise if a callback was given. + if (cb && cb instanceof Function) { + promise.then(cb.bind(null, null)).catch(cb); - // Don't return a promise if a callback was given. - if (cb && cb instanceof Function) { - promise.then(cb.bind(null, null)).catch(cb); + return; + } - return; + return promise; } - return promise; -}; + /** + * Export all users to a file using a long running job. + * + * @example + * var data = { + * connection_id: 'con_0000000000000001', + * format: 'csv', + * limit: 5, + * fields: [ + * { + * "name": "user_id" + * }, + * { + * "name": "name" + * }, + * { + * "name": "email" + * }, + * { + * "name": "identities[0].connection", + * "export_as": "provider" + * }, + * { + * "name": "user_metadata.some_field" + * } + * ] + * } + * + * management.jobs.exportUsers(data, function (err, results) { + * if (err) { + * // Handle error. + * } + * + * // Retrieved job. + * console.log(results); + * }); + * @param {object} data Users export data. + * @param {string} [data.connection_id] The connection id of the connection from which users will be exported + * @param {string} [data.format] The format of the file. Valid values are: "json" and "csv". + * @param {number} [data.limit] Limit the number of records. + * @param {object[]} [data.fields] A list of fields to be included in the CSV. If omitted, a set of predefined fields will be exported. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + exportUsers(data, cb) { + if (cb && cb instanceof Function) { + return this.usersExports.create(data, cb); + } -/** - * Export all users to a file using a long running job. - * - * @function exportUsers - * @memberof module:management.JobsManager.prototype - * @example - * var data = { - * connection_id: 'con_0000000000000001', - * format: 'csv', - * limit: 5, - * fields: [ - * { - * "name": "user_id" - * }, - * { - * "name": "name" - * }, - * { - * "name": "email" - * }, - * { - * "name": "identities[0].connection", - * "export_as": "provider" - * }, - * { - * "name": "user_metadata.some_field" - * } - * ] - * } - * - * management.jobs.exportUsers(data, function (err, results) { - * if (err) { - * // Handle error. - * } - * - * // Retrieved job. - * console.log(results); - * }); - * @param {object} data Users export data. - * @param {string} [data.connection_id] The connection id of the connection from which users will be exported - * @param {string} [data.format] The format of the file. Valid values are: "json" and "csv". - * @param {number} [data.limit] Limit the number of records. - * @param {object[]} [data.fields] A list of fields to be included in the CSV. If omitted, a set of predefined fields will be exported. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -JobsManager.prototype.exportUsers = function (data, cb) { - if (cb && cb instanceof Function) { - return this.usersExports.create(data, cb); + return this.usersExports.create(data); } - return this.usersExports.create(data); -}; + /** + * Given a job ID, retrieve the failed/errored items + * + * @example + * var params = { + * id: '{JOB_ID}' + * }; + * + * management.jobs.errors(params, function (err, job) { + * if (err) { + * // Handle error. + * } + * + * // Retrieved job. + * console.log(job); + * }); + * @param {object} params Job parameters. + * @param {string} params.id Job ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + errors(params, cb) { + if (!params.id || typeof params.id !== 'string') { + throw new ArgumentError('The id parameter must be a valid job id'); + } -/** - * Given a job ID, retrieve the failed/errored items - * - * @function errors - * @memberof module:management.JobsManager.prototype - * @example - * var params = { - * id: '{JOB_ID}' - * }; - * - * management.jobs.errors(params, function (err, job) { - * if (err) { - * // Handle error. - * } - * - * // Retrieved job. - * console.log(job); - * }); - * @param {object} params Job parameters. - * @param {string} params.id Job ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -JobsManager.prototype.errors = function (params, cb) { - if (!params.id || typeof params.id !== 'string') { - throw new ArgumentError('The id parameter must be a valid job id'); - } + if (cb && cb instanceof Function) { + return this.jobErrors.get(params, cb); + } - if (cb && cb instanceof Function) { - return this.jobErrors.get(params, cb); + // Return a promise. + return this.jobErrors.get(params); } - // Return a promise. - return this.jobErrors.get(params); -}; + /** + * Send a verification email to a user. + * + * @example + * var params = { + * user_id: '{USER_ID}' + * }; + * + * management.jobs.verifyEmail(function (err) { + * if (err) { + * // Handle error. + * } + * }); + * @param {object} data User data object. + * @param {string} data.user_id ID of the user to be verified. + * @param {string} [data.organization_id] Organization ID + * @param {string} [data.client_id] client_id of the client (application). If no value provided, the global Client ID will be used. + * @param {object} [data.identity] Used to verify secondary, federated, and passwordless-email identities. + * @param {string} data.identity.user_id user_id of the identity. + * @param {string} data.identity.provider provider of the identity. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + verifyEmail(data, cb) { + if (!data.user_id || typeof data.user_id !== 'string') { + throw new ArgumentError('Must specify a user ID'); + } -/** - * Send a verification email to a user. - * - * @function verifyEmail - * @memberof module:management.JobsManager.prototype - * @example - * var params = { - * user_id: '{USER_ID}' - * }; - * - * management.jobs.verifyEmail(function (err) { - * if (err) { - * // Handle error. - * } - * }); - * @param {object} data User data object. - * @param {string} data.user_id ID of the user to be verified. - * @param {string} [data.organization_id] Organization ID - * @param {string} [data.client_id] client_id of the client (application). If no value provided, the global Client ID will be used. - * @param {object} [data.identity] Used to verify secondary, federated, and passwordless-email identities. - * @param {string} data.identity.user_id user_id of the identity. - * @param {string} data.identity.provider provider of the identity. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -JobsManager.prototype.verifyEmail = function (data, cb) { - if (!data.user_id || typeof data.user_id !== 'string') { - throw new ArgumentError('Must specify a user ID'); - } + if (cb && cb instanceof Function) { + return this.jobs.create({ id: 'verification-email' }, data, cb); + } - if (cb && cb instanceof Function) { - return this.jobs.create({ id: 'verification-email' }, data, cb); + // Return a promise. + return this.jobs.create({ id: 'verification-email' }, data); } - - // Return a promise. - return this.jobs.create({ id: 'verification-email' }, data); -}; +} module.exports = JobsManager; diff --git a/src/management/LogStreamsManager.js b/src/management/LogStreamsManager.js index c242ec6c4..086235463 100644 --- a/src/management/LogStreamsManager.js +++ b/src/management/LogStreamsManager.js @@ -1,163 +1,163 @@ const { ArgumentError } = require('rest-facade'); -const utils = require('../utils'); const Auth0RestClient = require('../Auth0RestClient'); const RetryRestClient = require('../RetryRestClient'); /** - * @class LogStreamsManager * The logStreams class provides a simple abstraction for performing CRUD operations * on Auth0 Log Streams. - * @class - * @memberof module:management - * @param {object} options The client options. - * @param {string} options.baseUrl The URL of the API. - * @param {object} [options.headers] Headers to be included in all requests. - * @param {object} [options.retry] Retry Policy Config */ -const LogStreamsManager = function (options) { - if (options === null || typeof options !== 'object') { - throw new ArgumentError('Must provide client options'); - } +class LogStreamsManager { + /** + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config + */ + constructor(options) { + if (options === null || typeof options !== 'object') { + throw new ArgumentError('Must provide client options'); + } - if (options.baseUrl === null || options.baseUrl === undefined) { - throw new ArgumentError('Must provide a base URL for the API'); - } + if (options.baseUrl === null || options.baseUrl === undefined) { + throw new ArgumentError('Must provide a base URL for the API'); + } + + if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { + throw new ArgumentError('The provided base URL is invalid'); + } - if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { - throw new ArgumentError('The provided base URL is invalid'); + /** + * Options object for the Rest Client instance. + * + * @type {object} + */ + const clientOptions = { + headers: options.headers, + query: { repeatParams: false }, + }; + + /** + * Provides an abstraction layer for performing CRUD operations on + * {@link https://auth0.com/docs/api/management/v2#!/Log_Streams Auth0 + * Log Streams}. + * + * @type {external:RestClient} + */ + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/log-streams/:id `, + clientOptions, + options.tokenProvider + ); + this.resource = new RetryRestClient(auth0RestClient, options.retry); } /** - * Options object for the Rest Client instance. + * Get all Log Streams. + * + * @example * - * @type {object} + * management.logStreams.getAll(function (err, logStreams) { + * console.log(logStreams.length); + * }); + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const clientOptions = { - headers: options.headers, - query: { repeatParams: false }, - }; + getAll(...args) { + return this.resource.getAll(...args); + } /** - * Provides an abstraction layer for performing CRUD operations on - * {@link https://auth0.com/docs/api/management/v2#!/Log_Streams Auth0 - * Log Streams}. + * Get an Auth0 Log Streams. * - * @type {external:RestClient} + * @example + * management.logStreams.get({ id: LOG_STREAM_ID }, function (err, logStream) { + * if (err) { + * // Handle error. + * } + * + * console.log(logStream); + * }); + * @param {object} params Log Stream parameters. + * @param {string} params.id Log Stream ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const auth0RestClient = new Auth0RestClient( - `${options.baseUrl}/log-streams/:id `, - clientOptions, - options.tokenProvider - ); - this.resource = new RetryRestClient(auth0RestClient, options.retry); -}; - -/** - * Get all Log Streams. - * - * @function getAll - * @memberof module:management.LogStreamsManager.prototype - * @example - * - * management.logStreams.getAll(function (err, logStreams) { - * console.log(logStreams.length); - * }); - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(LogStreamsManager, 'getAll', 'resource.getAll'); - -/** - * Get an Auth0 Log Streams. - * - * @function get - * @memberof module:management.LogStreamsManager.prototype - * @example - * management.logStreams.get({ id: LOG_STREAM_ID }, function (err, logStream) { - * if (err) { - * // Handle error. - * } - * - * console.log(logStream); - * }); - * @param {object} params Log Stream parameters. - * @param {string} params.id Log Stream ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(LogStreamsManager, 'get', 'resource.get'); + get(...args) { + return this.resource.get(...args); + } -/** - * Create an Auth0 Log Stream. - * - * @function create - * @memberof module:management.LogStreamsManager.prototype - * @example - * management.logStreams.create(data, function (err, log) { - * if (err) { - * // Handle error. - * } - * - * console.log(log); - * }); - * @param {object} data Log Stream data. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(LogStreamsManager, 'create', 'resource.create'); + /** + * Create an Auth0 Log Stream. + * + * @example + * management.logStreams.create(data, function (err, log) { + * if (err) { + * // Handle error. + * } + * + * console.log(log); + * }); + * @param {object} data Log Stream data. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + create(...args) { + return this.resource.create(...args); + } -/** - * Update an Auth0 Log Streams. - * - * @function update - * @memberof module:management.LogStreamsManager.prototype - * @example - * var data = { name: 'New name' }; - * var params = { id: LOG_STREAM_ID }; - * - * // Using auth0 instance. - * management.updateLogStream(params, data, function (err, logStream) { - * if (err) { - * // Handle error. - * } - * - * console.log(logStream.name); // 'New name' - * }); - * - * // Using the logStreams manager directly. - * management.logStreams.update(params, data, function (err, logStream) { - * if (err) { - * // Handle error. - * } - * - * console.log(logStream.name); - * }); - * @param {object} params Log Stream parameters. - * @param {string} params.id Log Stream ID. - * @param {object} data Updated Log Stream data. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(LogStreamsManager, 'update', 'resource.patch'); + /** + * Update an Auth0 Log Streams. + * + * @example + * var data = { name: 'New name' }; + * var params = { id: LOG_STREAM_ID }; + * + * // Using auth0 instance. + * management.updateLogStream(params, data, function (err, logStream) { + * if (err) { + * // Handle error. + * } + * + * console.log(logStream.name); // 'New name' + * }); + * + * // Using the logStreams manager directly. + * management.logStreams.update(params, data, function (err, logStream) { + * if (err) { + * // Handle error. + * } + * + * console.log(logStream.name); + * }); + * @param {object} params Log Stream parameters. + * @param {string} params.id Log Stream ID. + * @param {object} data Updated Log Stream data. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + update(...args) { + return this.resource.patch(...args); + } -/** - * Delete an Auth0 Log Streams. - * - * @function delete - * @memberof module:management.LogStreamsManager.prototype - * @example - * management.logStreams.delete({ id: LOG_STREAM_ID }, function (err, log) { - * if (err) { - * // Handle error. - * } - * - * console.log(log); - * }); - * @param {object} params Log Stream parameters. - * @param {string} params.id Log Stream ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(LogStreamsManager, 'delete', 'resource.delete'); + /** + * Delete an Auth0 Log Streams. + * + * @example + * management.logStreams.delete({ id: LOG_STREAM_ID }, function (err, log) { + * if (err) { + * // Handle error. + * } + * + * console.log(log); + * }); + * @param {object} params Log Stream parameters. + * @param {string} params.id Log Stream ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + delete(...args) { + return this.resource.delete(...args); + } +} module.exports = LogStreamsManager; diff --git a/src/management/LogsManager.js b/src/management/LogsManager.js index 209fbc384..62973a70b 100644 --- a/src/management/LogsManager.js +++ b/src/management/LogsManager.js @@ -1,109 +1,109 @@ const { ArgumentError } = require('rest-facade'); -const utils = require('../utils'); const Auth0RestClient = require('../Auth0RestClient'); const RetryRestClient = require('../RetryRestClient'); /** - * @class LogsManager * Represents the relationship between Auth0 and an Identity provider. - * @class - * @memberof module:management - * @param {object} options The client options. - * @param {string} options.baseUrl The URL of the API. - * @param {object} [options.headers] Headers to be included in all requests. - * @param {object} [options.retry] Retry Policy Config */ -const LogsManager = function (options) { - if (options === null || typeof options !== 'object') { - throw new ArgumentError('Must provide client options'); - } +class LogsManager { + /** + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config + */ + constructor(options) { + if (options === null || typeof options !== 'object') { + throw new ArgumentError('Must provide client options'); + } - if (options.baseUrl === null || options.baseUrl === undefined) { - throw new ArgumentError('Must provide a base URL for the API'); - } + if (options.baseUrl === null || options.baseUrl === undefined) { + throw new ArgumentError('Must provide a base URL for the API'); + } + + if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { + throw new ArgumentError('The provided base URL is invalid'); + } - if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { - throw new ArgumentError('The provided base URL is invalid'); + /** + * Options object for the Rest Client instance. + * + * @type {object} + */ + const clientOptions = { + headers: options.headers, + query: { repeatParams: false }, + }; + + /** + * Provides an abstraction layer for performing CRUD operations on + * {@link https://auth0.com/docs/api/v2#!/LogsManagers Auth0 + * Logs}. + * + * @type {external:RestClient} + */ + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/logs/:id `, + clientOptions, + options.tokenProvider + ); + this.resource = new RetryRestClient(auth0RestClient, options.retry); } /** - * Options object for the Rest Client instance. + * Get all logs. + * + * @example + * This method takes an optional object as first argument that may be used to + * specify pagination settings and the search query. If pagination options are + * not present, the first page of a limited number of results will be returned. + * * - * @type {object} + * // Pagination settings. + * var params = { + * per_page: 10, + * page: 2 + * }; + * + * management.logs.getAll(params, function (err, logs) { + * console.log(logs.length); + * }); + * @param {object} [params] Logs params. + * @param {string} [params.q] Search Criteria using Query String Syntax + * @param {number} [params.page] Page number. Zero based + * @param {number} [params.per_page] The amount of entries per page + * @param {string} [params.sort] The field to use for sorting. + * @param {string} [params.fields] A comma separated list of fields to include or exclude + * @param {boolean} [params.include_fields] true if the fields specified are to be included in the result, false otherwise. + * @param {boolean} [params.include_totals] true if a query summary must be included in the result, false otherwise. Default false + * @param {string} [params.from] For checkpoint pagination, log event Id from which to start selection from. + * @param {number} [params.take] When using the `from` parameter, the number of entries to retrieve. Default 50, max 100. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const clientOptions = { - headers: options.headers, - query: { repeatParams: false }, - }; + getAll(...args) { + return this.resource.getAll(...args); + } /** - * Provides an abstraction layer for performing CRUD operations on - * {@link https://auth0.com/docs/api/v2#!/LogsManagers Auth0 - * Logs}. + * Get an Auth0 log. * - * @type {external:RestClient} + * @example + * management.logs.get({ id: EVENT_ID }, function (err, log) { + * if (err) { + * // Handle error. + * } + * + * console.log(log); + * }); + * @param {object} params Log parameters. + * @param {string} params.id Log ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const auth0RestClient = new Auth0RestClient( - `${options.baseUrl}/logs/:id `, - clientOptions, - options.tokenProvider - ); - this.resource = new RetryRestClient(auth0RestClient, options.retry); -}; - -/** - * Get all logs. - * - * @function getAll - * @memberof module:management.LogsManager.prototype - * @example - * This method takes an optional object as first argument that may be used to - * specify pagination settings and the search query. If pagination options are - * not present, the first page of a limited number of results will be returned. - * - * - * // Pagination settings. - * var params = { - * per_page: 10, - * page: 2 - * }; - * - * management.logs.getAll(params, function (err, logs) { - * console.log(logs.length); - * }); - * @param {object} [params] Logs params. - * @param {string} [params.q] Search Criteria using Query String Syntax - * @param {number} [params.page] Page number. Zero based - * @param {number} [params.per_page] The amount of entries per page - * @param {string} [params.sort] The field to use for sorting. - * @param {string} [params.fields] A comma separated list of fields to include or exclude - * @param {boolean} [params.include_fields] true if the fields specified are to be included in the result, false otherwise. - * @param {boolean} [params.include_totals] true if a query summary must be included in the result, false otherwise. Default false - * @param {string} [params.from] For checkpoint pagination, log event Id from which to start selection from. - * @param {number} [params.take] When using the `from` parameter, the number of entries to retrieve. Default 50, max 100. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(LogsManager, 'getAll', 'resource.getAll'); - -/** - * Get an Auth0 log. - * - * @function get - * @memberof module:management.LogsManager.prototype - * @example - * management.logs.get({ id: EVENT_ID }, function (err, log) { - * if (err) { - * // Handle error. - * } - * - * console.log(log); - * }); - * @param {object} params Log parameters. - * @param {string} params.id Log ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(LogsManager, 'get', 'resource.get'); + get(...args) { + return this.resource.get(...args); + } +} module.exports = LogsManager; diff --git a/src/management/MigrationsManager.js b/src/management/MigrationsManager.js index 55d2d672d..fb9b94330 100644 --- a/src/management/MigrationsManager.js +++ b/src/management/MigrationsManager.js @@ -3,100 +3,97 @@ const Auth0RestClient = require('../Auth0RestClient'); const RetryRestClient = require('../RetryRestClient'); /** - * @class * Abstracts interaction with the migrations endpoint. - * @class - * @memberof module:management - * @param {object} options The client options. - * @param {string} options.baseUrl The URL of the API. - * @param {object} [options.headers] Headers to be included in all requests. - * @param {object} [options.retry] Retry Policy Config */ -const MigrationsManager = function (options) { - if (options === null || typeof options !== 'object') { - throw new ArgumentError('Must provide manager options'); - } +class MigrationsManager { + /** + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config + */ + constructor(options) { + if (options === null || typeof options !== 'object') { + throw new ArgumentError('Must provide manager options'); + } - if (options.baseUrl === null || options.baseUrl === undefined) { - throw new ArgumentError('Must provide a base URL for the API'); - } + if (options.baseUrl === null || options.baseUrl === undefined) { + throw new ArgumentError('Must provide a base URL for the API'); + } - if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { - throw new ArgumentError('The provided base URL is invalid'); - } + if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { + throw new ArgumentError('The provided base URL is invalid'); + } - const clientOptions = { - errorFormatter: { message: 'message', name: 'error' }, - headers: options.headers, - query: { repeatParams: false }, - }; + const clientOptions = { + errorFormatter: { message: 'message', name: 'error' }, + headers: options.headers, + query: { repeatParams: false }, + }; + + /** + * Provides an abstraction layer for consuming the migrations endpoint + * + * @type {external:RestClient} + */ + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/migrations`, + clientOptions, + options.tokenProvider + ); + this.resource = new RetryRestClient(auth0RestClient, options.retry); + } /** - * Provides an abstraction layer for consuming the migrations endpoint + * Update the tenant migrations. * - * @type {external:RestClient} + * @example + * management.migrations.updateMigrations(data, function (err) { + * if (err) { + * // Handle error. + * } + * }); + * @param {object} data The tenant migrations to be updated + * @param {object} data.flags The tenant migrations flags to be updated + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const auth0RestClient = new Auth0RestClient( - `${options.baseUrl}/migrations`, - clientOptions, - options.tokenProvider - ); - this.resource = new RetryRestClient(auth0RestClient, options.retry); -}; + updateMigrations(data, cb) { + if (cb && cb instanceof Function) { + return this.resource.patch({}, data, cb); + } -/** - * Update the tenant migrations. - * - * @function updateMigrations - * @memberof module:management.MigrationsManager.prototype - * @example - * management.migrations.updateMigrations(data, function (err) { - * if (err) { - * // Handle error. - * } - * }); - * @param {object} data The tenant migrations to be updated - * @param {object} data.flags The tenant migrations flags to be updated - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -MigrationsManager.prototype.updateMigrations = function (data, cb) { - if (cb && cb instanceof Function) { - return this.resource.patch({}, data, cb); + // Return a promise. + return this.resource.patch({}, data); } - // Return a promise. - return this.resource.patch({}, data); -}; + /** + * Get the tenant migrations. + * + * @example + * management.migrations.getMigrations(function (err, migrations) { + * if (err) { + * // Handle error. + * } + * + * console.log(migrations.flags); + * }); + * @param data + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getMigrations(data, cb) { + if (data instanceof Function && !cb) { + cb = data; + data = {}; + } + if (cb && cb instanceof Function) { + return this.resource.get(data, cb); + } -/** - * Get the tenant migrations. - * - * @function getMigrations - * @memberof module:management.MigrationsManager.prototype - * @example - * management.migrations.getMigrations(function (err, migrations) { - * if (err) { - * // Handle error. - * } - * - * console.log(migrations.flags); - * }); - * @param data - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -MigrationsManager.prototype.getMigrations = function (data, cb) { - if (data instanceof Function && !cb) { - cb = data; - data = {}; + // Return a promise. + return this.resource.get(data); } - if (cb && cb instanceof Function) { - return this.resource.get(data, cb); - } - - // Return a promise. - return this.resource.get(data); -}; +} module.exports = MigrationsManager; diff --git a/src/management/OrganizationsManager.js b/src/management/OrganizationsManager.js index c18d2b550..e282585e7 100644 --- a/src/management/OrganizationsManager.js +++ b/src/management/OrganizationsManager.js @@ -1,814 +1,777 @@ const { ArgumentError } = require('rest-facade'); -const utils = require('../utils'); const Auth0RestClient = require('../Auth0RestClient'); const RetryRestClient = require('../RetryRestClient'); /** - * Simple facade for consuming a REST API endpoint. - * - * @external RestClient - * @see https://github.com/ngonzalvez/rest-facade - */ - -/** - * @class OrganizationsManager * The organizations class provides a simple abstraction for performing CRUD operations * on Auth0 OrganizationsManager. - * @class - * @memberof module:management - * @param {object} options The client options. - * @param {string} options.baseUrl The URL of the API. - * @param {object} [options.headers] Headers to be included in all requests. - * @param {object} [options.retry] Retry Policy Config */ -const OrganizationsManager = function (options) { - if (options === null || typeof options !== 'object') { - throw new ArgumentError('Must provide manager options'); +class OrganizationsManager { + /** + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config + */ + constructor(options) { + if (options === null || typeof options !== 'object') { + throw new ArgumentError('Must provide manager options'); + } + + if (options.baseUrl === null || options.baseUrl === undefined) { + throw new ArgumentError('Must provide a base URL for the API'); + } + + if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { + throw new ArgumentError('The provided base URL is invalid'); + } + + /** + * Options object for the Rest Client instance. + * + * @type {object} + */ + const clientOptions = { + headers: options.headers, + query: { repeatParams: false }, + }; + + /** + * Provides an abstraction layer for performing CRUD operations on + * {@link https://auth0.com/docs/api/v2}. + * + * @type {external:RestClient} + */ + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/organizations/:id`, + clientOptions, + options.tokenProvider + ); + this.organizations = new RetryRestClient(auth0RestClient, options.retry); + + const connectionsInRoleClient = new Auth0RestClient( + `${options.baseUrl}/organizations/:id/enabled_connections/:connection_id`, + clientOptions, + options.tokenProvider + ); + this.connections = new RetryRestClient(connectionsInRoleClient, options.retry); + + const membersClient = new Auth0RestClient( + `${options.baseUrl}/organizations/:id/members/:user_id`, + clientOptions, + options.tokenProvider + ); + this.members = new RetryRestClient(membersClient, options.retry); + + const invitationClient = new Auth0RestClient( + `${options.baseUrl}/organizations/:id/invitations/:invitation_id`, + clientOptions, + options.tokenProvider + ); + this.invitations = new RetryRestClient(invitationClient, options.retry); + + const rolesClient = new Auth0RestClient( + `${options.baseUrl}/organizations/:id/members/:user_id/roles`, + clientOptions, + options.tokenProvider + ); + this.roles = new RetryRestClient(rolesClient, options.retry); + + const organizationByNameClient = new Auth0RestClient( + `${options.baseUrl}/organizations/name/:name`, + clientOptions, + options.tokenProvider + ); + this.organizationsByName = new RetryRestClient(organizationByNameClient, options.retry); } - if (options.baseUrl === null || options.baseUrl === undefined) { - throw new ArgumentError('Must provide a base URL for the API'); + /** + * Create a new organization. + * + * @example + * management.organizations.create(data, function (err) { + * if (err) { + * // Handle error. + * } + * + * // Organization created. + * }); + * @param {object} data Organization data object. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + create(...args) { + return this.organizations.create(...args); } - if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { - throw new ArgumentError('The provided base URL is invalid'); + /** + * Get all organizations. + * + * @example + * This method takes an optional object as first argument that may be used to + * specify pagination settings. If pagination options are not present, + * the first page of a limited number of results will be returned. + * + * + * // Pagination settings. + * var params = { + * per_page: 10, + * page: 0 + * }; + * + * management.organizations.getAll(params, function (err, organizations) { + * console.log(organizations.length); + * }); + * @param {object} [params] Organizations parameters. + * @param {number} [params.per_page] Number of results per page. + * @param {number} [params.page] Page number, zero indexed. + * @param {string} [params.from] For checkpoint pagination, the Id from which to start selection from. + * @param {number} [params.take] For checkpoint pagination, the number of entries to retrieve. Default 50. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getAll(...args) { + return this.organizations.getAll(...args); } /** - * Options object for the Rest Client instance. + * Get an Auth0 organization. + * + * @example + * management.organizations.getByID({ id: ORGANIZATION_ID }, function (err, role) { + * if (err) { + * // Handle error. + * } * - * @type {object} + * console.log(organization); + * }); + * @param {object} params Organization parameters. + * @param {string} params.id Organization ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const clientOptions = { - headers: options.headers, - query: { repeatParams: false }, - }; + getByID(...args) { + return this.organizations.get(...args); + } /** - * Provides an abstraction layer for performing CRUD operations on - * {@link https://auth0.com/docs/api/v2}. + * Get an Auth0 organization. + * + * @example + * management.organizations.getByName({ name: ORGANIZATION_NAME}, function (err, role) { + * if (err) { + * // Handle error. + * } * - * @type {external:RestClient} + * console.log(organization); + * }); + * @param {object} params Organization parameters. + * @param {string} params.name Organization name. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const auth0RestClient = new Auth0RestClient( - `${options.baseUrl}/organizations/:id`, - clientOptions, - options.tokenProvider - ); - this.organizations = new RetryRestClient(auth0RestClient, options.retry); - - const connectionsInRoleClient = new Auth0RestClient( - `${options.baseUrl}/organizations/:id/enabled_connections/:connection_id`, - clientOptions, - options.tokenProvider - ); - this.connections = new RetryRestClient(connectionsInRoleClient, options.retry); - - const membersClient = new Auth0RestClient( - `${options.baseUrl}/organizations/:id/members/:user_id`, - clientOptions, - options.tokenProvider - ); - this.members = new RetryRestClient(membersClient, options.retry); - - const invitationClient = new Auth0RestClient( - `${options.baseUrl}/organizations/:id/invitations/:invitation_id`, - clientOptions, - options.tokenProvider - ); - this.invitations = new RetryRestClient(invitationClient, options.retry); - - const rolesClient = new Auth0RestClient( - `${options.baseUrl}/organizations/:id/members/:user_id/roles`, - clientOptions, - options.tokenProvider - ); - this.roles = new RetryRestClient(rolesClient, options.retry); - - const organizationByNameClient = new Auth0RestClient( - `${options.baseUrl}/organizations/name/:name`, - clientOptions, - options.tokenProvider - ); - this.organizationsByName = new RetryRestClient(organizationByNameClient, options.retry); -}; - -/** - * Create a new organization. - * - * @function create - * @memberof module:management.OrganizationsManager.prototype - * @example - * management.organizations.create(data, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Organization created. - * }); - * @param {object} data Organization data object. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(OrganizationsManager, 'create', 'organizations.create'); - -/** - * Get all organizations. - * - * @function getAll - * @memberof module:management.OrganizationsManager.prototype - * @example - * This method takes an optional object as first argument that may be used to - * specify pagination settings. If pagination options are not present, - * the first page of a limited number of results will be returned. - * - * - * // Pagination settings. - * var params = { - * per_page: 10, - * page: 0 - * }; - * - * management.organizations.getAll(params, function (err, organizations) { - * console.log(organizations.length); - * }); - * @param {object} [params] Organizations parameters. - * @param {number} [params.per_page] Number of results per page. - * @param {number} [params.page] Page number, zero indexed. - * @param {string} [params.from] For checkpoint pagination, the Id from which to start selection from. - * @param {number} [params.take] For checkpoint pagination, the number of entries to retrieve. Default 50. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(OrganizationsManager, 'getAll', 'organizations.getAll'); - -/** - * Get an Auth0 organization. - * - * @function getByID - * @memberof module:management.OrganizationsManager.prototype - * @example - * management.organizations.getByID({ id: ORGANIZATION_ID }, function (err, role) { - * if (err) { - * // Handle error. - * } - * - * console.log(organization); - * }); - * @param {object} params Organization parameters. - * @param {string} params.id Organization ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(OrganizationsManager, 'getByID', 'organizations.get'); - -/** - * Get an Auth0 organization. - * - * @function getByName - * @memberof module:management.OrganizationsManager.prototype - * @example - * management.organizations.getByName({ name: ORGANIZATION_NAME}, function (err, role) { - * if (err) { - * // Handle error. - * } - * - * console.log(organization); - * }); - * @param {object} params Organization parameters. - * @param {string} params.name Organization name. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(OrganizationsManager, 'getByName', 'organizationsByName.get'); - -/** - * Update an existing organization. - * - * @function update - * @memberof module:management.OrganizationsManager.prototype - * @example - * var data = { display_name: 'New name' }; - * var params = { id: ORGANIZATION_ID }; - * - * management.organizations.update(params, data, function (err, organization) { - * if (err) { - * // Handle error. - * } - * - * console.log(organization.name); // 'New name' - * }); - * @param {object} params Organization parameters. - * @param {string} params.id Organization ID. - * @param {object} data Updated organization data. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(OrganizationsManager, 'update', 'organizations.patch'); - -/** - * Delete an existing organization. - * - * @function delete - * @memberof module:management.OrganizationsManager.prototype - * @example - * management.organizations.delete({ id: ORGANIZATION_ID }, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Organization deleted. - * }); - * @param {object} params Organization parameters. - * @param {string} params.id Organization ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(OrganizationsManager, 'delete', 'organizations.delete'); - -/** - *Organization Connections - */ - -/** - * Get Enabled Connections in a Organization - * - * @function getEnabledConnections - * @memberof module:management.OrganizationsManager.prototype - * @example - * @param callback - * var params = {id : 'ORGANIZATION_ID'} - * @example - * This method takes an organization ID and returns the enabled connections in an Organization - * - * - * management.organizations.getEnabledConnections( {id : 'ORGANIZATION_ID'}, function (err, enabled_connections) { - * console.log(enabled_connections); - * }); - * @param {object} params Organization parameters. - * @param {string} params.id Organization ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -OrganizationsManager.prototype.getEnabledConnections = function (params, callback) { - return this.connections.getAll(params, callback); -}; + getByName(...args) { + return this.organizationsByName.get(...args); + } -/** - * Get Enabled Connection in a Organization - * - * @function getEnabledConnection - * @memberof module:management.OrganizationsManager.prototype - * @example - * var params = {id : 'ORGANIZATION_ID', connection_id: 'CONNECTION_ID'} - * @param callback - * @example - * This methods takes the organization ID and connection ID and returns the enabled connection - * - * - * management.organizations.getEnabledConnections( {id : 'ORGANIZATION_ID', connection_id: 'CONNECTION_ID'}, function (err, enabled_connection) { - * console.log(enabled_connection); - * }); - * @param {object} params Organization parameters. - * @param {string} params.id Organization ID. - * @param {string} params.connection_id Connection ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -OrganizationsManager.prototype.getEnabledConnection = function (params, callback) { - return this.connections.get(params, callback); -}; + /** + * Update an existing organization. + * + * @example + * var data = { display_name: 'New name' }; + * var params = { id: ORGANIZATION_ID }; + * + * management.organizations.update(params, data, function (err, organization) { + * if (err) { + * // Handle error. + * } + * + * console.log(organization.name); // 'New name' + * }); + * @param {object} params Organization parameters. + * @param {string} params.id Organization ID. + * @param {object} data Updated organization data. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + update(...args) { + return this.organizations.patch(...args); + } -/** - * Add an enabled connection for an organization - * - * @function addEnabledConnection - * @memberof module:management.OrganizationsManager.prototype - * @example - * var params = { id :'ORGANIZATION_ID'}; - * var data = { "connection_id" : "CONNECTION_ID", assign_membership_on_login: false }; - * - * management.organizations.addEnabledConnection(params, data, function (err) { - * if (err) { - * // Handle error. - * } - * }); - * @param {object} params Organization parameters - * @param {string} params.id ID of the Organization. - * @param {object} data enable connection data - * @param {string} data.connection_id connection ID to enable - * @param {boolean} data.assign_membership_on_login flag to allow assign membership on login - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ + /** + * Delete an existing organization. + * + * @example + * management.organizations.delete({ id: ORGANIZATION_ID }, function (err) { + * if (err) { + * // Handle error. + * } + * + * // Organization deleted. + * }); + * @param {object} params Organization parameters. + * @param {string} params.id Organization ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + delete(...args) { + return this.organizations.delete(...args); + } -OrganizationsManager.prototype.addEnabledConnection = function (params, data, cb) { - data = data || {}; - params = params || {}; + /** + *Organization Connections + */ - if (!params.id) { - throw new ArgumentError('The organization ID passed in params cannot be null or undefined'); - } - if (typeof params.id !== 'string') { - throw new ArgumentError('The organization ID has to be a string'); + /** + * Get Enabled Connections in a Organization + * + * @example + * @param callback + * var params = {id : 'ORGANIZATION_ID'} + * @example + * This method takes an organization ID and returns the enabled connections in an Organization + * + * + * management.organizations.getEnabledConnections( {id : 'ORGANIZATION_ID'}, function (err, enabled_connections) { + * console.log(enabled_connections); + * }); + * @param {object} params Organization parameters. + * @param {string} params.id Organization ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getEnabledConnections(params, callback) { + return this.connections.getAll(params, callback); } - if (cb && cb instanceof Function) { - return this.connections.create(params, data, cb); + /** + * Get Enabled Connection in a Organization + * + * @example + * var params = {id : 'ORGANIZATION_ID', connection_id: 'CONNECTION_ID'} + * @param callback + * @example + * This methods takes the organization ID and connection ID and returns the enabled connection + * + * + * management.organizations.getEnabledConnections( {id : 'ORGANIZATION_ID', connection_id: 'CONNECTION_ID'}, function (err, enabled_connection) { + * console.log(enabled_connection); + * }); + * @param {object} params Organization parameters. + * @param {string} params.id Organization ID. + * @param {string} params.connection_id Connection ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getEnabledConnection(params, callback) { + return this.connections.get(params, callback); } - return this.connections.create(params, data); -}; + /** + * Add an enabled connection for an organization + * + * @example + * var params = { id :'ORGANIZATION_ID'}; + * var data = { "connection_id" : "CONNECTION_ID", assign_membership_on_login: false }; + * + * management.organizations.addEnabledConnection(params, data, function (err) { + * if (err) { + * // Handle error. + * } + * }); + * @param {object} params Organization parameters + * @param {string} params.id ID of the Organization. + * @param {object} data enable connection data + * @param {string} data.connection_id connection ID to enable + * @param {boolean} data.assign_membership_on_login flag to allow assign membership on login + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ -/** - * Remove an enabled connection from an organization - * - * @function removeEnabledConnection - * @memberof module:management.OrganizationsManager.prototype - * @example - * var params = { id :'ORGANIZATION_ID', connection_id: 'CONNECTION_ID' }; - * - * management.organizations.removeEnabledConnection(params, function (err) { - * if (err) { - * // Handle error. - * } - * }); - * @param {object} params Organization parameters - * @param {string} params.id ID of the Organization. - * @param {string} params.connection_id ID of the Connection. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ + addEnabledConnection(params, data, cb) { + data = data || {}; + params = params || {}; -OrganizationsManager.prototype.removeEnabledConnection = function (params, cb) { - params = params || {}; + if (!params.id) { + throw new ArgumentError('The organization ID passed in params cannot be null or undefined'); + } + if (typeof params.id !== 'string') { + throw new ArgumentError('The organization ID has to be a string'); + } - if (!params.id) { - throw new ArgumentError('The organization ID passed in params cannot be null or undefined'); - } - if (typeof params.id !== 'string') { - throw new ArgumentError('The organization ID has to be a string'); - } + if (cb && cb instanceof Function) { + return this.connections.create(params, data, cb); + } - if (!params.connection_id) { - throw new ArgumentError('The connection ID passed in params cannot be null or undefined'); - } - if (typeof params.connection_id !== 'string') { - throw new ArgumentError('The connection ID has to be a string'); + return this.connections.create(params, data); } - if (cb && cb instanceof Function) { - return this.connections.delete(params, {}, cb); - } + /** + * Remove an enabled connection from an organization + * + * @example + * var params = { id :'ORGANIZATION_ID', connection_id: 'CONNECTION_ID' }; + * + * management.organizations.removeEnabledConnection(params, function (err) { + * if (err) { + * // Handle error. + * } + * }); + * @param {object} params Organization parameters + * @param {string} params.id ID of the Organization. + * @param {string} params.connection_id ID of the Connection. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ - return this.connections.delete(params, {}); -}; + removeEnabledConnection(params, cb) { + params = params || {}; -/** - * Update an enabled connection from an organization - * - * @function updateEnabledConnection - * @memberof module:management.OrganizationsManager.prototype - * @example - * var params = { id :'ORGANIZATION_ID', connection_id: 'CONNECTION_ID' }; - * var data = { assign_membership_on_login: true }; - * - * management.organizations.updateEnabledConnection(params, data, function (err) { - * if (err) { - * // Handle error. - * } - * }); - * @param {object} params Organization parameters - * @param {string} params.id ID of the Organization. - * @param {string} params.connection_id ID of the Connection. - * @param {object} data Updated connection. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ + if (!params.id) { + throw new ArgumentError('The organization ID passed in params cannot be null or undefined'); + } + if (typeof params.id !== 'string') { + throw new ArgumentError('The organization ID has to be a string'); + } -OrganizationsManager.prototype.updateEnabledConnection = function (params, data, cb) { - data = data || {}; - params = params || {}; + if (!params.connection_id) { + throw new ArgumentError('The connection ID passed in params cannot be null or undefined'); + } + if (typeof params.connection_id !== 'string') { + throw new ArgumentError('The connection ID has to be a string'); + } - if (!params.id) { - throw new ArgumentError('The organization ID passed in params cannot be null or undefined'); - } - if (typeof params.id !== 'string') { - throw new ArgumentError('The organization ID has to be a string'); - } + if (cb && cb instanceof Function) { + return this.connections.delete(params, {}, cb); + } - if (!params.connection_id) { - throw new ArgumentError('The connection ID passed in params cannot be null or undefined'); - } - if (typeof params.connection_id !== 'string') { - throw new ArgumentError('The connection ID has to be a string'); + return this.connections.delete(params, {}); } - if (cb && cb instanceof Function) { - return this.connections.patch(params, data, cb); - } + /** + * Update an enabled connection from an organization + * + * @example + * var params = { id :'ORGANIZATION_ID', connection_id: 'CONNECTION_ID' }; + * var data = { assign_membership_on_login: true }; + * + * management.organizations.updateEnabledConnection(params, data, function (err) { + * if (err) { + * // Handle error. + * } + * }); + * @param {object} params Organization parameters + * @param {string} params.id ID of the Organization. + * @param {string} params.connection_id ID of the Connection. + * @param {object} data Updated connection. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ - return this.connections.patch(params, data); -}; + updateEnabledConnection(params, data, cb) { + data = data || {}; + params = params || {}; -/** - *Organization Members - */ + if (!params.id) { + throw new ArgumentError('The organization ID passed in params cannot be null or undefined'); + } + if (typeof params.id !== 'string') { + throw new ArgumentError('The organization ID has to be a string'); + } -/** - * Get Members in a Organization - * - * @function getMembers - * @memberof module:management.OrganizationsManager.prototype - * @example - * var params = {id : 'ORGANIZATION_ID'} - * @example - * @param callback - * This method takes an organization ID and returns the members in an Organization - * - * - * management.organizations.getMembers( {id : 'ORGANIZATION_ID'}, function (err, members) { - * console.log(members); - * }); - * @param {object} params Organization parameters - * @param {string} params.id Organization ID - * @param {string} [params.from] For checkpoint pagination, the Id from which to start selection from. - * @param {number} [params.take] For checkpoint pagination, the number of entries to retrieve. Default 50. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -OrganizationsManager.prototype.getMembers = function (params, callback) { - return this.members.getAll(params, callback); -}; + if (!params.connection_id) { + throw new ArgumentError('The connection ID passed in params cannot be null or undefined'); + } + if (typeof params.connection_id !== 'string') { + throw new ArgumentError('The connection ID has to be a string'); + } -/** - * Add members in an organization - * - * @function addMembers - * @memberof module:management.OrganizationsManager.prototype - * @example - * var params = { id :'ORGANIZATION_ID'}; - * var data = { members: [ 'USER_ID1', 'USER_ID2' ] } - * management.organizations.addMembers(params, data, function (err) { - * if (err) { - * // Handle error. - * } - * }); - * @param {object} params Organization parameters - * @param {string} params.id ID of the Organization. - * @param {object} data add members data - * @param {Array} data.members Array of user IDs - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -OrganizationsManager.prototype.addMembers = function (params, data, cb) { - data = data || {}; - params = params || {}; + if (cb && cb instanceof Function) { + return this.connections.patch(params, data, cb); + } - if (!params.id) { - throw new ArgumentError('The organization ID passed in params cannot be null or undefined'); - } - if (typeof params.id !== 'string') { - throw new ArgumentError('The organization ID has to be a string'); + return this.connections.patch(params, data); } - if (cb && cb instanceof Function) { - return this.members.create(params, data, cb); + /** + *Organization Members + */ + + /** + * Get Members in a Organization + * + * @example + * var params = {id : 'ORGANIZATION_ID'} + * @example + * @param callback + * This method takes an organization ID and returns the members in an Organization + * + * + * management.organizations.getMembers( {id : 'ORGANIZATION_ID'}, function (err, members) { + * console.log(members); + * }); + * @param {object} params Organization parameters + * @param {string} params.id Organization ID + * @param {string} [params.from] For checkpoint pagination, the Id from which to start selection from. + * @param {number} [params.take] For checkpoint pagination, the number of entries to retrieve. Default 50. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getMembers(params, callback) { + return this.members.getAll(params, callback); } - return this.members.create(params, data); -}; + /** + * Add members in an organization + * + * @example + * var params = { id :'ORGANIZATION_ID'}; + * var data = { members: [ 'USER_ID1', 'USER_ID2' ] } + * management.organizations.addMembers(params, data, function (err) { + * if (err) { + * // Handle error. + * } + * }); + * @param {object} params Organization parameters + * @param {string} params.id ID of the Organization. + * @param {object} data add members data + * @param {Array} data.members Array of user IDs + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + addMembers(params, data, cb) { + data = data || {}; + params = params || {}; -/** - * Remove members from an organization - * - * @function removeMembers - * @memberof module:management.OrganizationsManager.prototype - * @example - * var params = { id :'ORGANIZATION_ID' }; - * var data = { members: [ 'USER_ID1', 'USER_ID2' ] } - * - * management.organizations.removeMembers(params, data, function (err) { - * if (err) { - * // Handle error. - * } - * }); - * @param {object} params Organization parameters - * @param {string} params.id ID of the Organization. - * @param {object} data add members data - * @param {Array} data.members Array of user IDs - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -OrganizationsManager.prototype.removeMembers = function (params, data, cb) { - data = data || {}; - params = params || {}; + if (!params.id) { + throw new ArgumentError('The organization ID passed in params cannot be null or undefined'); + } + if (typeof params.id !== 'string') { + throw new ArgumentError('The organization ID has to be a string'); + } - if (!params.id) { - throw new ArgumentError('The organization ID passed in params cannot be null or undefined'); - } - if (typeof params.id !== 'string') { - throw new ArgumentError('The organization ID has to be a string'); - } + if (cb && cb instanceof Function) { + return this.members.create(params, data, cb); + } - if (cb && cb instanceof Function) { - return this.members.delete(params, data, cb); + return this.members.create(params, data); } - return this.members.delete(params, data); -}; + /** + * Remove members from an organization + * + * @example + * var params = { id :'ORGANIZATION_ID' }; + * var data = { members: [ 'USER_ID1', 'USER_ID2' ] } + * + * management.organizations.removeMembers(params, data, function (err) { + * if (err) { + * // Handle error. + * } + * }); + * @param {object} params Organization parameters + * @param {string} params.id ID of the Organization. + * @param {object} data add members data + * @param {Array} data.members Array of user IDs + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + removeMembers(params, data, cb) { + data = data || {}; + params = params || {}; -/** - *Organization Invites - */ + if (!params.id) { + throw new ArgumentError('The organization ID passed in params cannot be null or undefined'); + } + if (typeof params.id !== 'string') { + throw new ArgumentError('The organization ID has to be a string'); + } -/** - * Get Invites in a Organization - * - * @function getInvitations - * @memberof module:management.OrganizationsManager.prototype - * @example - * var params = {id : 'ORGANIZATION_ID'} - * @example - * This method takes an organization ID and returns the invites in an Organization - * - * - * management.organizations.getInvitations( {id : 'ORGANIZATION_ID'}, function (err, invites) { - * console.log(invites); - * @param callback - * }); - * @param {object} params Organization parameters - * @param {string} params.id Organization ID - * @param {number} [params.per_page] Number of results per page. - * @param {number} [params.page] Page number, zero indexed. - * @param {string} [params.from] For checkpoint pagination, the Id from which to start selection from. - * @param {number} [params.take] For checkpoint pagination, the number of entries to retrieve. Default 50. - * @param {string} [params.fields] Comma-separated list of fields to include or exclude (based on value provided for include_fields) in the result. Leave empty to retrieve all fields. - * @param {boolean} [params.include_fields] Whether specified fields are to be included (true) or excluded (false). Defaults to true. - * @param {string} [params.sort] Field to sort by. Use field:order where order is 1 for ascending and -1 for descending Defaults to created_at:-1. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -OrganizationsManager.prototype.getInvitations = function (params, callback) { - return this.invitations.getAll(params, callback); -}; + if (cb && cb instanceof Function) { + return this.members.delete(params, data, cb); + } -/** - * Get an Invitation in a Organization - * - * @function getInvitation - * @memberof module:management.OrganizationsManager.prototype - * @example - * var params = {id : 'ORGANIZATION_ID', invitation_id: 'INVITATION_ID'} - * @param callback - * @example - * This methods takes the organization ID and user ID and returns the invitation - * - * - * management.organizations.getInvitation({id : 'ORGANIZATION_ID', invitation_id: 'INVITATION_ID'}, function (err, invite) { - * console.log(invite); - * }); - * @param {object} params Organization parameters - * @param {string} params.id Organization ID - * @param {string} params.invitation_id Invitation ID - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -OrganizationsManager.prototype.getInvitation = function (params, callback) { - if (!params.id) { - throw new ArgumentError('The organization ID passed in params cannot be null or undefined'); - } - if (typeof params.id !== 'string') { - throw new ArgumentError('The organization ID has to be a string'); + return this.members.delete(params, data); } - if (!params.invitation_id) { - throw new ArgumentError('The invitation ID passed in params cannot be null or undefined'); - } - if (typeof params.invitation_id !== 'string') { - throw new ArgumentError('The invitation ID has to be a string'); - } + /** + *Organization Invites + */ - return this.invitations.get(params, callback); -}; + /** + * Get Invites in a Organization + * + * @example + * var params = {id : 'ORGANIZATION_ID'} + * @example + * This method takes an organization ID and returns the invites in an Organization + * + * + * management.organizations.getInvitations( {id : 'ORGANIZATION_ID'}, function (err, invites) { + * console.log(invites); + * @param callback + * }); + * @param {object} params Organization parameters + * @param {string} params.id Organization ID + * @param {number} [params.per_page] Number of results per page. + * @param {number} [params.page] Page number, zero indexed. + * @param {string} [params.from] For checkpoint pagination, the Id from which to start selection from. + * @param {number} [params.take] For checkpoint pagination, the number of entries to retrieve. Default 50. + * @param {string} [params.fields] Comma-separated list of fields to include or exclude (based on value provided for include_fields) in the result. Leave empty to retrieve all fields. + * @param {boolean} [params.include_fields] Whether specified fields are to be included (true) or excluded (false). Defaults to true. + * @param {string} [params.sort] Field to sort by. Use field:order where order is 1 for ascending and -1 for descending Defaults to created_at:-1. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getInvitations(params, callback) { + return this.invitations.getAll(params, callback); + } -/** - * Create an invitation in an organization - * - * @function createInvitation - * @memberof module:management.OrganizationsManager.prototype - * @example - * var params = { id :'ORGANIZATION_ID'}; - * var data = { - * client_id: CLIENT_ID, - * invitee: { email: 'invitee@example.com' }, - * inviter: { name: 'John Doe' } - * }; - * - * management.organizations.createInvitation(params, data, function (err) { - * if (err) { - * // Handle error. - * } - * }); - * @param {object} params Organization parameters - * @param {string} params.id ID of the Organization. - * @param {Array} data Invitation data - * @param {object} data.inviter The person who is sending the invite. - * @param {string} data.inviter.name Name of the person who is sending the invite - * @param {object} data.invitee Invitee to whom invitation is intended for - * @param {object} data.invitee.email Email of the invitee to whom invitation is intended for - * @param {string} data.client_id Auth0 client used to resolve the default application login URI. This endpoint must expect &invitation=... and &organization=... parameters (added by API2) to continue the flow with /authorize. If client_id does not have configured login URI, use the tenant level default login route if configured, otherwise return 400 - * @param {string} [data.connection_id] Force user to authenticate against a specific identity provider. - * @param {object} [data.app_metadata] Application metadata to be assigned to the user after accept the invitation. - * @param {object} [data.user_metadata] User metadata to be assigned to the user after accept the invitation. - * @param {Array} [data.roles] List of roles to be assigned to the user - * @param {number} [data.ttl_sec] Number of seconds for which the invitation is valid before expiration. If unspecified or set to 0, this value defaults to 604800 seconds (7 days). Upper limit on ttl_sec is 30 days. - * @param {boolean} [data.send_invitation_email] Whether the user will receive an invitation email (true) or no email (false). Default is true. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -OrganizationsManager.prototype.createInvitation = function (params, data, cb) { - data = data || []; - params = params || {}; + /** + * Get an Invitation in a Organization + * + * @example + * var params = {id : 'ORGANIZATION_ID', invitation_id: 'INVITATION_ID'} + * @param callback + * @example + * This methods takes the organization ID and user ID and returns the invitation + * + * + * management.organizations.getInvitation({id : 'ORGANIZATION_ID', invitation_id: 'INVITATION_ID'}, function (err, invite) { + * console.log(invite); + * }); + * @param {object} params Organization parameters + * @param {string} params.id Organization ID + * @param {string} params.invitation_id Invitation ID + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getInvitation(params, callback) { + if (!params.id) { + throw new ArgumentError('The organization ID passed in params cannot be null or undefined'); + } + if (typeof params.id !== 'string') { + throw new ArgumentError('The organization ID has to be a string'); + } - if (!params.id) { - throw new ArgumentError('The organization ID passed in params cannot be null or undefined'); - } - if (typeof params.id !== 'string') { - throw new ArgumentError('The organization ID has to be a string'); - } + if (!params.invitation_id) { + throw new ArgumentError('The invitation ID passed in params cannot be null or undefined'); + } + if (typeof params.invitation_id !== 'string') { + throw new ArgumentError('The invitation ID has to be a string'); + } - if (cb && cb instanceof Function) { - return this.invitations.create(params, data, cb); + return this.invitations.get(params, callback); } - return this.invitations.create(params, data); -}; + /** + * Create an invitation in an organization + * + * @example + * var params = { id :'ORGANIZATION_ID'}; + * var data = { + * client_id: CLIENT_ID, + * invitee: { email: 'invitee@example.com' }, + * inviter: { name: 'John Doe' } + * }; + * + * management.organizations.createInvitation(params, data, function (err) { + * if (err) { + * // Handle error. + * } + * }); + * @param {object} params Organization parameters + * @param {string} params.id ID of the Organization. + * @param {Array} data Invitation data + * @param {object} data.inviter The person who is sending the invite. + * @param {string} data.inviter.name Name of the person who is sending the invite + * @param {object} data.invitee Invitee to whom invitation is intended for + * @param {object} data.invitee.email Email of the invitee to whom invitation is intended for + * @param {string} data.client_id Auth0 client used to resolve the default application login URI. This endpoint must expect &invitation=... and &organization=... parameters (added by API2) to continue the flow with /authorize. If client_id does not have configured login URI, use the tenant level default login route if configured, otherwise return 400 + * @param {string} [data.connection_id] Force user to authenticate against a specific identity provider. + * @param {object} [data.app_metadata] Application metadata to be assigned to the user after accept the invitation. + * @param {object} [data.user_metadata] User metadata to be assigned to the user after accept the invitation. + * @param {Array} [data.roles] List of roles to be assigned to the user + * @param {number} [data.ttl_sec] Number of seconds for which the invitation is valid before expiration. If unspecified or set to 0, this value defaults to 604800 seconds (7 days). Upper limit on ttl_sec is 30 days. + * @param {boolean} [data.send_invitation_email] Whether the user will receive an invitation email (true) or no email (false). Default is true. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + createInvitation(params, data, cb) { + data = data || []; + params = params || {}; -/** - * Delete an invitation from an organization - * - * @function deleteInvitation - * @memberof module:management.OrganizationsManager.prototype - * @example - * var params = { id :'ORGANIZATION_ID', invitation_id: 'INVITATION_ID }; - * - * management.organizations.deleteInvitation(params, function (err) { - * if (err) { - * // Handle error. - * } - * }); - * @param {object} params Organization parameters - * @param {string} params.id ID of the Organization. - * @param {string} params.invitation_id Invitation ID - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -OrganizationsManager.prototype.deleteInvitation = function (params, cb) { - params = params || {}; + if (!params.id) { + throw new ArgumentError('The organization ID passed in params cannot be null or undefined'); + } + if (typeof params.id !== 'string') { + throw new ArgumentError('The organization ID has to be a string'); + } - if (!params.id) { - throw new ArgumentError('The organization ID passed in params cannot be null or undefined'); - } - if (typeof params.id !== 'string') { - throw new ArgumentError('The organization ID has to be a string'); - } + if (cb && cb instanceof Function) { + return this.invitations.create(params, data, cb); + } - if (!params.invitation_id) { - throw new ArgumentError('The invitation ID passed in params cannot be null or undefined'); - } - if (typeof params.invitation_id !== 'string') { - throw new ArgumentError('The invitation ID has to be a string'); + return this.invitations.create(params, data); } - if (cb && cb instanceof Function) { - return this.invitations.delete(params, {}, cb); - } + /** + * Delete an invitation from an organization + * + * @example + * var params = { id :'ORGANIZATION_ID', invitation_id: 'INVITATION_ID }; + * + * management.organizations.deleteInvitation(params, function (err) { + * if (err) { + * // Handle error. + * } + * }); + * @param {object} params Organization parameters + * @param {string} params.id ID of the Organization. + * @param {string} params.invitation_id Invitation ID + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + deleteInvitation(params, cb) { + params = params || {}; - return this.invitations.delete(params, {}); -}; + if (!params.id) { + throw new ArgumentError('The organization ID passed in params cannot be null or undefined'); + } + if (typeof params.id !== 'string') { + throw new ArgumentError('The organization ID has to be a string'); + } -/** - *Organization Roles Membership - */ + if (!params.invitation_id) { + throw new ArgumentError('The invitation ID passed in params cannot be null or undefined'); + } + if (typeof params.invitation_id !== 'string') { + throw new ArgumentError('The invitation ID has to be a string'); + } -/** - * Get Roles from a Member in a Organization - * - * @function getMemberRoles - * @memberof module:management.OrganizationsManager.prototype - * @example - * var params = {id : 'ORGANIZATION_ID', user_id: 'user_id'} - * @param callback - * @example - * This methods takes the organization ID and user ID and returns the roles - * - * - * management.organizations.getMemberRoles( {id : 'ORGANIZATION_ID', user_id: 'user_id'}, function (err, roles) { - * console.log(roles); - * }); - * @param {object} params Organization parameters - * @param {string} params.id ID of the Organization. - * @param {string} params.user_id ID of the user. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -OrganizationsManager.prototype.getMemberRoles = function (params, callback) { - return this.roles.getAll(params, callback); -}; - -/** - * Add a Role to a Member in an organization - * - * @function addMemberRoles - * @memberof module:management.OrganizationsManager.prototype - * @example - * var params = {id : 'ORGANIZATION_ID', user_id: 'user_id'}; - * var data = { roles: ["ROLE_ID_1", "ROLE_ID_2"]} - * - * management.organizations.addMemberRoles(params, data, function (err) { - * if (err) { - * // Handle error. - * } - * }); - * @param {object} params Organization parameters - * @param {string} params.id ID of the Organization. - * @param {string} params.user_id ID of the user. - * @param {object} data Add member roles data. - * @param {Array} data.roles Array of role IDs. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -OrganizationsManager.prototype.addMemberRoles = function (params, data, cb) { - data = data || {}; - params = params || {}; + if (cb && cb instanceof Function) { + return this.invitations.delete(params, {}, cb); + } - if (!params.id) { - throw new ArgumentError('The organization ID passed in params cannot be null or undefined'); - } - if (typeof params.id !== 'string') { - throw new ArgumentError('The organization ID has to be a string'); + return this.invitations.delete(params, {}); } - if (!params.user_id) { - throw new ArgumentError('The user ID passed in params cannot be null or undefined'); - } - if (typeof params.user_id !== 'string') { - throw new ArgumentError('The user ID has to be a string'); - } + /** + *Organization Roles Membership + */ - if (cb && cb instanceof Function) { - return this.roles.create(params, data, cb); + /** + * Get Roles from a Member in a Organization + * + * @example + * var params = {id : 'ORGANIZATION_ID', user_id: 'user_id'} + * @param callback + * @example + * This methods takes the organization ID and user ID and returns the roles + * + * + * management.organizations.getMemberRoles( {id : 'ORGANIZATION_ID', user_id: 'user_id'}, function (err, roles) { + * console.log(roles); + * }); + * @param {object} params Organization parameters + * @param {string} params.id ID of the Organization. + * @param {string} params.user_id ID of the user. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getMemberRoles(params, callback) { + return this.roles.getAll(params, callback); } - return this.roles.create(params, data); -}; + /** + * Add a Role to a Member in an organization + * + * @example + * var params = {id : 'ORGANIZATION_ID', user_id: 'user_id'}; + * var data = { roles: ["ROLE_ID_1", "ROLE_ID_2"]} + * + * management.organizations.addMemberRoles(params, data, function (err) { + * if (err) { + * // Handle error. + * } + * }); + * @param {object} params Organization parameters + * @param {string} params.id ID of the Organization. + * @param {string} params.user_id ID of the user. + * @param {object} data Add member roles data. + * @param {Array} data.roles Array of role IDs. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + addMemberRoles(params, data, cb) { + data = data || {}; + params = params || {}; -/** - * Remove Roles from a Member of an organization - * - * @function removeMemberRoles - * @memberof module:management.OrganizationsManager.prototype - * @example - * var params = { id :'ORGANIZATION_ID', user_id: 'USER_ID }; - * var data = { roles: ["ROLE_ID_1", "ROLE_ID_2"]} - * - * management.organizations.removeMemberRoles(params, data, function (err) { - * if (err) { - * // Handle error. - * } - * }); - * @param {object} params Organization parameters - * @param {string} params.id ID of the Organization. - * @param {string} params.user_id Id of the User - * @param {object} data Remove member roles data. - * @param {Array} data.roles Array of role IDs. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -OrganizationsManager.prototype.removeMemberRoles = function (params, data, cb) { - data = data || {}; - params = params || {}; + if (!params.id) { + throw new ArgumentError('The organization ID passed in params cannot be null or undefined'); + } + if (typeof params.id !== 'string') { + throw new ArgumentError('The organization ID has to be a string'); + } - if (!params.id) { - throw new ArgumentError('The organization ID passed in params cannot be null or undefined'); - } - if (typeof params.id !== 'string') { - throw new ArgumentError('The organization ID has to be a string'); - } + if (!params.user_id) { + throw new ArgumentError('The user ID passed in params cannot be null or undefined'); + } + if (typeof params.user_id !== 'string') { + throw new ArgumentError('The user ID has to be a string'); + } - if (!params.user_id) { - throw new ArgumentError('The user ID passed in params cannot be null or undefined'); - } - if (typeof params.user_id !== 'string') { - throw new ArgumentError('The user ID has to be a string'); - } + if (cb && cb instanceof Function) { + return this.roles.create(params, data, cb); + } - if (cb && cb instanceof Function) { - return this.roles.delete(params, data, cb); + return this.roles.create(params, data); } - return this.roles.delete(params, data); -}; + /** + * Remove Roles from a Member of an organization + * + * @example + * var params = { id :'ORGANIZATION_ID', user_id: 'USER_ID }; + * var data = { roles: ["ROLE_ID_1", "ROLE_ID_2"]} + * + * management.organizations.removeMemberRoles(params, data, function (err) { + * if (err) { + * // Handle error. + * } + * }); + * @param {object} params Organization parameters + * @param {string} params.id ID of the Organization. + * @param {string} params.user_id Id of the User + * @param {object} data Remove member roles data. + * @param {Array} data.roles Array of role IDs. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + removeMemberRoles(params, data, cb) { + data = data || {}; + params = params || {}; + + if (!params.id) { + throw new ArgumentError('The organization ID passed in params cannot be null or undefined'); + } + if (typeof params.id !== 'string') { + throw new ArgumentError('The organization ID has to be a string'); + } + + if (!params.user_id) { + throw new ArgumentError('The user ID passed in params cannot be null or undefined'); + } + if (typeof params.user_id !== 'string') { + throw new ArgumentError('The user ID has to be a string'); + } + + if (cb && cb instanceof Function) { + return this.roles.delete(params, data, cb); + } + + return this.roles.delete(params, data); + } +} module.exports = OrganizationsManager; diff --git a/src/management/PromptsManager.js b/src/management/PromptsManager.js index aff8cad74..31ebaf7b1 100644 --- a/src/management/PromptsManager.js +++ b/src/management/PromptsManager.js @@ -1,203 +1,192 @@ const { ArgumentError } = require('rest-facade'); -const utils = require('../utils'); const Auth0RestClient = require('../Auth0RestClient'); const RetryRestClient = require('../RetryRestClient'); /** - * Simple facade for consuming a REST API endpoint. - * - * @external RestClient - * @see https://github.com/ngonzalvez/rest-facade - */ - -/** - * @class PromptsManager * Manages settings related to prompts. - * @class - * @memberof module:management - * @param {object} options The client options. - * @param {string} options.baseUrl The URL of the API. - * @param {object} [options.headers] Headers to be included in all requests. - * @param {object} [options.retry] Retry Policy Config */ -const PromptsManager = function (options) { - if (options === null || typeof options !== 'object') { - throw new ArgumentError('Must provide manager options'); - } - - if (options.baseUrl === null || options.baseUrl === undefined) { - throw new ArgumentError('Must provide a base URL for the API'); +class PromptsManager { + /** + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config + */ + constructor(options) { + if (options === null || typeof options !== 'object') { + throw new ArgumentError('Must provide manager options'); + } + + if (options.baseUrl === null || options.baseUrl === undefined) { + throw new ArgumentError('Must provide a base URL for the API'); + } + + if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { + throw new ArgumentError('The provided base URL is invalid'); + } + + const clientOptions = { + errorFormatter: { message: 'message', name: 'error' }, + headers: options.headers, + query: { repeatParams: false }, + }; + + /** + * Provides an abstraction layer for consuming the + * {@link https://auth0.com/docs/api/management/v2#!/Prompts Prompts endpoint}. + * + * @type {external:RestClient} + */ + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/prompts`, + clientOptions, + options.tokenProvider + ); + this.resource = new RetryRestClient(auth0RestClient, options.retry); + + /** + * Retrieve custom text for a specific prompt and language. + * {@link https://auth0.com/docs/api/management/v2#!/Prompts/get_custom_text_by_language Custom Text endpoint} + * + * + * @type {external:RestClient} + */ + const customTextByLanguageAuth0RestClient = new Auth0RestClient( + `${options.baseUrl}/prompts/:prompt/custom-text/:language`, + clientOptions, + options.tokenProvider + ); + this.customTextByLanguage = new RetryRestClient( + customTextByLanguageAuth0RestClient, + options.retry + ); } - if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { - throw new ArgumentError('The provided base URL is invalid'); + /** + * Update the prompts settings. + * + * @example + * management.prompts.updateSettings(params, data, function (err, prompts) { + * if (err) { + * // Handle error. + * } + * + * // Updated prompts + * console.log(prompts); + * }); + * @param {object} params Prompts parameters. + * @param {object} data Updated prompts data. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + updateSettings(...args) { + return this.resource.patch(...args); } - const clientOptions = { - errorFormatter: { message: 'message', name: 'error' }, - headers: options.headers, - query: { repeatParams: false }, - }; - /** - * Provides an abstraction layer for consuming the - * {@link https://auth0.com/docs/api/management/v2#!/Prompts Prompts endpoint}. + * Get the prompts settings.. * - * @type {external:RestClient} + * @example + * management.prompts.getSettings(data, function (err, prompts) { + * if (err) { + * // Handle error. + * } + * + * // Prompts + * console.log(prompts); + * }); + * @param {object} params Prompts parameters. + * @param {object} data Prompts data. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const auth0RestClient = new Auth0RestClient( - `${options.baseUrl}/prompts`, - clientOptions, - options.tokenProvider - ); - this.resource = new RetryRestClient(auth0RestClient, options.retry); + getSettings(...args) { + return this.resource.get(...args); + } /** * Retrieve custom text for a specific prompt and language. - * {@link https://auth0.com/docs/api/management/v2#!/Prompts/get_custom_text_by_language Custom Text endpoint} * + * @example + * var params = { prompt: PROMPT_NAME, language: LANGUAGE }; * - * @type {external:RestClient} + * management.prompts.getCustomTextByLanguage(params, function (err, customText) { + * if (err) { + * // Handle error. + * } + * + * console.log('CustomText', customText); + * }); + * @param {object} params Data object. + * @param {string} params.prompt Name of the prompt. + * @param {string} params.language Language to retrieve. + * @param {Function} [cb] Callback function + * @returns {Promise|undefined} */ - const customTextByLanguageAuth0RestClient = new Auth0RestClient( - `${options.baseUrl}/prompts/:prompt/custom-text/:language`, - clientOptions, - options.tokenProvider - ); - this.customTextByLanguage = new RetryRestClient( - customTextByLanguageAuth0RestClient, - options.retry - ); -}; - -/** - * Update the prompts settings. - * - * @function updateSettings - * @memberof module:management.PromptsManager.prototype - * @example - * management.prompts.updateSettings(params, data, function (err, prompts) { - * if (err) { - * // Handle error. - * } - * - * // Updated prompts - * console.log(prompts); - * }); - * @param {object} params Prompts parameters. - * @param {object} data Updated prompts data. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(PromptsManager, 'updateSettings', 'resource.patch'); + getCustomTextByLanguage(params, cb) { + params = params || {}; -/** - * Get the prompts settings.. - * - * @function getSettings - * @memberof module:management.PromptsManager.prototype - * @example - * management.prompts.getSettings(data, function (err, prompts) { - * if (err) { - * // Handle error. - * } - * - * // Prompts - * console.log(prompts); - * }); - * @param {object} params Prompts parameters. - * @param {object} data Prompts data. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(PromptsManager, 'getSettings', 'resource.get'); + if (!params.prompt || typeof params.prompt !== 'string') { + throw new ArgumentError('The prompt parameter must be a string'); + } -/** - * Retrieve custom text for a specific prompt and language. - * - * @function getCustomTextByLanguage - * @memberof module:management.PromptsManager.prototype - * @example - * var params = { prompt: PROMPT_NAME, language: LANGUAGE }; - * - * management.prompts.getCustomTextByLanguage(params, function (err, customText) { - * if (err) { - * // Handle error. - * } - * - * console.log('CustomText', customText); - * }); - * @param {object} params Data object. - * @param {string} params.prompt Name of the prompt. - * @param {string} params.language Language to retrieve. - * @param {Function} [cb] Callback function - * @returns {Promise|undefined} - */ -PromptsManager.prototype.getCustomTextByLanguage = function (params, cb) { - params = params || {}; + if (!params.language || typeof params.language !== 'string') { + throw new ArgumentError('The language parameter must be a string'); + } - if (!params.prompt || typeof params.prompt !== 'string') { - throw new ArgumentError('The prompt parameter must be a string'); - } + if (cb && cb instanceof Function) { + return this.customTextByLanguage.get(params, cb); + } - if (!params.language || typeof params.language !== 'string') { - throw new ArgumentError('The language parameter must be a string'); + return this.customTextByLanguage.get(params); } - if (cb && cb instanceof Function) { - return this.customTextByLanguage.get(params, cb); - } - - return this.customTextByLanguage.get(params); -}; + /** + * Set custom text for a specific prompt. + * + * @example + * var params = { prompt: PROMPT_NAME, language: LANGUAGE, body: BODY_OBJECT }; + * + * management.prompts.updateCustomTextByLanguage(params, function (err, customText) { + * if (err) { + * // Handle error. + * } + * + * console.log('CustomText', customText); + * }); + * @param {object} params Data object. + * @param {string} params.prompt Name of the prompt. + * @param {string} params.language Language to retrieve. + * @param {object} params.body An object containing custom dictionaries for a group of screens. + * @param {Function} [cb] Callback function + * @returns {Promise|undefined} + */ + updateCustomTextByLanguage(params, cb) { + params = params || {}; -/** - * Set custom text for a specific prompt. - * - * @function updateCustomTextByLanguage - * @memberof module:management.PromptsManager.prototype - * @example - * var params = { prompt: PROMPT_NAME, language: LANGUAGE, body: BODY_OBJECT }; - * - * management.prompts.updateCustomTextByLanguage(params, function (err, customText) { - * if (err) { - * // Handle error. - * } - * - * console.log('CustomText', customText); - * }); - * @param {object} params Data object. - * @param {string} params.prompt Name of the prompt. - * @param {string} params.language Language to retrieve. - * @param {object} params.body An object containing custom dictionaries for a group of screens. - * @param {Function} [cb] Callback function - * @returns {Promise|undefined} - */ -PromptsManager.prototype.updateCustomTextByLanguage = function (params, cb) { - params = params || {}; + if (!params.prompt || typeof params.prompt !== 'string') { + throw new ArgumentError('The prompt parameter must be a string'); + } - if (!params.prompt || typeof params.prompt !== 'string') { - throw new ArgumentError('The prompt parameter must be a string'); - } + if (!params.language || typeof params.language !== 'string') { + throw new ArgumentError('The language parameter must be a string'); + } - if (!params.language || typeof params.language !== 'string') { - throw new ArgumentError('The language parameter must be a string'); - } + if (!params.body || typeof params.body !== 'object') { + throw new ArgumentError('The body parameter must be an object'); + } - if (!params.body || typeof params.body !== 'object') { - throw new ArgumentError('The body parameter must be an object'); - } + const options = { + prompt: params.prompt, + language: params.language, + }; - const options = { - prompt: params.prompt, - language: params.language, - }; + if (cb && cb instanceof Function) { + return this.customTextByLanguage.update(options, params.body, cb); + } - if (cb && cb instanceof Function) { - return this.customTextByLanguage.update(options, params.body, cb); + return this.customTextByLanguage.update(options, params.body); } - - return this.customTextByLanguage.update(options, params.body); -}; +} module.exports = PromptsManager; diff --git a/src/management/ResourceServersManager.js b/src/management/ResourceServersManager.js index 41e2d89ec..219eb385e 100644 --- a/src/management/ResourceServersManager.js +++ b/src/management/ResourceServersManager.js @@ -1,10 +1,8 @@ const { ArgumentError } = require('rest-facade'); -const utils = require('../utils'); const Auth0RestClient = require('../Auth0RestClient'); const RetryRestClient = require('../RetryRestClient'); /** - * @class ResourceServersManager * Auth0 Resource Servers Manager. * * {@link https://auth0.com/docs/api/management/v2#!/Resource_Servers Resource Servers} represents @@ -12,160 +10,161 @@ const RetryRestClient = require('../RetryRestClient'); * You can learn more about this in the * {@link https://auth0.com/docs/api-auth API Authorization} section of the * documentation. - * @class - * @memberof module:management - * @param {object} options The client options. - * @param {string} options.baseUrl The URL of the API. - * @param {object} [options.headers] Headers to be included in all requests. - * @param {object} [options.retry] Retry Policy Config */ +class ResourceServersManager { + /** + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config + */ + constructor(options) { + if (options === null || typeof options !== 'object') { + throw new ArgumentError('Must provide resource server options'); + } -const ResourceServersManager = function (options) { - if (options === null || typeof options !== 'object') { - throw new ArgumentError('Must provide resource server options'); - } + if (options.baseUrl === null || options.baseUrl === undefined) { + throw new ArgumentError('Must provide a base URL for the API'); + } - if (options.baseUrl === null || options.baseUrl === undefined) { - throw new ArgumentError('Must provide a base URL for the API'); - } + if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { + throw new ArgumentError('The provided base URL is invalid'); + } - if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { - throw new ArgumentError('The provided base URL is invalid'); + /** + * Options object for the Rest Client instance. + * + * @type {object} + */ + const clientOptions = { + headers: options.headers, + query: { repeatParams: false }, + }; + + /** + * Provides an abstraction layer for consuming the + * {@link https://auth0.com/docs/api/v2#!/ResourceServers Auth0 Resource Servers endpoint}. + * + * @type {external:RestClient} + */ + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/resource-servers/:id`, + clientOptions, + options.tokenProvider + ); + this.resource = new RetryRestClient(auth0RestClient, options.retry); } /** - * Options object for the Rest Client instance. + * Create an API (Resource Server). + * + * @example + * management.resourceServers.create(data, function (err) { + * if (err) { + * // Handle error. + * } * - * @type {object} + * // Resource Server created. + * }); + * @param {object} data Resource Server data object. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const clientOptions = { - headers: options.headers, - query: { repeatParams: false }, - }; + create(...args) { + return this.resource.create(...args); + } /** - * Provides an abstraction layer for consuming the - * {@link https://auth0.com/docs/api/v2#!/ResourceServers Auth0 Resource Servers endpoint}. + * Get all resource servers. * - * @type {external:RestClient} + * @example + * This method takes an optional object as first argument that may be used to + * specify pagination settings. If pagination options are not present, + * the first page of a limited number of results will be returned. + * + * + * // Pagination settings. + * var params = { + * per_page: 10, + * page: 0 + * }; + * + * management.resourceServers.getAll(params, function (err, resourceServers) { + * console.log(resourceServers.length); + * }); + * @param {object} [params] Resource Servers parameters. + * @param {number} [params.per_page] Number of results per page. + * @param {number} [params.page] Page number, zero indexed. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const auth0RestClient = new Auth0RestClient( - `${options.baseUrl}/resource-servers/:id`, - clientOptions, - options.tokenProvider - ); - this.resource = new RetryRestClient(auth0RestClient, options.retry); -}; - -/** - * Create an API (Resource Server). - * - * @function create - * @memberof module:management.ResourceServersManager.prototype - * @example - * management.resourceServers.create(data, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Resource Server created. - * }); - * @param {object} data Resource Server data object. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ResourceServersManager, 'create', 'resource.create'); - -/** - * Get all resource servers. - * - * @function getAll - * @memberof module:management.ResourceServersManager.prototype - * @example - * This method takes an optional object as first argument that may be used to - * specify pagination settings. If pagination options are not present, - * the first page of a limited number of results will be returned. - * - * - * // Pagination settings. - * var params = { - * per_page: 10, - * page: 0 - * }; - * - * management.resourceServers.getAll(params, function (err, resourceServers) { - * console.log(resourceServers.length); - * }); - * @param {object} [params] Resource Servers parameters. - * @param {number} [params.per_page] Number of results per page. - * @param {number} [params.page] Page number, zero indexed. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ResourceServersManager, 'getAll', 'resource.getAll'); + getAll(...args) { + return this.resource.getAll(...args); + } -/** - * Get a Resource Server. - * - * @function get - * @memberof module:management.ResourceServersManager.prototype - * @example - * management.resourceServers.get({ id: RESOURCE_SERVER_ID }, function (err, resourceServer) { - * if (err) { - * // Handle error. - * } - * - * console.log(resourceServer); - * }); - * @param {object} params Resource Server parameters. - * @param {string} params.id Resource Server ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ResourceServersManager, 'get', 'resource.get'); + /** + * Get a Resource Server. + * + * @example + * management.resourceServers.get({ id: RESOURCE_SERVER_ID }, function (err, resourceServer) { + * if (err) { + * // Handle error. + * } + * + * console.log(resourceServer); + * }); + * @param {object} params Resource Server parameters. + * @param {string} params.id Resource Server ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + get(...args) { + return this.resource.get(...args); + } -/** - * Update an existing resource server. - * - * @function update - * @memberof module:management.ResourceServersManager.prototype - * @example - * var data = { name: 'newResourceServerName' }; - * var params = { id: RESOURCE_SERVER_ID }; - * - * management.resourceServers.update(params, data, function (err, resourceServer) { - * if (err) { - * // Handle error. - * } - * - * console.log(resourceServer.name); // 'newResourceServernName' - * }); - * @param {object} params Resource Server parameters. - * @param {string} params.id Resource Server ID. - * @param {object} data Updated Resource Server data. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ResourceServersManager, 'update', 'resource.patch'); + /** + * Update an existing resource server. + * + * @example + * var data = { name: 'newResourceServerName' }; + * var params = { id: RESOURCE_SERVER_ID }; + * + * management.resourceServers.update(params, data, function (err, resourceServer) { + * if (err) { + * // Handle error. + * } + * + * console.log(resourceServer.name); // 'newResourceServernName' + * }); + * @param {object} params Resource Server parameters. + * @param {string} params.id Resource Server ID. + * @param {object} data Updated Resource Server data. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + update(...args) { + return this.resource.patch(...args); + } -/** - * Delete an existing Resource Server. - * - * @function delete - * @memberof module:management.ResourceServersManager.prototype - * @example - * management.resourceServers.delete({ id: RESOURCE_SERVER_ID }, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Resource Server deleted. - * }); - * @param {object} params Resource Server parameters. - * @param {string} params.id Resource Server ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ResourceServersManager, 'delete', 'resource.delete'); + /** + * Delete an existing Resource Server. + * + * @example + * management.resourceServers.delete({ id: RESOURCE_SERVER_ID }, function (err) { + * if (err) { + * // Handle error. + * } + * + * // Resource Server deleted. + * }); + * @param {object} params Resource Server parameters. + * @param {string} params.id Resource Server ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + delete(...args) { + return this.resource.delete(...args); + } +} module.exports = ResourceServersManager; diff --git a/src/management/RolesManager.js b/src/management/RolesManager.js index 8a6b1a352..181b56dde 100644 --- a/src/management/RolesManager.js +++ b/src/management/RolesManager.js @@ -1,384 +1,367 @@ const { ArgumentError } = require('rest-facade'); -const utils = require('../utils'); const Auth0RestClient = require('../Auth0RestClient'); const RetryRestClient = require('../RetryRestClient'); /** - * Simple facade for consuming a REST API endpoint. - * - * @external RestClient - * @see https://github.com/ngonzalvez/rest-facade - */ - -/** - * @class RolesManager * The role class provides a simple abstraction for performing CRUD operations * on Auth0 RolesManager. - * @class - * @memberof module:management - * @param {object} options The client options. - * @param {string} options.baseUrl The URL of the API. - * @param {object} [options.headers] Headers to be included in all requests. - * @param {object} [options.retry] Retry Policy Config */ -const RolesManager = function (options) { - if (options === null || typeof options !== 'object') { - throw new ArgumentError('Must provide manager options'); - } +class RolesManager { + /** + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config + */ + constructor(options) { + if (options === null || typeof options !== 'object') { + throw new ArgumentError('Must provide manager options'); + } - if (options.baseUrl === null || options.baseUrl === undefined) { - throw new ArgumentError('Must provide a base URL for the API'); - } + if (options.baseUrl === null || options.baseUrl === undefined) { + throw new ArgumentError('Must provide a base URL for the API'); + } + + if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { + throw new ArgumentError('The provided base URL is invalid'); + } + + /** + * Options object for the Rest Client instance. + * + * @type {object} + */ + const clientOptions = { + headers: options.headers, + query: { repeatParams: false }, + }; + + /** + * Provides an abstraction layer for performing CRUD operations on + * {@link https://auth0.com/docs/api/v2#!/RolesManager Auth0 RolesManagers}. + * + * @type {external:RestClient} + */ + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/roles/:id`, + clientOptions, + options.tokenProvider + ); + this.resource = new RetryRestClient(auth0RestClient, options.retry); + + const permissionsInRoleClient = new Auth0RestClient( + `${options.baseUrl}/roles/:id/permissions`, + clientOptions, + options.tokenProvider + ); + this.permissions = new RetryRestClient(permissionsInRoleClient, options.retry); - if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { - throw new ArgumentError('The provided base URL is invalid'); + const usersInRoleClient = new Auth0RestClient( + `${options.baseUrl}/roles/:id/users`, + clientOptions, + options.tokenProvider + ); + this.users = new RetryRestClient(usersInRoleClient, options.retry); } /** - * Options object for the Rest Client instance. + * Create a new role. * - * @type {object} + * @example + * management.roles.create(data, function (err) { + * if (err) { + * // Handle error. + * } + * + * // Role created. + * }); + * @param {object} data Role data object. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const clientOptions = { - headers: options.headers, - query: { repeatParams: false }, - }; + create(...args) { + return this.resource.create(...args); + } /** - * Provides an abstraction layer for performing CRUD operations on - * {@link https://auth0.com/docs/api/v2#!/RolesManager Auth0 RolesManagers}. + * Get all roles. + * + * @example + * This method takes an optional object as first argument that may be used to + * specify pagination settings. If pagination options are not present, + * the first page of a limited number of results will be returned. + * * - * @type {external:RestClient} + * // Pagination settings. + * var params = { + * per_page: 10, + * page: 0 + * }; + * + * management.roles.getAll(params, function (err, roles) { + * console.log(roles.length); + * }); + * @param {object} [params] Roles parameters. + * @param {number} [params.per_page] Number of results per page. + * @param {number} [params.page] Page number, zero indexed. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const auth0RestClient = new Auth0RestClient( - `${options.baseUrl}/roles/:id`, - clientOptions, - options.tokenProvider - ); - this.resource = new RetryRestClient(auth0RestClient, options.retry); - - const permissionsInRoleClient = new Auth0RestClient( - `${options.baseUrl}/roles/:id/permissions`, - clientOptions, - options.tokenProvider - ); - this.permissions = new RetryRestClient(permissionsInRoleClient, options.retry); - - const usersInRoleClient = new Auth0RestClient( - `${options.baseUrl}/roles/:id/users`, - clientOptions, - options.tokenProvider - ); - this.users = new RetryRestClient(usersInRoleClient, options.retry); -}; + getAll(...args) { + return this.resource.getAll(...args); + } -/** - * Create a new role. - * - * @function create - * @memberof module:management.RolesManager.prototype - * @example - * management.roles.create(data, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Role created. - * }); - * @param {object} data Role data object. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(RolesManager, 'create', 'resource.create'); + /** + * Get an Auth0 role. + * + * @example + * management.roles.get({ id: ROLE_ID }, function (err, role) { + * if (err) { + * // Handle error. + * } + * + * console.log(role); + * }); + * @param {object} params Role parameters. + * @param {string} params.id Role ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + get(...args) { + return this.resource.get(...args); + } -/** - * Get all roles. - * - * @function getAll - * @memberof module:management.RolesManager.prototype - * @example - * This method takes an optional object as first argument that may be used to - * specify pagination settings. If pagination options are not present, - * the first page of a limited number of results will be returned. - * - * - * // Pagination settings. - * var params = { - * per_page: 10, - * page: 0 - * }; - * - * management.roles.getAll(params, function (err, roles) { - * console.log(roles.length); - * }); - * @param {object} [params] Roles parameters. - * @param {number} [params.per_page] Number of results per page. - * @param {number} [params.page] Page number, zero indexed. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(RolesManager, 'getAll', 'resource.getAll'); + /** + * Update an existing role. + * + * @example + * var data = { name: 'New name' }; + * var params = { id: ROLE_ID }; + * + * // Using auth0 instance. + * management.updateRole(params, data, function (err, role) { + * if (err) { + * // Handle error. + * } + * + * console.log(role.name); // 'New name' + * }); + * + * // Using the roles manager directly. + * management.roles.update(params, data, function (err, role) { + * if (err) { + * // Handle error. + * } + * + * console.log(role.name); // 'New name' + * }); + * @param {object} params Role parameters. + * @param {string} params.id Role ID. + * @param {object} data Updated role data. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + update(...args) { + return this.resource.patch(...args); + } -/** - * Get an Auth0 role. - * - * @function get - * @memberof module:management.RolesManager.prototype - * @example - * management.roles.get({ id: ROLE_ID }, function (err, role) { - * if (err) { - * // Handle error. - * } - * - * console.log(role); - * }); - * @param {object} params Role parameters. - * @param {string} params.id Role ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(RolesManager, 'get', 'resource.get'); + /** + * Delete an existing role. + * + * @example + * management.roles.delete({ id: ROLE_ID }, function (err) { + * if (err) { + * // Handle error. + * } + * + * // Role deleted. + * }); + * @param {object} params Role parameters. + * @param {string} params.id Role ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + delete(...args) { + return this.resource.delete(...args); + } -/** - * Update an existing role. - * - * @function update - * @memberof module:management.RolesManager.prototype - * @example - * var data = { name: 'New name' }; - * var params = { id: ROLE_ID }; - * - * // Using auth0 instance. - * management.updateRole(params, data, function (err, role) { - * if (err) { - * // Handle error. - * } - * - * console.log(role.name); // 'New name' - * }); - * - * // Using the roles manager directly. - * management.roles.update(params, data, function (err, role) { - * if (err) { - * // Handle error. - * } - * - * console.log(role.name); // 'New name' - * }); - * @param {object} params Role parameters. - * @param {string} params.id Role ID. - * @param {object} data Updated role data. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(RolesManager, 'update', 'resource.patch'); + /** + * Get Permissions in a Role + * + * @param params + * @param callback + * @example + * var params = {id : 'ROLE_ID'} + * @example + * This method takes a first argument as the roleId and returns the permissions within that role + * + * + * management.roles.getPermissions( {id : 'ROLE_ID'}, function (err, permissions) { + * console.log(permissions); + * }); + * @param {string} [email] Email address of user(s) to find + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getPermissions(params, callback) { + return this.permissions.getAll(params, callback); + } -/** - * Delete an existing role. - * - * @function delete - * @memberof module:management.RolesManager.prototype - * @example - * management.roles.delete({ id: ROLE_ID }, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Role deleted. - * }); - * @param {object} params Role parameters. - * @param {string} params.id Role ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(RolesManager, 'delete', 'resource.delete'); + /** + * Add permissions in a role + * + * @example + * var params = { id :'ROLE_ID'}; + * var data = { "permissions" : [{"permission_name" :"do:something" ,"resource_server_identifier" :"test123" }]}; + * + * management.roles.addPermissions(params, data, function (err, user) { + * if (err) { + * // Handle error. + * } + * + * // permissions added. + * }); + * @param {string} params.id ID of the Role. + * @param {object} data permissions data + * @param {string} data.permissions Array of permissions + * @param {string} data.permissions.permission_name Name of a permission + * @param {string} data.permissions.resource_server_identifier Identifier for a resource + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ -/** - * Get Permissions in a Role - * - * @function getPermissionsInRole - * @memberof module:management.RolesManager.prototype - * @param params - * @param callback - * @example - * var params = {id : 'ROLE_ID'} - * @example - * This method takes a first argument as the roleId and returns the permissions within that role - * - * - * management.roles.getPermissions( {id : 'ROLE_ID'}, function (err, permissions) { - * console.log(permissions); - * }); - * @param {string} [email] Email address of user(s) to find - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -RolesManager.prototype.getPermissions = function (params, callback) { - return this.permissions.getAll(params, callback); -}; + addPermissions(params, data, cb) { + data = data || {}; + params = params || {}; -/** - * Add permissions in a role - * - * @function addPermissions - * @memberof module:management.RolesManager.prototype - * @example - * var params = { id :'ROLE_ID'}; - * var data = { "permissions" : [{"permission_name" :"do:something" ,"resource_server_identifier" :"test123" }]}; - * - * management.roles.addPermissions(params, data, function (err, user) { - * if (err) { - * // Handle error. - * } - * - * // permissions added. - * }); - * @param {string} params.id ID of the Role. - * @param {object} data permissions data - * @param {string} data.permissions Array of permissions - * @param {string} data.permissions.permission_name Name of a permission - * @param {string} data.permissions.resource_server_identifier Identifier for a resource - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ + // Require a user ID. + if (!params.id) { + throw new ArgumentError('The roleId passed in params cannot be null or undefined'); + } + if (typeof params.id !== 'string') { + throw new ArgumentError('The role Id has to be a string'); + } -RolesManager.prototype.addPermissions = function (params, data, cb) { - data = data || {}; - params = params || {}; + if (cb && cb instanceof Function) { + return this.permissions.create(params, data, cb); + } - // Require a user ID. - if (!params.id) { - throw new ArgumentError('The roleId passed in params cannot be null or undefined'); - } - if (typeof params.id !== 'string') { - throw new ArgumentError('The role Id has to be a string'); + return this.permissions.create(params, data); } - if (cb && cb instanceof Function) { - return this.permissions.create(params, data, cb); - } + /** + * Remove permissions from a role + * + * @example + * var params = { id :'ROLE_ID'}; + * var data = { "permissions" : [{"permission_name" :"do:something" ,"resource_server_identifier" :"test123" }]}; + * + * management.roles.removePermissions(params, data, function (err, user) { + * if (err) { + * // Handle error. + * } + * + * // permissions added. + * }); + * @param {string} params.id ID of the Role. + * @param {object} data permissions data + * @param {string} data.permissions Array of permissions + * @param {string} data.permissions.permission_name Name of a permission + * @param {string} data.permissions.resource_server_identifier Identifier for a resource + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ - return this.permissions.create(params, data); -}; + removePermissions(params, data, cb) { + data = data || {}; + params = params || {}; -/** - * Remove permissions from a role - * - * @function removePermissions - * @memberof module:management.RolesManager.prototype - * @example - * var params = { id :'ROLE_ID'}; - * var data = { "permissions" : [{"permission_name" :"do:something" ,"resource_server_identifier" :"test123" }]}; - * - * management.roles.removePermissions(params, data, function (err, user) { - * if (err) { - * // Handle error. - * } - * - * // permissions added. - * }); - * @param {string} params.id ID of the Role. - * @param {object} data permissions data - * @param {string} data.permissions Array of permissions - * @param {string} data.permissions.permission_name Name of a permission - * @param {string} data.permissions.resource_server_identifier Identifier for a resource - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ + // Require a user ID. + if (!params.id) { + throw new ArgumentError('The roleId passed in params cannot be null or undefined'); + } + if (typeof params.id !== 'string') { + throw new ArgumentError('The role Id has to be a string'); + } -RolesManager.prototype.removePermissions = function (params, data, cb) { - data = data || {}; - params = params || {}; + if (cb && cb instanceof Function) { + return this.permissions.delete(params, data, cb); + } - // Require a user ID. - if (!params.id) { - throw new ArgumentError('The roleId passed in params cannot be null or undefined'); - } - if (typeof params.id !== 'string') { - throw new ArgumentError('The role Id has to be a string'); + return this.permissions.delete(params, data); } - if (cb && cb instanceof Function) { - return this.permissions.delete(params, data, cb); + /** + * Get Users in a Role + * + * @example + * var params = { + * roleId: 'ROLE_ID', + * per_page: 50, + * @param params + * @param callback + * page: 0 + * }; + * @example + * This method takes a roleId and returns all users within that role. Supports offset (page, per_page) and checkpoint pagination (from, take). You must use checkpoint pagination to retrieve beyond the first 1000 records. + * + * + * management.roles.getUsers(params, function (err, users) { + * console.log(users); + * }); + * @param {string} [roleId] Id of the role + * @param {number} [params.per_page] Number of results per page. + * @param {number} [params.page] Page number, zero indexed. + * @param {string} [params.from] For checkpoint pagination, the Id from which to start selection from. + * @param {number} [params.take] For checkpoint pagination, the number of entries to retrieve. Default 50. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getUsers(params, callback) { + return this.users.getAll(params, callback); } - return this.permissions.delete(params, data); -}; - -/** - * Get Users in a Role - * - * @function getUsers - * @memberof module:management.RolesManager.prototype - * @example - * var params = { - * roleId: 'ROLE_ID', - * per_page: 50, - * @param params - * @param callback - * page: 0 - * }; - * @example - * This method takes a roleId and returns all users within that role. Supports offset (page, per_page) and checkpoint pagination (from, take). You must use checkpoint pagination to retrieve beyond the first 1000 records. - * - * - * management.roles.getUsers(params, function (err, users) { - * console.log(users); - * }); - * @param {string} [roleId] Id of the role - * @param {number} [params.per_page] Number of results per page. - * @param {number} [params.page] Page number, zero indexed. - * @param {string} [params.from] For checkpoint pagination, the Id from which to start selection from. - * @param {number} [params.take] For checkpoint pagination, the number of entries to retrieve. Default 50. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -RolesManager.prototype.getUsers = function (params, callback) { - return this.users.getAll(params, callback); -}; + /** + * Assign users to a role + * + * @example + * var params = { id :'ROLE_ID'}; + * var data = { "users" : ["userId1","userId2"]}; + * + * management.roles.assignUsers(params, data, function (err, user) { + * if (err) { + * // Handle error. + * } + * + * // permissions added. + * }); + * @param {string} params.id ID of the Role. + * @param {object} data permissions data + * @param {string} data.permissions Array of permissions + * @param {string} data.permissions.permission_name Name of a permission + * @param {string} data.permissions.resource_server_identifier Identifier for a resource + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ -/** - * Assign users to a role - * - * @function assignUsers - * @memberof module:management.RolesManager.prototype - * @example - * var params = { id :'ROLE_ID'}; - * var data = { "users" : ["userId1","userId2"]}; - * - * management.roles.assignUsers(params, data, function (err, user) { - * if (err) { - * // Handle error. - * } - * - * // permissions added. - * }); - * @param {string} params.id ID of the Role. - * @param {object} data permissions data - * @param {string} data.permissions Array of permissions - * @param {string} data.permissions.permission_name Name of a permission - * @param {string} data.permissions.resource_server_identifier Identifier for a resource - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ + assignUsers(params, data, cb) { + data = data || {}; + params = params || {}; -RolesManager.prototype.assignUsers = function (params, data, cb) { - data = data || {}; - params = params || {}; + // Require a user ID. + if (!params.id) { + throw new ArgumentError('The roleId passed in params cannot be null or undefined'); + } + if (typeof params.id !== 'string') { + throw new ArgumentError('The role Id has to be a string'); + } - // Require a user ID. - if (!params.id) { - throw new ArgumentError('The roleId passed in params cannot be null or undefined'); - } - if (typeof params.id !== 'string') { - throw new ArgumentError('The role Id has to be a string'); - } + if (cb && cb instanceof Function) { + return this.permissions.create(params, data, cb); + } - if (cb && cb instanceof Function) { - return this.permissions.create(params, data, cb); + return this.users.create(params, data); } - - return this.users.create(params, data); -}; +} module.exports = RolesManager; diff --git a/src/management/RulesConfigsManager.js b/src/management/RulesConfigsManager.js index 24d190bb8..eb0585a95 100644 --- a/src/management/RulesConfigsManager.js +++ b/src/management/RulesConfigsManager.js @@ -1,120 +1,113 @@ const { ArgumentError } = require('rest-facade'); -const utils = require('../utils'); const Auth0RestClient = require('../Auth0RestClient'); const RetryRestClient = require('../RetryRestClient'); /** - * Simple facade for consuming a REST API endpoint. - * - * @external RestClient - * @see https://github.com/ngonzalvez/rest-facade - */ - -/** - * @class RulesConfigsManager * The rules configs manager class provides a simple abstraction for performing CRUD operations * on Auth0 RulesConfigsManager. - * @class - * @memberof module:management - * @param {object} options The client options. - * @param {string} options.baseUrl The URL of the API. - * @param {object} [options.headers] Headers to be included in all requests. - * @param {object} [options.retry] Retry Policy Config */ -const RulesConfigsManager = function (options) { - if (options === null || typeof options !== 'object') { - throw new ArgumentError('Must provide manager options'); - } +class RulesConfigsManager { + /** + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config + */ + constructor(options) { + if (options === null || typeof options !== 'object') { + throw new ArgumentError('Must provide manager options'); + } - if (options.baseUrl === null || options.baseUrl === undefined) { - throw new ArgumentError('Must provide a base URL for the API'); - } + if (options.baseUrl === null || options.baseUrl === undefined) { + throw new ArgumentError('Must provide a base URL for the API'); + } - if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { - throw new ArgumentError('The provided base URL is invalid'); + if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { + throw new ArgumentError('The provided base URL is invalid'); + } + + /** + * Options object for the Rest Client instance. + * + * @type {object} + */ + const clientOptions = { + headers: options.headers, + query: { repeatParams: false }, + }; + + /** + * Provides an abstraction layer for performing CRUD operations on + * {@link https://auth0.com/docs/api/v2#!/RulesConfigsManager Auth0 RulesConfigsManager}. + * + * @type {external:RestClient} + */ + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/rules-configs/:key`, + clientOptions, + options.tokenProvider + ); + this.resource = new RetryRestClient(auth0RestClient, options.retry); } /** - * Options object for the Rest Client instance. + * Set a new rules config. + * + * @example + * var params = { key: RULE_CONFIG_KEY }; + * var data = { value: RULES_CONFIG_VALUE }; * - * @type {object} + * management.rulesConfigs.set(params, data, function (err, rulesConfig) { + * if (err) { + * // Handle error. + * } + * + * // Rules Config set. + * }); + * @param {object} params Rule Config parameters. + * @param {string} params.key Rule Config key. + * @param {object} data Rule Config Data parameters. + * @param {string} data.value Rule Config Data value. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const clientOptions = { - headers: options.headers, - query: { repeatParams: false }, - }; + set(...args) { + return this.resource.update(...args); + } /** - * Provides an abstraction layer for performing CRUD operations on - * {@link https://auth0.com/docs/api/v2#!/RulesConfigsManager Auth0 RulesConfigsManager}. + * Get all rules configs. * - * @type {external:RestClient} + * @example + * management.rulesConfigs.getAll(function (err, rulesConfig) { + * console.log(rulesConfig.length); + * }); + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const auth0RestClient = new Auth0RestClient( - `${options.baseUrl}/rules-configs/:key`, - clientOptions, - options.tokenProvider - ); - this.resource = new RetryRestClient(auth0RestClient, options.retry); -}; - -/** - * Set a new rules config. - * - * @function set - * @memberof module:management.RulesConfigsManager.prototype - * @example - * var params = { key: RULE_CONFIG_KEY }; - * var data = { value: RULES_CONFIG_VALUE }; - * - * management.rulesConfigs.set(params, data, function (err, rulesConfig) { - * if (err) { - * // Handle error. - * } - * - * // Rules Config set. - * }); - * @param {object} params Rule Config parameters. - * @param {string} params.key Rule Config key. - * @param {object} data Rule Config Data parameters. - * @param {string} data.value Rule Config Data value. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(RulesConfigsManager, 'set', 'resource.update'); - -/** - * Get all rules configs. - * - * @function getAll - * @memberof module:management.RulesConfigsManager.prototype - * @example - * management.rulesConfigs.getAll(function (err, rulesConfig) { - * console.log(rulesConfig.length); - * }); - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(RulesConfigsManager, 'getAll', 'resource.getAll'); + getAll(...args) { + return this.resource.getAll(...args); + } -/** - * Delete an existing rules config. - * - * @function delete - * @memberof module:management.RulesConfigsManager.prototype - * @example - * management.rulesConfigs.delete({ key: RULE_CONFIG_KEY }, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Rules Config deleted. - * }); - * @param {object} params Rule Configs parameters. - * @param {string} params.key Rule Configs key. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(RulesConfigsManager, 'delete', 'resource.delete'); + /** + * Delete an existing rules config. + * + * @example + * management.rulesConfigs.delete({ key: RULE_CONFIG_KEY }, function (err) { + * if (err) { + * // Handle error. + * } + * + * // Rules Config deleted. + * }); + * @param {object} params Rule Configs parameters. + * @param {string} params.key Rule Configs key. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + delete(...args) { + return this.resource.delete(...args); + } +} module.exports = RulesConfigsManager; diff --git a/src/management/RulesManager.js b/src/management/RulesManager.js index 10e354a47..cfe43574d 100644 --- a/src/management/RulesManager.js +++ b/src/management/RulesManager.js @@ -1,182 +1,175 @@ const { ArgumentError } = require('rest-facade'); -const utils = require('../utils'); const Auth0RestClient = require('../Auth0RestClient'); const RetryRestClient = require('../RetryRestClient'); /** - * Simple facade for consuming a REST API endpoint. - * - * @external RestClient - * @see https://github.com/ngonzalvez/rest-facade - */ - -/** - * @class RulesManager * The rule class provides a simple abstraction for performing CRUD operations * on Auth0 RulesManagers. - * @class - * @memberof module:management - * @param {object} options The client options. - * @param {string} options.baseUrl The URL of the API. - * @param {object} [options.headers] Headers to be included in all requests. - * @param {object} [options.retry] Retry Policy Config */ -const RulesManager = function (options) { - if (options === null || typeof options !== 'object') { - throw new ArgumentError('Must provide manager options'); - } +class RulesManager { + /** + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config + */ + constructor(options) { + if (options === null || typeof options !== 'object') { + throw new ArgumentError('Must provide manager options'); + } - if (options.baseUrl === null || options.baseUrl === undefined) { - throw new ArgumentError('Must provide a base URL for the API'); - } + if (options.baseUrl === null || options.baseUrl === undefined) { + throw new ArgumentError('Must provide a base URL for the API'); + } + + if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { + throw new ArgumentError('The provided base URL is invalid'); + } + + /** + * Options object for the Rest Client instance. + * + * @type {object} + */ + const clientOptions = { + headers: options.headers, + query: { repeatParams: false }, + }; - if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { - throw new ArgumentError('The provided base URL is invalid'); + /** + * Provides an abstraction layer for performing CRUD operations on + * {@link https://auth0.com/docs/api/v2#!/RulesManagers Auth0 RulesManagers}. + * + * @type {external:RestClient} + */ + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/rules/:id`, + clientOptions, + options.tokenProvider + ); + this.resource = new RetryRestClient(auth0RestClient, options.retry); } /** - * Options object for the Rest Client instance. + * Create a new rule. * - * @type {object} + * @example + * management.rules.create(data, function (err) { + * if (err) { + * // Handle error. + * } + * + * // Rule created. + * }); + * @param {object} data Rule data object. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const clientOptions = { - headers: options.headers, - query: { repeatParams: false }, - }; + create(...args) { + return this.resource.create(...args); + } /** - * Provides an abstraction layer for performing CRUD operations on - * {@link https://auth0.com/docs/api/v2#!/RulesManagers Auth0 RulesManagers}. + * Get all rules. * - * @type {external:RestClient} + * @example + * This method takes an optional object as first argument that may be used to + * specify pagination settings. If pagination options are not present, + * the first page of a limited number of results will be returned. + * + * + * // Pagination settings. + * var params = { + * per_page: 10, + * page: 0 + * }; + * + * management.rules.getAll(params, function (err, rules) { + * console.log(rules.length); + * }); + * @param {object} [params] Rules parameters. + * @param {number} [params.per_page] Number of results per page. + * @param {number} [params.page] Page number, zero indexed. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const auth0RestClient = new Auth0RestClient( - `${options.baseUrl}/rules/:id`, - clientOptions, - options.tokenProvider - ); - this.resource = new RetryRestClient(auth0RestClient, options.retry); -}; - -/** - * Create a new rule. - * - * @function create - * @memberof module:management.RulesManager.prototype - * @example - * management.rules.create(data, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Rule created. - * }); - * @param {object} data Rule data object. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(RulesManager, 'create', 'resource.create'); - -/** - * Get all rules. - * - * @function getAll - * @memberof module:management.RulesManager.prototype - * @example - * This method takes an optional object as first argument that may be used to - * specify pagination settings. If pagination options are not present, - * the first page of a limited number of results will be returned. - * - * - * // Pagination settings. - * var params = { - * per_page: 10, - * page: 0 - * }; - * - * management.rules.getAll(params, function (err, rules) { - * console.log(rules.length); - * }); - * @param {object} [params] Rules parameters. - * @param {number} [params.per_page] Number of results per page. - * @param {number} [params.page] Page number, zero indexed. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(RulesManager, 'getAll', 'resource.getAll'); + getAll(...args) { + return this.resource.getAll(...args); + } -/** - * Get an Auth0 rule. - * - * @function get - * @memberof module:management.RulesManager.prototype - * @example - * management.rules.get({ id: RULE_ID }, function (err, rule) { - * if (err) { - * // Handle error. - * } - * - * console.log(rule); - * }); - * @param {object} params Rule parameters. - * @param {string} params.id Rule ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(RulesManager, 'get', 'resource.get'); + /** + * Get an Auth0 rule. + * + * @example + * management.rules.get({ id: RULE_ID }, function (err, rule) { + * if (err) { + * // Handle error. + * } + * + * console.log(rule); + * }); + * @param {object} params Rule parameters. + * @param {string} params.id Rule ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + get(...args) { + return this.resource.get(...args); + } -/** - * Update an existing rule. - * - * @function update - * @memberof module:management.RulesManager.prototype - * @example - * var data = { name: 'New name' }; - * var params = { id: RULE_ID }; - * - * // Using auth0 instance. - * management.updateRule(params, data, function (err, rule) { - * if (err) { - * // Handle error. - * } - * - * console.log(rule.name); // 'New name' - * }); - * - * // Using the rules manager directly. - * management.rules.update(params, data, function (err, rule) { - * if (err) { - * // Handle error. - * } - * - * console.log(rule.name); // 'New name' - * }); - * @param {object} params Rule parameters. - * @param {string} params.id Rule ID. - * @param {object} data Updated rule data. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(RulesManager, 'update', 'resource.patch'); + /** + * Update an existing rule. + * + * @example + * var data = { name: 'New name' }; + * var params = { id: RULE_ID }; + * + * // Using auth0 instance. + * management.updateRule(params, data, function (err, rule) { + * if (err) { + * // Handle error. + * } + * + * console.log(rule.name); // 'New name' + * }); + * + * // Using the rules manager directly. + * management.rules.update(params, data, function (err, rule) { + * if (err) { + * // Handle error. + * } + * + * console.log(rule.name); // 'New name' + * }); + * @param {object} params Rule parameters. + * @param {string} params.id Rule ID. + * @param {object} data Updated rule data. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + update(...args) { + return this.resource.patch(...args); + } -/** - * Delete an existing rule. - * - * @function delete - * @memberof module:management.RulesManager.prototype - * @example - * management.rules.delete({ id: RULE_ID }, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Rule deleted. - * }); - * @param {object} params Rule parameters. - * @param {string} params.id Rule ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(RulesManager, 'delete', 'resource.delete'); + /** + * Delete an existing rule. + * + * @example + * management.rules.delete({ id: RULE_ID }, function (err) { + * if (err) { + * // Handle error. + * } + * + * // Rule deleted. + * }); + * @param {object} params Rule parameters. + * @param {string} params.id Rule ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + delete(...args) { + return this.resource.delete(...args); + } +} module.exports = RulesManager; diff --git a/src/management/StatsManager.js b/src/management/StatsManager.js index 892ae9496..3dcd84359 100644 --- a/src/management/StatsManager.js +++ b/src/management/StatsManager.js @@ -3,115 +3,105 @@ const Auth0RestClient = require('../Auth0RestClient'); const RetryRestClient = require('../RetryRestClient'); /** - * Simple facade for consuming a REST API endpoint. - * - * @external RestClient - * @see https://github.com/ngonzalvez/rest-facade - */ - -/** - * @class * Abstracts interaction with the stats endpoint. - * @class - * @memberof module:management - * @param {object} options The client options. - * @param {string} options.baseUrl The URL of the API. - * @param {object} [options.headers] Headers to be included in all requests. - * @param {object} [options.retry] Retry Policy Config */ -const StatsManager = function (options) { - if (options === null || typeof options !== 'object') { - throw new ArgumentError('Must provide manager options'); - } +class StatsManager { + /** + * @param {object} options The client options. + * @param {string} options.baseUrl The URL of the API. + * @param {object} [options.headers] Headers to be included in all requests. + * @param {object} [options.retry] Retry Policy Config + */ + constructor(options) { + if (options === null || typeof options !== 'object') { + throw new ArgumentError('Must provide manager options'); + } - if (options.baseUrl === null || options.baseUrl === undefined) { - throw new ArgumentError('Must provide a base URL for the API'); - } + if (options.baseUrl === null || options.baseUrl === undefined) { + throw new ArgumentError('Must provide a base URL for the API'); + } - if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { - throw new ArgumentError('The provided base URL is invalid'); - } + if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { + throw new ArgumentError('The provided base URL is invalid'); + } - const clientOptions = { - errorFormatter: { message: 'message', name: 'error' }, - headers: options.headers, - query: { repeatParams: false }, - }; + const clientOptions = { + errorFormatter: { message: 'message', name: 'error' }, + headers: options.headers, + query: { repeatParams: false }, + }; + + /** + * Provides an abstraction layer for consuming the + * {@link https://auth0.com/docs/api/v2#!/Stats Stats endpoint}. + * + * @type {external:RestClient} + */ + const auth0RestClient = new Auth0RestClient( + `${options.baseUrl}/stats/:type`, + clientOptions, + options.tokenProvider + ); + this.resource = new RetryRestClient(auth0RestClient, options.retry); + } /** - * Provides an abstraction layer for consuming the - * {@link https://auth0.com/docs/api/v2#!/Stats Stats endpoint}. + * Get the daily stats. + * + * @example + * var params = { + * from: '{YYYYMMDD}', // First day included in the stats. + * to: '{YYYYMMDD}' // Last day included in the stats. + * }; * - * @type {external:RestClient} + * management.stats.getDaily(params, function (err, stats) { + * if (err) { + * // Handle error. + * } + * + * console.log(stats); + * }); + * @param {object} params Stats parameters. + * @param {string} params.from The first day in YYYYMMDD format. + * @param {string} params.to The last day in YYYYMMDD format. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - const auth0RestClient = new Auth0RestClient( - `${options.baseUrl}/stats/:type`, - clientOptions, - options.tokenProvider - ); - this.resource = new RetryRestClient(auth0RestClient, options.retry); -}; + getDaily(params, cb) { + params = params || {}; + params.type = 'daily'; -/** - * Get the daily stats. - * - * @function getDaily - * @memberof module:management.StatsManager.prototype - * @example - * var params = { - * from: '{YYYYMMDD}', // First day included in the stats. - * to: '{YYYYMMDD}' // Last day included in the stats. - * }; - * - * management.stats.getDaily(params, function (err, stats) { - * if (err) { - * // Handle error. - * } - * - * console.log(stats); - * }); - * @param {object} params Stats parameters. - * @param {string} params.from The first day in YYYYMMDD format. - * @param {string} params.to The last day in YYYYMMDD format. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -StatsManager.prototype.getDaily = function (params, cb) { - params = params || {}; - params.type = 'daily'; + if (cb && cb instanceof Function) { + return this.resource.get(params, cb); + } - if (cb && cb instanceof Function) { - return this.resource.get(params, cb); + return this.resource.get(params); } - return this.resource.get(params); -}; + /** + * Get a the active users count. + * + * @example + * management.stats.getActiveUsersCount(function (err, usersCount) { + * if (err) { + * // Handle error. + * } + * + * console.log(usersCount); + * }); + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getActiveUsersCount(cb) { + const options = { type: 'active-users' }; -/** - * Get a the active users count. - * - * @function getActiveUsersCount - * @memberof module:management.StatsManager.prototype - * @example - * management.stats.getActiveUsersCount(function (err, usersCount) { - * if (err) { - * // Handle error. - * } - * - * console.log(usersCount); - * }); - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -StatsManager.prototype.getActiveUsersCount = function (cb) { - const options = { type: 'active-users' }; + if (cb && cb instanceof Function) { + return this.resource.get(options, cb); + } - if (cb && cb instanceof Function) { - return this.resource.get(options, cb); + // Return a promise. + return this.resource.get(options); } - - // Return a promise. - return this.resource.get(options); -}; +} module.exports = StatsManager; diff --git a/src/management/TenantManager.js b/src/management/TenantManager.js index 68cd391ef..ecbd87a7d 100644 --- a/src/management/TenantManager.js +++ b/src/management/TenantManager.js @@ -48,8 +48,6 @@ class TenantManager { /** * Update the tenant settings. * - * @function updateSettings - * @memberof module:management.TenantManager.prototype * @example * management.tenant.updateSettings(data, function (err) { * if (err) { @@ -72,8 +70,6 @@ class TenantManager { /** * Get the tenant settings.. * - * @function getSettings - * @memberof module:management.TenantManager.prototype * @example * management.tenant.getSettings({ include_fields: true, fields: 'friendly_name' }, function (err, settings) { * if (err) { diff --git a/src/management/UserBlocksManager.js b/src/management/UserBlocksManager.js index 1636ef3b7..3058fcdb6 100644 --- a/src/management/UserBlocksManager.js +++ b/src/management/UserBlocksManager.js @@ -2,13 +2,6 @@ const { ArgumentError } = require('rest-facade'); const Auth0RestClient = require('../Auth0RestClient'); const RetryRestClient = require('../RetryRestClient'); -/** - * Simple facade for consuming a REST API endpoint. - * - * @external RestClient - * @see https://github.com/ngonzalvez/rest-facade - */ - /** * Abstracts interaction with the user-blocks endpoint. */ @@ -59,8 +52,6 @@ class UserBlocksManager { /** * Get user blocks by id. * - * @function get - * @memberof module:management.UserBlocksManager.prototype * @example * management.userBlocks.get({ id: USER_ID }, function (err, blocks) { * if (err) { @@ -85,8 +76,6 @@ class UserBlocksManager { /** * Unblock an user by its id. * - * @function delete - * @memberof module:management.UserBlocksManager.prototype * @example * management.userBlocks.delete({ id: USER_ID }, function (err) { * if (err) { @@ -111,8 +100,6 @@ class UserBlocksManager { /** * Get user blocks by identifier. * - * @function getByIdentifier - * @memberof module:management.UserBlocksManager.prototype * @example * management.userBlocks.getByIdentifier({ identifier: USER_ID }, function (err, blocks) { * if (err) { @@ -137,8 +124,6 @@ class UserBlocksManager { /** * Unblock an user by identifier. * - * @function deleteByIdentifier - * @memberof module:management.UserBlocksManager.prototype * @example * management.userBlocks.deleteByIdentifier({ identifier: USER_ID }, function (err) { * if (err) { diff --git a/src/management/UsersManager.js b/src/management/UsersManager.js index aee680909..7972b9076 100644 --- a/src/management/UsersManager.js +++ b/src/management/UsersManager.js @@ -795,7 +795,7 @@ class UsersManager { * }); * @param {object} params params object * @param {string} params.id user_id - * @param {string} data data object containing list of permission IDs + * @param {object} data data object containing list of permission IDs * @param {string} data.permissions Array of permission IDs * @param {Function} [cb] Callback function. * @returns {Promise|undefined} diff --git a/src/management/index.js b/src/management/index.js index 2ad6d0800..1d80c2355 100644 --- a/src/management/index.js +++ b/src/management/index.js @@ -1,7 +1,6 @@ const util = require('util'); const utils = require('../utils'); -const { jsonToBase64 } = utils; -const { generateClientInfo } = utils; +const { jsonToBase64, generateClientInfo } = utils; const { ArgumentError } = require('rest-facade'); // Managers. @@ -39,15 +38,13 @@ const BASE_URL_FORMAT = 'https://%s/api/v2'; const MANAGEMENT_API_AUD_FORMAT = 'https://%s/api/v2/'; /** - * @class ManagementClient * Management API SDK. * * The Auth0 Management API is meant to be used by back-end servers or trusted * parties performing administrative tasks. Generally speaking, anything that * can be done through the Auth0 dashboard (and more) can also be done through * this API. - * @class - * @memberof module:management + * * @example * Initialize your client class with an API v2 token (you can generate one * here) and a domain. @@ -75,3399 +72,3295 @@ const MANAGEMENT_API_AUD_FORMAT = 'https://%s/api/v2/'; * cacheTTLInSeconds: 10 * } * }); - * @param {object} options Options for the ManagementClient SDK. - * If a token is provided only the domain is required, other parameters are ignored. - * If no token is provided domain, clientId, clientSecret and scopes are required - * @param {string} options.domain ManagementClient server domain. - * @param {string} [options.token] API access token. - * @param {string} [options.clientId] Management API Non Interactive Client Id. - * @param {string} [options.clientSecret] Management API Non Interactive Client Secret. - * @param {string} [options.audience] Management API Audience. By default is your domain's, e.g. the domain is `tenant.auth0.com` and the audience is `http://tenant.auth0.com/api/v2/` - * @param {string} [options.scope] Management API Scopes. - * @param {boolean} [options.tokenProvider.enableCache=true] Enabled or Disable Cache. - * @param {number} [options.tokenProvider.cacheTTLInSeconds] By default the `expires_in` value will be used to determine the cached time of the token, this can be overridden. - * @param {boolean} [options.retry.enabled=true] Enabled or Disable Retry Policy functionality. - * @param {number} [options.retry.maxRetries=10] Retry failed requests X times. - * @param {object} [options.headers] Additional headers that will be added to the outgoing requests. */ -const ManagementClient = function (options) { - if (!options || typeof options !== 'object') { - throw new ArgumentError('Management API SDK options must be an object'); - } +class ManagementClient { + /** + * @param {object} options Options for the ManagementClient SDK. + * If a token is provided only the domain is required, other parameters are ignored. + * If no token is provided domain, clientId, clientSecret and scopes are required + * @param {string} options.domain ManagementClient server domain. + * @param {string} [options.token] API access token. + * @param {string} [options.clientId] Management API Non Interactive Client Id. + * @param {string} [options.clientSecret] Management API Non Interactive Client Secret. + * @param {string} [options.audience] Management API Audience. By default is your domain's, e.g. the domain is `tenant.auth0.com` and the audience is `http://tenant.auth0.com/api/v2/` + * @param {string} [options.scope] Management API Scopes. + * @param {boolean} [options.tokenProvider.enableCache=true] Enabled or Disable Cache. + * @param {number} [options.tokenProvider.cacheTTLInSeconds] By default the `expires_in` value will be used to determine the cached time of the token, this can be overridden. + * @param {boolean} [options.retry.enabled=true] Enabled or Disable Retry Policy functionality. + * @param {number} [options.retry.maxRetries=10] Retry failed requests X times. + * @param {object} [options.headers] Additional headers that will be added to the outgoing requests. + */ + constructor(options) { + if (!options || typeof options !== 'object') { + throw new ArgumentError('Management API SDK options must be an object'); + } - if (!options.domain || options.domain.length === 0) { - throw new ArgumentError('Must provide a domain'); - } + if (!options.domain || options.domain.length === 0) { + throw new ArgumentError('Must provide a domain'); + } + + const baseUrl = util.format(BASE_URL_FORMAT, options.domain); - const baseUrl = util.format(BASE_URL_FORMAT, options.domain); + const defaultHeaders = { + 'User-Agent': `node.js/${process.version.replace('v', '')}`, + 'Content-Type': 'application/json', + }; - const defaultHeaders = { - 'User-Agent': `node.js/${process.version.replace('v', '')}`, - 'Content-Type': 'application/json', - }; + const managerOptions = { + headers: Object.assign(defaultHeaders, options.headers || {}), + baseUrl, + }; - const managerOptions = { - headers: Object.assign(defaultHeaders, options.headers || {}), - baseUrl, - }; + if (options.token === undefined) { + const config = Object.assign( + { audience: util.format(MANAGEMENT_API_AUD_FORMAT, options.domain) }, + options + ); + + if (options.tokenProvider) { + config.enableCache = options.tokenProvider.enableCache; + config.cacheTTLInSeconds = options.tokenProvider.cacheTTLInSeconds; + delete config.tokenProvider; + } + + this.tokenProvider = new ManagementTokenProvider(config); + } else if (typeof options.token !== 'string' || options.token.length === 0) { + throw new ArgumentError('Must provide a token'); + } else { + this.tokenProvider = { + getAccessToken() { + return Promise.resolve(options.token); + }, + }; + managerOptions.headers['Authorization'] = `Bearer ${options.token}`; + } - if (options.token === undefined) { - const config = Object.assign( - { audience: util.format(MANAGEMENT_API_AUD_FORMAT, options.domain) }, - options - ); + managerOptions.tokenProvider = this.tokenProvider; - if (options.tokenProvider) { - config.enableCache = options.tokenProvider.enableCache; - config.cacheTTLInSeconds = options.tokenProvider.cacheTTLInSeconds; - delete config.tokenProvider; + if (options.telemetry !== false) { + const clientInfo = options.clientInfo || generateClientInfo(); + if ('string' === typeof clientInfo.name && clientInfo.name.length > 0) { + const telemetry = jsonToBase64(clientInfo); + managerOptions.headers['Auth0-Client'] = telemetry; + } } - this.tokenProvider = new ManagementTokenProvider(config); - } else if (typeof options.token !== 'string' || options.token.length === 0) { - throw new ArgumentError('Must provide a token'); - } else { - this.tokenProvider = { - getAccessToken() { - return Promise.resolve(options.token); - }, - }; - managerOptions.headers['Authorization'] = `Bearer ${options.token}`; + managerOptions.retry = options.retry; + + /** + * Simple abstraction for performing CRUD operations on the + * clients endpoint. + * + * @type {ClientsManager} + */ + this.clients = new ClientsManager(managerOptions); + + /** + * Simple abstraction for performing CRUD operations on the client grants + * endpoint. + * + * @type {ClientGrantsManager} + */ + this.clientGrants = new ClientGrantsManager(managerOptions); + + /** + * Simple abstraction for performing CRUD operations on the grants + * endpoint. + * + * @type {GrantsManager} + */ + this.grants = new GrantsManager(managerOptions); + + /** + * Simple abstraction for performing CRUD operations on the + * users endpoint. + * + * @type {UsersManager} + */ + this.users = new UsersManager(managerOptions); + + /** + * Simple abstraction for performing CRUD operations on the + * user-blocks endpoint. + * + * @type {UserBlocksManager} + */ + this.userBlocks = new UserBlocksManager(managerOptions); + + /** + * Simple abstraction for performing CRUD operations on the + * guardian endpoint. + * + * @type {GuardianManager} + */ + this.guardian = new GuardianManager(managerOptions); + + /** + * Simple abstraction for performing CRUD operations on the + * custom domains endpoint. + * + * @type {CustomDomainsManager} + */ + this.customDomains = new CustomDomainsManager(managerOptions); + + /** + * Simple abstraction for performing CRUD operations on the + * connections endpoint. + * + * @type {ConnectionsManager} + */ + this.connections = new ConnectionsManager(managerOptions); + + /** + * Simple abstraction for performing CRUD operations on the + * device credentials endpoint. + * + * @type {DeviceCredentialsManager} + */ + this.deviceCredentials = new DeviceCredentialsManager(managerOptions); + + /** + * Simple abstraction for performing CRUD operations on the + * rules endpoint. + * + * @type {RulesManager} + */ + this.rules = new RulesManager(managerOptions); + + /** + * Simple abstraction for performing CRUD operations on the + * blacklisted tokens endpoint. + * + * @type {BlacklistedtokensManager} + */ + this.blacklistedTokens = new BlacklistedTokensManager(managerOptions); + + /** + * Simple abstraction for performing CRUD operations on the + * email provider endpoint. + * + * @type {EmailProviderManager} + */ + this.emailProvider = new EmailProviderManager(managerOptions); + + /** + * ManagementClient account statistics manager. + * + * @type {StatsManager} + */ + this.stats = new StatsManager(managerOptions); + + /** + * ManagementClient tenant settings manager. + * + * @type {TenantManager} + */ + this.tenant = new TenantManager(managerOptions); + + /** + * Jobs manager. + * + * @type {JobsManager} + */ + this.jobs = new JobsManager(managerOptions); + + /** + * Tickets manager. + * + * @type {TicketsManager} + */ + this.tickets = new TicketsManager(managerOptions); + + /** + * Logs manager. + * + * @type {LogsManager} + */ + this.logs = new LogsManager(managerOptions); + + /** + * Log Streams manager. + * + * @type {LogStreamsManager} + */ + this.logStreams = new LogStreamsManager(managerOptions); + + /** + * Simple abstraction for performing CRUD operations on the + * resource servers endpoint. + * + * @type {ResourceServersManager} + */ + this.resourceServers = new ResourceServersManager(managerOptions); + + /** + * Simple abstraction for performing CRUD operations on + * Auth0's Email Templates + * + * @type {EmailTemplatesManager} + */ + this.emailTemplates = new EmailTemplatesManager(managerOptions); + + /** + * RulesConfigs manager. + * + * @type {RulesConfigsManager} + */ + this.rulesConfigs = new RulesConfigsManager(managerOptions); + + /** + * Simple abstraction for performing CRUD operations on the + * roles endpoint. + * + * @type {RolesManager} + */ + this.roles = new RolesManager(managerOptions); + + /** + * Simple abstraction for performing CRUD operations on the + * hooks endpoint. + * + * @type {HooksManager} + */ + this.hooks = new HooksManager(managerOptions); + + /** + * Simple abstraction for performing CRUD operations on the + * branding endpoint. + * + * @type {HooksManager} + */ + this.branding = new BrandingManager(managerOptions); + + /** + * ManagementClient migrations manager. + * + * @type {MigrationsManager} + */ + this.migrations = new MigrationsManager(managerOptions); + + /** + * Prompts Manager + * + * @type {PromptsManager} + */ + this.prompts = new PromptsManager(managerOptions); + + /** + * Simple abstraction for performing CRUD operations on the + * actions endpoint. + * + * @type {ActionsManager} + */ + this.actions = new ActionsManager(managerOptions); + + /** + * Organizations Manager + * + * @type {OrganizationsManager} + */ + this.organizations = new OrganizationsManager(managerOptions); } - managerOptions.tokenProvider = this.tokenProvider; - - if (options.telemetry !== false) { - const clientInfo = options.clientInfo || generateClientInfo(); - if ('string' === typeof clientInfo.name && clientInfo.name.length > 0) { - const telemetry = jsonToBase64(clientInfo); - managerOptions.headers['Auth0-Client'] = telemetry; - } + /** + * Get all connections. + * + * @example + * This method takes an optional object as first argument that may be used to + * specify pagination settings. If pagination options are not present, + * the first page of a limited number of results will be returned. + * + * + * // Pagination settings. + * var params = { + * per_page: 10, + * page: 0 + * }; + * + * management.getConnections(params, function (err, connections) { + * console.log(connections.length); + * }); + * @param {object} [params] Connections params. + * @param {number} [params.per_page] Number of results per page. + * @param {number} [params.page] Page number, zero indexed. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getConnections(...args) { + return this.connections.getAll(...args); } - managerOptions.retry = options.retry; + /** + * Create a new connection. + * + * @example + * management.createConnection(data, function (err) { + * if (err) { + * // Handle error. + * } + * + * // Connection created. + * }); + * @param {object} data Connection data object. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + + createConnection(...args) { + return this.connections.create(...args); + } /** - * Simple abstraction for performing CRUD operations on the - * clients endpoint. + * Get an Auth0 connection. + * + * @example + * management.getConnection({ id: CONNECTION_ID }, function (err, connection) { + * if (err) { + * // Handle error. + * } * - * @type {ClientsManager} + * console.log(connection); + * }); + * @param {object} params Connection parameters. + * @param {string} params.id Connection ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - this.clients = new ClientsManager(managerOptions); + getConnection(...args) { + return this.connections.get(...args); + } /** - * Simple abstraction for performing CRUD operations on the client grants - * endpoint. + * Delete an existing connection. + * + * @example + * management.deleteConnection({ id: CONNECTION_ID }, function (err) { + * if (err) { + * // Handle error. + * } * - * @type {ClientGrantsManager} + * // Connection deleted. + * }); + * @param {object} params Connection parameters. + * @param {string} params.id Connection ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - this.clientGrants = new ClientGrantsManager(managerOptions); + deleteConnection(...args) { + return this.connections.delete(...args); + } /** - * Simple abstraction for performing CRUD operations on the grants - * endpoint. + * Update an existing connection. + * + * @example + * var data = { name: 'newConnectionName' }; + * var params = { id: CONNECTION_ID }; * - * @type {GrantsManager} + * management.updateConnection(params, data, function (err, connection) { + * if (err) { + * // Handle error. + * } + * + * console.log(connection.name); // 'newConnectionName' + * }); + * @param {object} params Connection parameters. + * @param {string} params.id Connection ID. + * @param {object} data Updated connection data. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - this.grants = new GrantsManager(managerOptions); + updateConnection(...args) { + return this.connections.update(...args); + } /** - * Simple abstraction for performing CRUD operations on the - * users endpoint. + * Get all Auth0 clients. * - * @type {UsersManager} + * @example + * This method takes an optional object as first argument that may be used to + * specify pagination settings. If pagination options are not present, + * the first page of a limited number of results will be returned. + * + * + * // Pagination settings. + * var params = { + * per_page: 10, + * page: 0 + * }; + * + * management.getClients(params, function (err, clients) { + * console.log(clients.length); + * }); + * @param {object} [params] Clients parameters. + * @param {number} [params.per_page] Number of results per page. + * @param {number} [params.page] Page number, zero indexed. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - this.users = new UsersManager(managerOptions); + getClients(...args) { + return this.clients.getAll(...args); + } /** - * Simple abstraction for performing CRUD operations on the - * user-blocks endpoint. + * Get an Auth0 client. + * + * @example + * management.getClient({ client_id: CLIENT_ID }, function (err, client) { + * if (err) { + * // Handle error. + * } * - * @type {UserBlocksManager} + * console.log(client); + * }); + * @param {object} params Client parameters. + * @param {string} params.client_id Application client ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - this.userBlocks = new UserBlocksManager(managerOptions); + getClient(...args) { + return this.clients.get(...args); + } /** - * Simple abstraction for performing CRUD operations on the - * guardian endpoint. + * Create an Auth0 client. + * + * @example + * management.createClient(data, function (err) { + * if (err) { + * // Handle error. + * } * - * @type {GuardianManager} + * // Client created. + * }); + * @param {object} data The client data object. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - this.guardian = new GuardianManager(managerOptions); + createClient(...args) { + return this.clients.create(...args); + } /** - * Simple abstraction for performing CRUD operations on the - * custom domains endpoint. + * Update an Auth0 client. + * + * @example + * var data = { name: 'newClientName' }; + * var params = { client_id: CLIENT_ID }; * - * @type {CustomDomainsManager} + * management.updateClient(params, data, function (err, client) { + * if (err) { + * // Handle error. + * } + * + * console.log(client.name); // 'newClientName' + * }); + * @param {object} params Client parameters. + * @param {string} params.client_id Application client ID. + * @param {object} data Updated client data. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - this.customDomains = new CustomDomainsManager(managerOptions); + updateClient(...args) { + return this.clients.update(...args); + } /** - * Simple abstraction for performing CRUD operations on the - * connections endpoint. + * Delete an Auth0 client. * - * @type {ConnectionsManager} + * @example + * management.deleteClient({ client_id: CLIENT_ID }, function (err) { + * if (err) { + * // Handle error. + * } + * + * // Client deleted. + * }); + * @param {object} params Client parameters. + * @param {string} params.client_id Application client ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - this.connections = new ConnectionsManager(managerOptions); + deleteClient(...args) { + return this.clients.delete(...args); + } /** - * Simple abstraction for performing CRUD operations on the - * device credentials endpoint. + * Get all Auth0 Client Grants. * - * @type {DeviceCredentialsManager} + * @example + * This method takes an optional object as first argument that may be used to + * specify pagination settings. If pagination options are not present, + * the first page of a limited number of results will be returned. + * + * + * // Pagination settings. + * var params = { + * per_page: 10, + * page: 0 + * }; + * + * management.getClientGrants(params, function (err, grants) { + * console.log(grants.length); + * }); + * @param {object} [params] Client Grants parameters. + * @param {number} [params.per_page] Number of results per page. + * @param {number} [params.page] Page number, zero indexed. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - this.deviceCredentials = new DeviceCredentialsManager(managerOptions); + getClientGrants(...args) { + return this.clientGrants.getAll(...args); + } /** - * Simple abstraction for performing CRUD operations on the - * rules endpoint. + * Create an Auth0 client grant. + * + * @example + * management.clientGrants.create(data, function (err) { + * if (err) { + * // Handle error. + * } * - * @type {RulesManager} + * // Client grant created. + * }); + * @param {object} data The client data object. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - this.rules = new RulesManager(managerOptions); + createClientGrant(...args) { + return this.clientGrants.create(...args); + } /** - * Simple abstraction for performing CRUD operations on the - * blacklisted tokens endpoint. + * Update an Auth0 client grant. + * + * @example + * var data = { + * client_id: CLIENT_ID, + * audience: AUDIENCE, + * scope: [] + * }; + * var params = { id: CLIENT_GRANT_ID }; * - * @type {BlacklistedtokensManager} + * management.clientGrants.update(params, data, function (err, grant) { + * if (err) { + * // Handle error. + * } + * + * console.log(grant.id); + * }); + * @param {object} params Client parameters. + * @param {string} params.id Client grant ID. + * @param {object} data Updated client data. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - this.blacklistedTokens = new BlacklistedTokensManager(managerOptions); + updateClientGrant(...args) { + return this.clientGrants.update(...args); + } /** - * Simple abstraction for performing CRUD operations on the - * email provider endpoint. + * Delete an Auth0 client grant. * - * @type {EmailProviderManager} + * @example + * management.clientGrants.delete({ id: GRANT_ID }, function (err) { + * if (err) { + * // Handle error. + * } + * + * // Grant deleted. + * }); + * @param {object} params Client parameters. + * @param {string} params.id Client grant ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - this.emailProvider = new EmailProviderManager(managerOptions); + deleteClientGrant(...args) { + return this.clientGrants.delete(...args); + } /** - * ManagementClient account statistics manager. + * Get all Auth0 Grants. * - * @type {StatsManager} + * @example + * var params = { + * per_page: 10, + * page: 0, + * include_totals: true, + * user_id: USER_ID, + * client_id: CLIENT_ID, + * audience: AUDIENCE + * }; + * + * management.getGrants(params, function (err, grants) { + * console.log(grants.length); + * }); + * @param {object} params Grants parameters. + * @param {number} params.per_page Number of results per page. + * @param {number} params.page Page number, zero indexed. + * @param {boolean} params.include_totals true if a query summary must be included in the result, false otherwise. Default false; + * @param {string} params.user_id The user_id of the grants to retrieve. + * @param {string} params.client_id The client_id of the grants to retrieve. + * @param {string} params.audience The audience of the grants to retrieve. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - this.stats = new StatsManager(managerOptions); + getGrants(...args) { + return this.grants.getAll(...args); + } /** - * ManagementClient tenant settings manager. + * Delete an Auth0 grant. * - * @type {TenantManager} + * @example + * var params = { + * id: GRANT_ID, + * user_id: USER_ID + * }; + * + * management.deleteGrant(params, function (err) { + * if (err) { + * // Handle error. + * } + * + * // Grant deleted. + * }); + * @param {object} params Grant parameters. + * @param {string} params.id Grant ID. + * @param {string} params.user_id The user_id of the grants to delete. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - this.tenant = new TenantManager(managerOptions); + deleteGrant(...args) { + return this.grants.delete(...args); + } /** - * Jobs manager. + * Create an Auth0 credential. + * + * @example + * management.createConnection(data, function (err) { + * if (err) { + * // Handle error. + * } * - * @type {JobsManager} + * // Credential created. + * }); + * @param {object} data The device credential data object. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - this.jobs = new JobsManager(managerOptions); + createDevicePublicKey(...args) { + return this.deviceCredentials.createPublicKey(...args); + } /** - * Tickets manager. + * Get all Auth0 credentials. + * + * @example + * var params = {user_id: "USER_ID"}; * - * @type {TicketsManager} + * management.getDeviceCredentials(params, function (err, credentials) { + * console.log(credentials.length); + * }); + * @param {object} params Credential parameters. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - this.tickets = new TicketsManager(managerOptions); + getDeviceCredentials(...args) { + return this.deviceCredentials.getAll(...args); + } /** - * Logs manager. + * Delete an Auth0 device credential. + * + * @example + * var params = { id: CREDENTIAL_ID }; * - * @type {LogsManager} + * management.deleteDeviceCredential(params, function (err) { + * if (err) { + * // Handle error. + * } + * + * // Credential deleted. + * }); + * @param {object} params Credential parameters. + * @param {string} params.id Device credential ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - this.logs = new LogsManager(managerOptions); + deleteDeviceCredential(...args) { + return this.deviceCredentials.delete(...args); + } /** - * Log Streams manager. + * Get all rules. + * + * @example + * This method takes an optional object as first argument that may be used to + * specify pagination settings. If pagination options are not present, + * the first page of a limited number of results will be returned. + * + * + * // Pagination settings. + * var params = { + * per_page: 10, + * page: 0 + * }; * - * @type {LogStreamsManager} + * management.getRules(params, function (err, rules) { + * console.log(rules.length); + * }); + * @param {object} [params] Rules parameters. + * @param {number} [params.per_page] Number of results per page. + * @param {number} [params.page] Page number, zero indexed. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - this.logStreams = new LogStreamsManager(managerOptions); + getRules(...args) { + return this.rules.getAll(...args); + } /** - * Simple abstraction for performing CRUD operations on the - * resource servers endpoint. + * Create a new rule. + * + * @example + * management.createRule(data, function (err) { + * if (err) { + * // Handle error. + * } * - * @type {ResourceServersManager} + * // Rule created. + * }); + * @param {object} data Rule data object. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - this.resourceServers = new ResourceServersManager(managerOptions); + createRule(...args) { + return this.rules.create(...args); + } /** - * Simple abstraction for performing CRUD operations on - * Auth0's Email Templates + * Get an Auth0 rule. + * + * @example + * management.getRule({ id: RULE_ID }, function (err, rule) { + * if (err) { + * // Handle error. + * } * - * @type {EmailTemplatesManager} + * console.log(rule); + * }); + * @param {object} params Rule parameters. + * @param {string} params.id Rule ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - this.emailTemplates = new EmailTemplatesManager(managerOptions); + getRule(...args) { + return this.rules.get(...args); + } /** - * RulesConfigs manager. + * Delete an existing rule. + * + * @example + * auth0.deleteRule({ id: RULE_ID }, function (err) { + * if (err) { + * // Handle error. + * } * - * @type {RulesConfigsManager} + * // Rule deleted. + * }); + * @param {object} params Rule parameters. + * @param {string} params.id Rule ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - this.rulesConfigs = new RulesConfigsManager(managerOptions); + deleteRule(...args) { + return this.rules.delete(...args); + } /** - * Simple abstraction for performing CRUD operations on the - * roles endpoint. + * Update an existing rule. + * + * @example + * var params = { id: RULE_ID }; + * var data = { name: 'my-rule'}; + * management.updateRule(params, data, function (err, rule) { + * if (err) { + * // Handle error. + * } * - * @type {RolesManager} + * console.log(rule.name); // 'my-rule'. + * }); + * @param {object} params Rule parameters. + * @param {string} params.id Rule ID. + * @param {object} data Updated rule data. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - this.roles = new RolesManager(managerOptions); + updateRule(...args) { + return this.rules.update(...args); + } /** - * Simple abstraction for performing CRUD operations on the - * hooks endpoint. + * Get all users. + * + * @example + * This method takes an optional object as first argument that may be used to + * specify pagination settings. If pagination options are not present, + * the first page of a limited number of results will be returned. + * * - * @type {HooksManager} + * // Pagination settings. + * var params = { + * search_engine: 'v3', + * q: 'name:*jane*', + * per_page: 10, + * page: 0 + * }; + * + * auth0.getUsers(params, function (err, users) { + * console.log(users.length); + * }); + * @param {object} [params] Users params. + * @param {number} [params.search_engine] The version of the search engine to use. + * @param {string} [params.q] User Search string to filter which users are returned. Follows Lucene query string syntax as documented at https://auth0.com/docs/api/management/v2#!/Users/get_users. + * @param {number} [params.per_page] Number of results per page. + * @param {number} [params.page] Page number, zero indexed. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - this.hooks = new HooksManager(managerOptions); + getUsers(...args) { + return this.users.getAll(...args); + } /** - * Simple abstraction for performing CRUD operations on the - * branding endpoint. + * Get users for a given email address * - * @type {HooksManager} + * @example + * This method takes an email address as the first argument, + * and returns all users with that email address + * + * + * auth0.getUsersByEmail(email, function (err, users) { + * console.log(users); + * }); + * @param {string} [email] Email address of user(s) to find + * @param {object} [options] Additional options to pass to the endpoint + * @param {string} [options.fields] Comma-separated list of fields to include or exclude in the result + * @param {boolean} [options.include_fields] Whether specified fields are to be included (true) or excluded (false). Defaults to true. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - this.branding = new BrandingManager(managerOptions); + getUsersByEmail(...args) { + return this.users.getByEmail(...args); + } /** - * ManagementClient migrations manager. + * Get a user by its id. * - * @type {MigrationsManager} + * @example + * management.getUser({ id: USER_ID }, function (err, user) { + * console.log(user); + * }); + * @param {object} data The user data object. + * @param {string} data.id The user id. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - this.migrations = new MigrationsManager(managerOptions); + getUser(...args) { + return this.users.get(...args); + } /** - * Prompts Manager + * Delete all users. + * + * @example + * management.deleteAllUsers(function (err) { + * if (err) { + * // Handle error. + * } * - * @type {PromptsManager} + * // Users deleted + * }); + * @param {Function} [cb] Callback function + * @returns {Promise|undefined} + * @deprecated This method will be removed in the next major release. */ - this.prompts = new PromptsManager(managerOptions); + deleteAllUsers(...args) { + return this.users.deleteAll(...args); + } /** - * Simple abstraction for performing CRUD operations on the - * actions endpoint. + * Delete a user by its id. + * + * @example + * management.deleteUser({ id: USER_ID }, function (err) { + * if (err) { + * // Handle error. + * } * - * @type {ActionsManager} + * // User deleted. + * }); + * @param {object} params The user data object.. + * @param {string} params.id The user id. + * @param {Function} [cb] Callback function + * @returns {Promise|undefined} */ - this.actions = new ActionsManager(managerOptions); + deleteUser(...args) { + return this.users.delete(...args); + } /** - * Organizations Manager + * Create a new user. + * + * @example + * management.createUser(data, function (err) { + * if (err) { + * // Handle error. + * } * - * @type {OrganizationsManager} + * // User created. + * }); + * @param {object} data User data. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} */ - this.organizations = new OrganizationsManager(managerOptions); -}; + createUser(...args) { + return this.users.create(...args); + } -/** - * Get all connections. - * - * @function getConnections - * @memberof module:management.ManagementClient.prototype - * @example - * This method takes an optional object as first argument that may be used to - * specify pagination settings. If pagination options are not present, - * the first page of a limited number of results will be returned. - * - * - * // Pagination settings. - * var params = { - * per_page: 10, - * page: 0 - * }; - * - * management.getConnections(params, function (err, connections) { - * console.log(connections.length); - * }); - * @param {object} [params] Connections params. - * @param {number} [params.per_page] Number of results per page. - * @param {number} [params.page] Page number, zero indexed. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getConnections', 'connections.getAll'); + /** + * Update a user by its id. + * + * @example + * var params = { id: USER_ID }; + * + * management.updateUser(params, data, function (err, user) { + * if (err) { + * // Handle error. + * } + * + * // Updated user. + * console.log(user); + * }); + * @param {object} params The user parameters. + * @param {string} params.id The user id. + * @param {object} data New user data. + * @param {Function} [cb] Callback function + * @returns {Promise|undefined} + */ + updateUser(...args) { + return this.users.update(...args); + } -/** - * Create a new connection. - * - * @function createConnection - * @memberof module:management.ManagementClient.prototype - * @example - * management.createConnection(data, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Connection created. - * }); - * @param {object} data Connection data object. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'createConnection', 'connections.create'); + /** + * Update the user metadata for a user. + * + * @example + * var params = { id: USER_ID }; + * var metadata = { + * address: '123th Node.js Street' + * }; + * + * management.updateUserMetadata(params, metadata, function (err, user) { + * if (err) { + * // Handle error. + * } + * + * // Updated user. + * console.log(user); + * }); + * @param {object} params The user data object.. + * @param {string} params.id The user id. + * @param {object} metadata New user metadata. + * @param {Function} [cb] Callback function + * @returns {Promise|undefined} + */ + updateUserMetadata(...args) { + return this.users.updateUserMetadata(...args); + } -/** - * Get an Auth0 connection. - * - * @function getConnection - * @memberof module:management.ManagementClient.prototype - * @example - * management.getConnection({ id: CONNECTION_ID }, function (err, connection) { - * if (err) { - * // Handle error. - * } - * - * console.log(connection); - * }); - * @param {object} params Connection parameters. - * @param {string} params.id Connection ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getConnection', 'connections.get'); + /** + * Update the app metadata for a user. + * + * @example + * var params = { id: USER_ID }; + * var metadata = { + * foo: 'bar' + * }; + * + * management.updateAppMetadata(params, metadata, function (err, user) { + * if (err) { + * // Handle error. + * } + * + * // Updated user. + * console.log(user); + * }); + * @param {object} params The user data object.. + * @param {string} params.id The user id. + * @param {object} metadata New app metadata. + * @param {Function} [cb] Callback function + * @returns {Promise|undefined} + */ + updateAppMetadata(...args) { + return this.users.updateAppMetadata(...args); + } -/** - * Delete an existing connection. - * - * @function deleteConnection - * @memberof module:management.ManagementClient.prototype - * @example - * management.deleteConnection({ id: CONNECTION_ID }, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Connection deleted. - * }); - * @param {object} params Connection parameters. - * @param {string} params.id Connection ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'deleteConnection', 'connections.delete'); + /** + * Delete a multifactor provider for a user. + * + * @example + * var params = { id: USER_ID, provider: MULTIFACTOR_PROVIDER }; + * + * management.deleteUserMultifactor(params, function (err, user) { + * if (err) { + * // Handle error. + * } + * + * // Users accounts unlinked. + * }); + * @param {object} params Data object. + * @param {string} params.id The user id. + * @param {string} params.provider Multifactor provider. + * @param {Function} [cb] Callback function + * @returns {Promise|undefined} + */ + deleteUserMultifactor(...args) { + return this.users.deleteMultifactorProvider(...args); + } -/** - * Update an existing connection. - * - * @function updateConnection - * @memberof module:management.ManagementClient.prototype - * @example - * var data = { name: 'newConnectionName' }; - * var params = { id: CONNECTION_ID }; - * - * management.updateConnection(params, data, function (err, connection) { - * if (err) { - * // Handle error. - * } - * - * console.log(connection.name); // 'newConnectionName' - * }); - * @param {object} params Connection parameters. - * @param {string} params.id Connection ID. - * @param {object} data Updated connection data. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'updateConnection', 'connections.update'); + /** + * Delete a multifactor provider for a user. + * + * @example + * var params = { id: USER_ID, provider: MULTIFACTOR_PROVIDER }; + * + * management.deleteUserMultifcator(params, function (err, user) { + * if (err) { + * // Handle error. + * } + * + * // Users accounts unlinked. + * }); + * @param {object} params Data object. + * @param {string} params.id The user id. + * @param {string} params.provider Multifactor provider. + * @param {Function} [cb] Callback function + * @returns {Promise|undefined} + * @deprecated The function name has a typo. + * We're shipping this so it doesn't break compatibility. + * Use {@link deleteUserMultifactor} instead. + */ + deleteUserMultifcator(...args) { + return this.users.deleteMultifactorProvider(...args); + } -/** - * Get all Auth0 clients. - * - * @function getClients - * @memberof module:management.ManagementClient.prototype - * @example - * This method takes an optional object as first argument that may be used to - * specify pagination settings. If pagination options are not present, - * the first page of a limited number of results will be returned. - * - * - * // Pagination settings. - * var params = { - * per_page: 10, - * page: 0 - * }; - * - * management.getClients(params, function (err, clients) { - * console.log(clients.length); - * }); - * @param {object} [params] Clients parameters. - * @param {number} [params.per_page] Number of results per page. - * @param {number} [params.page] Page number, zero indexed. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getClients', 'clients.getAll'); + /** + * Unlink the given accounts. + * + * @example + * var params = { id: USER_ID, provider: 'auht0', user_id: OTHER_USER_ID }; + * + * management.unlinkUsers(params, function (err, user) { + * if (err) { + * // Handle error. + * } + * + * // Users accounts unlinked. + * }); + * @param {object} params Linked users data. + * @param {string} params.id Primary user ID. + * @param {string} params.provider Identity provider in use. + * @param {string} params.user_id Secondary user ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + unlinkUsers(...args) { + return this.users.unlink(...args); + } -/** - * Get an Auth0 client. - * - * @function getClient - * @memberof module:management.ManagementClient.prototype - * @example - * management.getClient({ client_id: CLIENT_ID }, function (err, client) { - * if (err) { - * // Handle error. - * } - * - * console.log(client); - * }); - * @param {object} params Client parameters. - * @param {string} params.client_id Application client ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getClient', 'clients.get'); + /** + * Link the user with another account. + * + * @example + * var userId = 'USER_ID'; + * var params = { + * user_id: 'OTHER_USER_ID', + * connection_id: 'CONNECTION_ID' + * }; + * + * management.linkUsers(userId, params, function (err, user) { + * if (err) { + * // Handle error. + * } + * + * // Users linked. + * }); + * @param {string} userId ID of the primary user. + * @param {object} params Secondary user data. + * @param {string} params.user_id ID of the user to be linked. + * @param {string} params.connection_id ID of the connection to be used. + * @param {string} params.provider Identity provider of the secondary user account being linked. + * @param {string} params.link_with JWT for the secondary account being linked. If sending this parameter, provider, user_id, and connection_id must not be sent. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + linkUsers(...args) { + return this.users.link(...args); + } -/** - * Create an Auth0 client. - * - * @function createClient - * @memberof module:management.ManagementClient.prototype - * @example - * management.createClient(data, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Client created. - * }); - * @param {object} data The client data object. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'createClient', 'clients.create'); + /** + * Get user's log events. + * + * @example + * var params = { id: USER_ID, page: 0, per_page: 50, sort: 'date:-1', include_totals: true }; + * + * management.getUserLogs(params, function (err, logs) { + * if (err) { + * // Handle error. + * } + * + * console.log(logs); + * }); + * @param {object} params Get logs data. + * @param {string} params.id User id. + * @param {number} params.per_page Number of results per page. + * @param {number} params.page Page number, zero indexed. + * @param {string} params.sort The field to use for sorting. Use field:order where order is 1 for ascending and -1 for descending. For example date:-1. + * @param {boolean} params.include_totals true if a query summary must be included in the result, false otherwise. Default false; + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getUserLogs(...args) { + return this.users.logs(...args); + } -/** - * Update an Auth0 client. - * - * @function updateClient - * @memberof module:management.ManagementClient.prototype - * @example - * var data = { name: 'newClientName' }; - * var params = { client_id: CLIENT_ID }; - * - * management.updateClient(params, data, function (err, client) { - * if (err) { - * // Handle error. - * } - * - * console.log(client.name); // 'newClientName' - * }); - * @param {object} params Client parameters. - * @param {string} params.client_id Application client ID. - * @param {object} data Updated client data. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'updateClient', 'clients.update'); + /** + * Get user's roles + * + * @example + * var params = { id: USER_ID, page: 0, per_page: 50, sort: 'date:-1', include_totals: true }; + * + * management.getUserRoles(params, function (err, logs) { + * if (err) { + * // Handle error. + * } + * + * console.log(logs); + * }); + * @param {object} params Get roles data. + * @param {string} params.id User id. + * @param {number} params.per_page Number of results per page. + * @param {number} params.page Page number, zero indexed. + * @param {string} params.sort The field to use for sorting. Use field:order where order is 1 for ascending and -1 for descending. For example date:-1. + * @param {boolean} params.include_totals true if a query summary must be included in the result, false otherwise. Default false; + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getUserRoles(...args) { + return this.users.getRoles(...args); + } -/** - * Delete an Auth0 client. - * - * @function deleteClient - * @memberof module:management.ManagementClient.prototype - * @example - * management.deleteClient({ client_id: CLIENT_ID }, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Client deleted. - * }); - * @param {object} params Client parameters. - * @param {string} params.client_id Application client ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'deleteClient', 'clients.delete'); + /** + * Assign roles to a user + * + * @example + * var parms = { id : 'USER_ID'}; + * var data = { "roles" :["role1"]}; + * + * management.assignRolestoUser(params, data, function (err) { + * if (err) { + * // Handle error. + * } + * + * // User assigned roles. + * }); + * @param {object} params params object + * @param {string} params.id user_id + * @param {object} data data object containing list of role IDs + * @param {string} data.roles Array of role IDs + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + assignRolestoUser(...args) { + return this.roles.assignRoles(...args); + } -/** - * Get all Auth0 Client Grants. - * - * @function getClientGrants - * @memberof module:management.ManagementClient.prototype - * @example - * This method takes an optional object as first argument that may be used to - * specify pagination settings. If pagination options are not present, - * the first page of a limited number of results will be returned. - * - * - * // Pagination settings. - * var params = { - * per_page: 10, - * page: 0 - * }; - * - * management.getClientGrants(params, function (err, grants) { - * console.log(grants.length); - * }); - * @param {object} [params] Client Grants parameters. - * @param {number} [params.per_page] Number of results per page. - * @param {number} [params.page] Page number, zero indexed. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getClientGrants', 'clientGrants.getAll'); + /** + * Assign users to a role + * + * @example + * var params = { id :'ROLE_ID'}; + * var data = { "users" : ["userId1","userId2"]}; + * + * management.roles.assignUsers(params, data, function (err, user) { + * if (err) { + * // Handle error. + * } + * + * // permissions added. + * }); + * @param {string} params.id ID of the Role. + * @param {object} data permissions data + * @param {string} data.permissions Array of permissions + * @param {string} data.permissions.permission_name Name of a permission + * @param {string} data.permissions.resource_server_identifier Identifier for a resource + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + assignUsersToRole(...args) { + return this.roles.assignUsers(...args); + } -/** - * Create an Auth0 client grant. - * - * @function createClientGrant - * @memberof module:management.ManagementClient.prototype - * @example - * management.clientGrants.create(data, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Client grant created. - * }); - * @param {object} data The client data object. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'createClientGrant', 'clientGrants.create'); + /** + * Remove roles from a user + * + * @example + * var parms = { id : 'USER_ID'}; + * var data = { "roles" :["role1"]}; + * + * management.removeRolesFromUser(params, data, function (err) { + * if (err) { + * // Handle error. + * } + * + * // User assigned roles. + * }); + * @param {object} params params object + * @param {string} params.id user_id + * @param {string} data data object containing list of role IDs + * @param {string} data.roles Array of role IDs + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + removeRolesFromUser(...args) { + return this.users.removeRoles(...args); + } -/** - * Update an Auth0 client grant. - * - * @function updateClientGrant - * @memberof module:management.ManagementClient.prototype - * @example - * var data = { - * client_id: CLIENT_ID, - * audience: AUDIENCE, - * scope: [] - * }; - * var params = { id: CLIENT_GRANT_ID }; - * - * management.clientGrants.update(params, data, function (err, grant) { - * if (err) { - * // Handle error. - * } - * - * console.log(grant.id); - * }); - * @param {object} params Client parameters. - * @param {string} params.id Client grant ID. - * @param {object} data Updated client data. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'updateClientGrant', 'clientGrants.update'); + /** + * Get user's permissions + * + * @example + * var params = { id: USER_ID, page: 0, per_page: 50, sort: 'date:-1', include_totals: true }; + * + * management.getUserPermissions(params, function (err, logs) { + * if (err) { + * // Handle error. + * } + * + * console.log(logs); + * }); + * @param {object} params Get permissions data. + * @param {string} params.id User id. + * @param {number} params.per_page Number of results per page. + * @param {number} params.page Page number, zero indexed. + * @param {string} params.sort The field to use for sorting. Use field:order where order is 1 for ascending and -1 for descending. For example date:-1. + * @param {boolean} params.include_totals true if a query summary must be included in the result, false otherwise. Default false; + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getUserPermissions(...args) { + return this.users.getPermissions(...args); + } -/** - * Delete an Auth0 client grant. - * - * @function deleteClientGrant - * @memberof module:management.ManagementClient.prototype - * @example - * management.clientGrants.delete({ id: GRANT_ID }, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Grant deleted. - * }); - * @param {object} params Client parameters. - * @param {string} params.id Client grant ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'deleteClientGrant', 'clientGrants.delete'); + /** + * Assign permissions to a user + * + * @example + * var parms = { id : 'USER_ID'}; + * var data = { "permissions" : [{"permission_name" :"do:something" ,"resource_server_identifier" :"test123" }]}; + * + * management.assignPermissionsToUser(params, data, function (err) { + * if (err) { + * // Handle error. + * } + * + * // User assigned permissions. + * }); + * @param {object} params params object + * @param {string} params.id user_id + * @param {string} data data object containing list of permissions + * @param {string} data.permissions Array of permission IDs + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + assignPermissionsToUser(...args) { + return this.users.assignPermissions(...args); + } -/** - * Get all Auth0 Grants. - * - * @function getGrants - * @memberof module:management.ManagementClient.prototype - * @example - * var params = { - * per_page: 10, - * page: 0, - * include_totals: true, - * user_id: USER_ID, - * client_id: CLIENT_ID, - * audience: AUDIENCE - * }; - * - * management.getGrants(params, function (err, grants) { - * console.log(grants.length); - * }); - * @param {object} params Grants parameters. - * @param {number} params.per_page Number of results per page. - * @param {number} params.page Page number, zero indexed. - * @param {boolean} params.include_totals true if a query summary must be included in the result, false otherwise. Default false; - * @param {string} params.user_id The user_id of the grants to retrieve. - * @param {string} params.client_id The client_id of the grants to retrieve. - * @param {string} params.audience The audience of the grants to retrieve. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getGrants', 'grants.getAll'); + /** + * Remove permissions from a user + * + * @example + * var parms = { id : 'USER_ID'}; + * var data = { "permissions" : [{"permission_name" :"do:something" ,"resource_server_identifier" :"test123" }]}; + * + * management.removePermissionsFromUser(params, data, function (err) { + * if (err) { + * // Handle error. + * } + * + * // User assigned permissions. + * }); + * @param {object} params params object + * @param {string} params.id user_id + * @param {string} data data object containing list of permission IDs + * @param {string} data.permissions Array of permission IDs + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + removePermissionsFromUser(...args) { + return this.users.removePermissions(...args); + } -/** - * Delete an Auth0 grant. - * - * @function deleteGrant - * @memberof module:management.GrantsManager.prototype - * @example - * var params = { - * id: GRANT_ID, - * user_id: USER_ID - * }; - * - * management.deleteGrant(params, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Grant deleted. - * }); - * @param {object} params Grant parameters. - * @param {string} params.id Grant ID. - * @param {string} params.user_id The user_id of the grants to delete. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'deleteGrant', 'grants.delete'); + /** + * Get a list of a user's Guardian enrollments. + * + * @example + * management.getGuardianEnrollments({ id: USER_ID }, function (err, enrollments) { + * console.log(enrollments); + * }); + * @param {object} data The user data object. + * @param {string} data.id The user id. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getGuardianEnrollments(...args) { + return this.users.getGuardianEnrollments(...args); + } -/** - * Create an Auth0 credential. - * - * @function createDevicePublicKey - * @memberof module:management.ManagementClient.prototype - * @example - * management.createConnection(data, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Credential created. - * }); - * @param {object} data The device credential data object. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod( - ManagementClient, - 'createDevicePublicKey', - 'deviceCredentials.createPublicKey' -); + /** + * Generate new Guardian recovery code. + * + * @example + * management.regenerateRecoveryCode({ id: USER_ID }, function (err, newRecoveryCode) { + * console.log(newRecoveryCode); + * }); + * @param {object} data The user data object. + * @param {string} data.id The user id. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + regenerateRecoveryCode(...args) { + return this.users.regenerateRecoveryCode(...args); + } -/** - * Get all Auth0 credentials. - * - * @function getDeviceCredentials - * @memberof module:management.ManagementClient.prototype - * @example - * var params = {user_id: "USER_ID"}; - * - * management.getDeviceCredentials(params, function (err, credentials) { - * console.log(credentials.length); - * }); - * @param {object} params Credential parameters. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getDeviceCredentials', 'deviceCredentials.getAll'); + /** + * Invalidate all remembered browsers for MFA. + * + * @example + * management.invalidateRememberBrowser({ id: USER_ID }, function (err) { + * if (err) { + * // Handle error. + * } + * + * // Invalidated all remembered browsers. + * }); + * @param {object} data The user data object. + * @param {string} data.id The user id. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + invalidateRememberBrowser(...args) { + return this.users.invalidateRememberBrowser(...args); + } -/** - * Delete an Auth0 device credential. - * - * @function deleteDeviceCredential - * @memberof module:management.ManagementClient.prototype - * @example - * var params = { id: CREDENTIAL_ID }; - * - * management.deleteDeviceCredential(params, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Credential deleted. - * }); - * @param {object} params Credential parameters. - * @param {string} params.id Device credential ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'deleteDeviceCredential', 'deviceCredentials.delete'); + /** + * Get user blocks by its id. + * + * @example + * management.getUserBlocks({ id: USER_ID }, function (err, blocks) { + * if (err) { + * // Handle error. + * } + * + * console.log(blocks); + * }); + * @param {object} params The user data object.. + * @param {string} params.id The user id. + * @param {Function} [cb] Callback function + * @returns {Promise|undefined} + */ + getUserBlocks(...args) { + return this.userBlocks.get(...args); + } -/** - * Get all rules. - * - * @function getRules - * @memberof module:management.ManagementClient.prototype - * @example - * This method takes an optional object as first argument that may be used to - * specify pagination settings. If pagination options are not present, - * the first page of a limited number of results will be returned. - * - * - * // Pagination settings. - * var params = { - * per_page: 10, - * page: 0 - * }; - * - * management.getRules(params, function (err, rules) { - * console.log(rules.length); - * }); - * @param {object} [params] Rules parameters. - * @param {number} [params.per_page] Number of results per page. - * @param {number} [params.page] Page number, zero indexed. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getRules', 'rules.getAll'); + /** + * Unblock an user by its id. + * + * @example + * management.unblockUser({ id: USER_ID }, function (err) { + * if (err) { + * // Handle error. + * } + * + * // User unblocked. + * }); + * @param {object} params The user data object.. + * @param {string} params.id The user id. + * @param {Function} [cb] Callback function + * @returns {Promise|undefined} + */ + unblockUser(...args) { + return this.userBlocks.delete(...args); + } -/** - * Create a new rule. - * - * @function createRule - * @memberof module:management.ManagementClient.prototype - * @example - * management.createRule(data, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Rule created. - * }); - * @param {object} data Rule data object. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'createRule', 'rules.create'); + /** + * Get user blocks by its identifier. + * + * @example + * management.getUserBlocksByIdentifier({ identifier: USER_ID }, function (err, blocks) { + * if (err) { + * // Handle error. + * } + * + * console.log(blocks); + * }); + * @param {object} params The user data object.. + * @param {string} params.identifier The user identifier, any of: username, phone_number, email. + * @param {Function} [cb] Callback function + * @returns {Promise|undefined} + */ + getUserBlocksByIdentifier(...args) { + return this.userBlocks.getByIdentifier(...args); + } -/** - * Get an Auth0 rule. - * - * @function getRule - * @memberof module:management.ManagementClient.prototype - * @example - * management.getRule({ id: RULE_ID }, function (err, rule) { - * if (err) { - * // Handle error. - * } - * - * console.log(rule); - * }); - * @param {object} params Rule parameters. - * @param {string} params.id Rule ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getRule', 'rules.get'); + /** + * Unblock an user by its id. + * + * @example + * management.unblockUserByIdentifier({ identifier: USER_ID }, function (err) { + * if (err) { + * // Handle error. + * } + * + * // User unblocked. + * }); + * @param {object} params The user data object.. + * @param {string} params.identifier The user identifier, any of: username, phone_number, email. + * @param {Function} [cb] Callback function + * @returns {Promise|undefined} + */ + unblockUserByIdentifier(...args) { + return this.userBlocks.deleteByIdentifier(...args); + } -/** - * Delete an existing rule. - * - * @function deleteRule - * @memberof module:management.ManagementClient.prototype - * @example - * auth0.deleteRule({ id: RULE_ID }, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Rule deleted. - * }); - * @param {object} params Rule parameters. - * @param {string} params.id Rule ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'deleteRule', 'rules.delete'); + /** + * Get a single Guardian enrollment. + * + * @example + * management.getGuardianEnrollment({ id: ENROLLMENT_ID }, function (err, enrollment) { + * console.log(enrollment); + * }); + * @param {object} data The Guardian enrollment data object. + * @param {string} data.id The Guardian enrollment id. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getGuardianEnrollment(...args) { + return this.guardian.getGuardianEnrollment(...args); + } -/** - * Update an existing rule. - * - * @function updateRule - * @memberof module:management.ManagementClient.prototype - * @example - * var params = { id: RULE_ID }; - * var data = { name: 'my-rule'}; - * management.updateRule(params, data, function (err, rule) { - * if (err) { - * // Handle error. - * } - * - * console.log(rule.name); // 'my-rule'. - * }); - * @param {object} params Rule parameters. - * @param {string} params.id Rule ID. - * @param {object} data Updated rule data. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'updateRule', 'rules.update'); + /** + * Delete a user's Guardian enrollment. + * + * @example + * management.deleteGuardianEnrollment({ id: ENROLLMENT_ID }, function (err) { + * if (err) { + * // Handle error. + * } + * + * // Email provider deleted. + * }); + * @param {object} data The Guardian enrollment data object. + * @param {string} data.id The Guardian enrollment id. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + deleteGuardianEnrollment(...args) { + return this.guardian.deleteGuardianEnrollment(...args); + } -/** - * Get all users. - * - * @function getUsers - * @memberof module:management.ManagementClient.prototype - * @example - * This method takes an optional object as first argument that may be used to - * specify pagination settings. If pagination options are not present, - * the first page of a limited number of results will be returned. - * - * - * // Pagination settings. - * var params = { - * search_engine: 'v3', - * q: 'name:*jane*', - * per_page: 10, - * page: 0 - * }; - * - * auth0.getUsers(params, function (err, users) { - * console.log(users.length); - * }); - * @param {object} [params] Users params. - * @param {number} [params.search_engine] The version of the search engine to use. - * @param {string} [params.q] User Search string to filter which users are returned. Follows Lucene query string syntax as documented at https://auth0.com/docs/api/management/v2#!/Users/get_users. - * @param {number} [params.per_page] Number of results per page. - * @param {number} [params.page] Page number, zero indexed. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getUsers', 'users.getAll'); + /** + * Get all blacklisted tokens. + * + * @example + * management.getBlacklistedTokens(function (err, tokens) { + * console.log(tokens.length); + * }); + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getBlacklistedTokens(...args) { + return this.blacklistedTokens.getAll(...args); + } -/** - * Get users for a given email address - * - * @function getUsersByEmail - * @memberof module:management.ManagementClient.prototype - * @example - * This method takes an email address as the first argument, - * and returns all users with that email address - * - * - * auth0.getUsersByEmail(email, function (err, users) { - * console.log(users); - * }); - * @param {string} [email] Email address of user(s) to find - * @param {object} [options] Additional options to pass to the endpoint - * @param {string} [options.fields] Comma-separated list of fields to include or exclude in the result - * @param {boolean} [options.include_fields] Whether specified fields are to be included (true) or excluded (false). Defaults to true. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getUsersByEmail', 'users.getByEmail'); + /** + * Blacklist a new token. + * + * @example + * var token = { + * aud: 'aud', + * jti: 'jti' + * }; + * + * management.blacklistToken(token, function (err) { + * if (err) { + * // Handle error. + * } + * + * // Token blacklisted. + * }); + * @param {object} token Token data. + * @param {string} token.aud Audience (your app client ID). + * @param {string} token.jti The JWT ID claim. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + blacklistToken(...args) { + return this.blacklistedTokens.add(...args); + } -/** - * Get a user by its id. - * - * @function getUser - * @memberof module:management.ManagementClient.prototype - * @example - * management.getUser({ id: USER_ID }, function (err, user) { - * console.log(user); - * }); - * @param {object} data The user data object. - * @param {string} data.id The user id. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getUser', 'users.get'); + /** + * Create a new Email Template. + * + * @example + * management.createEmailTemplate(data, function (err) { + * if (err) { + * // Handle error. + * // Email Template created. + * }); + * @param {object} data Email Template data object. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + createEmailTemplate(...args) { + return this.emailTemplates.create(...args); + } -/** - * Delete all users. - * - * @function deleteAllUsers - * @memberof module:management.ManagementClient.prototype - * @example - * management.deleteAllUsers(function (err) { - * if (err) { - * // Handle error. - * } - * - * // Users deleted - * }); - * @param {Function} [cb] Callback function - * @returns {Promise|undefined} - * @deprecated This method will be removed in the next major release. - */ -utils.wrapPropertyMethod(ManagementClient, 'deleteAllUsers', 'users.deleteAll'); + /** + * Get an Auth0 Email Template. + * + * @example + * management.getEmailTemplate({ name: EMAIL_TEMPLATE_NAME }, function (err, emailTemplate) { + * if (err) { + * // Handle error. + * } + * + * console.log(emailTemplate); + * }); + * @param {object} params Email Template parameters. + * @param {string} params.name Template Name + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getEmailTemplate(...args) { + return this.emailTemplates.get(...args); + } -/** - * Delete a user by its id. - * - * @function deleteUser - * @memberof module:management.ManagementClient.prototype - * @example - * management.deleteUser({ id: USER_ID }, function (err) { - * if (err) { - * // Handle error. - * } - * - * // User deleted. - * }); - * @param {object} params The user data object.. - * @param {string} params.id The user id. - * @param {Function} [cb] Callback function - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'deleteUser', 'users.delete'); + /** + * Update an existing Email Template. + * + * @example + * var data = { from: 'new@email.com' }; + * var params = { name: EMAIL_TEMPLATE_NAME }; + * + * management.updateEmailTemplates(params, data, function (err, emailTemplate) { + * if (err) { + * // Handle error. + * } + * + * console.log(emailTemplate.from); // 'new@email.com' + * }); + * @param {object} params Email Template parameters. + * @param {string} params.name Template Name + * @param {object} data Updated Email Template data. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + updateEmailTemplate(...args) { + return this.emailTemplates.update(...args); + } -/** - * Create a new user. - * - * @function createUser - * @memberof module:management.ManagementClient.prototype - * @example - * management.createUser(data, function (err) { - * if (err) { - * // Handle error. - * } - * - * // User created. - * }); - * @param {object} data User data. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'createUser', 'users.create'); + /** + * Get the email provider. + * + * @example + * management.getEmailProvider(function (err, provider) { + * console.log(provider.length); + * }); + * @param {Function} [cb] Callback function. + * @param {object} [params] Clients parameters. + * @param {number} [params.fields] A comma separated list of fields to include or exclude (depending on include_fields) from the result, empty to retrieve: name, enabled, settings fields. + * @param {number} [params.include_fields] true if the fields specified are to be excluded from the result, false otherwise (defaults to true) + * @returns {Promise|undefined} + */ + getEmailProvider(...args) { + return this.emailProvider.get(...args); + } -/** - * Update a user by its id. - * - * @function updateUser - * @memberof module:management.ManagementClient.prototype - * @example - * var params = { id: USER_ID }; - * - * management.updateUser(params, data, function (err, user) { - * if (err) { - * // Handle error. - * } - * - * // Updated user. - * console.log(user); - * }); - * @param {object} params The user parameters. - * @param {string} params.id The user id. - * @param {object} data New user data. - * @param {Function} [cb] Callback function - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'updateUser', 'users.update'); + /** + * Configure the email provider. + * + * @example + * management.configureEmailProvider(data, function (err) { + * if (err) { + * // Handle error. + * } + * + * // Email provider configured. + * }); + * @param {object} data The email provider data object. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + configureEmailProvider(...args) { + return this.emailProvider.configure(...args); + } -/** - * Update the user metadata for a user. - * - * @function updateUserMetadata - * @memberof module:management.ManagementClient.prototype - * @example - * var params = { id: USER_ID }; - * var metadata = { - * address: '123th Node.js Street' - * }; - * - * management.updateUserMetadata(params, metadata, function (err, user) { - * if (err) { - * // Handle error. - * } - * - * // Updated user. - * console.log(user); - * }); - * @param {object} params The user data object.. - * @param {string} params.id The user id. - * @param {object} metadata New user metadata. - * @param {Function} [cb] Callback function - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'updateUserMetadata', 'users.updateUserMetadata'); + /** + * Delete email provider. + * + * @example + * management.deleteEmailProvider(function (err) { + * if (err) { + * // Handle error. + * } + * + * // Email provider deleted. + * }); + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + deleteEmailProvider(...args) { + return this.emailProvider.delete(...args); + } -/** - * Update the app metadata for a user. - * - * @function updateAppMetadata - * @memberof module:management.ManagementClient.prototype - * @example - * var params = { id: USER_ID }; - * var metadata = { - * foo: 'bar' - * }; - * - * management.updateAppMetadata(params, metadata, function (err, user) { - * if (err) { - * // Handle error. - * } - * - * // Updated user. - * console.log(user); - * }); - * @param {object} params The user data object.. - * @param {string} params.id The user id. - * @param {object} metadata New app metadata. - * @param {Function} [cb] Callback function - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'updateAppMetadata', 'users.updateAppMetadata'); + /** + * Update the email provider. + * + * @example + * management.updateEmailProvider(params, data, function (err, provider) { + * if (err) { + * // Handle error. + * } + * + * // Updated email provider. + * console.log(provider); + * }); + * @param {object} params Email provider parameters. + * @param {object} data Updated email provider data. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + updateEmailProvider(...args) { + return this.emailProvider.update(...args); + } -/** - * Delete a multifactor provider for a user. - * - * @function deleteUserMultifactor - * @memberof module:management.ManagementClient.prototype - * @example - * var params = { id: USER_ID, provider: MULTIFACTOR_PROVIDER }; - * - * management.deleteUserMultifactor(params, function (err, user) { - * if (err) { - * // Handle error. - * } - * - * // Users accounts unlinked. - * }); - * @param {object} params Data object. - * @param {string} params.id The user id. - * @param {string} params.provider Multifactor provider. - * @param {Function} [cb] Callback function - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod( - ManagementClient, - 'deleteUserMultifactor', - 'users.deleteMultifactorProvider' -); + /** + * Get a the active users count. + * + * @example + * management.getActiveUsersCount(function (err, usersCount) { + * if (err) { + * // Handle error. + * } + * + * console.log(usersCount); + * }); + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getActiveUsersCount(...args) { + return this.stats.getActiveUsersCount(...args); + } -/** - * Delete a multifactor provider for a user. - * - * @function deleteUserMultifcator - * @memberof module:management.ManagementClient.prototype - * @example - * var params = { id: USER_ID, provider: MULTIFACTOR_PROVIDER }; - * - * management.deleteUserMultifcator(params, function (err, user) { - * if (err) { - * // Handle error. - * } - * - * // Users accounts unlinked. - * }); - * @param {object} params Data object. - * @param {string} params.id The user id. - * @param {string} params.provider Multifactor provider. - * @param {Function} [cb] Callback function - * @returns {Promise|undefined} - * @deprecated The function name has a typo. - * We're shipping this so it doesn't break compatibility. - * Use {@link deleteUserMultifactor} instead. - */ -utils.wrapPropertyMethod( - ManagementClient, - 'deleteUserMultifcator', - 'users.deleteMultifactorProvider' -); + /** + * Get the daily stats. + * + * @example + * var params = { + * from: '{YYYYMMDD}', // First day included in the stats. + * to: '{YYYYMMDD}' // Last day included in the stats. + * }; + * + * management.getDaily(params, function (err, stats) { + * if (err) { + * // Handle error. + * } + * + * console.log(stats); + * }); + * @param {object} params Stats parameters. + * @param {string} params.from The first day in YYYYMMDD format. + * @param {string} params.to The last day in YYYYMMDD format. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getDailyStats(...args) { + return this.stats.getDaily(...args); + } -/** - * Unlink the given accounts. - * - * @function unlinkUsers - * @memberof module:management.ManagementClient.prototype - * @example - * var params = { id: USER_ID, provider: 'auht0', user_id: OTHER_USER_ID }; - * - * management.unlinkUsers(params, function (err, user) { - * if (err) { - * // Handle error. - * } - * - * // Users accounts unlinked. - * }); - * @param {object} params Linked users data. - * @param {string} params.id Primary user ID. - * @param {string} params.provider Identity provider in use. - * @param {string} params.user_id Secondary user ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'unlinkUsers', 'users.unlink'); + /** + * Get the tenant settings.. + * + * @example + * management.getSettings(function (err, settings) { + * if (err) { + * // Handle error. + * } + * + * console.log(settings); + * }); + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getTenantSettings(...args) { + return this.tenant.getSettings(...args); + } -/** - * Link the user with another account. - * - * @function linkUsers - * @memberof module:management.ManagementClient.prototype - * @example - * var userId = 'USER_ID'; - * var params = { - * user_id: 'OTHER_USER_ID', - * connection_id: 'CONNECTION_ID' - * }; - * - * management.linkUsers(userId, params, function (err, user) { - * if (err) { - * // Handle error. - * } - * - * // Users linked. - * }); - * @param {string} userId ID of the primary user. - * @param {object} params Secondary user data. - * @param {string} params.user_id ID of the user to be linked. - * @param {string} params.connection_id ID of the connection to be used. - * @param {string} params.provider Identity provider of the secondary user account being linked. - * @param {string} params.link_with JWT for the secondary account being linked. If sending this parameter, provider, user_id, and connection_id must not be sent. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'linkUsers', 'users.link'); + /** + * Update the tenant settings. + * + * @example + * management.updateTenantSettings(data, function (err) { + * if (err) { + * // Handle error. + * } + * }); + * @param {object} data The new tenant settings. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + updateTenantSettings(...args) { + return this.tenant.updateSettings(...args); + } -/** - * Get user's log events. - * - * @function getUserLogs - * @memberof module:management.ManagementClient.prototype - * @example - * var params = { id: USER_ID, page: 0, per_page: 50, sort: 'date:-1', include_totals: true }; - * - * management.getUserLogs(params, function (err, logs) { - * if (err) { - * // Handle error. - * } - * - * console.log(logs); - * }); - * @param {object} params Get logs data. - * @param {string} params.id User id. - * @param {number} params.per_page Number of results per page. - * @param {number} params.page Page number, zero indexed. - * @param {string} params.sort The field to use for sorting. Use field:order where order is 1 for ascending and -1 for descending. For example date:-1. - * @param {boolean} params.include_totals true if a query summary must be included in the result, false otherwise. Default false; - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getUserLogs', 'users.logs'); + /** + * Get a job by its ID. + * + * @example + * var params = { + * id: '{JOB_ID}' + * }; + * + * management.getJob(params, function (err, job) { + * if (err) { + * // Handle error. + * } + * + * // Retrieved job. + * console.log(job); + * }); + * @param {object} params Job parameters. + * @param {string} params.id Job ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getJob(...args) { + return this.jobs.get(...args); + } -/** - * Get user's roles - * - * @function getUserRoles - * @memberof module:management.ManagementClient.prototype - * @example - * var params = { id: USER_ID, page: 0, per_page: 50, sort: 'date:-1', include_totals: true }; - * - * management.getUserRoles(params, function (err, logs) { - * if (err) { - * // Handle error. - * } - * - * console.log(logs); - * }); - * @param {object} params Get roles data. - * @param {string} params.id User id. - * @param {number} params.per_page Number of results per page. - * @param {number} params.page Page number, zero indexed. - * @param {string} params.sort The field to use for sorting. Use field:order where order is 1 for ascending and -1 for descending. For example date:-1. - * @param {boolean} params.include_totals true if a query summary must be included in the result, false otherwise. Default false; - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getUserRoles', 'users.getRoles'); - -/** - * Assign roles to a user - * - * @function assignRolestoUser - * @memberof module:management.ManagementClient.prototype - * @example - * var parms = { id : 'USER_ID'}; - * var data = { "roles" :["role1"]}; - * - * management.assignRolestoUser(params, data, function (err) { - * if (err) { - * // Handle error. - * } - * - * // User assigned roles. - * }); - * @param {object} params params object - * @param {string} params.id user_id - * @param {object} data data object containing list of role IDs - * @param {string} data.roles Array of role IDs - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'assignRolestoUser', 'users.assignRoles'); - -/** - * Assign users to a role - * - * @function assignUsersToRole - * @memberof module:management.ManagementClient.prototype - * @example - * var params = { id :'ROLE_ID'}; - * var data = { "users" : ["userId1","userId2"]}; - * - * management.roles.assignUsers(params, data, function (err, user) { - * if (err) { - * // Handle error. - * } - * - * // permissions added. - * }); - * @param {string} params.id ID of the Role. - * @param {object} data permissions data - * @param {string} data.permissions Array of permissions - * @param {string} data.permissions.permission_name Name of a permission - * @param {string} data.permissions.resource_server_identifier Identifier for a resource - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'assignUsersToRole', 'roles.assignUsers'); - -/** - * Remove roles from a user - * - * @function removeRolesFromUser - * @memberof module:management.ManagementClient.prototype - * @example - * var parms = { id : 'USER_ID'}; - * var data = { "roles" :["role1"]}; - * - * management.removeRolesFromUser(params, data, function (err) { - * if (err) { - * // Handle error. - * } - * - * // User assigned roles. - * }); - * @param {object} params params object - * @param {string} params.id user_id - * @param {string} data data object containing list of role IDs - * @param {string} data.roles Array of role IDs - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'removeRolesFromUser', 'users.removeRoles'); - -/** - * Get user's permissions - * - * @function getUserPermissions - * @memberof module:management.ManagementClient.prototype - * @example - * var params = { id: USER_ID, page: 0, per_page: 50, sort: 'date:-1', include_totals: true }; - * - * management.getUserPermissions(params, function (err, logs) { - * if (err) { - * // Handle error. - * } - * - * console.log(logs); - * }); - * @param {object} params Get permissions data. - * @param {string} params.id User id. - * @param {number} params.per_page Number of results per page. - * @param {number} params.page Page number, zero indexed. - * @param {string} params.sort The field to use for sorting. Use field:order where order is 1 for ascending and -1 for descending. For example date:-1. - * @param {boolean} params.include_totals true if a query summary must be included in the result, false otherwise. Default false; - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getUserPermissions', 'users.getPermissions'); - -/** - * Assign permissions to a user - * - * @function assignPermissionsToUser - * @memberof module:management.ManagementClient.prototype - * @example - * var parms = { id : 'USER_ID'}; - * var data = { "permissions" : [{"permission_name" :"do:something" ,"resource_server_identifier" :"test123" }]}; - * - * management.assignPermissionsToUser(params, data, function (err) { - * if (err) { - * // Handle error. - * } - * - * // User assigned permissions. - * }); - * @param {object} params params object - * @param {string} params.id user_id - * @param {string} data data object containing list of permissions - * @param {string} data.permissions Array of permission IDs - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'assignPermissionsToUser', 'users.assignPermissions'); - -/** - * Remove permissions from a user - * - * @function removePermissionsFromUser - * @memberof module:management.ManagementClient.prototype - * @example - * var parms = { id : 'USER_ID'}; - * var data = { "permissions" : [{"permission_name" :"do:something" ,"resource_server_identifier" :"test123" }]}; - * - * management.removePermissionsFromUser(params, data, function (err) { - * if (err) { - * // Handle error. - * } - * - * // User assigned permissions. - * }); - * @param {object} params params object - * @param {string} params.id user_id - * @param {string} data data object containing list of permission IDs - * @param {string} data.permissions Array of permission IDs - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'removePermissionsFromUser', 'users.removePermissions'); - -/** - * Get a list of a user's Guardian enrollments. - * - * @function getGuardianEnrollments - * @memberof module:management.ManagementClient.prototype - * @example - * management.getGuardianEnrollments({ id: USER_ID }, function (err, enrollments) { - * console.log(enrollments); - * }); - * @param {object} data The user data object. - * @param {string} data.id The user id. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod( - ManagementClient, - 'getGuardianEnrollments', - 'users.getGuardianEnrollments' -); - -/** - * Generate new Guardian recovery code. - * - * @function regenerateRecoveryCode - * @memberof module:management.ManagementClient.prototype - * @example - * management.regenerateRecoveryCode({ id: USER_ID }, function (err, newRecoveryCode) { - * console.log(newRecoveryCode); - * }); - * @param {object} data The user data object. - * @param {string} data.id The user id. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod( - ManagementClient, - 'regenerateRecoveryCode', - 'users.regenerateRecoveryCode' -); - -/** - * Invalidate all remembered browsers for MFA. - * - * @function invalidateRememberBrowser - * @memberof module:management.ManagementClient.prototype - * @example - * management.invalidateRememberBrowser({ id: USER_ID }, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Invalidated all remembered browsers. - * }); - * @param {object} data The user data object. - * @param {string} data.id The user id. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod( - ManagementClient, - 'invalidateRememberBrowser', - 'users.invalidateRememberBrowser' -); - -/** - * Get user blocks by its id. - * - * @function getUserBlocks - * @memberof module:management.ManagementClient.prototype - * @example - * management.getUserBlocks({ id: USER_ID }, function (err, blocks) { - * if (err) { - * // Handle error. - * } - * - * console.log(blocks); - * }); - * @param {object} params The user data object.. - * @param {string} params.id The user id. - * @param {Function} [cb] Callback function - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getUserBlocks', 'userBlocks.get'); - -/** - * Unblock an user by its id. - * - * @function unblockUser - * @memberof module:management.ManagementClient.prototype - * @example - * management.unblockUser({ id: USER_ID }, function (err) { - * if (err) { - * // Handle error. - * } - * - * // User unblocked. - * }); - * @param {object} params The user data object.. - * @param {string} params.id The user id. - * @param {Function} [cb] Callback function - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'unblockUser', 'userBlocks.delete'); - -/** - * Get user blocks by its identifier. - * - * @function getUserBlocksByIdentifier - * @memberof module:management.ManagementClient.prototype - * @example - * management.getUserBlocksByIdentifier({ identifier: USER_ID }, function (err, blocks) { - * if (err) { - * // Handle error. - * } - * - * console.log(blocks); - * }); - * @param {object} params The user data object.. - * @param {string} params.identifier The user identifier, any of: username, phone_number, email. - * @param {Function} [cb] Callback function - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod( - ManagementClient, - 'getUserBlocksByIdentifier', - 'userBlocks.getByIdentifier' -); - -/** - * Unblock an user by its id. - * - * @function unblockUser - * @memberof module:management.ManagementClient.prototype - * @example - * management.unblockUserByIdentifier({ identifier: USER_ID }, function (err) { - * if (err) { - * // Handle error. - * } - * - * // User unblocked. - * }); - * @param {object} params The user data object.. - * @param {string} params.identifier The user identifier, any of: username, phone_number, email. - * @param {Function} [cb] Callback function - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod( - ManagementClient, - 'unblockUserByIdentifier', - 'userBlocks.deleteByIdentifier' -); - -/** - * Get a single Guardian enrollment. - * - * @function getGuardianEnrollment - * @memberof module:management.ManagementClient.prototype - * @example - * management.getGuardianEnrollment({ id: ENROLLMENT_ID }, function (err, enrollment) { - * console.log(enrollment); - * }); - * @param {object} data The Guardian enrollment data object. - * @param {string} data.id The Guardian enrollment id. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod( - ManagementClient, - 'getGuardianEnrollment', - 'guardian.getGuardianEnrollment' -); - -/** - * Delete a user's Guardian enrollment. - * - * @function deleteGuardianEnrollment - * @memberof module:management.ManagementClient.prototype - * @example - * management.deleteGuardianEnrollment({ id: ENROLLMENT_ID }, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Email provider deleted. - * }); - * @param {object} data The Guardian enrollment data object. - * @param {string} data.id The Guardian enrollment id. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod( - ManagementClient, - 'deleteGuardianEnrollment', - 'guardian.deleteGuardianEnrollment' -); - -/** - * Get all blacklisted tokens. - * - * @function getBlacklistedTokens - * @memberof module:management.ManagementClient.prototype - * @example - * management.getBlacklistedTokens(function (err, tokens) { - * console.log(tokens.length); - * }); - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getBlacklistedTokens', 'blacklistedTokens.getAll'); - -/** - * Blacklist a new token. - * - * @function blacklistToken - * @memberof module:management.ManagementClient.prototype - * @example - * var token = { - * aud: 'aud', - * jti: 'jti' - * }; - * - * management.blacklistToken(token, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Token blacklisted. - * }); - * @param {object} token Token data. - * @param {string} token.aud Audience (your app client ID). - * @param {string} token.jti The JWT ID claim. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'blacklistToken', 'blacklistedTokens.add'); - -/** - * Create a new Email Template. - * - * @function createEmailTemplate - * @memberof module:management.ManagementClient.prototype - * @example - * management.createEmailTemplate(data, function (err) { - * if (err) { - * // Handle error. - * // Email Template created. - * }); - * @param {object} data Email Template data object. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'createEmailTemplate', 'emailTemplates.create'); - -/** - * Get an Auth0 Email Template. - * - * @function getEmailTemplate - * @memberof module:management.ManagementClient.prototype - * @example - * management.getEmailTemplate({ name: EMAIL_TEMPLATE_NAME }, function (err, emailTemplate) { - * if (err) { - * // Handle error. - * } - * - * console.log(emailTemplate); - * }); - * @param {object} params Email Template parameters. - * @param {string} params.name Template Name - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getEmailTemplate', 'emailTemplates.get'); - -/** - * Update an existing Email Template. - * - * @function updateEmailTemplates - * @memberof module:management.ManagementClient.prototype - * @example - * var data = { from: 'new@email.com' }; - * var params = { name: EMAIL_TEMPLATE_NAME }; - * - * management.updateEmailTemplates(params, data, function (err, emailTemplate) { - * if (err) { - * // Handle error. - * } - * - * console.log(emailTemplate.from); // 'new@email.com' - * }); - * @param {object} params Email Template parameters. - * @param {string} params.name Template Name - * @param {object} data Updated Email Template data. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'updateEmailTemplate', 'emailTemplates.update'); - -/** - * Get the email provider. - * - * @function getEmailProvider - * @memberof module:management.ManagementClient.prototype - * @example - * management.getEmailProvider(function (err, provider) { - * console.log(provider.length); - * }); - * @param {Function} [cb] Callback function. - * @param {object} [params] Clients parameters. - * @param {number} [params.fields] A comma separated list of fields to include or exclude (depending on include_fields) from the result, empty to retrieve: name, enabled, settings fields. - * @param {number} [params.include_fields] true if the fields specified are to be excluded from the result, false otherwise (defaults to true) - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getEmailProvider', 'emailProvider.get'); - -/** - * Configure the email provider. - * - * @function configureEmailProvider - * @memberof module:management.ManagementClient.prototype - * @example - * management.configureEmailProvider(data, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Email provider configured. - * }); - * @param {object} data The email provider data object. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'configureEmailProvider', 'emailProvider.configure'); - -/** - * Delete email provider. - * - * @function deleteEmailProvider - * @memberof module:management.ManagementClient.prototype - * @example - * management.deleteEmailProvider(function (err) { - * if (err) { - * // Handle error. - * } - * - * // Email provider deleted. - * }); - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'deleteEmailProvider', 'emailProvider.delete'); - -/** - * Update the email provider. - * - * @function updateEmailProvider - * @memberof module:management.ManagementClient.prototype - * @example - * management.updateEmailProvider(params, data, function (err, provider) { - * if (err) { - * // Handle error. - * } - * - * // Updated email provider. - * console.log(provider); - * }); - * @param {object} params Email provider parameters. - * @param {object} data Updated email provider data. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'updateEmailProvider', 'emailProvider.update'); - -/** - * Get a the active users count. - * - * @function getActiveUsersCount - * @memberof module:management.ManagementClient.prototype - * @example - * management.getActiveUsersCount(function (err, usersCount) { - * if (err) { - * // Handle error. - * } - * - * console.log(usersCount); - * }); - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getActiveUsersCount', 'stats.getActiveUsersCount'); - -/** - * Get the daily stats. - * - * @function getDailyStats - * @memberof module:management.ManagementClient.prototype - * @example - * var params = { - * from: '{YYYYMMDD}', // First day included in the stats. - * to: '{YYYYMMDD}' // Last day included in the stats. - * }; - * - * management.getDaily(params, function (err, stats) { - * if (err) { - * // Handle error. - * } - * - * console.log(stats); - * }); - * @param {object} params Stats parameters. - * @param {string} params.from The first day in YYYYMMDD format. - * @param {string} params.to The last day in YYYYMMDD format. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getDailyStats', 'stats.getDaily'); - -/** - * Get the tenant settings.. - * - * @function getTenantSettings - * @memberof module:management.ManagementClient.prototype - * @example - * management.getSettings(function (err, settings) { - * if (err) { - * // Handle error. - * } - * - * console.log(settings); - * }); - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getTenantSettings', 'tenant.getSettings'); - -/** - * Update the tenant settings. - * - * @function updateTenantSettings - * @memberof module:management.ManagementClient.prototype - * @example - * management.updateTenantSettings(data, function (err) { - * if (err) { - * // Handle error. - * } - * }); - * @param {object} data The new tenant settings. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'updateTenantSettings', 'tenant.updateSettings'); - -/** - * Get a job by its ID. - * - * @function getJob - * @memberof module:management.ManagementClient.prototype - * @example - * var params = { - * id: '{JOB_ID}' - * }; - * - * management.getJob(params, function (err, job) { - * if (err) { - * // Handle error. - * } - * - * // Retrieved job. - * console.log(job); - * }); - * @param {object} params Job parameters. - * @param {string} params.id Job ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getJob', 'jobs.get'); - -/** - * Given a path to a file and a connection id, create a new job that imports the - * users contained in the file or JSON string and associate them with the given - * connection. - * - * @function importUsers - * @memberof module:management.ManagementClient.prototype - * @example - * var params = { - * connection_id: '{CONNECTION_ID}', - * users: '{PATH_TO_USERS_FILE}' // or users_json: '{USERS_JSON_STRING}' - * }; - * - * management.importUsers(params, function (err) { - * if (err) { - * // Handle error. - * } - * }); - * @param {object} data Users import data. - * @param {string} data.connection_id connection_id of the connection to which users will be imported. - * @param {string} [data.users] Path to the users data file. Either users or users_json is mandatory. - * @param {string} [data.users_json] JSON data for the users. - * @param {boolean} [data.upsert] Whether to update users if they already exist (true) or to ignore them (false). - * @param {boolean} [data.send_completion_email] Whether to send a completion email to all tenant owners when the job is finished (true) or not (false). - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'importUsers', 'jobs.importUsers'); - -/** - * Given a path to a file and a connection id, create a new job that imports the - * users contained in the file or JSON string and associate them with the given - * connection. - * - * @function importUsersJob - * @memberof module:management.ManagementClient.prototype - * @example - * var params = { - * connection_id: '{CONNECTION_ID}', - * users: '{PATH_TO_USERS_FILE}' // or users_json: '{USERS_JSON_STRING}' - * }; - * - * management.importUsersJob(params, function (err) { - * if (err) { - * // Handle error. - * } - * }); - * @param {object} data Users import data. - * @param {string} data.connection_id connection_id of the connection to which users will be imported. - * @param {string} [data.users] Path to the users data file. Either users or users_json is mandatory. - * @param {string} [data.users_json] JSON data for the users. - * @param {boolean} [data.upsert] Whether to update users if they already exist (true) or to ignore them (false). - * @param {boolean} [data.send_completion_email] Whether to send a completion email to all tenant owners when the job is finished (true) or not (false). - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'importUsersJob', 'jobs.importUsersJob'); - -/** - * Export all users to a file using a long running job. - * - * @function exportUsers - * @memberof module:management.ManagementClient.prototype - * @example - * var data = { - * connection_id: 'con_0000000000000001', - * format: 'csv', - * limit: 5, - * fields: [ - * { - * "name": "user_id" - * }, - * { - * "name": "name" - * }, - * { - * "name": "email" - * }, - * { - * "name": "identities[0].connection", - * "export_as": "provider" - * }, - * { - * "name": "user_metadata.some_field" - * } - * ] - * } - * - * management.exportUsers(data, function (err, results) { - * if (err) { - * // Handle error. - * } - * - * // Retrieved job. - * console.log(results); - * }); - * @param {object} data Users export data. - * @param {string} [data.connection_id] The connection id of the connection from which users will be exported - * @param {string} [data.format] The format of the file. Valid values are: "json" and "csv". - * @param {number} [data.limit] Limit the number of records. - * @param {object[]} [data.fields] A list of fields to be included in the CSV. If omitted, a set of predefined fields will be exported. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'exportUsers', 'jobs.exportUsers'); - -/** - * Given a job ID, retrieve the failed/errored items - * - * @function errors - * @memberof module:management.JobsManager.prototype - * @example - * var params = { - * id: '{JOB_ID}' - * }; - * - * management.jobs.errors(params, function (err, job) { - * if (err) { - * // Handle error. - * } - * - * // Retrieved job. - * console.log(job); - * }); - * @param {object} params Job parameters. - * @param {string} params.id Job ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getJobErrors', 'jobs.errors'); - -/** - * Send a verification email to a user. - * - * @function sendEmailVerification - * @memberof module:management.ManagementClient.prototype - * @example - * var params = { - * user_id: '{USER_ID}' - * }; - * - * management.sendEmailVerification(params, function (err) { - * if (err) { - * // Handle error. - * } - * }); - * @param {object} data User data object. - * @param {string} data.user_id ID of the user to be verified. - * @param {string} [data.organization_id] Organization ID - * @param {string} [data.client_id] client_id of the client (application). If no value provided, the global Client ID will be used. - * @param {object} [data.identity] Used to verify secondary, federated, and passwordless-email identities. - * @param {string} data.identity.user_id user_id of the identity. - * @param {string} data.identity.provider provider of the identity. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'sendEmailVerification', 'jobs.verifyEmail'); - -/** - * Create a new password change ticket. - * - * @function createPasswordChangeTicket - * @memberof module:management.ManagementClient.prototype - * @example - * - * var params = { - * result_url: '{REDIRECT_URL}', // Redirect after using the ticket. - * user_id: '{USER_ID}' - * }; - * - * // or - * - * var params = { - * result_url: '{REDIRECT_URL}', // Redirect after using the ticket. - * email: '{USER_EMAIL}', - * connection_id: '{CONNECTION}' // eg. con_00000000001 - * }; - * - * auth0.createPasswordChangeTicket(params, function (err) { - * if (err) { - * // Handle error. - * } - * }); - * @param {Function} [cb] Callback function. - * @returns {Promise} - */ -utils.wrapPropertyMethod(ManagementClient, 'createPasswordChangeTicket', 'tickets.changePassword'); + /** + * Given a path to a file and a connection id, create a new job that imports the + * users contained in the file or JSON string and associate them with the given + * connection. + * + * @example + * var params = { + * connection_id: '{CONNECTION_ID}', + * users: '{PATH_TO_USERS_FILE}' // or users_json: '{USERS_JSON_STRING}' + * }; + * + * management.importUsers(params, function (err) { + * if (err) { + * // Handle error. + * } + * }); + * @param {object} data Users import data. + * @param {string} data.connection_id connection_id of the connection to which users will be imported. + * @param {string} [data.users] Path to the users data file. Either users or users_json is mandatory. + * @param {string} [data.users_json] JSON data for the users. + * @param {boolean} [data.upsert] Whether to update users if they already exist (true) or to ignore them (false). + * @param {boolean} [data.send_completion_email] Whether to send a completion email to all tenant owners when the job is finished (true) or not (false). + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + importUsers(...args) { + return this.jobs.importUsers(...args); + } -/** - * Create an email verification ticket. - * - * @function createEmailVerificationTicket - * @memberof module:management.ManagementClient.prototype - * @example - * var data = { - * user_id: '{USER_ID}', - * result_url: '{REDIRECT_URL}' // Optional redirect after the ticket is used. - * }; - * - * auth0.createEmailVerificationTicket(data, function (err) { - * if (err) { - * // Handle error. - * } - * }); - * @param {Function} [cb] Callback function. - * @returns {Promise} - */ -utils.wrapPropertyMethod(ManagementClient, 'createEmailVerificationTicket', 'tickets.verifyEmail'); + /** + * Given a path to a file and a connection id, create a new job that imports the + * users contained in the file or JSON string and associate them with the given + * connection. + * + * @example + * var params = { + * connection_id: '{CONNECTION_ID}', + * users: '{PATH_TO_USERS_FILE}' // or users_json: '{USERS_JSON_STRING}' + * }; + * + * management.importUsersJob(params, function (err) { + * if (err) { + * // Handle error. + * } + * }); + * @param {object} data Users import data. + * @param {string} data.connection_id connection_id of the connection to which users will be imported. + * @param {string} [data.users] Path to the users data file. Either users or users_json is mandatory. + * @param {string} [data.users_json] JSON data for the users. + * @param {boolean} [data.upsert] Whether to update users if they already exist (true) or to ignore them (false). + * @param {boolean} [data.send_completion_email] Whether to send a completion email to all tenant owners when the job is finished (true) or not (false). + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + importUsersJob(...args) { + return this.jobs.importUsersJob(...args); + } -/** - * Get an Auth0 log. - * - * @function getLog - * @memberof module:management.ManagementClient.prototype - * @example - * management.getLog({ id: EVENT_ID }, function (err, log) { - * if (err) { - * // Handle error. - * } - * - * console.log(log); - * }); - * @param {object} params Log parameters. - * @param {string} params.id Event ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getLog', 'logs.get'); + /** + * Export all users to a file using a long running job. + * + * @example + * var data = { + * connection_id: 'con_0000000000000001', + * format: 'csv', + * limit: 5, + * fields: [ + * { + * "name": "user_id" + * }, + * { + * "name": "name" + * }, + * { + * "name": "email" + * }, + * { + * "name": "identities[0].connection", + * "export_as": "provider" + * }, + * { + * "name": "user_metadata.some_field" + * } + * ] + * } + * + * management.exportUsers(data, function (err, results) { + * if (err) { + * // Handle error. + * } + * + * // Retrieved job. + * console.log(results); + * }); + * @param {object} data Users export data. + * @param {string} [data.connection_id] The connection id of the connection from which users will be exported + * @param {string} [data.format] The format of the file. Valid values are: "json" and "csv". + * @param {number} [data.limit] Limit the number of records. + * @param {object[]} [data.fields] A list of fields to be included in the CSV. If omitted, a set of predefined fields will be exported. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + exportUsers(...args) { + return this.jobs.exportUsers(...args); + } -/** - * Get all logs. - * - * @function getLogs - * @memberof module:management.ManagementClient.prototype - * @example - * This method takes an optional object as first argument that may be used to - * specify pagination settings and the search query. If pagination options are - * not present, the first page of a limited number of results will be returned. - * - * - * // Pagination settings. - * var params = { - * per_page: 10, - * page: 2 - * }; - * - * management.getLogs(params, function (err, logs) { - * console.log(logs.length); - * }); - * @param {object} [params] Logs params. - * @param {string} [params.q] Search Criteria using Query String Syntax - * @param {number} [params.page] Page number. Zero based - * @param {number} [params.per_page] The amount of entries per page - * @param {string} [params.sort] The field to use for sorting. - * @param {string} [params.fields] A comma separated list of fields to include or exclude - * @param {boolean} [params.include_fields] true if the fields specified are to be included in the result, false otherwise. - * @param {boolean} [params.include_totals] true if a query summary must be included in the result, false otherwise. Default false - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getLogs', 'logs.getAll'); + /** + * Given a job ID, retrieve the failed/errored items + * + * @example + * var params = { + * id: '{JOB_ID}' + * }; + * + * management.jobs.errors(params, function (err, job) { + * if (err) { + * // Handle error. + * } + * + * // Retrieved job. + * console.log(job); + * }); + * @param {object} params Job parameters. + * @param {string} params.id Job ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getJobErrors(...args) { + return this.jobs.errors(...args); + } -/** - * Get all Log Streams. - * - * @function getLogStreams - * @memberof module:management.ManagementClient.prototype - * - * - * - * management.getLogStreams( function (err, logStreams) { - * console.log(logStreams.length); - * }); - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getLogStreams', 'logStreams.getAll'); + /** + * Send a verification email to a user. + * + * @example + * var params = { + * user_id: '{USER_ID}' + * }; + * + * management.sendEmailVerification(params, function (err) { + * if (err) { + * // Handle error. + * } + * }); + * @param {object} data User data object. + * @param {string} data.user_id ID of the user to be verified. + * @param {string} [data.organization_id] Organization ID + * @param {string} [data.client_id] client_id of the client (application). If no value provided, the global Client ID will be used. + * @param {object} [data.identity] Used to verify secondary, federated, and passwordless-email identities. + * @param {string} data.identity.user_id user_id of the identity. + * @param {string} data.identity.provider provider of the identity. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + sendEmailVerification(...args) { + return this.jobs.verifyEmail(...args); + } -/** - * Create a new Log Stream. - * - * @function createLogStream - * @memberof module:management.ManagementClient.prototype - * @example - * management.createLogStream(data, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Log Stream created. - * }); - * @param {object} data Log Stream data. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'createLogStream', 'logStreams.create'); + /** + * Create a new password change ticket. + * + * @example + * + * var params = { + * result_url: '{REDIRECT_URL}', // Redirect after using the ticket. + * user_id: '{USER_ID}' + * }; + * + * // or + * + * var params = { + * result_url: '{REDIRECT_URL}', // Redirect after using the ticket. + * email: '{USER_EMAIL}', + * connection_id: '{CONNECTION}' // eg. con_00000000001 + * }; + * + * auth0.createPasswordChangeTicket(params, function (err) { + * if (err) { + * // Handle error. + * } + * }); + * @param {Function} [cb] Callback function. + * @returns {Promise} + */ + createPasswordChangeTicket(...args) { + return this.tickets.changePassword(...args); + } -/** - * Get an Auth0 Log Stream. - * - * @function getLogStream - * @memberof module:management.ManagementClient.prototype - * @example - * management.getLogStream({ id: LOG_STREAM_ID }, function (err, logStream) { - * if (err) { - * // Handle error. - * } - * - * console.log(logStream); - * }); - * @param {object} params Log Stream parameters. - * @param {string} params.id Log Stream ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getLogStream', 'logStreams.get'); + /** + * Create an email verification ticket. + * + * @example + * var data = { + * user_id: '{USER_ID}', + * result_url: '{REDIRECT_URL}' // Optional redirect after the ticket is used. + * }; + * + * auth0.createEmailVerificationTicket(data, function (err) { + * if (err) { + * // Handle error. + * } + * }); + * @param {Function} [cb] Callback function. + * @returns {Promise} + */ + createEmailVerificationTicket(...args) { + return this.tickets.verifyEmail(...args); + } -/** - * Delete an existing Log Stream. - * - * @function deleteLogStream - * @memberof module:management.ManagementClient.prototype - * @example - * management.deleteLogStream({ id: LOG_STREAM_ID }, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Log Stream deleted. - * }); - * @param {object} params Log Stream parameters. - * @param {string} params.id Log Stream ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'deleteLogStream', 'logStreams.delete'); + /** + * Get an Auth0 log. + * + * @example + * management.getLog({ id: EVENT_ID }, function (err, log) { + * if (err) { + * // Handle error. + * } + * + * console.log(log); + * }); + * @param {object} params Log parameters. + * @param {string} params.id Event ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getLog(...args) { + return this.logs.get(...args); + } -/** - * Update an existing Log Stream. - * - * @function updateLogStream - * @memberof module:management.ManagementClient.prototype - * @example - * var params = { id: LOG_STREAM_ID }; - * var data = { name: 'my-log-stream'}; - * management.updateLogStream(params, data, function (err, logStream) { - * if (err) { - * // Handle error. - * } - * - * console.log(logStream.name); // 'my-log-stream'. - * }); - * @param {object} params Rule parameters. - * @param {string} params.id Rule ID. - * @param {object} data Updated rule data. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'updateLogStream', 'logStreams.update'); + /** + * Get all logs. + * + * @example + * This method takes an optional object as first argument that may be used to + * specify pagination settings and the search query. If pagination options are + * not present, the first page of a limited number of results will be returned. + * + * + * // Pagination settings. + * var params = { + * per_page: 10, + * page: 2 + * }; + * + * management.getLogs(params, function (err, logs) { + * console.log(logs.length); + * }); + * @param {object} [params] Logs params. + * @param {string} [params.q] Search Criteria using Query String Syntax + * @param {number} [params.page] Page number. Zero based + * @param {number} [params.per_page] The amount of entries per page + * @param {string} [params.sort] The field to use for sorting. + * @param {string} [params.fields] A comma separated list of fields to include or exclude + * @param {boolean} [params.include_fields] true if the fields specified are to be included in the result, false otherwise. + * @param {boolean} [params.include_totals] true if a query summary must be included in the result, false otherwise. Default false + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getLogs(...args) { + return this.logs.getAll(...args); + } -/** - * Create a new resource server. - * - * @function createResourceServer - * @memberof module:management.ManagementClient.prototype - * @example - * management.createResourceServer(data, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Resource Server created. - * }); - * @param {object} data Resource Server data object. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'createResourceServer', 'resourceServers.create'); + /** + * Get all Log Streams. + * + * + * + * management.getLogStreams( function (err, logStreams) { + * console.log(logStreams.length); + * }); + * + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getLogStreams(...args) { + return this.logStreams.getAll(...args); + } -/** - * Get all resource servers. - * - * @function getResourceServers - * @memberof module:management.ManagementClient.prototype - * @example - * This method takes an optional object as first argument that may be used to - * specify pagination settings. If pagination options are not present, - * the first page of a limited number of results will be returned. - * - * - * // Pagination settings. - * var params = { - * per_page: 10, - * page: 0 - * }; - * - * management.getResourceServers(params, function (err, resourceServers) { - * console.log(resourceServers.length); - * }); - * @param {object} [params] Resource Servers parameters. - * @param {number} [params.per_page] Number of results per page. - * @param {number} [params.page] Page number, zero indexed. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getResourceServers', 'resourceServers.getAll'); + /** + * Create a new Log Stream. + * + * @example + * management.createLogStream(data, function (err) { + * if (err) { + * // Handle error. + * } + * + * // Log Stream created. + * }); + * @param {object} data Log Stream data. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + createLogStream(...args) { + return this.logStreams.create(...args); + } -/** - * Get a Resource Server. - * - * @function getResourceServer - * @memberof module:management.ManagementClient.prototype - * @example - * management.getResourceServer({ id: RESOURCE_SERVER_ID }, function (err, resourceServer) { - * if (err) { - * // Handle error. - * } - * - * console.log(resourceServer); - * }); - * @param {object} params Resource Server parameters. - * @param {string} params.id Resource Server ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getResourceServer', 'resourceServers.get'); + /** + * Get an Auth0 Log Stream. + * + * @example + * management.getLogStream({ id: LOG_STREAM_ID }, function (err, logStream) { + * if (err) { + * // Handle error. + * } + * + * console.log(logStream); + * }); + * @param {object} params Log Stream parameters. + * @param {string} params.id Log Stream ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getLogStream(...args) { + return this.logStreams.get(...args); + } -/** - * Delete an existing resource server. - * - * @function deleteResourceServer - * @memberof module:management.ManagementClient.prototype - * @example - * management.deleteResourceServer({ id: RESOURCE_SERVER_ID }, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Resource Server deleted. - * }); - * @param {object} params Resource Server parameters. - * @param {string} params.id Resource Server ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'deleteResourceServer', 'resourceServers.delete'); + /** + * Delete an existing Log Stream. + * + * @example + * management.deleteLogStream({ id: LOG_STREAM_ID }, function (err) { + * if (err) { + * // Handle error. + * } + * + * // Log Stream deleted. + * }); + * @param {object} params Log Stream parameters. + * @param {string} params.id Log Stream ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + deleteLogStream(...args) { + return this.logStreams.delete(...args); + } -/** - * Update an existing resource server. - * - * @function updateResourceServer - * @memberof module:management.ManagementClient.prototype - * @example - * var data = { name: 'newResourceServerName' }; - * var params = { id: RESOURCE_SERVER_ID }; - * - * management.updateResourceServer(params, data, function (err, resourceServer) { - * if (err) { - * // Handle error. - * } - * - * console.log(resourceServer.name); // 'newResourceServerName' - * }); - * @param {object} params Resource Server parameters. - * @param {string} params.id Resource Server ID. - * @param {object} data Updated Resource Server data. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'updateResourceServer', 'resourceServers.update'); + /** + * Update an existing Log Stream. + * + * @example + * var params = { id: LOG_STREAM_ID }; + * var data = { name: 'my-log-stream'}; + * management.updateLogStream(params, data, function (err, logStream) { + * if (err) { + * // Handle error. + * } + * + * console.log(logStream.name); // 'my-log-stream'. + * }); + * @param {object} params Rule parameters. + * @param {string} params.id Rule ID. + * @param {object} data Updated rule data. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + updateLogStream(...args) { + return this.logStreams.update(...args); + } -/** - * Set a new rules config. - * - * @function setRulesConfig - * @memberof module:management.ManagementClient.prototype - * @example - * var params = { key: RULE_CONFIG_KEY }; - * var data = { value: RULES_CONFIG_VALUE }; - * - * management.setRulesConfig(params, data, function (err, rulesConfig) { - * if (err) { - * // Handle error. - * } - * - * // Rules Config set. - * }); - * @param {object} params Rule Config parameters. - * @param {string} params.key Rule Config key. - * @param {object} data Rule Config Data parameters. - * @param {string} data.value Rule Config Data value. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'setRulesConfig', 'rulesConfigs.set'); + /** + * Create a new resource server. + * + * @example + * management.createResourceServer(data, function (err) { + * if (err) { + * // Handle error. + * } + * + * // Resource Server created. + * }); + * @param {object} data Resource Server data object. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + createResourceServer(...args) { + return this.resourceServers.create(...args); + } -/** - * Get rules config. - * - * @function getRulesConfigs - * @memberof module:management.ManagementClient.prototype - * @param {Function} [cb] Callback function. - * @example - * - * management.getRulesConfigs(function (err, rulesConfigs) { - * if (err) { - * // Handle error. - * } - * - * // Get Rules Configs. - * }); - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getRulesConfigs', 'rulesConfigs.getAll'); + /** + * Get all resource servers. + * + * @example + * This method takes an optional object as first argument that may be used to + * specify pagination settings. If pagination options are not present, + * the first page of a limited number of results will be returned. + * + * + * // Pagination settings. + * var params = { + * per_page: 10, + * page: 0 + * }; + * + * management.getResourceServers(params, function (err, resourceServers) { + * console.log(resourceServers.length); + * }); + * @param {object} [params] Resource Servers parameters. + * @param {number} [params.per_page] Number of results per page. + * @param {number} [params.page] Page number, zero indexed. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getResourceServers(...args) { + return this.resourceServers.getAll(...args); + } -/** - * Delete rules config. - * - * @function deleteRulesConfig - * @memberof module:management.ManagementClient.prototype - * @example - * - * management.deleteRulesConfig({ key: RULE_CONFIG_KEY }, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Rules Config deleted. - * }); - * @param {object} params Rule Configs parameters. - * @param {string} params.key Rule Configs key. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'deleteRulesConfig', 'rulesConfigs.delete'); + /** + * Get a Resource Server. + * + * @example + * management.getResourceServer({ id: RESOURCE_SERVER_ID }, function (err, resourceServer) { + * if (err) { + * // Handle error. + * } + * + * console.log(resourceServer); + * }); + * @param {object} params Resource Server parameters. + * @param {string} params.id Resource Server ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getResourceServer(...args) { + return this.resourceServers.get(...args); + } -/** - * Create an Auth0 Custom Domain. - * - * @function createCustomDomain - * @memberof module:management.ManagementClient.prototype - * @example - * management.createCustomDomain(data, function (err) { - * if (err) { - * // Handle error. - * } - * - * // CustomDomain created. - * }); - * @param {object} data The custom domain data object. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'createCustomDomain', 'customDomains.create'); + /** + * Delete an existing resource server. + * + * @example + * management.deleteResourceServer({ id: RESOURCE_SERVER_ID }, function (err) { + * if (err) { + * // Handle error. + * } + * + * // Resource Server deleted. + * }); + * @param {object} params Resource Server parameters. + * @param {string} params.id Resource Server ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + deleteResourceServer(...args) { + return this.resourceServers.delete(...args); + } -/** - * Get all Auth0 CustomDomains. - * - * @function getCustomDomains - * @memberof module:management.ManagementClient.prototype - * @example - * management.getCustomDomains(function (err, customDomains) { - * console.log(customDomains.length); - * }); - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getCustomDomains', 'customDomains.getAll'); + /** + * Update an existing resource server. + * + * @example + * var data = { name: 'newResourceServerName' }; + * var params = { id: RESOURCE_SERVER_ID }; + * + * management.updateResourceServer(params, data, function (err, resourceServer) { + * if (err) { + * // Handle error. + * } + * + * console.log(resourceServer.name); // 'newResourceServerName' + * }); + * @param {object} params Resource Server parameters. + * @param {string} params.id Resource Server ID. + * @param {object} data Updated Resource Server data. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + updateResourceServer(...args) { + return this.resourceServers.update(...args); + } -/** - * Get a Custom Domain. - * - * @function getCustomDomain - * @memberof module:management.ManagementClient.prototype - * @example - * management.getCustomDomain({ id: CUSTOM_DOMAIN_ID }, function (err, customDomain) { - * if (err) { - * // Handle error. - * } - * - * console.log(customDomain); - * }); - * @param {object} params Custom Domain parameters. - * @param {string} params.id Custom Domain ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getCustomDomain', 'customDomains.get'); + /** + * Set a new rules config. + * + * @example + * var params = { key: RULE_CONFIG_KEY }; + * var data = { value: RULES_CONFIG_VALUE }; + * + * management.setRulesConfig(params, data, function (err, rulesConfig) { + * if (err) { + * // Handle error. + * } + * + * // Rules Config set. + * }); + * @param {object} params Rule Config parameters. + * @param {string} params.key Rule Config key. + * @param {object} data Rule Config Data parameters. + * @param {string} data.value Rule Config Data value. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + setRulesConfig(...args) { + return this.rulesConfigs.set(...args); + } -/** - * Verify a Custom Domain. - * - * @function verifyCustomDomain - * @memberof module:management.ManagementClient.prototype - * @example - * management.verifyCustomDomain({ id: CUSTOM_DOMAIN_ID }, function (err, customDomain) { - * if (err) { - * // Handle error. - * } - * - * console.log(customDomain); - * }); - * @param {object} params Custom Domain parameters. - * @param {string} params.id Custom Domain ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'verifyCustomDomain', 'customDomains.verify'); + /** + * Get rules config. + * + * @param {Function} [cb] Callback function. + * @example + * + * management.getRulesConfigs(function (err, rulesConfigs) { + * if (err) { + * // Handle error. + * } + * + * // Get Rules Configs. + * }); + * @returns {Promise|undefined} + */ + getRulesConfigs(...args) { + return this.rulesConfigs.getAll(...args); + } -/** - * Delete a Custom Domain. - * - * @function deleteCustomDomain - * @memberof module:management.ManagementClient.prototype - * @example - * management.deleteCustomDomain({ id: CUSTOM_DOMAIN_ID }, function (err) { - * if (err) { - * // Handle error. - * } - * - * // CustomDomain deleted. - * }); - * @param {object} params Custom Domain parameters. - * @param {string} params.id Custom Domain ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'deleteCustomDomain', 'customDomains.delete'); + /** + * Delete rules config. + * + * @example + * + * management.deleteRulesConfig({ key: RULE_CONFIG_KEY }, function (err) { + * if (err) { + * // Handle error. + * } + * + * // Rules Config deleted. + * }); + * @param {object} params Rule Configs parameters. + * @param {string} params.key Rule Configs key. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + deleteRulesConfig(...args) { + return this.rulesConfigs.delete(...args); + } -/** - * Create a Guardian enrollment ticket. - * - * @function createGuardianEnrollmentTicket - * @memberof module:management.ManagementClient.prototype - * @example - * management.createGuardianEnrollmentTicket(function (err, ticket) { - * console.log(ticket); - * }); - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod( - ManagementClient, - 'createGuardianEnrollmentTicket', - 'guardian.createEnrollmentTicket' -); + /** + * Create an Auth0 Custom Domain. + * + * @example + * management.createCustomDomain(data, function (err) { + * if (err) { + * // Handle error. + * } + * + * // CustomDomain created. + * }); + * @param {object} data The custom domain data object. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + createCustomDomain(...args) { + return this.customDomains.create(...args); + } -/** - * Get a list of Guardian factors and statuses. - * - * @function getGuardianFactors - * @memberof module:management.ManagementClient.prototype - * @example - * management.getGuardianFactors(function (err, factors) { - * console.log(factors.length); - * }); - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getGuardianFactors', 'guardian.getFactors'); + /** + * Get all Auth0 CustomDomains. + * + * @example + * management.getCustomDomains(function (err, customDomains) { + * console.log(customDomains.length); + * }); + * @returns {Promise|undefined} + */ + getCustomDomains(...args) { + return this.customDomains.getAll(...args); + } -/** - * Get the settings of a Guardian factor. - * - * @function getGuardianFactorSettings - * @memberof module:management.ManagementClient.prototype - * @example - * management.getGuardianFactorSettings({ name: 'duo' }, function (err, settings) { - * console.log(settings); - * }); - * @param {object} params Factor parameters. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod( - ManagementClient, - 'getGuardianFactorSettings', - 'guardian.getFactorSettings' -); + /** + * Get a Custom Domain. + * + * @example + * management.getCustomDomain({ id: CUSTOM_DOMAIN_ID }, function (err, customDomain) { + * if (err) { + * // Handle error. + * } + * + * console.log(customDomain); + * }); + * @param {object} params Custom Domain parameters. + * @param {string} params.id Custom Domain ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getCustomDomain(...args) { + return this.customDomains.get(...args); + } -/** - * Get Guardian factor provider configuration - * - * @function getGuardianFactorProvider - * @memberof module:management.ManagementClient.prototype - * @example - * management.getFactorProvider({ name: 'sms', provider: 'twilio'}, function (err, provider) { - * console.log(provider); - * }); - * @param {object} params Factor provider parameters. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod( - ManagementClient, - 'getGuardianFactorProvider', - 'guardian.getFactorProvider' -); + /** + * Verify a Custom Domain. + * + * @example + * management.verifyCustomDomain({ id: CUSTOM_DOMAIN_ID }, function (err, customDomain) { + * if (err) { + * // Handle error. + * } + * + * console.log(customDomain); + * }); + * @param {object} params Custom Domain parameters. + * @param {string} params.id Custom Domain ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + verifyCustomDomain(...args) { + return this.customDomains.verify(...args); + } -/** - * Update Guardian's factor provider - * - * @function updateFactorProvider - * @memberof module:management.ManagementClient.prototype - * @example - * management.updateGuardianFactorProvider({ name: 'sms', provider: 'twilio' }, { - * messaging_service_sid: 'XXXXXXXXXXXXXX', - * auth_token: 'XXXXXXXXXXXXXX', - * sid: 'XXXXXXXXXXXXXX' - * }, function (err, provider) { - * console.log(provider); - * }); - * @param {object} params Factor provider parameters. - * @param {object} data Updated Factor provider data. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod( - ManagementClient, - 'updateGuardianFactorProvider', - 'guardian.updateFactorProvider' -); + /** + * Delete a Custom Domain. + * + * @example + * management.deleteCustomDomain({ id: CUSTOM_DOMAIN_ID }, function (err) { + * if (err) { + * // Handle error. + * } + * + * // CustomDomain deleted. + * }); + * @param {object} params Custom Domain parameters. + * @param {string} params.id Custom Domain ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + deleteCustomDomain(...args) { + return this.customDomains.delete(...args); + } -/** - * Update a Guardian's factor settings - * - * @function updateGuardianFactorSettings - * @memberof module:management.ManagementClient.prototype - * @example - * management.updateGuardianFactorSettings( - * { name: 'webauthn-roaming' }, - * { userVerification: 'discouraged', overrideRelyingParty: false }, - * function (err, settings) { - * console.log(settings); - * }) - * @param {object} params Factor parameters. - * @param {object} data Updated Factor settings data. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod( - ManagementClient, - 'updateGuardianFactorSettings', - 'guardian.updateFactorSettings' -); + /** + * Create a Guardian enrollment ticket. + * + * @example + * management.createGuardianEnrollmentTicket(function (err, ticket) { + * console.log(ticket); + * }); + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + createGuardianEnrollmentTicket(...args) { + return this.guardian.createEnrollmentTicket(...args); + } -/** - * Get Guardian enrollment and verification factor templates - * - * @function getGuardianFactorTemplates - * @memberof module:management.ManagementClient.prototype - * @example - * management.getGuardianFactorTemplates({ name: 'sms' }, function (err, templates) { - * console.log(templates); - * }); - * @param {object} params Factor parameters. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod( - ManagementClient, - 'getGuardianFactorTemplates', - 'guardian.getFactorTemplates' -); + /** + * Get a list of Guardian factors and statuses. + * + * @example + * management.getGuardianFactors(function (err, factors) { + * console.log(factors.length); + * }); + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getGuardianFactors(...args) { + return this.guardian.getFactors(...args); + } -/** - * Update Guardian enrollment and verification factor templates - * - * @function updateGuardianFactorTemplates - * @memberof module:management.ManagementClient.prototype - * @example - * management.updateGuardianFactorTemplates({ name: 'sms' }, { - * enrollment_message: "{{code}} is your verification code for {{tenant.friendly_name}}. Please enter this code to verify your enrollment.", - * verification_message: "{{code}} is your verification code for {{tenant.friendly_name}}" - * }, function (err, templates) { - * console.log(templates); - * }); - * @param {object} params Factor parameters. - * @param {object} data Updated factor templates data. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod( - ManagementClient, - 'updateGuardianFactorTemplates', - 'guardian.updateFactorTemplates' -); + /** + * Get the settings of a Guardian factor. + * + * @example + * management.getGuardianFactorSettings({ name: 'duo' }, function (err, settings) { + * console.log(settings); + * }); + * @param {object} params Factor parameters. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getGuardianFactorSettings(...args) { + return this.guardian.getFactorSettings(...args); + } -/** - * Update Guardian Factor - * - * @function updateGuardianFactor - * @memberof module:management.ManagementClient.prototype - * @example - * management.updateGuardianFactor({ name: 'sms' }, { - * enabled: true - * }, function (err, factor) { - * console.log(factor); - * }); - * @param {object} params Factor parameters. - * @param {object} data Updated factor data. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'updateGuardianFactor', 'guardian.updateFactor'); + /** + * Get Guardian factor provider configuration + * + * @example + * management.getFactorProvider({ name: 'sms', provider: 'twilio'}, function (err, provider) { + * console.log(provider); + * }); + * @param {object} params Factor provider parameters. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getGuardianFactorProvider(...args) { + return this.guardian.getFactorProvider(...args); + } -/** - * Get enabled Guardian policies - * - * @function getGuardianPolicies - * @memberof module:management.ManagementClient.prototype - * @example - * management.getGuardianPolicies(function (err, policies) { - * console.log(policies); - * }); - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getGuardianPolicies', 'guardian.getPolicies'); + /** + * Update Guardian's factor provider + * + * @example + * management.updateGuardianFactorProvider({ name: 'sms', provider: 'twilio' }, { + * messaging_service_sid: 'XXXXXXXXXXXXXX', + * auth_token: 'XXXXXXXXXXXXXX', + * sid: 'XXXXXXXXXXXXXX' + * }, function (err, provider) { + * console.log(provider); + * }); + * @param {object} params Factor provider parameters. + * @param {object} data Updated Factor provider data. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + updateGuardianFactorProvider(...args) { + return this.guardian.updateFactorProvider(...args); + } -/** - * Update enabled Guardian policies - * - * @function updateGuardianPolicies - * @memberof module:management.ManagementClient.prototype - * @example - * management.updateGuardianPolicies({}, [ - * 'all-applications' - * ], function (err, policies) { - * console.log(policies); - * }); - * @param {object} params Parameters. - * @param {string[]} data Policies to enable. Empty array disables all policies. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'updateGuardianPolicies', 'guardian.updatePolicies'); + /** + * Update a Guardian's factor settings + * + * @example + * management.updateGuardianFactorSettings( + * { name: 'webauthn-roaming' }, + * { userVerification: 'discouraged', overrideRelyingParty: false }, + * function (err, settings) { + * console.log(settings); + * }) + * @param {object} params Factor parameters. + * @param {object} data Updated Factor settings data. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + updateGuardianFactorSettings(...args) { + return this.guardian.updateFactorSettings(...args); + } -/** - * Get the Guardian phone factor's selected provider - * - * @function getGuardianPhoneFactorSelectedProvider - * @memberof module:management.ManagementClient.prototype - * @example - * management.getGuardianPhoneFactorSelectedProvider(function (err, selectedProvider) { - * console.log(selectedProvider); - * }); - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod( - ManagementClient, - 'getGuardianPhoneFactorSelectedProvider', - 'guardian.getPhoneFactorSelectedProvider' -); + /** + * Get Guardian enrollment and verification factor templates + * + * @example + * management.getGuardianFactorTemplates({ name: 'sms' }, function (err, templates) { + * console.log(templates); + * }); + * @param {object} params Factor parameters. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getGuardianFactorTemplates(...args) { + return this.guardian.getFactorTemplates(...args); + } -/** - * Update the Guardian phone factor's selected provider - * - * @function updateGuardianPhoneFactorSelectedProvider - * @memberof module:management.ManagementClient.prototype - * @example - * management.updateGuardianPhoneFactorSelectedProvider({}, { - * provider: 'twilio' - * }, function (err, factor) { - * console.log(factor); - * }); - * @param {object} params Parameters. - * @param {object} data Updated selected provider data. - * @param {string} data.provider Name of the selected provider - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod( - ManagementClient, - 'updateGuardianPhoneFactorSelectedProvider', - 'guardian.updatePhoneFactorSelectedProvider' -); + /** + * Update Guardian enrollment and verification factor templates + * + * @example + * management.updateGuardianFactorTemplates({ name: 'sms' }, { + * enrollment_message: "{{code}} is your verification code for {{tenant.friendly_name}}. Please enter this code to verify your enrollment.", + * verification_message: "{{code}} is your verification code for {{tenant.friendly_name}}" + * }, function (err, templates) { + * console.log(templates); + * }); + * @param {object} params Factor parameters. + * @param {object} data Updated factor templates data. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + updateGuardianFactorTemplates(...args) { + return this.guardian.updateFactorTemplates(...args); + } -/** - * Get the Guardian phone factor's message types - * - * @function getGuardianPhoneFactorMessageTypes - * @memberof module:management.ManagementClient.prototype - * @example - * management.getGuardianPhoneFactorMessageTypes(function (err, messageTypes) { - * console.log(messageTypes); - * }); - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod( - ManagementClient, - 'getGuardianPhoneFactorMessageTypes', - 'guardian.getPhoneFactorMessageTypes' -); + /** + * Update Guardian Factor + * + * @example + * management.updateGuardianFactor({ name: 'sms' }, { + * enabled: true + * }, function (err, factor) { + * console.log(factor); + * }); + * @param {object} params Factor parameters. + * @param {object} data Updated factor data. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + updateGuardianFactor(...args) { + return this.guardian.updateFactor(...args); + } -/** - * Update the Guardian phone factor's message types - * - * @function updateGuardianPhoneFactorMessageTypes - * @memberof module:management.ManagementClient.prototype - * @example - * management.updateGuardianPhoneFactorMessageTypes({}, { - * message_types: ['sms', 'voice'] - * }, function (err, factor) { - * console.log(factor); - * }); - * @param {object} params Parameters. - * @param {object} data Updated selected provider data. - * @param {string[]} data.message_types Message types (only `"sms"` and `"voice"` are supported). - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod( - ManagementClient, - 'updateGuardianPhoneFactorMessageTypes', - 'guardian.updatePhoneFactorMessageTypes' -); + /** + * Get enabled Guardian policies + * + * @example + * management.getGuardianPolicies(function (err, policies) { + * console.log(policies); + * }); + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getGuardianPolicies(...args) { + return this.guardian.getPolicies(...args); + } -/** - * Get all roles. - * - * @function getRoles - * @memberof module:management.ManagementClient.prototype - * @example - * This method takes an optional object as first argument that may be used to - * specify pagination settings. If pagination options are not present, - * the first page of a limited number of results will be returned. - * - * - * // Pagination settings. - * var params = { - * per_page: 10, - * page: 0 - * }; - * - * management.getRoles(params, function (err, roles) { - * console.log(roles.length); - * }); - * @param {object} [params] Roles parameters. - * @param {number} [params.per_page] Number of results per page. - * @param {number} [params.page] Page number, zero indexed. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getRoles', 'roles.getAll'); + /** + * Update enabled Guardian policies + * + * @example + * management.updateGuardianPolicies({}, [ + * 'all-applications' + * ], function (err, policies) { + * console.log(policies); + * }); + * @param {object} params Parameters. + * @param {string[]} data Policies to enable. Empty array disables all policies. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + updateGuardianPolicies(...args) { + return this.guardian.updatePolicies(...args); + } -/** - * Create a new role. - * - * @function createRole - * @memberof module:management.ManagementClient.prototype - * @example - * data = {"name": "test1","description": "123"} - * management.createRole(data, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Role created. - * }); - * @param {object} data Role data object. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'createRole', 'roles.create'); + /** + * Get the Guardian phone factor's selected provider + * + * @example + * management.getGuardianPhoneFactorSelectedProvider(function (err, selectedProvider) { + * console.log(selectedProvider); + * }); + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getGuardianPhoneFactorSelectedProvider(...args) { + return this.guardian.getPhoneFactorSelectedProvider(...args); + } -/** - * Get an Auth0 role. - * - * @function getRole - * @memberof module:management.ManagementClient.prototype - * @example - * management.getRole({ id: ROLE_ID }, function (err, role) { - * if (err) { - * // Handle error. - * } - * - * console.log(role); - * }); - * @param {object} params Role parameters. - * @param {string} params.id Role ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getRole', 'roles.get'); + /** + * Update the Guardian phone factor's selected provider + * + * @example + * management.updateGuardianPhoneFactorSelectedProvider({}, { + * provider: 'twilio' + * }, function (err, factor) { + * console.log(factor); + * }); + * @param {object} params Parameters. + * @param {object} data Updated selected provider data. + * @param {string} data.provider Name of the selected provider + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + updateGuardianPhoneFactorSelectedProvider(...args) { + return this.guardian.updatePhoneFactorSelectedProvider(...args); + } -/** - * Delete an existing role. - * - * @function deleteRole - * @memberof module:management.ManagementClient.prototype - * @example - * management.deleteRole({ id: ROLE_ID }, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Role deleted. - * }); - * @param {object} params Role parameters. - * @param {string} params.id Role ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'deleteRole', 'roles.delete'); + /** + * Get the Guardian phone factor's message types + * + * @example + * management.getGuardianPhoneFactorMessageTypes(function (err, messageTypes) { + * console.log(messageTypes); + * }); + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getGuardianPhoneFactorMessageTypes(...args) { + return this.guardian.getPhoneFactorMessageTypes(...args); + } -/** - * Update an existing role. - * - * @function updateRole - * @memberof module:management.ManagementClient.prototype - * @example - * var params = { id: ROLE_ID }; - * var data = { name: 'my-role'}; - * management.updateRole(params, data, function (err, role) { - * if (err) { - * // Handle error. - * } - * - * console.log(role.name); // 'my-role'. - * }); - * @param {object} params Role parameters. - * @param {string} params.id Role ID. - * @param {object} data Updated role data. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'updateRole', 'roles.update'); + /** + * Update the Guardian phone factor's message types + * + * @example + * management.updateGuardianPhoneFactorMessageTypes({}, { + * message_types: ['sms', 'voice'] + * }, function (err, factor) { + * console.log(factor); + * }); + * @param {object} params Parameters. + * @param {object} data Updated selected provider data. + * @param {string[]} data.message_types Message types (only `"sms"` and `"voice"` are supported). + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + updateGuardianPhoneFactorMessageTypes(...args) { + return this.guardian.updatePhoneFactorMessageTypes(...args); + } -/** - * Get permissions for a given role - * - * @function getPermissionsInRole - * @memberof module:management.ManagementClient.prototype - * @example - * var params = { id :'ROLE_ID'}; - * @example - * This method takes a roleId and - * returns all permissions within that role - * - * - * - * management.getPermissionsInRole(params, function (err, permissions) { - * console.log(permissions); - * }); - * @param {string} [roleId] Id of the role - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getPermissionsInRole', 'roles.getPermissions'); + /** + * Get all roles. + * + * @example + * This method takes an optional object as first argument that may be used to + * specify pagination settings. If pagination options are not present, + * the first page of a limited number of results will be returned. + * + * + * // Pagination settings. + * var params = { + * per_page: 10, + * page: 0 + * }; + * + * management.getRoles(params, function (err, roles) { + * console.log(roles.length); + * }); + * @param {object} [params] Roles parameters. + * @param {number} [params.per_page] Number of results per page. + * @param {number} [params.page] Page number, zero indexed. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getRoles(...args) { + return this.roles.getAll(...args); + } -/** - * Add permissions in a role - * - * @function addPermissionsInRole - * @memberof module:management.ManagementClient.prototype - * @example - * var params = { id :'ROLE_ID'}; - * var data = { "permissions" : [{"permission_name" :"do:something" ,"resource_server_identifier" :"test123" }]}; - * - * management.addPermissionsInRole(params, data, function (err, permissions) { - * console.log(permissions); - * }); - * @param {string} params.id ID of the Role. - * @param {object} data permissions data - * @param {string} data.permissions Array of permissions - * @param {string} data.permissions.permission_name Name of a permission - * @param {string} data.permissions.resource_server_identifier Identifier for a resource - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'addPermissionsInRole', 'roles.addPermissions'); + /** + * Create a new role. + * + * @example + * data = {"name": "test1","description": "123"} + * management.createRole(data, function (err) { + * if (err) { + * // Handle error. + * } + * + * // Role created. + * }); + * @param {object} data Role data object. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + createRole(...args) { + return this.roles.create(...args); + } -/** - * Remove permissions from a role - * - * @function removePermissionsFromRole - * @memberof module:management.ManagementClient.prototype - * @example - * var params = { id :'ROLE_ID'}; - * var data = { "permissions" : [{"permission_name" :"do:something" ,"resource_server_identifier" :"test123" }]}; - * - * management.removePermissionsFromRole(params, data, function (err, permissions) { - * console.log(permissions); - * }); - * @param {string} params.id ID of the Role. - * @param {object} data permissions data - * @param {string} data.permissions Array of permissions - * @param {string} data.permissions.permission_name Name of a permission - * @param {string} data.permissions.resource_server_identifier Identifier for a resource - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'removePermissionsFromRole', 'roles.removePermissions'); + /** + * Get an Auth0 role. + * + * @example + * management.getRole({ id: ROLE_ID }, function (err, role) { + * if (err) { + * // Handle error. + * } + * + * console.log(role); + * }); + * @param {object} params Role parameters. + * @param {string} params.id Role ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getRole(...args) { + return this.roles.get(...args); + } -/** - * Get users in a given role - * - * @function getUsersInRole - * @memberof module:management.ManagementClient.prototype - * @example - * var params = { - * id: 'ROLE_ID', - * per_page: 50, - * page: 0 - * }; - * @example - * This method takes a roleId and returns all users within that role. Supports offset (page, per_page) and checkpoint pagination (from, take). You must use checkpoint pagination to retrieve beyond the first 1000 records. - * - * - * management.getUsersInRole(params, function (err, users) { - * console.log(users); - * }); - * @param {string} [id] Id of the role - * @param {number} [params.per_page] Number of results per page. - * @param {number} [params.page] Page number, zero indexed. - * @param {string} [params.from] Optional id from which to start selection. - * @param {number} [params.take] The total amount of entries to retrieve when using the from parameter. Defaults to 50. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getUsersInRole', 'roles.getUsers'); + /** + * Delete an existing role. + * + * @example + * management.deleteRole({ id: ROLE_ID }, function (err) { + * if (err) { + * // Handle error. + * } + * + * // Role deleted. + * }); + * @param {object} params Role parameters. + * @param {string} params.id Role ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + deleteRole(...args) { + return this.roles.delete(...args); + } -/** - * Get all hooks. - * - * @function getHooks - * @memberof module:management.ManagementClient.prototype - * @example - * This method takes an optional object as first argument that may be used to - * specify pagination settings. If pagination options are not present, - * the first page of a limited number of results will be returned. - * - * - * // Pagination settings. - * var params = { - * per_page: 10, - * page: 0 - * }; - * - * management.getHooks(params, function (err, hooks) { - * console.log(hooks.length); - * }); - * @param {object} [params] Hooks parameters. - * @param {number} [params.per_page] Number of results per page. - * @param {number} [params.page] Page number, zero indexed. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getHooks', 'hooks.getAll'); + /** + * Update an existing role. + * + * @example + * var params = { id: ROLE_ID }; + * var data = { name: 'my-role'}; + * management.updateRole(params, data, function (err, role) { + * if (err) { + * // Handle error. + * } + * + * console.log(role.name); // 'my-role'. + * }); + * @param {object} params Role parameters. + * @param {string} params.id Role ID. + * @param {object} data Updated role data. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + updateRole(...args) { + return this.roles.update(...args); + } -/** - * Get an Auth0 hook. - * - * @function getHook - * @memberof module:management.ManagementClient.prototype - * @example - * management.getHook({ id: HOOK_ID }, function (err, hook) { - * if (err) { - * // Handle error. - * } - * - * console.log(hook); - * }); - * @param {object} params Hook parameters. - * @param {string} params.id Hook ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getHook', 'hooks.get'); + /** + * Get permissions for a given role + * + * @example + * var params = { id :'ROLE_ID'}; + * @example + * This method takes a roleId and + * returns all permissions within that role + * + * + * + * management.getPermissionsInRole(params, function (err, permissions) { + * console.log(permissions); + * }); + * @param {string} [roleId] Id of the role + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getPermissionsInRole(...args) { + return this.roles.getPermissions(...args); + } -/** - * Create a new hook. - * - * @function createHook - * @memberof module:management.ManagementClient.prototype - * @example - * management.createHook(data, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Hook created. - * }); - * @param {object} data Hook data object. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'createHook', 'hooks.create'); + /** + * Add permissions in a role + * + * @example + * var params = { id :'ROLE_ID'}; + * var data = { "permissions" : [{"permission_name" :"do:something" ,"resource_server_identifier" :"test123" }]}; + * + * management.addPermissionsInRole(params, data, function (err, permissions) { + * console.log(permissions); + * }); + * @param {string} params.id ID of the Role. + * @param {object} data permissions data + * @param {string} data.permissions Array of permissions + * @param {string} data.permissions.permission_name Name of a permission + * @param {string} data.permissions.resource_server_identifier Identifier for a resource + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + addPermissionsInRole(...args) { + return this.roles.addPermissions(...args); + } -/** - * Update an existing hook. - * - * @function updateHook - * @memberof module:management.ManagementClient.prototype - * @example - * var params = { id: HOOK_ID }; - * var data = { name: 'my-hook'}; - * management.updateHook(params, data, function (err, hook) { - * if (err) { - * // Handle error. - * } - * - * console.log(hook.name); // 'my-hook'. - * }); - * @param {object} params Hook parameters. - * @param {string} params.id Hook ID. - * @param {object} data Updated hook data. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'updateHook', 'hooks.update'); + /** + * Remove permissions from a role + * + * @example + * var params = { id :'ROLE_ID'}; + * var data = { "permissions" : [{"permission_name" :"do:something" ,"resource_server_identifier" :"test123" }]}; + * + * management.removePermissionsFromRole(params, data, function (err, permissions) { + * console.log(permissions); + * }); + * @param {string} params.id ID of the Role. + * @param {object} data permissions data + * @param {string} data.permissions Array of permissions + * @param {string} data.permissions.permission_name Name of a permission + * @param {string} data.permissions.resource_server_identifier Identifier for a resource + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + removePermissionsFromRole(...args) { + return this.roles.removePermissions(...args); + } -/** - * Delete an existing hook. - * - * @function deleteHook - * @memberof module:management.ManagementClient.prototype - * @example - * auth0.deleteHook({ id: HOOK_ID }, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Hook deleted. - * }); - * @param {object} params Hook parameters. - * @param {string} params.id Hook ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'deleteHook', 'hooks.delete'); + /** + * Get users in a given role + * + * @example + * var params = { + * id: 'ROLE_ID', + * per_page: 50, + * page: 0 + * }; + * @example + * This method takes a roleId and returns all users within that role. Supports offset (page, per_page) and checkpoint pagination (from, take). You must use checkpoint pagination to retrieve beyond the first 1000 records. + * + * + * management.getUsersInRole(params, function (err, users) { + * console.log(users); + * }); + * @param {string} [id] Id of the role + * @param {number} [params.per_page] Number of results per page. + * @param {number} [params.page] Page number, zero indexed. + * @param {string} [params.from] Optional id from which to start selection. + * @param {number} [params.take] The total amount of entries to retrieve when using the from parameter. Defaults to 50. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getUsersInRole(...args) { + return this.roles.getUsers(...args); + } -/** - * Get an Auth0 hook's secrets. - * - * @function getHookSecrets - * @memberof module:management.ManagementClient.prototype - * @example - * var params = { id: HOOK_ID } - * management.getHookSecrets(params, function (err, secrets) { - * if (err) { - * // Handle error. - * } - * - * console.log(secrets); - * }); - * @param {object} params Hook parameters. - * @param {string} params.id Hook ID. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getHookSecrets', 'hooks.getSecrets'); + /** + * Get all hooks. + * + * @example + * This method takes an optional object as first argument that may be used to + * specify pagination settings. If pagination options are not present, + * the first page of a limited number of results will be returned. + * + * + * // Pagination settings. + * var params = { + * per_page: 10, + * page: 0 + * }; + * + * management.getHooks(params, function (err, hooks) { + * console.log(hooks.length); + * }); + * @param {object} [params] Hooks parameters. + * @param {number} [params.per_page] Number of results per page. + * @param {number} [params.page] Page number, zero indexed. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getHooks(...args) { + return this.hooks.getAll(...args); + } -/** - * Add hook screts. - * - * @function addHookScrets - * @memberof module:management.ManagementClient.prototype - * @example - * var params = { id: 'HOOK_ID' } - * var data = { DB_PASSWORD: 'password1', API_TOKEN: 'secret' } - * management.addHookScrets(params, data, function (err, secrets) { - * if (err) { - * // Handle error. - * } - * - * // Hook secrets created. - * }); - * @param {object} params Hook parameters. - * @param {string} params.id Hook ID. - * @param {object} data Secrets key/value pairs - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'addHookSecrets', 'hooks.addSecrets'); + /** + * Get an Auth0 hook. + * + * @example + * management.getHook({ id: HOOK_ID }, function (err, hook) { + * if (err) { + * // Handle error. + * } + * + * console.log(hook); + * }); + * @param {object} params Hook parameters. + * @param {string} params.id Hook ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getHook(...args) { + return this.hooks.get(...args); + } -/** - * Update an existing hook. - * - * @function updateHookSecrets - * @memberof module:management.ManagementClient.prototype - * @example - * var params = { id: HOOK_ID }; - * var data = { API_TOKEN: 'updated-secret'}; - * management.updateHookSecrets(params, data, function (err, secrets) { - * if (err) { - * // Handle error. - * } - * - * console.log(secrets) - * }); - * @param {object} params Hook parameters. - * @param {string} params.id Hook ID. - * @param {object} data Secrets key/value pairs - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'updateHookSecrets', 'hooks.updateSecrets'); + /** + * Create a new hook. + * + * @example + * management.createHook(data, function (err) { + * if (err) { + * // Handle error. + * } + * + * // Hook created. + * }); + * @param {object} data Hook data object. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + createHook(...args) { + return this.hooks.create(...args); + } -/** - * Delete an existing hook. - * - * @function removeHookSecrets - * @memberof module:management.ManagementClient.prototype - * @example - * var params = { id: HOOK_ID } - * var data = ['API_TOKEN', 'DB_PASSWORD'] - * auth0.removeHookSecrets(params, data, function (err) { - * if (err) { - * // Handle error. - * } - * - * // Hook deleted. - * }); - * @param {object} params Hook parameters. - * @param {string} params.id Hook ID. - * @param {object} data Secrets key/value pairs - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'removeHookSecrets', 'hooks.removeSecrets'); + /** + * Update an existing hook. + * + * @example + * var params = { id: HOOK_ID }; + * var data = { name: 'my-hook'}; + * management.updateHook(params, data, function (err, hook) { + * if (err) { + * // Handle error. + * } + * + * console.log(hook.name); // 'my-hook'. + * }); + * @param {object} params Hook parameters. + * @param {string} params.id Hook ID. + * @param {object} data Updated hook data. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + updateHook(...args) { + return this.hooks.update(...args); + } -/** - * Returns the access_token. - * - * @function getAccessToken - * @memberof module:management.ManagementClient.prototype - * @returns {Promise} Promise returning an access_token. - */ -utils.wrapPropertyMethod(ManagementClient, 'getAccessToken', 'tokenProvider.getAccessToken'); + /** + * Delete an existing hook. + * + * @example + * auth0.deleteHook({ id: HOOK_ID }, function (err) { + * if (err) { + * // Handle error. + * } + * + * // Hook deleted. + * }); + * @param {object} params Hook parameters. + * @param {string} params.id Hook ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + deleteHook(...args) { + return this.hooks.delete(...args); + } -/** - * Update the branding settings. - * - * @function updateBrandingSettings - * @memberof module:management.ManagementClient.prototype - * @example - * management.updateBrandingSettings(data, function (err, branding) { - * if (err) { - * // Handle error. - * } - * - * // Updated branding - * console.log(branding); - * }); - * @param {object} params Branding parameters. - * @param {object} data Updated branding data. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'updateBrandingSettings', 'branding.updateSettings'); + /** + * Get an Auth0 hook's secrets. + * + * @example + * var params = { id: HOOK_ID } + * management.getHookSecrets(params, function (err, secrets) { + * if (err) { + * // Handle error. + * } + * + * console.log(secrets); + * }); + * @param {object} params Hook parameters. + * @param {string} params.id Hook ID. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getHookSecrets(...args) { + return this.hooks.getSecrets(...args); + } -/** - * Get the branding settings.. - * - * @function getBrandingSettings - * @memberof module:management.ManagementClient.prototype - * @example - * management.getBrandingSettings(data, function (err, branding) { - * if (err) { - * // Handle error. - * } - * - * // Branding - * console.log(branding); - * }); - * @param {object} params Branding parameters. - * @param {object} data Branding data. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getBrandingSettings', 'branding.getSettings'); + /** + * Add hook screts. + * + * @example + * var params = { id: 'HOOK_ID' } + * var data = { DB_PASSWORD: 'password1', API_TOKEN: 'secret' } + * management.addHookScrets(params, data, function (err, secrets) { + * if (err) { + * // Handle error. + * } + * + * // Hook secrets created. + * }); + * @param {object} params Hook parameters. + * @param {string} params.id Hook ID. + * @param {object} data Secrets key/value pairs + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + addHookSecrets(...args) { + return this.hooks.addSecrets(...args); + } -/** - * Get the new universal login template. - * - * @function getBrandingUniversalLoginTemplate - * @memberof module:management.ManagementClient.prototype - * @example - * management.getBrandingUniversalLoginTemplate(data, function (err, template) { - * if (err) { - * // Handle error. - * } - * - * // Branding - * console.log(template); - * }); - * @param {object} params Branding parameters (leave empty). - * @param {object} data Branding data (leave empty). - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod( - ManagementClient, - 'getBrandingUniversalLoginTemplate', - 'branding.getUniversalLoginTemplate' -); + /** + * Update an existing hook. + * + * @example + * var params = { id: HOOK_ID }; + * var data = { API_TOKEN: 'updated-secret'}; + * management.updateHookSecrets(params, data, function (err, secrets) { + * if (err) { + * // Handle error. + * } + * + * console.log(secrets) + * }); + * @param {object} params Hook parameters. + * @param {string} params.id Hook ID. + * @param {object} data Secrets key/value pairs + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + updateHookSecrets(...args) { + return this.hooks.updateSecrets(...args); + } -/** - * Get the new universal login template. - * - * @function setBrandingUniversalLoginTemplate - * @memberof module:management.ManagementClient.prototype - * @example - * management.setBrandingUniversalLoginTemplate({ template: "a template" }, function (err, template) { - * if (err) { - * // Handle error. - * } - * }); - * @param {object} params Branding parameters (leave empty). - * @param {object} template Branding data (object with template field). - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod( - ManagementClient, - 'setBrandingUniversalLoginTemplate', - 'branding.setUniversalLoginTemplate' -); + /** + * Delete an existing hook. + * + * @example + * var params = { id: HOOK_ID } + * var data = ['API_TOKEN', 'DB_PASSWORD'] + * auth0.removeHookSecrets(params, data, function (err) { + * if (err) { + * // Handle error. + * } + * + * // Hook deleted. + * }); + * @param {object} params Hook parameters. + * @param {string} params.id Hook ID. + * @param {object} data Secrets key/value pairs + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + removeHookSecrets(...args) { + return this.hooks.removeSecrets(...args); + } -/** - * Delete the new universal login template. - * - * @function deleteBrandingUniversalLoginTemplate - * @memberof module:management.ManagementClient.prototype - * @example - * management.deleteBrandingUniversalLoginTemplate(template, function (err) { - * if (err) { - * // Handle error. - * } - * }); - * @param {object} params Branding parameters (leave empty). - * @param {object} data Branding data (leave empty). - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod( - ManagementClient, - 'deleteBrandingUniversalLoginTemplate', - 'branding.deleteUniversalLoginTemplate' -); + /** + * Returns the access_token. + * + * @returns {Promise} Promise returning an access_token. + */ + getAccessToken(...args) { + return this.tokenProvider.getAccessToken(...args); + } -/** - * Update the tenant migrations. - * - * @function updateMigrations - * @memberof module:management.ManagementClient.prototype - * @example - * data = { flags: { migration: true } }; - * management.updateMigrations(data, function (err, migrations) { - * if (err) { - * // Handle error. - * } - * - * // Updated migrations flags - * console.log(migrations.flags); - * }); - * @param {object} data Updated migrations data. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'updateMigrations', 'migrations.updateMigrations'); + /** + * Update the branding settings. + * + * @example + * management.updateBrandingSettings(data, function (err, branding) { + * if (err) { + * // Handle error. + * } + * + * // Updated branding + * console.log(branding); + * }); + * @param {object} params Branding parameters. + * @param {object} data Updated branding data. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + updateBrandingSettings(...args) { + return this.branding.updateSettings(...args); + } -/** - * Get migrations flags - * - * @function getMigrations - * @memberof module:management.ManagementClient.prototype - * @example - * management.getMigrations(function (err, migrations) { - * if (err) { - * // Handle error. - * } - * - * // Migration flags - * console.log(migrations.flags); - * }); - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ -utils.wrapPropertyMethod(ManagementClient, 'getMigrations', 'migrations.getMigrations'); + /** + * Get the branding settings.. + * + * @example + * management.getBrandingSettings(data, function (err, branding) { + * if (err) { + * // Handle error. + * } + * + * // Branding + * console.log(branding); + * }); + * @param {object} params Branding parameters. + * @param {object} data Branding data. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getBrandingSettings(...args) { + return this.branding.getSettings(...args); + } -/** - * Get prompts settings.. - * - * @function getPromptsSettings - * @memberof module:management.ManagementClient.prototype - * @example - * management.getPromptsSettings(function (err, settings) { - * console.log(settings); - * }); - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ + /** + * Get the new universal login template. + * + * @example + * management.getBrandingUniversalLoginTemplate(data, function (err, template) { + * if (err) { + * // Handle error. + * } + * + * // Branding + * console.log(template); + * }); + * @param {object} params Branding parameters (leave empty). + * @param {object} data Branding data (leave empty). + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getBrandingUniversalLoginTemplate(...args) { + return this.branding.getUniversalLoginTemplate(...args); + } -utils.wrapPropertyMethod(ManagementClient, 'getPromptsSettings', 'prompts.getSettings'); + /** + * Get the new universal login template. + * + * @example + * management.setBrandingUniversalLoginTemplate({ template: "a template" }, function (err, template) { + * if (err) { + * // Handle error. + * } + * }); + * @param {object} params Branding parameters (leave empty). + * @param {object} template Branding data (object with template field). + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + setBrandingUniversalLoginTemplate(...args) { + return this.branding.setUniversalLoginTemplate(...args); + } -/** - * Update prompts settings. - * - * @function updatePromptsSettings - * @memberof module:management.ManagementClient.prototype - * @example - * management.updatePromptsSettings(data, function (err) { - * if (err) { - * // Handle error. - * } - * }); - * @param {object} data The new prompts settings. - * @param {Function} [cb] Callback function. - * @returns {Promise|undefined} - */ + /** + * Delete the new universal login template. + * + * @example + * management.deleteBrandingUniversalLoginTemplate(template, function (err) { + * if (err) { + * // Handle error. + * } + * }); + * @param {object} params Branding parameters (leave empty). + * @param {object} data Branding data (leave empty). + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + deleteBrandingUniversalLoginTemplate(...args) { + return this.branding.deleteUniversalLoginTemplate(...args); + } -utils.wrapPropertyMethod(ManagementClient, 'updatePromptsSettings', 'prompts.updateSettings'); + /** + * Update the tenant migrations. + * + * @example + * data = { flags: { migration: true } }; + * management.updateMigrations(data, function (err, migrations) { + * if (err) { + * // Handle error. + * } + * + * // Updated migrations flags + * console.log(migrations.flags); + * }); + * @param {object} data Updated migrations data. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + updateMigrations(...args) { + return this.migrations.updateMigrations(...args); + } -/** - * Retrieve custom text for a specific prompt and language. - * - * @function getCustomTextByLanguage - * @memberof module:management.PromptsManager.prototype - * @example - * var params = { prompt: PROMPT_NAME, language: LANGUAGE }; - * - * management.prompts.getCustomTextByLanguage(params, function (err, customText) { - * console.log('CustomText', customText); - * }); - * @param {object} params Data object. - * @param {string} params.prompt Name of the prompt. - * @param {string} params.language Language to retrieve. - * @param {Function} [cb] Callback function - * @returns {Promise|undefined} - */ + /** + * Get migrations flags + * + * @example + * management.getMigrations(function (err, migrations) { + * if (err) { + * // Handle error. + * } + * + * // Migration flags + * console.log(migrations.flags); + * }); + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getMigrations(...args) { + return this.migrations.getMigrations(...args); + } -utils.wrapPropertyMethod( - ManagementClient, - 'getCustomTextByLanguage', - 'prompts.getCustomTextByLanguage' -); + /** + * Get prompts settings.. + * + * @example + * management.getPromptsSettings(function (err, settings) { + * console.log(settings); + * }); + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + getPromptsSettings(...args) { + return this.prompts.getSettings(...args); + } -/** - * Set custom text for a specific prompt. - * - * @function updateCustomTextByLanguage - * @memberof module:management.PromptsManager.prototype - * @example - * var params = { prompt: PROMPT_NAME, language: LANGUAGE, body: BODY_OBJECT }; - * - * management.prompts.updateCustomTextByLanguage(params, function (err, customText) { - * console.log('CustomText', customText); - * }); - * @param {object} params Data object. - * @param {string} params.prompt Name of the prompt. - * @param {string} params.language Language to retrieve. - * @param {object} params.body An object containing custom dictionaries for a group of screens. - * @param {Function} [cb] Callback function - * @returns {Promise|undefined} - */ + /** + * Update prompts settings. + * + * @example + * management.updatePromptsSettings(data, function (err) { + * if (err) { + * // Handle error. + * } + * }); + * @param {object} data The new prompts settings. + * @param {Function} [cb] Callback function. + * @returns {Promise|undefined} + */ + updatePromptsSettings(...args) { + return this.prompts.updateSettings(...args); + } + /** + * Retrieve custom text for a specific prompt and language. + * + * @example + * var params = { prompt: PROMPT_NAME, language: LANGUAGE }; + * + * management.prompts.getCustomTextByLanguage(params, function (err, customText) { + * console.log('CustomText', customText); + * }); + * @param {object} params Data object. + * @param {string} params.prompt Name of the prompt. + * @param {string} params.language Language to retrieve. + * @param {Function} [cb] Callback function + * @returns {Promise|undefined} + */ + getCustomTextByLanguage(...args) { + return this.prompts.getCustomTextByLanguage(...args); + } -utils.wrapPropertyMethod( - ManagementClient, - 'updateCustomTextByLanguage', - 'prompts.updateCustomTextByLanguage' -); + /** + * Set custom text for a specific prompt. + * + * @example + * var params = { prompt: PROMPT_NAME, language: LANGUAGE, body: BODY_OBJECT }; + * + * management.prompts.updateCustomTextByLanguage(params, function (err, customText) { + * console.log('CustomText', customText); + * }); + * @param {object} params Data object. + * @param {string} params.prompt Name of the prompt. + * @param {string} params.language Language to retrieve. + * @param {object} params.body An object containing custom dictionaries for a group of screens. + * @param {Function} [cb] Callback function + * @returns {Promise|undefined} + */ + updateCustomTextByLanguage(...args) { + return this.prompts.updateCustomTextByLanguage(...args); + } +} module.exports = ManagementClient; diff --git a/src/utils.js b/src/utils.js index 8285540ba..e553250ee 100644 --- a/src/utils.js +++ b/src/utils.js @@ -26,28 +26,6 @@ const generateClientInfo = () => ({ }, }); -/** - * Simple wrapper that, given a class, a property name and a method name, - * creates a new method in the class that is a wrapper for the given - * property method. - */ - -const wrapPropertyMethod = (Parent, name, propertyMethod) => { - const path = propertyMethod.split('.'); - if (path.length > 2) { - throw new Error('wrapPropertyMethod() only supports one level of nesting for propertyMethod'); - } - const property = path.shift(); - const method = path.pop(); - - Object.defineProperty(Parent.prototype, name, { - enumerable: false, - get() { - return this[property][method].bind(this[property]); - }, - }); -}; - const containsUnsafeChars = (s) => { const safeChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$-_.+!*'(),%"; return !!s.split('').find((c) => !safeChars.includes(c)); @@ -76,7 +54,6 @@ const sanitizeArguments = function (optionsCandidate, cbCandidate) { module.exports = { jsonToBase64, generateClientInfo, - wrapPropertyMethod, containsUnsafeChars, maybeDecode, sanitizeArguments, diff --git a/test/auth/authentication-client.tests.js b/test/auth/authentication-client.tests.js index 6af54558d..dd97adcdc 100644 --- a/test/auth/authentication-client.tests.js +++ b/test/auth/authentication-client.tests.js @@ -16,16 +16,15 @@ const { ensureProperty } = require('../utils'); describe('AuthenticationClient', () => { describe('#constructor', () => { it('should raise an error when no options object is provided', () => { - expect(AuthenticationClient).to.throw( - ArgumentError, - 'Authentication Client SDK options must be an object' - ); + expect(() => { + new AuthenticationClient(); + }).to.throw(ArgumentError, 'Authentication Client SDK options must be an object'); }); it('should raise an error when the domain is not valid', () => { - const client = AuthenticationClient.bind(null, { token: 'token', domain: '' }); - - expect(client).to.throw(ArgumentError, 'Must provide a domain'); + expect(() => { + new AuthenticationClient({ token: 'token', domain: '' }); + }).to.throw(ArgumentError, 'Must provide a domain'); }); }); diff --git a/test/auth/oauth-with-idtoken-validation.tests.js b/test/auth/oauth-with-idtoken-validation.tests.js index 6e265391a..da14493af 100644 --- a/test/auth/oauth-with-idtoken-validation.tests.js +++ b/test/auth/oauth-with-idtoken-validation.tests.js @@ -61,11 +61,11 @@ describe('OAUthWithIDTokenValidation', () => { create(params, data) { expect(params).to.be.equal(PARAMS); expect(data).to.be.equal(DATA); - return new Promise((res) => res({})); + done(); }, }; const oauthWithValidation = new OAUthWithIDTokenValidation(oauth, {}); - oauthWithValidation.create(PARAMS, DATA, done); + oauthWithValidation.create(PARAMS, DATA); }); it('Does nothing when there is no id_token', (done) => { const oauth = { diff --git a/test/management/branding.tests.js b/test/management/branding.tests.js index 1e7da3743..398ac8d25 100644 --- a/test/management/branding.tests.js +++ b/test/management/branding.tests.js @@ -27,19 +27,21 @@ describe('BrandingManager', () => { describe('#constructor', () => { it('should error when no options are provided', () => { - expect(BrandingManager).to.throw(ArgumentError, 'Must provide manager options'); + expect(() => { + new BrandingManager(); + }).to.throw(ArgumentError, 'Must provide manager options'); }); it('should throw an error when no base URL is provided', () => { - const client = BrandingManager.bind(null, {}); - - expect(client).to.throw(ArgumentError, 'Must provide a base URL for the API'); + expect(() => { + new BrandingManager({}); + }).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); it('should throw an error when the base URL is invalid', () => { - const client = BrandingManager.bind(null, { baseUrl: '' }); - - expect(client).to.throw(ArgumentError, 'The provided base URL is invalid'); + expect(() => { + new BrandingManager({ baseUrl: '' }); + }).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); diff --git a/test/management/client-grants.tests.js b/test/management/client-grants.tests.js index 18083626f..f67f4f1a6 100644 --- a/test/management/client-grants.tests.js +++ b/test/management/client-grants.tests.js @@ -33,19 +33,21 @@ describe('ClientGrantsManager', () => { describe('#constructor', () => { it('should error when no options are provided', () => { - expect(ClientGrantsManager).to.throw(ArgumentError, 'Must provide client options'); + expect(() => { + new ClientGrantsManager(); + }).to.throw(ArgumentError, 'Must provide client options'); }); it('should throw an error when no base URL is provided', () => { - const grants = ClientGrantsManager.bind(null, {}); - - expect(grants).to.throw(ArgumentError, 'Must provide a base URL for the API'); + expect(() => { + new ClientGrantsManager({}); + }).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); it('should throw an error when the base URL is invalid', () => { - const grants = ClientGrantsManager.bind(null, { baseUrl: '' }); - - expect(grants).to.throw(ArgumentError, 'The provided base URL is invalid'); + expect(() => { + new ClientGrantsManager({ baseUrl: '' }); + }).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); diff --git a/test/management/client.tests.js b/test/management/client.tests.js index 2860a426a..1720202ad 100644 --- a/test/management/client.tests.js +++ b/test/management/client.tests.js @@ -33,19 +33,21 @@ describe('ClientsManager', () => { describe('#constructor', () => { it('should error when no options are provided', () => { - expect(ClientsManager).to.throw(ArgumentError, 'Must provide client options'); + expect(() => { + new ClientsManager(); + }).to.throw(ArgumentError, 'Must provide client options'); }); it('should throw an error when no base URL is provided', () => { - const client = ClientsManager.bind(null, {}); - - expect(client).to.throw(ArgumentError, 'Must provide a base URL for the API'); + expect(() => { + new ClientsManager({}); + }).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); it('should throw an error when the base URL is invalid', () => { - const client = ClientsManager.bind(null, { baseUrl: '' }); - - expect(client).to.throw(ArgumentError, 'The provided base URL is invalid'); + expect(() => { + new ClientsManager({ baseUrl: '' }); + }).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); diff --git a/test/management/custom-domains.tests.js b/test/management/custom-domains.tests.js index 6442ea2a7..e9b57e80c 100644 --- a/test/management/custom-domains.tests.js +++ b/test/management/custom-domains.tests.js @@ -27,19 +27,21 @@ describe('CustomDomainsManager', () => { describe('#constructor', () => { it('should error when no options are provided', () => { - expect(CustomDomainsManager).to.throw(ArgumentError, 'Must provide manager options'); + expect(() => { + new CustomDomainsManager(); + }).to.throw(ArgumentError, 'Must provide manager options'); }); it('should throw an error when no base URL is provided', () => { - const client = CustomDomainsManager.bind(null, {}); - - expect(client).to.throw(ArgumentError, 'Must provide a base URL for the API'); + expect(() => { + new CustomDomainsManager({}); + }).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); it('should throw an error when the base URL is invalid', () => { - const client = CustomDomainsManager.bind(null, { baseUrl: '' }); - - expect(client).to.throw(ArgumentError, 'The provided base URL is invalid'); + expect(() => { + new CustomDomainsManager({ baseUrl: '' }); + }).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); diff --git a/test/management/device-credentials.tests.js b/test/management/device-credentials.tests.js index fcf2f7b2d..10cd533f9 100644 --- a/test/management/device-credentials.tests.js +++ b/test/management/device-credentials.tests.js @@ -27,19 +27,21 @@ describe('DeviceCredentialsManager', () => { describe('#constructor', () => { it('should error when no options are provided', () => { - expect(DeviceCredentialsManager).to.throw(ArgumentError, 'Must provide manager options'); + expect(() => { + new DeviceCredentialsManager(); + }).to.throw(ArgumentError, 'Must provide manager options'); }); it('should throw an error when no base URL is provided', () => { - const client = DeviceCredentialsManager.bind(null, {}); - - expect(client).to.throw(ArgumentError, 'Must provide a base URL for the API'); + expect(() => { + new DeviceCredentialsManager({}); + }).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); it('should throw an error when the base URL is invalid', () => { - const client = DeviceCredentialsManager.bind(null, { baseUrl: '' }); - - expect(client).to.throw(ArgumentError, 'The provided base URL is invalid'); + expect(() => { + new DeviceCredentialsManager({ baseUrl: '' }); + }).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); diff --git a/test/management/email-provider.tests.js b/test/management/email-provider.tests.js index 520ff1a54..977f9bb11 100644 --- a/test/management/email-provider.tests.js +++ b/test/management/email-provider.tests.js @@ -27,19 +27,21 @@ describe('EmailProviderManager', () => { describe('#constructor', () => { it('should error when no options are provided', () => { - expect(EmailProviderManager).to.throw(ArgumentError, 'Must provide client options'); + expect(() => { + new EmailProviderManager(); + }).to.throw(ArgumentError, 'Must provide client options'); }); it('should throw an error when no base URL is provided', () => { - const client = EmailProviderManager.bind(null, {}); - - expect(client).to.throw(ArgumentError, 'Must provide a base URL for the API'); + expect(() => { + new EmailProviderManager({}); + }).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); it('should throw an error when the base URL is invalid', () => { - const client = EmailProviderManager.bind(null, { baseUrl: '' }); - - expect(client).to.throw(ArgumentError, 'The provided base URL is invalid'); + expect(() => { + new EmailProviderManager({ baseUrl: '' }); + }).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); diff --git a/test/management/email-templates.tests.js b/test/management/email-templates.tests.js index 5e737f8b7..8c3acd18d 100644 --- a/test/management/email-templates.tests.js +++ b/test/management/email-templates.tests.js @@ -37,19 +37,21 @@ describe('EmailTemplatesManager', () => { describe('#constructor', () => { it('should error when no options are provided', () => { - expect(EmailTemplatesManager).to.throw(ArgumentError, 'Must provide manager options'); + expect(() => { + new EmailTemplatesManager(); + }).to.throw(ArgumentError, 'Must provide manager options'); }); it('should throw an error when no base URL is provided', () => { - const client = EmailTemplatesManager.bind(null, {}); - - expect(client).to.throw(ArgumentError, 'Must provide a valid string as base URL for the API'); + expect(() => { + new EmailTemplatesManager({}); + }).to.throw(ArgumentError, 'Must provide a valid string as base URL for the API'); }); it('should throw an error when the base URL is invalid', () => { - const client = EmailTemplatesManager.bind(null, { baseUrl: '' }); - - expect(client).to.throw(ArgumentError, 'Must provide a valid string as base URL for the API'); + expect(() => { + new EmailTemplatesManager({ baseUrl: '' }); + }).to.throw(ArgumentError, 'Must provide a valid string as base URL for the API'); }); }); diff --git a/test/management/grants.tests.js b/test/management/grants.tests.js index 816217130..11222d68d 100644 --- a/test/management/grants.tests.js +++ b/test/management/grants.tests.js @@ -33,19 +33,21 @@ describe('GrantsManager', () => { describe('#constructor', () => { it('should error when no options are provided', () => { - expect(GrantsManager).to.throw(ArgumentError, 'Must provide client options'); + expect(() => { + new GrantsManager(); + }).to.throw(ArgumentError, 'Must provide client options'); }); it('should throw an error when no base URL is provided', () => { - const grants = GrantsManager.bind(null, {}); - - expect(grants).to.throw(ArgumentError, 'Must provide a base URL for the API'); + expect(() => { + new GrantsManager({}); + }).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); it('should throw an error when the base URL is invalid', () => { - const grants = GrantsManager.bind(null, { baseUrl: '' }); - - expect(grants).to.throw(ArgumentError, 'The provided base URL is invalid'); + expect(() => { + new GrantsManager({ baseUrl: '' }); + }).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); diff --git a/test/management/guardian.tests.js b/test/management/guardian.tests.js index 66f38d678..fd5f19e08 100644 --- a/test/management/guardian.tests.js +++ b/test/management/guardian.tests.js @@ -42,19 +42,21 @@ describe('GuardianManager', () => { describe('#constructor', () => { it('should error when no options are provided', () => { - expect(GuardianManager).to.throw(ArgumentError, 'Must provide manager options'); + expect(() => { + new GuardianManager(); + }).to.throw(ArgumentError, 'Must provide manager options'); }); it('should throw an error when no base URL is provided', () => { - const manager = GuardianManager.bind(null, {}); - - expect(manager).to.throw(ArgumentError, 'Must provide a base URL for the API'); + expect(() => { + new GuardianManager({}); + }).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); it('should throw an error when the base URL is invalid', () => { - const manager = GuardianManager.bind(null, { baseUrl: '' }); - - expect(manager).to.throw(ArgumentError, 'The provided base URL is invalid'); + expect(() => { + new GuardianManager({ baseUrl: '' }); + }).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); diff --git a/test/management/hooks.tests.js b/test/management/hooks.tests.js index a5169b510..fca141c39 100644 --- a/test/management/hooks.tests.js +++ b/test/management/hooks.tests.js @@ -37,19 +37,21 @@ describe('HookManager', () => { describe('#constructor', () => { it('should error when no options are provided', () => { - expect(HookManager).to.throw(ArgumentError, 'Must provide manager options'); + expect(() => { + new HookManager(); + }).to.throw(ArgumentError, 'Must provide manager options'); }); it('should throw an error when no base URL is provided', () => { - const client = HookManager.bind(null, {}); - - expect(client).to.throw(ArgumentError, 'Must provide a base URL for the API'); + expect(() => { + new HookManager({}); + }).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); it('should throw an error when the base URL is invalid', () => { - const client = HookManager.bind(null, { baseUrl: '' }); - - expect(client).to.throw(ArgumentError, 'The provided base URL is invalid'); + expect(() => { + new HookManager({ baseUrl: '' }); + }).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); diff --git a/test/management/jobs.tests.js b/test/management/jobs.tests.js index 32c76fe38..e1b7b8c74 100644 --- a/test/management/jobs.tests.js +++ b/test/management/jobs.tests.js @@ -37,19 +37,21 @@ describe('JobsManager', () => { describe('#constructor', () => { it('should error when no options are provided', () => { - expect(JobsManager).to.throw(ArgumentError, 'Must provide client options'); + expect(() => { + new JobsManager(); + }).to.throw(ArgumentError, 'Must provide client options'); }); it('should throw an error when no base URL is provided', () => { - const client = JobsManager.bind(null, {}); - - expect(client).to.throw(ArgumentError, 'Must provide a base URL for the API'); + expect(() => { + new JobsManager({}); + }).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); it('should throw an error when the base URL is invalid', () => { - const client = JobsManager.bind(null, { baseUrl: '' }); - - expect(client).to.throw(ArgumentError, 'The provided base URL is invalid'); + expect(() => { + new JobsManager({ baseUrl: '' }); + }).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); diff --git a/test/management/log-streams.tests.js b/test/management/log-streams.tests.js index 0b339f5f7..781ff921e 100644 --- a/test/management/log-streams.tests.js +++ b/test/management/log-streams.tests.js @@ -27,19 +27,21 @@ describe('LogStreamsManager', () => { describe('#constructor', () => { it('should error when no options are provided', () => { - expect(LogStreamsManager).to.throw(ArgumentError, 'Must provide client options'); + expect(() => { + new LogStreamsManager(); + }).to.throw(ArgumentError, 'Must provide client options'); }); it('should throw an error when no base URL is provided', () => { - const client = LogStreamsManager.bind(null, {}); - - expect(client).to.throw(ArgumentError, 'Must provide a base URL for the API'); + expect(() => { + new LogStreamsManager({}); + }).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); it('should throw an error when the base URL is invalid', () => { - const client = LogStreamsManager.bind(null, { baseUrl: '' }); - - expect(client).to.throw(ArgumentError, 'The provided base URL is invalid'); + expect(() => { + new LogStreamsManager({ baseUrl: '' }); + }).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); diff --git a/test/management/logs.tests.js b/test/management/logs.tests.js index d40814f16..d5ee44995 100644 --- a/test/management/logs.tests.js +++ b/test/management/logs.tests.js @@ -27,19 +27,21 @@ describe('LogsManager', () => { describe('#constructor', () => { it('should error when no options are provided', () => { - expect(LogsManager).to.throw(ArgumentError, 'Must provide client options'); + expect(() => { + new LogsManager(); + }).to.throw(ArgumentError, 'Must provide client options'); }); it('should throw an error when no base URL is provided', () => { - const client = LogsManager.bind(null, {}); - - expect(client).to.throw(ArgumentError, 'Must provide a base URL for the API'); + expect(() => { + new LogsManager({}); + }).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); it('should throw an error when the base URL is invalid', () => { - const client = LogsManager.bind(null, { baseUrl: '' }); - - expect(client).to.throw(ArgumentError, 'The provided base URL is invalid'); + expect(() => { + new LogsManager({ baseUrl: '' }); + }).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); diff --git a/test/management/management-client.tests.js b/test/management/management-client.tests.js index 01aa16aa9..619e91c23 100644 --- a/test/management/management-client.tests.js +++ b/test/management/management-client.tests.js @@ -56,50 +56,54 @@ describe('ManagementClient', () => { }); it('should raise an error when no options object is provided', () => { - expect(ManagementClient).to.throw( - ArgumentError, - 'Management API SDK options must be an object' - ); + expect(() => { + new ManagementClient(); + }).to.throw(ArgumentError, 'Management API SDK options must be an object'); }); it('should raise an error when the domain is not set', () => { - const config = Object.assign({}, withTokenConfig); - delete config.domain; - const client = ManagementClient.bind(null, config); + const options = Object.assign({}, withTokenConfig); + delete options.domain; - expect(client).to.throw(ArgumentError, 'Must provide a domain'); + expect(() => { + new ManagementClient(options); + }).to.throw(ArgumentError, 'Must provide a domain'); }); it('should raise an error when the domain is not valid', () => { - const config = Object.assign({}, withTokenConfig); - config.domain = ''; - const client = ManagementClient.bind(null, config); + const options = Object.assign({}, withTokenConfig); + options.domain = ''; - expect(client).to.throw(ArgumentError, 'Must provide a domain'); + expect(() => { + new ManagementClient(options); + }).to.throw(ArgumentError, 'Must provide a domain'); }); it('should raise an error when the token is not valid', () => { - const config = Object.assign({}, withTokenConfig); - config.token = ''; - const client = ManagementClient.bind(null, config); + const options = Object.assign({}, withTokenConfig); + options.token = ''; - expect(client).to.throw(ArgumentError, 'Must provide a token'); + expect(() => { + new ManagementClient(options); + }).to.throw(ArgumentError, 'Must provide a token'); }); it('should raise an error when the token and clientId are not set', () => { - const config = Object.assign({}, withTokenProviderConfig); - delete config.clientId; - const client = ManagementClient.bind(null, config); + const options = Object.assign({}, withTokenProviderConfig); + delete options.clientId; - expect(client).to.throw(ArgumentError, 'Must provide a clientId'); + expect(() => { + new ManagementClient(options); + }).to.throw(ArgumentError, 'Must provide a clientId'); }); it('should raise an error when the token and clientSecret are not set', () => { - const config = Object.assign({}, withTokenProviderConfig); - delete config.clientSecret; - const client = ManagementClient.bind(null, config); + const options = Object.assign({}, withTokenProviderConfig); + delete options.clientSecret; - expect(client).to.throw(ArgumentError, 'Must provide a clientSecret'); + expect(() => { + new ManagementClient(options); + }).to.throw(ArgumentError, 'Must provide a clientSecret'); }); describe('getAccessToken', () => { diff --git a/test/management/management-token-provider.tests.js b/test/management/management-token-provider.tests.js index 7c1f59e4d..0435bdf3a 100644 --- a/test/management/management-token-provider.tests.js +++ b/test/management/management-token-provider.tests.js @@ -154,30 +154,32 @@ describe('ManagementTokenProvider', () => { expect(provider.options.headers).to.be.equal(options.headers); }); - it('should handle network errors correctly', (done) => { + it('should handle network errors correctly', async () => { const options = Object.assign({}, defaultOptions); options.domain = 'domain'; const client = new ManagementTokenProvider(options); nock(`https://${options.domain}`).post('/oauth/token').reply(401); - client.getAccessToken().catch((err) => { + try { + await client.getAccessToken(); + } catch (err) { expect(err).to.exist; - done(); nock.cleanAll(); - }); + } }); - it('should handle unauthorized errors correctly', (done) => { + it('should handle unauthorized errors correctly', async () => { const client = new ManagementTokenProvider(defaultOptions); nock(`https://${defaultOptions.domain}`).post('/oauth/token').reply(401); - client.getAccessToken().catch((err) => { + try { + await client.getAccessToken(); + } catch (err) { expect(err).to.exist.to.be.an.instanceOf(SanitizedError); expect(err.statusCode).to.be.equal(401); - done(); nock.cleanAll(); - }); + } }); it('should expire access token from cache by the expires_in setting', async () => { @@ -219,7 +221,7 @@ describe('ManagementTokenProvider', () => { clock.restore(); }); - it('should return access token', (done) => { + it('should return access token', async () => { const options = Object.assign({}, defaultOptions); options.domain = 'auth0-node-sdk-1.auth0.com'; const client = new ManagementTokenProvider(options); @@ -229,12 +231,9 @@ describe('ManagementTokenProvider', () => { expires_in: 3600, }); - client.getAccessToken().then((access_token) => { - expect(access_token).to.exist; - expect(access_token).to.be.equal('token'); - done(); - nock.cleanAll(); - }); + const accessToken = await client.getAccessToken(); + expect(accessToken).to.exist; + expect(accessToken).to.be.equal('token'); }); it('should contain correct body payload', (done) => { @@ -247,19 +246,18 @@ describe('ManagementTokenProvider', () => { expect(body.client_id).to.equal('clientId'); expect(body.client_secret).to.equal('clientSecret'); expect(body.grant_type).to.equal('client_credentials'); + nock.cleanAll(); + done(); return true; }) .reply((uri, requestBody, cb) => cb(null, [200, { access_token: 'token', expires_in: 3600 }]) ); - client.getAccessToken().then(() => { - done(); - nock.cleanAll(); - }); + client.getAccessToken(); }); - it('should return access token from the cache the second call', (done) => { + it('should return access token from the cache the second call', async () => { const options = Object.assign({}, defaultOptions); options.domain = 'auth0-node-sdk-3.auth0.com'; const client = new ManagementTokenProvider(options); @@ -269,26 +267,24 @@ describe('ManagementTokenProvider', () => { expires_in: 3600, }); - client.getAccessToken().then((access_token) => { - expect(access_token).to.exist; - expect(access_token).to.be.equal('access_token'); + const clock = sinon.useFakeTimers(); + let getAccessTokenPromise = client.getAccessToken(); + await clock.runAllAsync(); + await clock.runAllAsync(); + await clock.runAllAsync(); + const accessToken = await getAccessTokenPromise; + expect(accessToken).to.exist; + expect(accessToken).to.be.equal('access_token'); - setTimeout(() => { - client - .getAccessToken() - .then((access_token) => { - expect(access_token).to.exist; - expect(access_token).to.be.equal('access_token'); - done(); - nock.cleanAll(); - }) - .catch(() => { - expect.fail(); - done(); - nock.cleanAll(); - }); - }, 40); - }); + clock.tick(40); + + getAccessTokenPromise = client.getAccessToken(); + await clock.runAllAsync(); + const accessToken2 = await getAccessTokenPromise; + expect(accessToken2).to.exist; + expect(accessToken2).to.be.equal('access_token'); + nock.cleanAll(); + clock.restore(); }); it('should request new access token when cache is expired', (done) => { diff --git a/test/management/migrations.tests.js b/test/management/migrations.tests.js index e68554cf6..7563eb351 100644 --- a/test/management/migrations.tests.js +++ b/test/management/migrations.tests.js @@ -27,19 +27,21 @@ describe('MigrationsManager', () => { describe('#constructor', () => { it('should error when no options are provided', () => { - expect(MigrationsManager).to.throw(ArgumentError, 'Must provide manager options'); + expect(() => { + new MigrationsManager(); + }).to.throw(ArgumentError, 'Must provide manager options'); }); it('should throw an error when no base URL is provided', () => { - const manager = MigrationsManager.bind(null, {}); - - expect(manager).to.throw(ArgumentError, 'Must provide a base URL for the API'); + expect(() => { + new MigrationsManager({}); + }).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); it('should throw an error when the base URL is invalid', () => { - const manager = MigrationsManager.bind(null, { baseUrl: '' }); - - expect(manager).to.throw(ArgumentError, 'The provided base URL is invalid'); + expect(() => { + new MigrationsManager({ baseUrl: '' }); + }).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); diff --git a/test/management/organizations.tests.js b/test/management/organizations.tests.js index 077770eab..d811c1c95 100644 --- a/test/management/organizations.tests.js +++ b/test/management/organizations.tests.js @@ -7,10 +7,20 @@ const OrganizationsManager = require(`../../src/management/OrganizationsManager` const { ArgumentError } = require('rest-facade'); describe('OrganizationsManager', () => { - before(function () { - this.token = 'TOKEN'; - this.organizations = new OrganizationsManager({ - headers: { authorization: `Bearer ${this.token}` }, + /** + * @type {OrganizationsManager} + */ + let organizations; + + /** + * @type {string} + */ + let token; + + before(() => { + token = 'TOKEN'; + organizations = new OrganizationsManager({ + headers: { authorization: `Bearer ${token}` }, baseUrl: API_URL, }); }); @@ -41,27 +51,29 @@ describe('OrganizationsManager', () => { ]; methods.forEach((method) => { - it(`should have a ${method} method`, function () { - expect(this.organizations[method]).to.exist.to.be.an.instanceOf(Function); + it(`should have a ${method} method`, () => { + expect(organizations[method]).to.exist.to.be.an.instanceOf(Function); }); }); }); describe('#constructor', () => { it('should error when no options are provided', () => { - expect(OrganizationsManager).to.throw(ArgumentError, 'Must provide manager options'); + expect(() => { + new OrganizationsManager(); + }).to.throw(ArgumentError, 'Must provide manager options'); }); it('should throw an error when no base URL is provided', () => { - const client = OrganizationsManager.bind(null, {}); - - expect(client).to.throw(ArgumentError, 'Must provide a base URL for the API'); + expect(() => { + new OrganizationsManager({}); + }).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); it('should throw an error when the base URL is invalid', () => { - const client = OrganizationsManager.bind(null, { baseUrl: '' }); - - expect(client).to.throw(ArgumentError, 'The provided base URL is invalid'); + expect(() => { + new OrganizationsManager({ baseUrl: '' }); + }).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); @@ -70,34 +82,34 @@ describe('OrganizationsManager', () => { this.request = nock(API_URL).get('/organizations').reply(200); }); - it('should accept a callback', function (done) { - this.organizations.getAll(() => { + it('should accept a callback', (done) => { + organizations.getAll(() => { done(); }); }); - it('should return a promise if no callback is given', function (done) { - this.organizations.getAll().then(done.bind(null, null)).catch(done.bind(null, null)); + it('should return a promise if no callback is given', (done) => { + organizations.getAll().then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function (done) { + it('should pass any errors to the promise catch handler', (done) => { nock.cleanAll(); nock(API_URL).get('/organizations').reply(500); - this.organizations.getAll().catch((err) => { + organizations.getAll().catch((err) => { expect(err).to.exist; done(); }); }); - it('should pass the body of the response to the "then" handler', function (done) { + it('should pass the body of the response to the "then" handler', (done) => { nock.cleanAll(); const data = [{ test: true }]; nock(API_URL).get('/organizations').reply(200, data); - this.organizations.getAll().then((credentials) => { + organizations.getAll().then((credentials) => { expect(credentials).to.be.an.instanceOf(Array); expect(credentials.length).to.equal(data.length); @@ -111,27 +123,27 @@ describe('OrganizationsManager', () => { it('should perform a GET request to /api/v2/organizations', function (done) { const { request } = this; - this.organizations.getAll().then(() => { + organizations.getAll().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function (done) { + it('should include the token in the Authorization header', (done) => { nock.cleanAll(); const request = nock(API_URL) .get('/organizations') - .matchHeader('Authorization', `Bearer ${this.token}`) + .matchHeader('Authorization', `Bearer ${token}`) .reply(200); - this.organizations.getAll().then(() => { + organizations.getAll().then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the parameters in the query-string', function (done) { + it('should pass the parameters in the query-string', (done) => { nock.cleanAll(); const params = { @@ -140,7 +152,7 @@ describe('OrganizationsManager', () => { }; const request = nock(API_URL).get('/organizations').query(params).reply(200); - this.organizations.getAll(params).then(() => { + organizations.getAll(params).then(() => { expect(request.isDone()).to.be.true; done(); @@ -162,11 +174,11 @@ describe('OrganizationsManager', () => { it('should accept a callback', function (done) { const params = { id: this.data.id }; - this.organizations.getByID(params, done.bind(null, null)); + organizations.getByID(params, done.bind(null, null)); }); it('should return a promise if no callback is given', function (done) { - this.organizations + organizations .getByID({ id: this.data.id }) .then(done.bind(null, null)) .catch(done.bind(null, null)); @@ -175,7 +187,7 @@ describe('OrganizationsManager', () => { it('should perform a GET request to /api/v2/organizations/:id', function (done) { const { request } = this; - this.organizations.getByID({ id: this.data.id }).then(() => { + organizations.getByID({ id: this.data.id }).then(() => { expect(request.isDone()).to.be.true; done(); @@ -187,7 +199,7 @@ describe('OrganizationsManager', () => { nock(API_URL).get(`/organizations/${this.data.id}`).reply(500); - this.organizations.getByID({ id: this.data.id }).catch((err) => { + organizations.getByID({ id: this.data.id }).catch((err) => { expect(err).to.exist; done(); @@ -199,10 +211,10 @@ describe('OrganizationsManager', () => { const request = nock(API_URL) .get(`/organizations/${this.data.id}`) - .matchHeader('Authorization', `Bearer ${this.token}`) + .matchHeader('Authorization', `Bearer ${token}`) .reply(200); - this.organizations.getByID({ id: this.data.id }).then(() => { + organizations.getByID({ id: this.data.id }).then(() => { expect(request.isDone()).to.be.true; done(); @@ -226,11 +238,11 @@ describe('OrganizationsManager', () => { it('should accept a callback', function (done) { const params = { name: this.data.name }; - this.organizations.getByName(params, done.bind(null, null)); + organizations.getByName(params, done.bind(null, null)); }); it('should return a promise if no callback is given', function (done) { - this.organizations + organizations .getByName({ name: this.data.name }) .then(done.bind(null, null)) .catch(done.bind(null, null)); @@ -239,7 +251,7 @@ describe('OrganizationsManager', () => { it('should perform a GET request to /api/v2/organizations/name/:name', function (done) { const { request } = this; - this.organizations.getByName({ name: this.data.name }).then(() => { + organizations.getByName({ name: this.data.name }).then(() => { expect(request.isDone()).to.be.true; done(); @@ -251,7 +263,7 @@ describe('OrganizationsManager', () => { nock(API_URL).get(`/organizations/${this.data.name}`).reply(500); - this.organizations.getByName({ name: this.data.name }).catch((err) => { + organizations.getByName({ name: this.data.name }).catch((err) => { expect(err).to.exist; done(); @@ -263,10 +275,10 @@ describe('OrganizationsManager', () => { const request = nock(API_URL) .get(`/organizations/name/${this.data.name}`) - .matchHeader('Authorization', `Bearer ${this.token}`) + .matchHeader('Authorization', `Bearer ${token}`) .reply(200); - this.organizations.getByName({ name: this.data.name }).then(() => { + organizations.getByName({ name: this.data.name }).then(() => { expect(request.isDone()).to.be.true; done(); @@ -285,22 +297,22 @@ describe('OrganizationsManager', () => { this.request = nock(API_URL).post('/organizations').reply(200); }); - it('should accept a callback', function (done) { - this.organizations.create(data, () => { + it('should accept a callback', (done) => { + organizations.create(data, () => { done(); }); }); - it('should return a promise if no callback is given', function (done) { - this.organizations.create(data).then(done.bind(null, null)).catch(done.bind(null, null)); + it('should return a promise if no callback is given', (done) => { + organizations.create(data).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should pass any errors to the promise catch handler', function (done) { + it('should pass any errors to the promise catch handler', (done) => { nock.cleanAll(); nock(API_URL).post('/organizations').reply(500); - this.organizations.create(data).catch((err) => { + organizations.create(data).catch((err) => { expect(err).to.exist; done(); @@ -310,34 +322,34 @@ describe('OrganizationsManager', () => { it('should perform a POST request to /api/v2/organizations', function (done) { const { request } = this; - this.organizations.create(data).then(() => { + organizations.create(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass the data in the body of the request', function (done) { + it('should pass the data in the body of the request', (done) => { nock.cleanAll(); const request = nock(API_URL).post('/organizations', data).reply(200); - this.organizations.create(data).then(() => { + organizations.create(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should include the token in the Authorization header', function (done) { + it('should include the token in the Authorization header', (done) => { nock.cleanAll(); const request = nock(API_URL) .post('/organizations') - .matchHeader('Authorization', `Bearer ${this.token}`) + .matchHeader('Authorization', `Bearer ${token}`) .reply(200); - this.organizations.create(data).then(() => { + organizations.create(data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -352,12 +364,12 @@ describe('OrganizationsManager', () => { this.request = nock(API_URL).patch(`/organizations/${this.data.id}`).reply(200, this.data); }); - it('should accept a callback', function (done) { - this.organizations.update({ id: 'org_123' }, {}, done.bind(null, null)); + it('should accept a callback', (done) => { + organizations.update({ id: 'org_123' }, {}, done.bind(null, null)); }); - it('should return a promise if no callback is given', function (done) { - this.organizations + it('should return a promise if no callback is given', (done) => { + organizations .update({ id: 'org_123' }, {}) .then(done.bind(null, null)) .catch(done.bind(null, null)); @@ -366,7 +378,7 @@ describe('OrganizationsManager', () => { it('should perform a PATCH request to /api/v2/organizations/org_123', function (done) { const { request } = this; - this.organizations.update({ id: 'org_123' }, {}).then(() => { + organizations.update({ id: 'org_123' }, {}).then(() => { expect(request.isDone()).to.be.true; done(); @@ -378,7 +390,7 @@ describe('OrganizationsManager', () => { const request = nock(API_URL).patch(`/organizations/${this.data.id}`, this.data).reply(200); - this.organizations.update({ id: 'org_123' }, this.data).then(() => { + organizations.update({ id: 'org_123' }, this.data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -390,7 +402,7 @@ describe('OrganizationsManager', () => { nock(API_URL).patch(`/organizations/${this.data.id}`).reply(500); - this.organizations.update({ id: this.data.id }, this.data).catch((err) => { + organizations.update({ id: this.data.id }, this.data).catch((err) => { expect(err).to.exist; done(); @@ -405,45 +417,45 @@ describe('OrganizationsManager', () => { this.request = nock(API_URL).delete(`/organizations/${id}`).reply(200); }); - it('should accept a callback', function (done) { - this.organizations.delete({ id }, done.bind(null, null)); + it('should accept a callback', (done) => { + organizations.delete({ id }, done.bind(null, null)); }); - it('should return a promise when no callback is given', function (done) { - this.organizations.delete({ id }).then(done.bind(null, null)); + it('should return a promise when no callback is given', (done) => { + organizations.delete({ id }).then(done.bind(null, null)); }); it(`should perform a delete request to /organizations/${id}`, function (done) { const { request } = this; - this.organizations.delete({ id }).then(() => { + organizations.delete({ id }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function (done) { + it('should pass any errors to the promise catch handler', (done) => { nock.cleanAll(); nock(API_URL).delete(`/organizations/${id}`).reply(500); - this.organizations.delete({ id }).catch((err) => { + organizations.delete({ id }).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the authorization header', function (done) { + it('should include the token in the authorization header', (done) => { nock.cleanAll(); const request = nock(API_URL) .delete(`/organizations/${id}`) - .matchHeader('authorization', `Bearer ${this.token}`) + .matchHeader('authorization', `Bearer ${token}`) .reply(200); - this.organizations.delete({ id }).then(() => { + organizations.delete({ id }).then(() => { expect(request.isDone()).to.be.true; done(); @@ -461,45 +473,45 @@ describe('OrganizationsManager', () => { this.request = nock(API_URL).get(`/organizations/${data.id}/enabled_connections`).reply(200); }); - it('should accept a callback', function (done) { - this.organizations.getEnabledConnections(data, done.bind(null, null)); + it('should accept a callback', (done) => { + organizations.getEnabledConnections(data, done.bind(null, null)); }); - it('should return a promise when no callback is given', function (done) { - this.organizations.getEnabledConnections(data).then(done.bind(null, null)); + it('should return a promise when no callback is given', (done) => { + organizations.getEnabledConnections(data).then(done.bind(null, null)); }); it('should perform a GET request to /api/v2/organizations/org_id/enabled_connections', function (done) { const { request } = this; - this.organizations.getEnabledConnections(data).then(() => { + organizations.getEnabledConnections(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function (done) { + it('should pass any errors to the promise catch handler', (done) => { nock.cleanAll(); nock(API_URL).get(`/organizations/${data.id}/enabled_connections`).reply(500); - this.organizations.getEnabledConnections(data).catch((err) => { + organizations.getEnabledConnections(data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the authorization header', function (done) { + it('should include the token in the authorization header', (done) => { nock.cleanAll(); const request = nock(API_URL) .get(`/organizations/${data.id}/enabled_connections`) - .matchHeader('authorization', `Bearer ${this.token}`) + .matchHeader('authorization', `Bearer ${token}`) .reply(200); - this.organizations.getEnabledConnections(data).then(() => { + organizations.getEnabledConnections(data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -519,47 +531,47 @@ describe('OrganizationsManager', () => { .reply(200); }); - it('should accept a callback', function (done) { - this.organizations.getEnabledConnection(data, done.bind(null, null)); + it('should accept a callback', (done) => { + organizations.getEnabledConnection(data, done.bind(null, null)); }); - it('should return a promise when no callback is given', function (done) { - this.organizations.getEnabledConnection(data).then(done.bind(null, null)); + it('should return a promise when no callback is given', (done) => { + organizations.getEnabledConnection(data).then(done.bind(null, null)); }); it('should perform a GET request to /api/v2/organizations/rol_ID/enabled_connections/con_id', function (done) { const { request } = this; - this.organizations.getEnabledConnection(data).then(() => { + organizations.getEnabledConnection(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function (done) { + it('should pass any errors to the promise catch handler', (done) => { nock.cleanAll(); nock(API_URL) .get(`/organizations/${data.id}/enabled_connections/${data.connection_id}`) .reply(500); - this.organizations.getEnabledConnection(data).catch((err) => { + organizations.getEnabledConnection(data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the authorization header', function (done) { + it('should include the token in the authorization header', (done) => { nock.cleanAll(); const request = nock(API_URL) .get(`/organizations/${data.id}/enabled_connections/${data.connection_id}`) - .matchHeader('authorization', `Bearer ${this.token}`) + .matchHeader('authorization', `Bearer ${token}`) .reply(200); - this.organizations.getEnabledConnection(data).then(() => { + organizations.getEnabledConnection(data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -580,13 +592,13 @@ describe('OrganizationsManager', () => { }); it('should accept a callback', function (done) { - this.organizations.addEnabledConnection(this.data, {}, () => { + organizations.addEnabledConnection(this.data, {}, () => { done(); }); }); it('should return a promise if no callback is given', function (done) { - this.organizations + organizations .addEnabledConnection(this.data, {}) .then(done.bind(null, null)) .catch(done.bind(null, null)); @@ -597,7 +609,7 @@ describe('OrganizationsManager', () => { nock(API_URL).post(`/organizations/${this.data.id}/enabled_connections`).reply(500); - this.organizations.addEnabledConnection(this.data, {}).catch((err) => { + organizations.addEnabledConnection(this.data, {}).catch((err) => { expect(err).to.exist; done(); @@ -607,24 +619,22 @@ describe('OrganizationsManager', () => { it('should perform a POST request to /api/v2/organizations/org_id/enabled_connections', function (done) { const { request } = this; - this.organizations.addEnabledConnection(this.data, this.body).then(() => { + organizations.addEnabledConnection(this.data, this.body).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should return error when id is not sent', function () { - const _this = this; + it('should return error when id is not sent', () => { expect(() => { - _this.organizations.addEnabledConnection({ id: null }, {}, () => {}); + organizations.addEnabledConnection({ id: null }, {}, () => {}); }).to.throw('The organization ID passed in params cannot be null or undefined'); }); - it('should return error when id is not a string', function () { - const _this = this; + it('should return error when id is not a string', () => { expect(() => { - _this.organizations.addEnabledConnection({ id: 123 }, {}, () => {}); + organizations.addEnabledConnection({ id: 123 }, {}, () => {}); }).to.throw('The organization ID has to be a string'); }); @@ -635,7 +645,7 @@ describe('OrganizationsManager', () => { .post(`/organizations/${this.data.id}/enabled_connections`, this.body) .reply(200); - this.organizations.addEnabledConnection(this.data, this.body).then(() => { + organizations.addEnabledConnection(this.data, this.body).then(() => { expect(request.isDone()).to.be.true; done(); @@ -647,10 +657,10 @@ describe('OrganizationsManager', () => { const request = nock(API_URL) .post(`/organizations/${this.data.id}/enabled_connections`) - .matchHeader('Authorization', `Bearer ${this.token}`) + .matchHeader('Authorization', `Bearer ${token}`) .reply(200); - this.organizations.addEnabledConnection(this.data, {}).then(() => { + organizations.addEnabledConnection(this.data, {}).then(() => { expect(request.isDone()).to.be.true; done(); @@ -672,13 +682,13 @@ describe('OrganizationsManager', () => { }); it('should accept a callback', function (done) { - this.organizations.updateEnabledConnection(this.data, this.body, () => { + organizations.updateEnabledConnection(this.data, this.body, () => { done(); }); }); it('should return a promise if no callback is given', function (done) { - this.organizations + organizations .updateEnabledConnection(this.data, this.body) .then(done.bind(null, null)) .catch(done.bind(null, null)); @@ -691,7 +701,7 @@ describe('OrganizationsManager', () => { .patch(`/organizations/${this.data.id}/enabled_connections/${this.data.connection_id}`) .reply(500); - this.organizations.updateEnabledConnection(this.data, this.body).catch((err) => { + organizations.updateEnabledConnection(this.data, this.body).catch((err) => { expect(err).to.exist; done(); @@ -701,46 +711,34 @@ describe('OrganizationsManager', () => { it('should perform a PATCH request to /api/v2/organizations/org_id/enabled_connections/conn_id', function (done) { const { request } = this; - this.organizations.updateEnabledConnection(this.data, this.body).then(() => { + organizations.updateEnabledConnection(this.data, this.body).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should return error when id is not sent', function () { - const _this = this; + it('should return error when id is not sent', () => { expect(() => { - _this.organizations.updateEnabledConnection({ id: null }, {}, () => {}); + organizations.updateEnabledConnection({ id: null }, {}, () => {}); }).to.throw('The organization ID passed in params cannot be null or undefined'); }); - it('should return error when id is not a string', function () { - const _this = this; + it('should return error when id is not a string', () => { expect(() => { - _this.organizations.updateEnabledConnection({ id: 123 }, {}, () => {}); + organizations.updateEnabledConnection({ id: 123 }, {}, () => {}); }).to.throw('The organization ID has to be a string'); }); - it('should return error when connection_id is not sent', function () { - const _this = this; + it('should return error when connection_id is not sent', () => { expect(() => { - _this.organizations.updateEnabledConnection( - { id: 'org_123', connection_id: null }, - {}, - () => {} - ); + organizations.updateEnabledConnection({ id: 'org_123', connection_id: null }, {}, () => {}); }).to.throw('The connection ID passed in params cannot be null or undefined'); }); - it('should return error when connection_id is not a string', function () { - const _this = this; + it('should return error when connection_id is not a string', () => { expect(() => { - _this.organizations.updateEnabledConnection( - { id: 'org_123', connection_id: 123 }, - {}, - () => {} - ); + organizations.updateEnabledConnection({ id: 'org_123', connection_id: 123 }, {}, () => {}); }).to.throw('The connection ID has to be a string'); }); @@ -754,7 +752,7 @@ describe('OrganizationsManager', () => { ) .reply(200); - this.organizations.updateEnabledConnection(this.data, this.body).then(() => { + organizations.updateEnabledConnection(this.data, this.body).then(() => { expect(request.isDone()).to.be.true; done(); @@ -766,10 +764,10 @@ describe('OrganizationsManager', () => { const request = nock(API_URL) .patch(`/organizations/${this.data.id}/enabled_connections/${this.data.connection_id}`) - .matchHeader('Authorization', `Bearer ${this.token}`) + .matchHeader('Authorization', `Bearer ${token}`) .reply(200); - this.organizations.updateEnabledConnection(this.data, this.body).then(() => { + organizations.updateEnabledConnection(this.data, this.body).then(() => { expect(request.isDone()).to.be.true; done(); @@ -789,45 +787,40 @@ describe('OrganizationsManager', () => { .reply(200); }); - it('should validate empty organizationId', function () { - const _this = this; + it('should validate empty organizationId', () => { expect(() => { - _this.organizations.removeEnabledConnection({ id: null }, () => {}); + organizations.removeEnabledConnection({ id: null }, () => {}); }).to.throw('The organization ID passed in params cannot be null or undefined'); }); it('should validate empty connectionId', function () { const _this = this; expect(() => { - _this.organizations.removeEnabledConnection({ id: _this.data.id }, () => {}); + organizations.removeEnabledConnection({ id: _this.data.id }, () => {}); }).to.throw('The connection ID passed in params cannot be null or undefined'); }); - it('should validate non-string organizationId', function () { - const _this = this; + it('should validate non-string organizationId', () => { expect(() => { - _this.organizations.removeEnabledConnection({ id: 123 }, () => {}); + organizations.removeEnabledConnection({ id: 123 }, () => {}); }).to.throw('The organization ID has to be a string'); }); it('should validate non-string connectionId', function () { const _this = this; expect(() => { - _this.organizations.removeEnabledConnection( - { id: _this.data.id, connection_id: 123 }, - () => {} - ); + organizations.removeEnabledConnection({ id: _this.data.id, connection_id: 123 }, () => {}); }).to.throw('The connection ID has to be a string'); }); it('should accept a callback', function (done) { - this.organizations.removeEnabledConnection(this.data, () => { + organizations.removeEnabledConnection(this.data, () => { done(); }); }); it('should return a promise if no callback is given', function (done) { - this.organizations + organizations .removeEnabledConnection(this.data) .then(done.bind(null, null)) .catch(done.bind(null, null)); @@ -840,7 +833,7 @@ describe('OrganizationsManager', () => { .delete(`/organizations/${this.data.id}/enabled_connections/${this.data.connection_id}`) .reply(500); - this.organizations.removeEnabledConnection(this.data, {}).catch((err) => { + organizations.removeEnabledConnection(this.data, {}).catch((err) => { expect(err).to.exist; done(); @@ -850,7 +843,7 @@ describe('OrganizationsManager', () => { it('should perform a DELETE request to /api/v2/organizations/organization_id/enabled_connections/connection_id', function (done) { const { request } = this; - this.organizations.removeEnabledConnection(this.data).then(() => { + organizations.removeEnabledConnection(this.data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -862,10 +855,10 @@ describe('OrganizationsManager', () => { const request = nock(API_URL) .delete(`/organizations/${this.data.id}/enabled_connections/${this.data.connection_id}`) - .matchHeader('Authorization', `Bearer ${this.token}`) + .matchHeader('Authorization', `Bearer ${token}`) .reply(200); - this.organizations.removeEnabledConnection(this.data, {}).then(() => { + organizations.removeEnabledConnection(this.data, {}).then(() => { expect(request.isDone()).to.be.true; done(); @@ -883,45 +876,45 @@ describe('OrganizationsManager', () => { this.request = nock(API_URL).get(`/organizations/${data.id}/members`).reply(200); }); - it('should accept a callback', function (done) { - this.organizations.getMembers(data, done.bind(null, null)); + it('should accept a callback', (done) => { + organizations.getMembers(data, done.bind(null, null)); }); - it('should return a promise when no callback is given', function (done) { - this.organizations.getMembers(data).then(done.bind(null, null)); + it('should return a promise when no callback is given', (done) => { + organizations.getMembers(data).then(done.bind(null, null)); }); it('should perform a GET request to /api/v2/organizations/org_ID/members', function (done) { const { request } = this; - this.organizations.getMembers(data).then(() => { + organizations.getMembers(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function (done) { + it('should pass any errors to the promise catch handler', (done) => { nock.cleanAll(); nock(API_URL).get(`/organizations/${data.id}/members`).reply(500); - this.organizations.getMembers(data).catch((err) => { + organizations.getMembers(data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the authorization header', function (done) { + it('should include the token in the authorization header', (done) => { nock.cleanAll(); const request = nock(API_URL) .get(`/organizations/${data.id}/members`) - .matchHeader('authorization', `Bearer ${this.token}`) + .matchHeader('authorization', `Bearer ${token}`) .reply(200); - this.organizations.getMembers(data).then(() => { + organizations.getMembers(data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -940,13 +933,13 @@ describe('OrganizationsManager', () => { }); it('should accept a callback', function (done) { - this.organizations.addMembers(this.data, {}, () => { + organizations.addMembers(this.data, {}, () => { done(); }); }); it('should return a promise if no callback is given', function (done) { - this.organizations + organizations .addMembers(this.data, {}) .then(done.bind(null, null)) .catch(done.bind(null, null)); @@ -957,7 +950,7 @@ describe('OrganizationsManager', () => { nock(API_URL).post(`/organizations/${this.data.id}/members`).reply(500); - this.organizations.addMembers(this.data, {}).catch((err) => { + organizations.addMembers(this.data, {}).catch((err) => { expect(err).to.exist; done(); @@ -967,24 +960,22 @@ describe('OrganizationsManager', () => { it('should perform a POST request to /api/v2/organizations/org_id/members', function (done) { const { request } = this; - this.organizations.addMembers(this.data, {}).then(() => { + organizations.addMembers(this.data, {}).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should return error when id is not sent', function () { - const _this = this; + it('should return error when id is not sent', () => { expect(() => { - _this.organizations.addMembers({ id: null }, {}, () => {}); + organizations.addMembers({ id: null }, {}, () => {}); }).to.throw('The organization ID passed in params cannot be null or undefined'); }); - it('should return error when id is not sent', function () { - const _this = this; + it('should return error when id is not sent', () => { expect(() => { - _this.organizations.addMembers({ id: 123 }, {}, () => {}); + organizations.addMembers({ id: 123 }, {}, () => {}); }).to.throw('The organization ID has to be a string'); }); @@ -995,7 +986,7 @@ describe('OrganizationsManager', () => { .post(`/organizations/${this.data.id}/members`, this.body) .reply(200); - this.organizations.addMembers(this.data, this.body).then(() => { + organizations.addMembers(this.data, this.body).then(() => { expect(request.isDone()).to.be.true; done(); @@ -1007,10 +998,10 @@ describe('OrganizationsManager', () => { const request = nock(API_URL) .post(`/organizations/${this.data.id}/members`) - .matchHeader('Authorization', `Bearer ${this.token}`) + .matchHeader('Authorization', `Bearer ${token}`) .reply(200); - this.organizations.addMembers(this.data, {}).then(() => { + organizations.addMembers(this.data, {}).then(() => { expect(request.isDone()).to.be.true; done(); @@ -1029,22 +1020,21 @@ describe('OrganizationsManager', () => { this.request = nock(API_URL).delete(`/organizations/${this.data.id}/members`, {}).reply(200); }); - it('should validate empty organizationId', function () { - const _this = this; + it('should validate empty organizationId', () => { expect(function () { - _this.organizations.removeMembers({ id: null }, this.body, () => {}); + organizations.removeMembers({ id: null }, this.body, () => {}); }).to.throw('The organization ID passed in params cannot be null or undefined'); }); it('should validate non-string organizationId', function () { const _this = this; expect(() => { - _this.organizations.removeMembers({ id: 123 }, _this.body, () => {}); + organizations.removeMembers({ id: 123 }, _this.body, () => {}); }).to.throw('The organization ID has to be a string'); }); it('should return a promise if no callback is given', function (done) { - this.organizations + organizations .removeMembers(this.data, this.body) .then(done.bind(null, null)) .catch(done.bind(null, null)); @@ -1055,7 +1045,7 @@ describe('OrganizationsManager', () => { nock(API_URL).delete(`/organizations/${this.data.id}/members`).reply(500); - this.organizations.removeMembers(this.data, this.body).catch((err) => { + organizations.removeMembers(this.data, this.body).catch((err) => { expect(err).to.exist; done(); @@ -1067,7 +1057,7 @@ describe('OrganizationsManager', () => { .delete(`/organizations/${this.data.id}/members`, this.body) .reply(200); - this.organizations.removeMembers(this.data, this.body, () => { + organizations.removeMembers(this.data, this.body, () => { expect(request.isDone()).to.be.true; done(); @@ -1079,10 +1069,10 @@ describe('OrganizationsManager', () => { const request = nock(API_URL) .delete(`/organizations/${this.data.id}/members`, this.body) - .matchHeader('Authorization', `Bearer ${this.token}`) + .matchHeader('Authorization', `Bearer ${token}`) .reply(200); - this.organizations.removeMembers(this.data, this.body).then(() => { + organizations.removeMembers(this.data, this.body).then(() => { expect(request.isDone()).to.be.true; done(); @@ -1103,45 +1093,45 @@ describe('OrganizationsManager', () => { .reply(200); }); - it('should accept a callback', function (done) { - this.organizations.getMemberRoles(data, done.bind(null, null)); + it('should accept a callback', (done) => { + organizations.getMemberRoles(data, done.bind(null, null)); }); - it('should return a promise when no callback is given', function (done) { - this.organizations.getMemberRoles(data).then(done.bind(null, null)); + it('should return a promise when no callback is given', (done) => { + organizations.getMemberRoles(data).then(done.bind(null, null)); }); it('should perform a GET request to /api/v2/organizations/org_ID/members/user_id/roles', function (done) { const { request } = this; - this.organizations.getMemberRoles(data).then(() => { + organizations.getMemberRoles(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function (done) { + it('should pass any errors to the promise catch handler', (done) => { nock.cleanAll(); nock(API_URL).get(`/organizations/${data.id}/members/${data.user_id}/roles`).reply(500); - this.organizations.getMemberRoles(data).catch((err) => { + organizations.getMemberRoles(data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the authorization header', function (done) { + it('should include the token in the authorization header', (done) => { nock.cleanAll(); const request = nock(API_URL) .get(`/organizations/${data.id}/members/${data.user_id}/roles`) - .matchHeader('authorization', `Bearer ${this.token}`) + .matchHeader('authorization', `Bearer ${token}`) .reply(200); - this.organizations.getMemberRoles(data).then(() => { + organizations.getMemberRoles(data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -1163,13 +1153,13 @@ describe('OrganizationsManager', () => { }); it('should accept a callback', function (done) { - this.organizations.addMemberRoles(this.data, this.body, () => { + organizations.addMemberRoles(this.data, this.body, () => { done(); }); }); it('should return a promise if no callback is given', function (done) { - this.organizations + organizations .addMemberRoles(this.data, this.body) .then(done.bind(null, null)) .catch(done.bind(null, null)); @@ -1182,7 +1172,7 @@ describe('OrganizationsManager', () => { .post(`/organizations/${this.data.id}/members/${this.data.user_id}/roles`) .reply(500); - this.organizations.addMemberRoles(this.data, {}).catch((err) => { + organizations.addMemberRoles(this.data, {}).catch((err) => { expect(err).to.exist; done(); @@ -1192,38 +1182,34 @@ describe('OrganizationsManager', () => { it('should perform a POST request to /api/v2/organizations/org_id/members/user_id/roles', function (done) { const { request } = this; - this.organizations.addMemberRoles(this.data, this.body).then(() => { + organizations.addMemberRoles(this.data, this.body).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should return error when id is not sent', function () { - const _this = this; + it('should return error when id is not sent', () => { expect(() => { - _this.organizations.addMemberRoles({ id: null }, {}, () => {}); + organizations.addMemberRoles({ id: null }, {}, () => {}); }).to.throw('The organization ID passed in params cannot be null or undefined'); }); - it('should return error when id is not sent', function () { - const _this = this; + it('should return error when id is not sent', () => { expect(() => { - _this.organizations.addMemberRoles({ id: 123 }, {}, () => {}); + organizations.addMemberRoles({ id: 123 }, {}, () => {}); }).to.throw('The organization ID has to be a string'); }); - it('should return error when id is not sent', function () { - const _this = this; + it('should return error when id is not sent', () => { expect(() => { - _this.organizations.addMemberRoles({ id: 'org_123', user_id: null }, {}, () => {}); + organizations.addMemberRoles({ id: 'org_123', user_id: null }, {}, () => {}); }).to.throw('The user ID passed in params cannot be null or undefined'); }); - it('should return error when id is not sent', function () { - const _this = this; + it('should return error when id is not sent', () => { expect(() => { - _this.organizations.addMemberRoles({ id: 'org_123', user_id: 123 }, {}, () => {}); + organizations.addMemberRoles({ id: 'org_123', user_id: 123 }, {}, () => {}); }).to.throw('The user ID has to be a string'); }); @@ -1234,7 +1220,7 @@ describe('OrganizationsManager', () => { .post(`/organizations/${this.data.id}/members/${this.data.user_id}/roles`, this.body) .reply(200); - this.organizations.addMemberRoles(this.data, this.body).then(() => { + organizations.addMemberRoles(this.data, this.body).then(() => { expect(request.isDone()).to.be.true; done(); @@ -1246,10 +1232,10 @@ describe('OrganizationsManager', () => { const request = nock(API_URL) .post(`/organizations/${this.data.id}/members/${this.data.user_id}/roles`) - .matchHeader('Authorization', `Bearer ${this.token}`) + .matchHeader('Authorization', `Bearer ${token}`) .reply(200); - this.organizations.addMemberRoles(this.data, {}).then(() => { + organizations.addMemberRoles(this.data, {}).then(() => { expect(request.isDone()).to.be.true; done(); @@ -1271,22 +1257,21 @@ describe('OrganizationsManager', () => { .reply(200); }); - it('should validate empty organizationId', function () { - const _this = this; + it('should validate empty organizationId', () => { expect(function () { - _this.organizations.removeMemberRoles({ id: null }, this.body, () => {}); + organizations.removeMemberRoles({ id: null }, this.body, () => {}); }).to.throw('The organization ID passed in params cannot be null or undefined'); }); it('should validate non-string organizationId', function () { const _this = this; expect(() => { - _this.organizations.removeMemberRoles({ id: 123 }, _this.body, () => {}); + organizations.removeMemberRoles({ id: 123 }, _this.body, () => {}); }).to.throw('The organization ID has to be a string'); }); it('should return a promise if no callback is given', function (done) { - this.organizations + organizations .removeMemberRoles(this.data, this.body) .then(done.bind(null, null)) .catch(done.bind(null, null)); @@ -1299,24 +1284,22 @@ describe('OrganizationsManager', () => { .delete(`/organizations/${this.data.id}/members/${this.data.user_id}/roles`) .reply(500); - this.organizations.removeMemberRoles(this.data, this.body).catch((err) => { + organizations.removeMemberRoles(this.data, this.body).catch((err) => { expect(err).to.exist; done(); }); }); - it('should return error when id is not sent', function () { - const _this = this; + it('should return error when id is not sent', () => { expect(() => { - _this.organizations.removeMemberRoles({ id: 'org_123', user_id: null }, {}, () => {}); + organizations.removeMemberRoles({ id: 'org_123', user_id: null }, {}, () => {}); }).to.throw('The user ID passed in params cannot be null or undefined'); }); - it('should return error when id is not sent', function () { - const _this = this; + it('should return error when id is not sent', () => { expect(() => { - _this.organizations.removeMemberRoles({ id: 'org_123', user_id: 123 }, {}, () => {}); + organizations.removeMemberRoles({ id: 'org_123', user_id: 123 }, {}, () => {}); }).to.throw('The user ID has to be a string'); }); @@ -1325,7 +1308,7 @@ describe('OrganizationsManager', () => { .delete(`/organizations/${this.data.id}/members/${this.data.user_id}/roles`, this.body) .reply(200); - this.organizations.removeMemberRoles(this.data, this.body, () => { + organizations.removeMemberRoles(this.data, this.body, () => { expect(request.isDone()).to.be.true; done(); @@ -1337,10 +1320,10 @@ describe('OrganizationsManager', () => { const request = nock(API_URL) .delete(`/organizations/${this.data.id}/members/${this.data.user_id}/roles`, this.body) - .matchHeader('Authorization', `Bearer ${this.token}`) + .matchHeader('Authorization', `Bearer ${token}`) .reply(200); - this.organizations.removeMemberRoles(this.data, this.body).then(() => { + organizations.removeMemberRoles(this.data, this.body).then(() => { expect(request.isDone()).to.be.true; done(); @@ -1358,45 +1341,45 @@ describe('OrganizationsManager', () => { this.request = nock(API_URL).get(`/organizations/${data.id}/invitations`).reply(200); }); - it('should accept a callback', function (done) { - this.organizations.getInvitations(data, done.bind(null, null)); + it('should accept a callback', (done) => { + organizations.getInvitations(data, done.bind(null, null)); }); - it('should return a promise when no callback is given', function (done) { - this.organizations.getInvitations(data).then(done.bind(null, null)); + it('should return a promise when no callback is given', (done) => { + organizations.getInvitations(data).then(done.bind(null, null)); }); it('should perform a GET request to /api/v2/organizations/org_ID/invitations', function (done) { const { request } = this; - this.organizations.getInvitations(data).then(() => { + organizations.getInvitations(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function (done) { + it('should pass any errors to the promise catch handler', (done) => { nock.cleanAll(); nock(API_URL).get(`/organizations/${data.id}/invitations`).reply(500); - this.organizations.getInvitations(data).catch((err) => { + organizations.getInvitations(data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should include the token in the authorization header', function (done) { + it('should include the token in the authorization header', (done) => { nock.cleanAll(); const request = nock(API_URL) .get(`/organizations/${data.id}/invitations`) - .matchHeader('authorization', `Bearer ${this.token}`) + .matchHeader('authorization', `Bearer ${token}`) .reply(200); - this.organizations.getInvitations(data).then(() => { + organizations.getInvitations(data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -1416,73 +1399,69 @@ describe('OrganizationsManager', () => { .reply(200); }); - it('should accept a callback', function (done) { - this.organizations.getInvitation(data, done.bind(null, null)); + it('should accept a callback', (done) => { + organizations.getInvitation(data, done.bind(null, null)); }); - it('should return a promise when no callback is given', function (done) { - this.organizations.getInvitation(data).then(done.bind(null, null)); + it('should return a promise when no callback is given', (done) => { + organizations.getInvitation(data).then(done.bind(null, null)); }); it('should perform a GET request to /api/v2/organizations/rol_ID/invitations/inv_id', function (done) { const { request } = this; - this.organizations.getInvitation(data).then(() => { + organizations.getInvitation(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should pass any errors to the promise catch handler', function (done) { + it('should pass any errors to the promise catch handler', (done) => { nock.cleanAll(); nock(API_URL).get(`/organizations/${data.id}/invitations/${data.invitation_id}`).reply(500); - this.organizations.getInvitation(data).catch((err) => { + organizations.getInvitation(data).catch((err) => { expect(err).to.exist; done(); }); }); - it('should return error when id is not sent', function () { - const _this = this; + it('should return error when id is not sent', () => { expect(() => { - _this.organizations.getInvitation({ id: null }, () => {}); + organizations.getInvitation({ id: null }, () => {}); }).to.throw('The organization ID passed in params cannot be null or undefined'); }); - it('should return error when id is not sent', function () { - const _this = this; + it('should return error when id is not sent', () => { expect(() => { - _this.organizations.getInvitation({ id: 123 }, () => {}); + organizations.getInvitation({ id: 123 }, () => {}); }).to.throw('The organization ID has to be a string'); }); - it('should return error when id is not sent', function () { - const _this = this; + it('should return error when id is not sent', () => { expect(() => { - _this.organizations.getInvitation({ id: 'org_123', invitation_id: null }, () => {}); + organizations.getInvitation({ id: 'org_123', invitation_id: null }, () => {}); }).to.throw('The invitation ID passed in params cannot be null or undefined'); }); - it('should return error when id is not sent', function () { - const _this = this; + it('should return error when id is not sent', () => { expect(() => { - _this.organizations.getInvitation({ id: 'org_123', invitation_id: 123 }, () => {}); + organizations.getInvitation({ id: 'org_123', invitation_id: 123 }, () => {}); }).to.throw('The invitation ID has to be a string'); }); - it('should include the token in the authorization header', function (done) { + it('should include the token in the authorization header', (done) => { nock.cleanAll(); const request = nock(API_URL) .get(`/organizations/${data.id}/invitations/${data.invitation_id}`) - .matchHeader('authorization', `Bearer ${this.token}`) + .matchHeader('authorization', `Bearer ${token}`) .reply(200); - this.organizations.getInvitation(data).then(() => { + organizations.getInvitation(data).then(() => { expect(request.isDone()).to.be.true; done(); @@ -1506,13 +1485,13 @@ describe('OrganizationsManager', () => { }); it('should accept a callback', function (done) { - this.organizations.createInvitation(this.data, {}, () => { + organizations.createInvitation(this.data, {}, () => { done(); }); }); it('should return a promise if no callback is given', function (done) { - this.organizations + organizations .createInvitation(this.data, {}) .then(done.bind(null, null)) .catch(done.bind(null, null)); @@ -1523,7 +1502,7 @@ describe('OrganizationsManager', () => { nock(API_URL).post(`/organizations/${this.data.id}/invitations`).reply(500); - this.organizations.createInvitation(this.data, {}).catch((err) => { + organizations.createInvitation(this.data, {}).catch((err) => { expect(err).to.exist; done(); @@ -1533,24 +1512,22 @@ describe('OrganizationsManager', () => { it('should perform a POST request to /api/v2/organizations/org_id/invitations', function (done) { const { request } = this; - this.organizations.createInvitation(this.data, {}).then(() => { + organizations.createInvitation(this.data, {}).then(() => { expect(request.isDone()).to.be.true; done(); }); }); - it('should return error when id is not sent', function () { - const _this = this; + it('should return error when id is not sent', () => { expect(() => { - _this.organizations.createInvitation({ id: null }, {}, () => {}); + organizations.createInvitation({ id: null }, {}, () => {}); }).to.throw('The organization ID passed in params cannot be null or undefined'); }); - it('should return error when id is not sent', function () { - const _this = this; + it('should return error when id is not sent', () => { expect(() => { - _this.organizations.createInvitation({ id: 123 }, {}, () => {}); + organizations.createInvitation({ id: 123 }, {}, () => {}); }).to.throw('The organization ID has to be a string'); }); @@ -1561,7 +1538,7 @@ describe('OrganizationsManager', () => { .post(`/organizations/${this.data.id}/invitations`, this.body) .reply(200); - this.organizations.createInvitation(this.data, this.body).then(() => { + organizations.createInvitation(this.data, this.body).then(() => { expect(request.isDone()).to.be.true; done(); @@ -1573,10 +1550,10 @@ describe('OrganizationsManager', () => { const request = nock(API_URL) .post(`/organizations/${this.data.id}/invitations`) - .matchHeader('Authorization', `Bearer ${this.token}`) + .matchHeader('Authorization', `Bearer ${token}`) .reply(200); - this.organizations.createInvitation(this.data, {}).then(() => { + organizations.createInvitation(this.data, {}).then(() => { expect(request.isDone()).to.be.true; done(); @@ -1596,22 +1573,20 @@ describe('OrganizationsManager', () => { .reply(200); }); - it('should validate empty organizationId', function () { - const _this = this; + it('should validate empty organizationId', () => { expect(() => { - _this.organizations.deleteInvitation({ id: null }, () => {}); + organizations.deleteInvitation({ id: null }, () => {}); }).to.throw('The organization ID passed in params cannot be null or undefined'); }); - it('should validate non-string organizationId', function () { - const _this = this; + it('should validate non-string organizationId', () => { expect(() => { - _this.organizations.deleteInvitation({ id: 123 }, () => {}); + organizations.deleteInvitation({ id: 123 }, () => {}); }).to.throw('The organization ID has to be a string'); }); it('should return a promise if no callback is given', function (done) { - this.organizations + organizations .removeMembers(this.data) .then(done.bind(null, null)) .catch(done.bind(null, null)); @@ -1624,7 +1599,7 @@ describe('OrganizationsManager', () => { .delete(`/organizations/${this.data.id}/invitations/${this.data.invitation_id}`, {}) .reply(500); - this.organizations.deleteInvitation(this.data).catch((err) => { + organizations.deleteInvitation(this.data).catch((err) => { expect(err).to.exist; done(); @@ -1638,24 +1613,22 @@ describe('OrganizationsManager', () => { .delete(`/organizations/${this.data.id}/invitations/${this.data.invitation_id}`, {}) .reply(200); - this.organizations.deleteInvitation(this.data, () => { + organizations.deleteInvitation(this.data, () => { expect(request.isDone()).to.be.true; done(); }); }); - it('should return error when id is not sent', function () { - const _this = this; + it('should return error when id is not sent', () => { expect(() => { - _this.organizations.deleteInvitation({ id: 'org_123', invitation_id: null }, () => {}); + organizations.deleteInvitation({ id: 'org_123', invitation_id: null }, () => {}); }).to.throw('The invitation ID passed in params cannot be null or undefined'); }); - it('should return error when id is not sent', function () { - const _this = this; + it('should return error when id is not sent', () => { expect(() => { - _this.organizations.deleteInvitation({ id: 'org_123', invitation_id: 123 }, () => {}); + organizations.deleteInvitation({ id: 'org_123', invitation_id: 123 }, () => {}); }).to.throw('The invitation ID has to be a string'); }); @@ -1664,10 +1637,10 @@ describe('OrganizationsManager', () => { const request = nock(API_URL) .delete(`/organizations/${this.data.id}/invitations/${this.data.invitation_id}`, {}) - .matchHeader('Authorization', `Bearer ${this.token}`) + .matchHeader('Authorization', `Bearer ${token}`) .reply(200); - this.organizations.deleteInvitation(this.data).then(() => { + organizations.deleteInvitation(this.data).then(() => { expect(request.isDone()).to.be.true; done(); diff --git a/test/management/prompts.tests.js b/test/management/prompts.tests.js index e08920b04..b1bd439d2 100644 --- a/test/management/prompts.tests.js +++ b/test/management/prompts.tests.js @@ -27,19 +27,21 @@ describe('PromptsManager', () => { describe('#constructor', () => { it('should error when no options are provided', () => { - expect(PromptsManager).to.throw(ArgumentError, 'Must provide manager options'); + expect(() => { + new PromptsManager(); + }).to.throw(ArgumentError, 'Must provide manager options'); }); it('should throw an error when no base URL is provided', () => { - const client = PromptsManager.bind(null, {}); - - expect(client).to.throw(ArgumentError, 'Must provide a base URL for the API'); + expect(() => { + new PromptsManager({}); + }).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); it('should throw an error when the base URL is invalid', () => { - const client = PromptsManager.bind(null, { baseUrl: '' }); - - expect(client).to.throw(ArgumentError, 'The provided base URL is invalid'); + expect(() => { + new PromptsManager({ baseUrl: '' }); + }).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); diff --git a/test/management/resource-servers.tests.js b/test/management/resource-servers.tests.js index 88261f995..fe391244b 100644 --- a/test/management/resource-servers.tests.js +++ b/test/management/resource-servers.tests.js @@ -33,22 +33,21 @@ describe('ResourceServersManager', () => { describe('#constructor', () => { it('should error when no options are provided', () => { - expect(ResourceServersManager).to.throw( - ArgumentError, - 'Must provide resource server options' - ); + expect(() => { + new ResourceServersManager(); + }).to.throw(ArgumentError, 'Must provide resource server options'); }); it('should throw an error when no base URL is provided', () => { - const resourceServerManager = ResourceServersManager.bind(null, {}); - - expect(resourceServerManager).to.throw(ArgumentError, 'Must provide a base URL for the API'); + expect(() => { + new ResourceServersManager({}); + }).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); it('should throw an error when the base URL is invalid', () => { - const resourceServerManager = ResourceServersManager.bind(null, { baseUrl: '' }); - - expect(resourceServerManager).to.throw(ArgumentError, 'The provided base URL is invalid'); + expect(() => { + new ResourceServersManager({ baseUrl: '' }); + }).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); diff --git a/test/management/roles.tests.js b/test/management/roles.tests.js index 7ce428fde..6891caee8 100644 --- a/test/management/roles.tests.js +++ b/test/management/roles.tests.js @@ -38,19 +38,21 @@ describe('RolesManager', () => { describe('#constructor', () => { it('should error when no options are provided', () => { - expect(RolesManager).to.throw(ArgumentError, 'Must provide manager options'); + expect(() => { + new RolesManager(); + }).to.throw(ArgumentError, 'Must provide manager options'); }); it('should throw an error when no base URL is provided', () => { - const client = RolesManager.bind(null, {}); - - expect(client).to.throw(ArgumentError, 'Must provide a base URL for the API'); + expect(() => { + new RolesManager({}); + }).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); it('should throw an error when the base URL is invalid', () => { - const client = RolesManager.bind(null, { baseUrl: '' }); - - expect(client).to.throw(ArgumentError, 'The provided base URL is invalid'); + expect(() => { + new RolesManager({ baseUrl: '' }); + }).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); diff --git a/test/management/rules-configs.tests.js b/test/management/rules-configs.tests.js index 97c819471..ce6d4c378 100644 --- a/test/management/rules-configs.tests.js +++ b/test/management/rules-configs.tests.js @@ -27,19 +27,21 @@ describe('RulesConfigsManager', () => { describe('#constructor', () => { it('should error when no options are provided', () => { - expect(RulesConfigsManager).to.throw(ArgumentError, 'Must provide manager options'); + expect(() => { + new RulesConfigsManager(); + }).to.throw(ArgumentError, 'Must provide manager options'); }); it('should throw an error when no base URL is provided', () => { - const client = RulesConfigsManager.bind(null, {}); - - expect(client).to.throw(ArgumentError, 'Must provide a base URL for the API'); + expect(() => { + new RulesConfigsManager({}); + }).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); it('should throw an error when the base URL is invalid', () => { - const client = RulesConfigsManager.bind(null, { baseUrl: '' }); - - expect(client).to.throw(ArgumentError, 'The provided base URL is invalid'); + expect(() => { + new RulesConfigsManager({ baseUrl: '' }); + }).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); diff --git a/test/management/rules.tests.js b/test/management/rules.tests.js index 565e99b24..67afffe19 100644 --- a/test/management/rules.tests.js +++ b/test/management/rules.tests.js @@ -27,19 +27,21 @@ describe('RulesManager', () => { describe('#constructor', () => { it('should error when no options are provided', () => { - expect(RulesManager).to.throw(ArgumentError, 'Must provide manager options'); + expect(() => { + new RulesManager(); + }).to.throw(ArgumentError, 'Must provide manager options'); }); it('should throw an error when no base URL is provided', () => { - const client = RulesManager.bind(null, {}); - - expect(client).to.throw(ArgumentError, 'Must provide a base URL for the API'); + expect(() => { + new RulesManager({}); + }).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); it('should throw an error when the base URL is invalid', () => { - const client = RulesManager.bind(null, { baseUrl: '' }); - - expect(client).to.throw(ArgumentError, 'The provided base URL is invalid'); + expect(() => { + new RulesManager({ baseUrl: '' }); + }).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); diff --git a/test/management/stats.tests.js b/test/management/stats.tests.js index 38ebcf98d..2452b0308 100644 --- a/test/management/stats.tests.js +++ b/test/management/stats.tests.js @@ -27,19 +27,21 @@ describe('StatsManager', () => { describe('#constructor', () => { it('should error when no options are provided', () => { - expect(StatsManager).to.throw(ArgumentError, 'Must provide manager options'); + expect(() => { + new StatsManager(); + }).to.throw(ArgumentError, 'Must provide manager options'); }); it('should throw an error when no base URL is provided', () => { - const client = StatsManager.bind(null, {}); - - expect(client).to.throw(ArgumentError, 'Must provide a base URL for the API'); + expect(() => { + new StatsManager({}); + }).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); it('should throw an error when the base URL is invalid', () => { - const client = StatsManager.bind(null, { baseUrl: '' }); - - expect(client).to.throw(ArgumentError, 'The provided base URL is invalid'); + expect(() => { + new StatsManager({ baseUrl: '' }); + }).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); diff --git a/test/management/users.tests.js b/test/management/users.tests.js index 64aceaeef..7d0cbbf15 100644 --- a/test/management/users.tests.js +++ b/test/management/users.tests.js @@ -7,10 +7,19 @@ const UsersManager = require(`../../src/management/UsersManager`); const { ArgumentError } = require('rest-facade'); describe('UsersManager', () => { - before(function () { - this.token = 'TOKEN'; - this.users = new UsersManager({ - headers: { authorization: `Bearer ${this.token}` }, + /** + * @type {string} + */ + let token; + + /** + * @type {UsersManager} + */ + let usersManager; + before(() => { + token = 'TOKEN'; + usersManager = new UsersManager({ + headers: { authorization: `Bearer ${token}` }, baseUrl: API_URL, }); }); @@ -42,8 +51,8 @@ describe('UsersManager', () => { ]; methods.forEach((method) => { - it(`should have a ${method} method`, function () { - expect(this.users[method]).to.exist.to.be.an.instanceOf(Function); + it(`should have a ${method} method`, () => { + expect(usersManager[method]).to.exist.to.be.an.instanceOf(Function); }); }); }); @@ -69,75 +78,66 @@ describe('UsersManager', () => { }); describe('#getAll', () => { - beforeEach(function () { - this.request = nock(API_URL).get('/users').reply(200); + /** + * @type {nock} + */ + let scope; + beforeEach(() => { + scope = nock(API_URL).get('/users').reply(200); }); - it('should accept a callback', function (done) { - this.users.getAll(() => { + it('should accept a callback', (done) => { + usersManager.getAll(() => { done(); }); }); - it('should return a promise if no callback is given', function (done) { - this.users.getAll().then(done.bind(null, null)).catch(done.bind(null, null)); + it('should return a promise if no callback is given', () => { + expect(usersManager.getAll()).instanceOf(Promise); }); - it('should pass any errors to the promise catch handler', function (done) { + it('should pass any errors to the promise catch handler', async () => { nock.cleanAll(); nock(API_URL).get('/users').reply(500); - this.users.getAll().catch((err) => { + try { + await usersManager.getAll(); + } catch (err) { expect(err).to.exist; - - done(); - }); + } }); - it('should pass the body of the response to the "then" handler', function (done) { + it('should pass the body of the response to the "then" handler', async () => { nock.cleanAll(); const data = [{ test: true }]; nock(API_URL).get('/users').reply(200, data); - this.users.getAll().then((users) => { - expect(users).to.be.an.instanceOf(Array); - - expect(users.length).to.equal(data.length); - - expect(users[0].test).to.equal(data[0].test); - - done(); - }); + const users = await usersManager.getAll(); + expect(users).to.be.an.instanceOf(Array); + expect(users.length).to.equal(data.length); + expect(users[0].test).to.equal(data[0].test); }); - it('should perform a GET request to /api/v2/users', function (done) { - const { request } = this; - - this.users.getAll().then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + it('should perform a GET request to /api/v2/users', async () => { + await usersManager.getAll(); + expect(scope.isDone()).to.be.true; }); - it('should include the token in the Authorization header', function (done) { + it('should include the token in the Authorization header', async () => { nock.cleanAll(); const request = nock(API_URL) .get('/users') - .matchHeader('Authorization', `Bearer ${this.token}`) + .matchHeader('Authorization', `Bearer ${token}`) .reply(200); - this.users.getAll().then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await usersManager.getAll(); + expect(request.isDone()).to.be.true; }); - it('should pass the parameters in the query-string', function (done) { + it('should pass the parameters in the query-string', async () => { nock.cleanAll(); const params = { @@ -146,84 +146,72 @@ describe('UsersManager', () => { }; const request = nock(API_URL).get('/users').query(params).reply(200); - this.users.getAll(params).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await usersManager.getAll(params); + expect(request.isDone()).to.be.true; }); }); describe('#getByEmail', () => { - beforeEach(function () { - this.request = nock(API_URL).get('/users-by-email').reply(200); + /** + * @type {nock} + */ + let scope; + beforeEach(() => { + scope = nock(API_URL).get('/users-by-email').reply(200); }); - it('should accept a callback', function (done) { - this.users.getByEmail('someone@example.com', () => { + it('should accept a callback', (done) => { + usersManager.getByEmail('someone@example.com', () => { done(); }); }); - it('should return a promise if no callback is given', function (done) { - this.users.getByEmail().then(done.bind(null, null)).catch(done.bind(null, null)); + it('should return a promise if no callback is given', () => { + expect(usersManager.getByEmail()).instanceOf(Promise); }); - it('should pass any errors to the promise catch handler', function (done) { + it('should pass any errors to the promise catch handler', async () => { nock.cleanAll(); nock(API_URL).get('/users-by-email').reply(500); - this.users.getByEmail().catch((err) => { + try { + await usersManager.getByEmail(); + } catch (err) { expect(err).to.exist; - - done(); - }); + } }); - it('should pass the body of the response to the "then" handler', function (done) { + it('should pass the body of the response to the "then" handler', async () => { nock.cleanAll(); const data = [{ test: true }]; nock(API_URL).get('/users-by-email').reply(200, data); - this.users.getByEmail().then((users) => { - expect(users).to.be.an.instanceOf(Array); - - expect(users.length).to.equal(data.length); - - expect(users[0].test).to.equal(data[0].test); - - done(); - }); + const users = await usersManager.getByEmail(); + expect(users).to.be.an.instanceOf(Array); + expect(users.length).to.equal(data.length); + expect(users[0].test).to.equal(data[0].test); }); - it('should perform a GET request to /api/v2/users-by-email', function (done) { - const { request } = this; - - this.users.getByEmail().then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + it('should perform a GET request to /api/v2/users-by-email', async () => { + await usersManager.getByEmail(); + expect(scope.isDone()).to.be.true; }); - it('should include the token in the Authorization header', function (done) { + it('should include the token in the Authorization header', async () => { nock.cleanAll(); const request = nock(API_URL) .get('/users-by-email') - .matchHeader('Authorization', `Bearer ${this.token}`) + .matchHeader('Authorization', `Bearer ${token}`) .reply(200); - this.users.getByEmail().then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await usersManager.getByEmail(); + expect(request.isDone()).to.be.true; }); - it('should pass an email in as a query string', function (done) { + it('should pass an email in as a query string', async () => { nock.cleanAll(); const params = { @@ -231,14 +219,11 @@ describe('UsersManager', () => { }; const request = nock(API_URL).get('/users-by-email').query(params).reply(200); - this.users.getByEmail(params.email).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await usersManager.getByEmail(params.email); + expect(request.isDone()).to.be.true; }); - it('should pass additional options into the query string', function (done) { + it('should pass additional options into the query string', async () => { nock.cleanAll(); const additionalOptions = { @@ -252,17 +237,32 @@ describe('UsersManager', () => { const request = nock(API_URL).get('/users-by-email').query(params).reply(200); - this.users.getByEmail(params.email, additionalOptions).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await usersManager.getByEmail(params.email, additionalOptions); + expect(request.isDone()).to.be.true; }); }); describe('#get', () => { - beforeEach(function () { - this.data = { + /** + * @typedef {object} data + * @property {number} id Id + * @property {string} name Name + * @property {boolean} enabled Enabled + * @property {string} script Script + * @property {string} stage Stage + */ + + /** + * @type {data} + */ + let data; + + /** + * @type {nock} + */ + let scope; + beforeEach(() => { + data = { id: 5, name: 'Test rule', enabled: true, @@ -270,54 +270,46 @@ describe('UsersManager', () => { stage: 'login_success', }; - this.request = nock(API_URL).get(`/users/${this.data.id}`).reply(200, this.data); + scope = nock(API_URL).get(`/users/${data.id}`).reply(200, data); }); - it('should accept a callback', function (done) { - const params = { id: this.data.id }; + it('should accept a callback', (done) => { + const params = { id: data.id }; - this.users.get(params, done.bind(null, null)); + usersManager.get(params, done.bind(null, null)); }); - it('should return a promise if no callback is given', function (done) { - this.users.get({ id: this.data.id }).then(done.bind(null, null)).catch(done.bind(null, null)); + it('should return a promise if no callback is given', () => { + expect(usersManager.get({ id: data.id })).instanceOf(Promise); }); - it('should perform a POST request to /api/v2/users/5', function (done) { - const { request } = this; - - this.users.get({ id: this.data.id }).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + it('should perform a POST request to /api/v2/users/5', async () => { + await usersManager.get({ id: data.id }); + expect(scope.isDone()).to.be.true; }); - it('should pass any errors to the promise catch handler', function (done) { + it('should pass any errors to the promise catch handler', async () => { nock.cleanAll(); - nock(API_URL).get(`/users/${this.data.id}`).reply(500); + nock(API_URL).get(`/users/${data.id}`).reply(500); - this.users.get({ id: this.data.id }).catch((err) => { + try { + await usersManager.get({ id: data.id }); + } catch (err) { expect(err).to.exist; - - done(); - }); + } }); - it('should include the token in the Authorization header', function (done) { + it('should include the token in the Authorization header', async () => { nock.cleanAll(); const request = nock(API_URL) - .get(`/users/${this.data.id}`) - .matchHeader('Authorization', `Bearer ${this.token}`) + .get(`/users/${data.id}`) + .matchHeader('Authorization', `Bearer ${token}`) .reply(200); - this.users.get({ id: this.data.id }).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await usersManager.get({ id: data.id }); + expect(request.isDone()).to.be.true; }); }); @@ -330,170 +322,167 @@ describe('UsersManager', () => { stage: 'login_success', }; - beforeEach(function () { - this.request = nock(API_URL).post('/users').reply(200); + /** + * @type {nock} + */ + let scope; + beforeEach(() => { + scope = nock(API_URL).post('/users').reply(200); }); - it('should accept a callback', function (done) { - this.users.create(data, () => { + it('should accept a callback', (done) => { + usersManager.create(data, () => { done(); }); }); - it('should return a promise if no callback is given', function (done) { - this.users.create(data).then(done.bind(null, null)).catch(done.bind(null, null)); + it('should return a promise if no callback is given', () => { + expect(usersManager.create(data)).instanceOf(Promise); }); - it('should pass any errors to the promise catch handler', function (done) { + it('should pass any errors to the promise catch handler', async () => { nock.cleanAll(); nock(API_URL).post('/users').reply(500); - this.users.create(data).catch((err) => { + try { + await usersManager.create(data); + } catch (err) { expect(err).to.exist; - - done(); - }); + } }); - it('should perform a POST request to /api/v2/users', function (done) { - const { request } = this; - - this.users.create(data).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + it('should perform a POST request to /api/v2/users', async () => { + await usersManager.create(data); + expect(scope.isDone()).to.be.true; }); - it('should pass the data in the body of the request', function (done) { + it('should pass the data in the body of the request', async () => { nock.cleanAll(); const request = nock(API_URL).post('/users', data).reply(200); - this.users.create(data).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await usersManager.create(data); + expect(request.isDone()).to.be.true; }); - it('should include the token in the Authorization header', function (done) { + it('should include the token in the Authorization header', async () => { nock.cleanAll(); const request = nock(API_URL) .post('/users') - .matchHeader('Authorization', `Bearer ${this.token}`) + .matchHeader('Authorization', `Bearer ${token}`) .reply(200); - this.users.create(data).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await usersManager.create(data); + expect(request.isDone()).to.be.true; }); }); describe('#update', () => { - beforeEach(function () { - this.data = { id: 5 }; + /** + * @typedef {object} data + * @property {number} id Id + */ - this.request = nock(API_URL).patch(`/users/${this.data.id}`).reply(200, this.data); - }); + /** + * @type {data} + */ + let data; - it('should accept a callback', function (done) { - this.users.update({ id: 5 }, {}, done.bind(null, null)); - }); + /** + * @type {nock} + */ + let scope; + beforeEach(() => { + data = { id: 5 }; - it('should return a promise if no callback is given', function (done) { - this.users.update({ id: 5 }, {}).then(done.bind(null, null)).catch(done.bind(null, null)); + scope = nock(API_URL).patch(`/users/${data.id}`).reply(200, data); }); - it('should perform a PATCH request to /api/v2/users/5', function (done) { - const { request } = this; + it('should accept a callback', (done) => { + usersManager.update({ id: 5 }, {}, done.bind(null, null)); + }); - this.users.update({ id: 5 }, {}).then(() => { - expect(request.isDone()).to.be.true; + it('should return a promise if no callback is given', () => { + expect(usersManager.update({ id: 5 }, {})).instanceOf(Promise); + }); - done(); - }); + it('should perform a PATCH request to /api/v2/users/5', async () => { + usersManager.update({ id: 5 }, {}); + expect(scope.isDone()).to.be.true; }); - it('should include the new data in the body of the request', function (done) { + it('should include the new data in the body of the request', async () => { nock.cleanAll(); - const request = nock(API_URL).patch(`/users/${this.data.id}`, this.data).reply(200); + const request = nock(API_URL).patch(`/users/${data.id}`, data).reply(200); - this.users.update({ id: 5 }, this.data).then(() => { - expect(request.isDone()).to.be.true; + await usersManager.update({ id: 5 }, data); - done(); - }); + expect(request.isDone()).to.be.true; }); - it('should pass any errors to the promise catch handler', function (done) { + it('should pass any errors to the promise catch handler', async () => { nock.cleanAll(); - nock(API_URL).patch(`/users/${this.data.id}`).reply(500); + nock(API_URL).patch(`/users/${data.id}`).reply(500); - this.users.update({ id: this.data.id }, this.data).catch((err) => { + try { + await usersManager.update({ id: data.id }, data); + } catch (err) { expect(err).to.exist; - - done(); - }); + } }); }); describe('#delete', () => { const id = 'USER_5'; - beforeEach(function () { - this.request = nock(API_URL).delete(`/users/${id}`).reply(200); - }); + /** + * @type {nock} + */ + let scope; - it('should accept a callback', function (done) { - this.users.delete({ id }, done.bind(null, null)); + beforeEach(() => { + scope = nock(API_URL).delete(`/users/${id}`).reply(200); }); - it('should return a promise when no callback is given', function (done) { - this.users.delete({ id }).then(done.bind(null, null)); + it('should accept a callback', (done) => { + usersManager.delete({ id }, done.bind(null, null)); }); - it(`should perform a delete request to /users/${id}`, function (done) { - const { request } = this; - - this.users.delete({ id }).then(() => { - expect(request.isDone()).to.be.true; + it('should return a promise when no callback is given', () => { + expect(usersManager.delete({ id })).instanceOf(Promise); + }); - done(); - }); + it(`should perform a delete request to /users/${id}`, async () => { + await usersManager.delete({ id }); + expect(scope.isDone()).to.be.true; }); - it('should pass any errors to the promise catch handler', function (done) { + it('should pass any errors to the promise catch handler', async () => { nock.cleanAll(); nock(API_URL).delete(`/users/${id}`).reply(500); - this.users.delete({ id }).catch((err) => { + try { + await usersManager.delete({ id }); + } catch (err) { expect(err).to.exist; - - done(); - }); + } }); - it('should include the token in the authorization header', function (done) { + it('should include the token in the authorization header', async () => { nock.cleanAll(); const request = nock(API_URL) .delete(`/users/${id}`) - .matchHeader('authorization', `Bearer ${this.token}`) + .matchHeader('authorization', `Bearer ${token}`) .reply(200); - this.users.delete({ id }).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await usersManager.delete({ id }); + expect(request.isDone()).to.be.true; }); }); @@ -504,81 +493,73 @@ describe('UsersManager', () => { user_id: '191919191919191', }; - beforeEach(function () { - this.request = nock(API_URL).post(`/users/${userId}/identities`).reply(200); + /** + * @type {nock} + */ + let scope; + + beforeEach(() => { + scope = nock(API_URL).post(`/users/${userId}/identities`).reply(200); }); - it('should validate empty userId', function () { - const _this = this; + it('should validate empty userId', () => { expect(() => { - _this.users.link(null, data, () => {}); + usersManager.link(null, data, () => {}); }).to.throw('The userId cannot be null or undefined'); }); - it('should validate non-string userId', function () { - const _this = this; + it('should validate non-string userId', () => { expect(() => { - _this.users.link(123, data, () => {}); + usersManager.link(123, data, () => {}); }).to.throw('The userId has to be a string'); }); - it('should accept a callback', function (done) { - this.users.link(userId, data, () => { + it('should accept a callback', (done) => { + usersManager.link(userId, data, () => { done(); }); }); - it('should return a promise if no callback is given', function (done) { - this.users.link(userId, data).then(done.bind(null, null)).catch(done.bind(null, null)); + it('should return a promise if no callback is given', () => { + expect(usersManager.link(userId, data)).instanceOf(Promise); }); - it('should pass any errors to the promise catch handler', function (done) { + it('should pass any errors to the promise catch handler', async () => { nock.cleanAll(); nock(API_URL).post(`/users/${userId}/identities`).reply(500); - this.users.link(userId, data).catch((err) => { + try { + await usersManager.link(userId, data); + } catch (err) { expect(err).to.exist; - - done(); - }); + } }); - it('should perform a POST request to /api/v2/users', function (done) { - const { request } = this; - - this.users.link(userId, data).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + it('should perform a POST request to /api/v2/users', async () => { + await usersManager.link(userId, data); + expect(scope.isDone()).to.be.true; }); - it('should pass the data in the body of the request', function (done) { + it('should pass the data in the body of the request', async () => { nock.cleanAll(); const request = nock(API_URL).post(`/users/${userId}/identities`, data).reply(200); - this.users.link(userId, data).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await usersManager.link(userId, data); + expect(request.isDone()).to.be.true; }); - it('should include the token in the Authorization header', function (done) { + it('should include the token in the Authorization header', async () => { nock.cleanAll(); const request = nock(API_URL) .post(`/users/${userId}/identities`) - .matchHeader('Authorization', `Bearer ${this.token}`) + .matchHeader('Authorization', `Bearer ${token}`) .reply(200); - this.users.link(userId, data).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await usersManager.link(userId, data); + expect(request.isDone()).to.be.true; }); }); @@ -590,53 +571,50 @@ describe('UsersManager', () => { }; const url = `/users/${data.id}/identities/${data.provider}/${data.user_id}`; - beforeEach(function () { - this.request = nock(API_URL).delete(url).reply(200); - }); + /** + * @type {nock} + */ + let scope; - it('should accept a callback', function (done) { - this.users.unlink(data, done.bind(null, null)); + beforeEach(() => { + scope = nock(API_URL).delete(url).reply(200); }); - it('should return a promise when no callback is given', function (done) { - this.users.unlink(data).then(done.bind(null, null)); + it('should accept a callback', (done) => { + usersManager.unlink(data, done.bind(null, null)); }); - it(`should perform a DELETE request to ${url}`, function (done) { - const { request } = this; - - this.users.unlink(data).then(() => { - expect(request.isDone()).to.be.true; + it('should return a promise when no callback is given', () => { + expect(usersManager.unlink(data)).instanceOf(Promise); + }); - done(); - }); + it(`should perform a DELETE request to ${url}`, async () => { + await usersManager.unlink(data); + expect(scope.isDone()).to.be.true; }); - it('should pass any errors to the promise catch handler', function (done) { + it('should pass any errors to the promise catch handler', async () => { nock.cleanAll(); nock(API_URL).delete(url).reply(500); - this.users.unlink(data).catch((err) => { + try { + usersManager.unlink(data); + } catch (err) { expect(err).to.exist; - - done(); - }); + } }); - it('should include the token in the authorization header', function (done) { + it('should include the token in the authorization header', async () => { nock.cleanAll(); const request = nock(API_URL) .delete(url) - .matchHeader('authorization', `Bearer ${this.token}`) + .matchHeader('authorization', `Bearer ${token}`) .reply(200); - this.users.unlink(data).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await usersManager.unlink(data); + expect(request.isDone()).to.be.true; }); }); @@ -647,117 +625,117 @@ describe('UsersManager', () => { }; const url = `/users/${data.id}/multifactor/${data.provider}`; - beforeEach(function () { - this.request = nock(API_URL).delete(url).reply(200); - }); + /** + * @type {nock} + */ + let scope; - it('should accept a callback', function (done) { - this.users.deleteMultifactorProvider(data, done.bind(null, null)); + beforeEach(() => { + scope = nock(API_URL).delete(url).reply(200); }); - it('should return a promise when no callback is given', function (done) { - this.users.deleteMultifactorProvider(data).then(done.bind(null, null)); + it('should accept a callback', (done) => { + usersManager.deleteMultifactorProvider(data, done.bind(null, null)); }); - it(`should perform a DELETE request to ${url}`, function (done) { - const { request } = this; - - this.users.deleteMultifactorProvider(data).then(() => { - expect(request.isDone()).to.be.true; + it('should return a promise when no callback is given', () => { + expect(usersManager.deleteMultifactorProvider(data)).instanceOf(Promise); + }); - done(); - }); + it(`should perform a DELETE request to ${url}`, async () => { + await usersManager.deleteMultifactorProvider(data); + expect(scope.isDone()).to.be.true; }); - it('should pass any errors to the promise catch handler', function (done) { + it('should pass any errors to the promise catch handler', async () => { nock.cleanAll(); nock(API_URL).delete(url).reply(500); - this.users.deleteMultifactorProvider(data).catch((err) => { + try { + await usersManager.deleteMultifactorProvider(data); + } catch (err) { expect(err).to.exist; - - done(); - }); + } }); - it('should include the token in the authorization header', function (done) { + it('should include the token in the authorization header', async () => { nock.cleanAll(); const request = nock(API_URL) .delete(url) - .matchHeader('authorization', `Bearer ${this.token}`) + .matchHeader('authorization', `Bearer ${token}`) .reply(200); - this.users.deleteMultifactorProvider(data).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await usersManager.deleteMultifactorProvider(data); + expect(request.isDone()).to.be.true; }); }); describe('#updateUserMetadata', () => { - beforeEach(function () { - this.data = { + /** + * @typedef {object} data + * @property {number} id Id + * @property {string} foo Foo + * @property {string} test Test + */ + + /** + * @type {data} + */ + let data; + + /** + * @type {nock} + */ + let scope; + + beforeEach(() => { + data = { id: 5, foo: 'bar', test: 'data', }; - this.request = nock(API_URL).patch(`/users/${this.data.id}`).reply(200, this.data); + scope = nock(API_URL).patch(`/users/${data.id}`).reply(200, data); }); - it('should accept a callback', function (done) { - this.users.updateUserMetadata({ id: 5 }, {}, done.bind(null, null)); + it('should accept a callback', (done) => { + usersManager.updateUserMetadata({ id: 5 }, {}, done.bind(null, null)); }); - it('should return a promise if no callback is given', function (done) { - this.users - .updateUserMetadata({ id: 5 }, {}) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', () => { + expect(usersManager.updateUserMetadata({ id: 5 }, {})).instanceOf(Promise); }); - it('should perform a PATCH request to /api/v2/users/5', function (done) { - const { request } = this; - - this.users.updateUserMetadata({ id: 5 }, {}).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + it('should perform a PATCH request to /api/v2/users/5', async () => { + await usersManager.updateUserMetadata({ id: 5 }, {}); + expect(scope.isDone()).to.be.true; }); - it('should include the metadata in the body of the request', function (done) { + it('should include the metadata in the body of the request', async () => { nock.cleanAll(); const request = nock(API_URL) - .patch(`/users/${this.data.id}`, { - user_metadata: this.data, + .patch(`/users/${data.id}`, { + user_metadata: data, }) .reply(200); - this.users - .updateUserMetadata({ id: 5 }, this.data) - .then(() => { - expect(request.isDone()).to.be.true; - - done(); - }) - .catch(done); + await usersManager.updateUserMetadata({ id: 5 }, data); + expect(request.isDone()).to.be.true; }); - it('should pass any errors to the promise catch handler', function (done) { + it('should pass any errors to the promise catch handler', async () => { nock.cleanAll(); - nock(API_URL).patch(`/users/${this.data.id}`).reply(500); + nock(API_URL).patch(`/users/${data.id}`).reply(500); - this.users.updateUserMetadata({ id: this.data.id }, this.data).catch((err) => { + try { + await usersManager.updateUserMetadata({ id: data.id }, data); + } catch (err) { expect(err).to.exist; - - done(); - }); + } }); }); @@ -767,73 +745,67 @@ describe('UsersManager', () => { }; const url = `/users/${data.id}/logs`; - beforeEach(function () { - this.request = nock(API_URL).get(url).reply(200); - }); + /** + * @type {nock} + */ + let scope; - it('should accept a callback', function (done) { - this.users.logs(data, done.bind(null, null)); + beforeEach(() => { + scope = nock(API_URL).get(url).reply(200); }); - it('should return a promise when no callback is given', function (done) { - this.users.logs(data).then(done.bind(null, null)); + it('should accept a callback', (done) => { + usersManager.logs(data, done.bind(null, null)); }); - it(`should perform a GET request to ${url}`, function (done) { - const { request } = this; - - this.users.logs(data).then(() => { - expect(request.isDone()).to.be.true; + it('should return a promise when no callback is given', () => { + expect(usersManager.logs(data)).instanceOf(Promise); + }); - done(); - }); + it(`should perform a GET request to ${url}`, async () => { + await usersManager.logs(data); + expect(scope.isDone()).to.be.true; }); - it('should pass any errors to the promise catch handler', function (done) { + it('should pass any errors to the promise catch handler', async () => { nock.cleanAll(); nock(API_URL).get(url).reply(500); - this.users.logs(data).catch((err) => { + try { + await usersManager.logs(data); + } catch (err) { expect(err).to.exist; - - done(); - }); + } }); - it('should include the token in the authorization header', function (done) { + it('should include the token in the authorization header', async () => { nock.cleanAll(); const request = nock(API_URL) .get(url) - .matchHeader('authorization', `Bearer ${this.token}`) + .matchHeader('authorization', `Bearer ${token}`) .reply(200); - this.users.logs(data).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await usersManager.logs(data); + expect(request.isDone()).to.be.true; }); - it('should pass the body of the response to the "then" handler', function (done) { + it('should pass the body of the response to the "then" handler', async () => { nock.cleanAll(); const response = [{ test: true }]; nock(API_URL).get(url).reply(200, response); - this.users.logs(data).then((logs) => { - expect(logs).to.be.an.instanceOf(Array); - - expect(logs.length).to.equal(response.length); + const logs = await usersManager.logs(data); + expect(logs).to.be.an.instanceOf(Array); - expect(logs[0].test).to.equal(response[0].test); + expect(logs.length).to.equal(response.length); - done(); - }); + expect(logs[0].test).to.equal(response[0].test); }); - it('should pass the parameters in the query-string', function (done) { + it('should pass the parameters in the query-string', async () => { nock.cleanAll(); const params = { @@ -842,14 +814,12 @@ describe('UsersManager', () => { }; const request = nock(API_URL).get(url).query(params).reply(200); - data.page = params.page; - data.per_page = params.per_page; + const ownData = { ...data }; + ownData.page = params.page; + ownData.per_page = params.per_page; - this.users.logs(data).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await usersManager.logs(ownData); + expect(request.isDone()).to.be.true; }); }); @@ -858,53 +828,50 @@ describe('UsersManager', () => { id: 5, }; - beforeEach(function () { - this.request = nock(API_URL).get(`/users/${data.id}/enrollments`).reply(200); - }); + /** + * @type {nock} + */ + let scope; - it('should accept a callback', function (done) { - this.users.getGuardianEnrollments(data, done.bind(null, null)); + beforeEach(() => { + scope = nock(API_URL).get(`/users/${data.id}/enrollments`).reply(200); }); - it('should return a promise when no callback is given', function (done) { - this.users.getGuardianEnrollments(data).then(done.bind(null, null)); + it('should accept a callback', (done) => { + usersManager.getGuardianEnrollments(data, done.bind(null, null)); }); - it('should perform a GET request to /api/v2/users/5/enrollments', function (done) { - const { request } = this; - - this.users.getGuardianEnrollments(data).then(() => { - expect(request.isDone()).to.be.true; + it('should return a promise when no callback is given', () => { + expect(usersManager.getGuardianEnrollments(data)).instanceOf(Promise); + }); - done(); - }); + it('should perform a GET request to /api/v2/users/5/enrollments', async () => { + await usersManager.getGuardianEnrollments(data); + expect(scope.isDone()).to.be.true; }); - it('should pass any errors to the promise catch handler', function (done) { + it('should pass any errors to the promise catch handler', async () => { nock.cleanAll(); nock(API_URL).get(`/users/${data.id}/enrollments`).reply(500); - this.users.getGuardianEnrollments(data).catch((err) => { + try { + await usersManager.getGuardianEnrollments(data); + } catch (err) { expect(err).to.exist; - - done(); - }); + } }); - it('should include the token in the authorization header', function (done) { + it('should include the token in the authorization header', async () => { nock.cleanAll(); const request = nock(API_URL) .get(`/users/${data.id}/enrollments`) - .matchHeader('authorization', `Bearer ${this.token}`) + .matchHeader('authorization', `Bearer ${token}`) .reply(200); - this.users.getGuardianEnrollments(data).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await usersManager.getGuardianEnrollments(data); + expect(request.isDone()).to.be.true; }); }); @@ -913,65 +880,58 @@ describe('UsersManager', () => { id: 'USER_ID', }; - beforeEach(function () { - this.request = nock(API_URL).post(`/users/${data.id}/recovery-code-regeneration`).reply(200); + /** + * @type {nock} + */ + let scope; + + beforeEach(() => { + scope = nock(API_URL).post(`/users/${data.id}/recovery-code-regeneration`).reply(200); }); - it('should validate empty userId', function () { - const _this = this; + it('should validate empty userId', () => { expect(() => { - _this.users.regenerateRecoveryCode(null, () => {}); + usersManager.regenerateRecoveryCode(null, () => {}); }).to.throw('The userId cannot be null or undefined'); }); - it('should accept a callback', function (done) { - this.users.regenerateRecoveryCode(data, () => { + it('should accept a callback', (done) => { + usersManager.regenerateRecoveryCode(data, () => { done(); }); }); - it('should return a promise if no callback is given', function (done) { - this.users - .regenerateRecoveryCode(data) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', () => { + expect(usersManager.regenerateRecoveryCode(data)).instanceOf(Promise); }); - it('should pass any errors to the promise catch handler', function (done) { + it('should pass any errors to the promise catch handler', async () => { nock.cleanAll(); nock(API_URL).post(`/users/${data.id}/recovery-code-regeneration`).reply(500); - this.users.regenerateRecoveryCode(data).catch((err) => { + try { + await usersManager.regenerateRecoveryCode(data); + } catch (err) { expect(err).to.exist; - - done(); - }); + } }); - it('should perform a POST request to /api/v2/users/:id/recovery-code-regeneration', function (done) { - const { request } = this; - - this.users.regenerateRecoveryCode(data).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + it('should perform a POST request to /api/v2/users/:id/recovery-code-regeneration', async () => { + await usersManager.regenerateRecoveryCode(data); + expect(scope.isDone()).to.be.true; }); - it('should include the token in the Authorization header', function (done) { + it('should include the token in the Authorization header', async () => { nock.cleanAll(); const request = nock(API_URL) .post(`/users/${data.id}/recovery-code-regeneration`) - .matchHeader('Authorization', `Bearer ${this.token}`) + .matchHeader('Authorization', `Bearer ${token}`) .reply(200); - this.users.regenerateRecoveryCode(data).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await usersManager.regenerateRecoveryCode(data); + expect(request.isDone()).to.be.true; }); }); @@ -980,69 +940,62 @@ describe('UsersManager', () => { id: 'USER_ID', }; - beforeEach(function () { - this.request = nock(API_URL) + /** + * @type {nock} + */ + let scope; + + beforeEach(() => { + scope = nock(API_URL) .post(`/users/${data.id}/multifactor/actions/invalidate-remember-browser`) .reply(204); }); - it('should validate empty userId', function () { - const _this = this; + it('should validate empty userId', () => { expect(() => { - _this.users.invalidateRememberBrowser(null, () => {}); + usersManager.invalidateRememberBrowser(null, () => {}); }).to.throw('The userId cannot be null or undefined'); }); - it('should accept a callback', function (done) { - this.users.invalidateRememberBrowser(data, () => { + it('should accept a callback', (done) => { + usersManager.invalidateRememberBrowser(data, () => { done(); }); }); - it('should return a promise if no callback is given', function (done) { - this.users - .invalidateRememberBrowser(data) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', () => { + expect(usersManager.invalidateRememberBrowser(data)).instanceOf(Promise); }); - it('should pass any errors to the promise catch handler', function (done) { + it('should pass any errors to the promise catch handler', async () => { nock.cleanAll(); nock(API_URL) .post(`/users/${data.id}/multifactor/actions/invalidate-remember-browser`) .reply(500); - this.users.invalidateRememberBrowser(data).catch((err) => { + try { + await usersManager.invalidateRememberBrowser(data); + } catch (err) { expect(err).to.exist; - - done(); - }); + } }); - it('should perform a POST request to /api/v2/users/:id/multifactor/actions/invalidate-remember-browser', function (done) { - const { request } = this; - - this.users.invalidateRememberBrowser(data).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + it('should perform a POST request to /api/v2/users/:id/multifactor/actions/invalidate-remember-browser', async () => { + await usersManager.invalidateRememberBrowser(data); + expect(scope.isDone()).to.be.true; }); - it('should include the token in the Authorization header', function (done) { + it('should include the token in the Authorization header', async () => { nock.cleanAll(); const request = nock(API_URL) .post(`/users/${data.id}/multifactor/actions/invalidate-remember-browser`) - .matchHeader('Authorization', `Bearer ${this.token}`) + .matchHeader('Authorization', `Bearer ${token}`) .reply(200); - this.users.invalidateRememberBrowser(data).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await usersManager.invalidateRememberBrowser(data); + expect(request.isDone()).to.be.true; }); }); @@ -1051,227 +1004,242 @@ describe('UsersManager', () => { id: 'user_id', }; - beforeEach(function () { - this.request = nock(API_URL).get(`/users/${data.id}/roles`).reply(200); - }); + /** + * @type {nock} + */ + let scope; - it('should accept a callback', function (done) { - this.users.getRoles(data, done.bind(null, null)); + beforeEach(() => { + scope = nock(API_URL).get(`/users/${data.id}/roles`).reply(200); }); - it('should return a promise when no callback is given', function (done) { - this.users.getRoles(data).then(done.bind(null, null)); + it('should accept a callback', (done) => { + usersManager.getRoles(data, done.bind(null, null)); }); - it('should perform a GET request to /api/v2/users/user_id/roles', function (done) { - const { request } = this; - - this.users.getRoles(data).then(() => { - expect(request.isDone()).to.be.true; + it('should return a promise when no callback is given', () => { + expect(usersManager.getRoles(data)).instanceOf(Promise); + }); - done(); - }); + it('should perform a GET request to /api/v2/users/user_id/roles', async () => { + await usersManager.getRoles(data); + expect(scope.isDone()).to.be.true; }); - it('should pass any errors to the promise catch handler', function (done) { + it('should pass any errors to the promise catch handler', async () => { nock.cleanAll(); nock(API_URL).get(`/users/${data.id}/roles`).reply(500); - this.users.getRoles(data).catch((err) => { + try { + await usersManager.getRoles(data); + } catch (err) { expect(err).to.exist; - - done(); - }); + } }); - it('should include the token in the authorization header', function (done) { + it('should include the token in the authorization header', async () => { nock.cleanAll(); const request = nock(API_URL) .get(`/users/${data.id}/roles`) - .matchHeader('authorization', `Bearer ${this.token}`) + .matchHeader('authorization', `Bearer ${token}`) .reply(200); - this.users.getRoles(data).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await usersManager.getRoles(data); + expect(request.isDone()).to.be.true; }); }); describe('#assignRoles', () => { - beforeEach(function () { - this.data = { + /** + * @typedef {object} data + * @property {string} id Id + */ + + /** + * @typedef {object} body + * @property {Array} roles Roles + */ + + /** + * @type {data} + */ + let data; + + /** + * @type {body} + */ + let body; + + /** + * @type {nock} + */ + let scope; + + beforeEach(() => { + data = { id: 'user_id', }; - this.body = { roles: ['role1', 'role2', 'role3'] }; + body = { roles: ['role1', 'role2', 'role3'] }; - this.request = nock(API_URL).post(`/users/${this.data.id}/roles`).reply(200); + scope = nock(API_URL).post(`/users/${data.id}/roles`).reply(200); }); - it('should validate empty user_id', function () { - const _this = this; + it('should validate empty user_id', () => { expect(() => { - _this.users.assignRoles({ id: null }, _this.body, () => {}); + usersManager.assignRoles({ id: null }, body, () => {}); }).to.throw('The user_id cannot be null or undefined'); }); - it('should validate non-string user_id', function () { - const _this = this; + it('should validate non-string user_id', () => { expect(() => { - _this.users.assignRoles({ id: 127 }, _this.body, () => {}); + usersManager.assignRoles({ id: 127 }, body, () => {}); }).to.throw('The user_id has to be a string'); }); - it('should accept a callback', function (done) { - this.users.assignRoles(this.data, {}, () => { + it('should accept a callback', (done) => { + usersManager.assignRoles(data, {}, () => { done(); }); }); - it('should return a promise if no callback is given', function (done) { - this.users - .assignRoles(this.data, {}) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', () => { + expect(usersManager.assignRoles(data, {})).instanceOf(Promise); }); - it('should pass any errors to the promise catch handler', function (done) { + it('should pass any errors to the promise catch handler', () => { nock.cleanAll(); - nock(API_URL).post(`/users/${this.data.id}/roles`).reply(500); + nock(API_URL).post(`/users/${data.id}/roles`).reply(500); - this.users.assignRoles(this.data, {}).catch((err) => { + try { + usersManager.assignRoles(data, {}); + } catch (err) { expect(err).to.exist; - - done(); - }); + } }); - it('should perform a POST request to /api/v2/users/user_id/roles', function (done) { - const { request } = this; - - this.users.assignRoles(this.data, {}).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + it('should perform a POST request to /api/v2/users/user_id/roles', async () => { + await usersManager.assignRoles(data, {}); + expect(scope.isDone()).to.be.true; }); - it('should pass the data in the body of the request', function (done) { + it('should pass the data in the body of the request', async () => { nock.cleanAll(); - const request = nock(API_URL).post(`/users/${this.data.id}/roles`, this.body).reply(200); - - this.users.assignRoles(this.data, this.body).then(() => { - expect(request.isDone()).to.be.true; + const request = nock(API_URL).post(`/users/${data.id}/roles`, body).reply(200); - done(); - }); + await usersManager.assignRoles(data, body); + expect(request.isDone()).to.be.true; }); - it('should include the token in the Authorization header', function (done) { + it('should include the token in the Authorization header', async () => { nock.cleanAll(); const request = nock(API_URL) - .post(`/users/${this.data.id}/roles`) - .matchHeader('Authorization', `Bearer ${this.token}`) + .post(`/users/${data.id}/roles`) + .matchHeader('Authorization', `Bearer ${token}`) .reply(200); - this.users.assignRoles(this.data, {}).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await usersManager.assignRoles(data, {}); + expect(request.isDone()).to.be.true; }); }); describe('#removeRoles', () => { - beforeEach(function () { - this.data = { + /** + * @typedef {object} data + * @property {string} id Id + */ + + /** + * @typedef {object} body + * @property {Array} roles Roles + */ + + /** + * @type {data} + */ + let data; + + /** + * @type {body} + */ + let body; + + /** + * @type {nock} + */ + let scope; + + beforeEach(() => { + data = { id: 'user_id', }; - this.body = { roles: ['role1', 'role2', 'role3'] }; + body = { roles: ['role1', 'role2', 'role3'] }; - this.request = nock(API_URL).delete(`/users/${this.data.id}/roles`, {}).reply(200); + scope = nock(API_URL).delete(`/users/${data.id}/roles`, {}).reply(200); }); - it('should validate empty user_id', function () { - const _this = this; - expect(function () { - _this.users.removeRoles({ id: null }, this.body, () => {}); + it('should validate empty user_id', () => { + expect(() => { + usersManager.removeRoles({ id: null }, body, () => {}); }).to.throw('The user_id cannot be null or undefined'); }); - it('should validate non-string user_id', function () { - const _this = this; + it('should validate non-string user_id', () => { expect(() => { - _this.users.removeRoles({ id: 123 }, _this.body, () => {}); + usersManager.removeRoles({ id: 123 }, body, () => {}); }).to.throw('The user_id has to be a string'); }); - it('should accept a callback', function (done) { - this.users.removeRoles(this.data, {}, () => { + it('should accept a callback', (done) => { + usersManager.removeRoles(data, {}, () => { done(); }); }); - it('should return a promise if no callback is given', function (done) { - this.users - .removeRoles(this.data, {}) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', () => { + expect(usersManager.removeRoles(data, {})).instanceOf(Promise); }); - it('should pass any errors to the promise catch handler', function (done) { + it('should pass any errors to the promise catch handler', async () => { nock.cleanAll(); - nock(API_URL).post(`/users/${this.data.id}/roles`).reply(500); + nock(API_URL).post(`/users/${data.id}/roles`).reply(500); - this.users.removeRoles(this.data, {}).catch((err) => { + try { + await usersManager.removeRoles(data, {}); + } catch (err) { expect(err).to.exist; - - done(); - }); + } }); - it('should perform a DELETE request to /api/v2/users/user_id/roles', function (done) { - const { request } = this; - - this.users.removeRoles(this.data, {}).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + it('should perform a DELETE request to /api/v2/users/user_id/roles', async () => { + await usersManager.removeRoles(data, {}); + expect(scope.isDone()).to.be.true; }); - it('should pass the data in the body of the request', function (done) { + it('should pass the data in the body of the request', async () => { nock.cleanAll(); - const request = nock(API_URL).delete(`/users/${this.data.id}/roles`, this.body).reply(200); + const request = nock(API_URL).delete(`/users/${data.id}/roles`, body).reply(200); - this.users.removeRoles(this.data, this.body).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await usersManager.removeRoles(data, body); + expect(request.isDone()).to.be.true; }); - it('should include the token in the Authorization header', function (done) { + it('should include the token in the Authorization header', async () => { nock.cleanAll(); const request = nock(API_URL) - .delete(`/users/${this.data.id}/roles`) - .matchHeader('Authorization', `Bearer ${this.token}`) + .delete(`/users/${data.id}/roles`) + .matchHeader('Authorization', `Bearer ${token}`) .reply(200); - this.users.removeRoles(this.data, {}).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await usersManager.removeRoles(data, {}); + expect(request.isDone()).to.be.true; }); }); @@ -1280,231 +1248,244 @@ describe('UsersManager', () => { id: 'user_id', }; - beforeEach(function () { - this.request = nock(API_URL).get(`/users/${data.id}/permissions`).reply(200); - }); + /** + * @type {nock} + */ + let scope; - it('should accept a callback', function (done) { - this.users.getPermissions(data, done.bind(null, null)); + beforeEach(() => { + scope = nock(API_URL).get(`/users/${data.id}/permissions`).reply(200); }); - it('should return a promise when no callback is given', function (done) { - this.users.getPermissions(data).then(done.bind(null, null)); + it('should accept a callback', (done) => { + usersManager.getPermissions(data, done.bind(null, null)); }); - it('should perform a GET request to /api/v2/users/user_id/permissions', function (done) { - const { request } = this; - - this.users.getPermissions(data).then(() => { - expect(request.isDone()).to.be.true; + it('should return a promise when no callback is given', () => { + expect(usersManager.getPermissions(data)).instanceOf(Promise); + }); - done(); - }); + it('should perform a GET request to /api/v2/users/user_id/permissions', async () => { + await usersManager.getPermissions(data); + expect(scope.isDone()).to.be.true; }); - it('should pass any errors to the promise catch handler', function (done) { + it('should pass any errors to the promise catch handler', async () => { nock.cleanAll(); nock(API_URL).get(`/users/${data.id}/permissions`).reply(500); - this.users.getPermissions(data).catch((err) => { + try { + usersManager.getPermissions(data); + } catch (err) { expect(err).to.exist; - - done(); - }); + } }); - it('should include the token in the authorization header', function (done) { + it('should include the token in the authorization header', async () => { nock.cleanAll(); const request = nock(API_URL) .get(`/users/${data.id}/permissions`) - .matchHeader('authorization', `Bearer ${this.token}`) + .matchHeader('authorization', `Bearer ${token}`) .reply(200); - this.users.getPermissions(data).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await usersManager.getPermissions(data); + expect(request.isDone()).to.be.true; }); }); describe('#assignPermissions', () => { - beforeEach(function () { - this.data = { + /** + * @typedef {object} data + * @property {string} id Id + */ + + /** + * @typedef {object} body + * @property {string} permission_name Permission name + * @property {string} resource_server_identifier Resource server identifier + */ + + /** + * @type {data} + */ + let data; + + /** + * @type {body} + */ + let body; + + /** + * @type {nock} + */ + let scope; + + beforeEach(() => { + data = { id: 'user_id', }; - this.body = { permission_name: 'My Permission', resource_server_identifier: 'test123' }; + body = { permission_name: 'My Permission', resource_server_identifier: 'test123' }; - this.request = nock(API_URL).post(`/users/${this.data.id}/permissions`).reply(200); + scope = nock(API_URL).post(`/users/${data.id}/permissions`).reply(200); }); - it('should validate empty user_id', function () { - const _this = this; - expect(function () { - _this.users.assignPermissions({ id: null }, this.body, () => {}); + it('should validate empty user_id', () => { + expect(() => { + usersManager.assignPermissions({ id: null }, body, () => {}); }).to.throw('The user_id cannot be null or undefined'); }); - it('should validate non-string user_id', function () { - const _this = this; + it('should validate non-string user_id', () => { expect(() => { - _this.users.assignPermissions({ id: 123 }, _this.body, () => {}); + usersManager.assignPermissions({ id: 123 }, body, () => {}); }).to.throw('The user_id has to be a string'); }); - it('should accept a callback', function (done) { - this.users.assignPermissions(this.data, {}, () => { + it('should accept a callback', (done) => { + usersManager.assignPermissions(data, {}, () => { done(); }); }); - it('should return a promise if no callback is given', function (done) { - this.users - .assignPermissions(this.data, {}) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', () => { + expect(usersManager.assignPermissions(data, {})).instanceOf(Promise); }); - it('should pass any errors to the promise catch handler', function (done) { + it('should pass any errors to the promise catch handler', async () => { nock.cleanAll(); - nock(API_URL).post(`/users/${this.data.id}/permissions`).reply(500); + nock(API_URL).post(`/users/${data.id}/permissions`).reply(500); - this.users.assignPermissions(this.data, {}).catch((err) => { + try { + await usersManager.assignPermissions(data, {}); + } catch (err) { expect(err).to.exist; - - done(); - }); + } }); - it('should perform a POST request to /api/v2/users/user_id/permissions', function (done) { - const { request } = this; - - this.users.assignPermissions(this.data, {}).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + it('should perform a POST request to /api/v2/users/user_id/permissions', async () => { + await usersManager.assignPermissions(data, {}); + expect(scope.isDone()).to.be.true; }); - it('should pass the data in the body of the request', function (done) { + it('should pass the data in the body of the request', async () => { nock.cleanAll(); - const request = nock(API_URL) - .post(`/users/${this.data.id}/permissions`, this.body) - .reply(200); + const request = nock(API_URL).post(`/users/${data.id}/permissions`, body).reply(200); - this.users.assignPermissions(this.data, this.body).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await usersManager.assignPermissions(data, body); + expect(request.isDone()).to.be.true; }); - it('should include the token in the Authorization header', function (done) { + it('should include the token in the Authorization header', async () => { nock.cleanAll(); const request = nock(API_URL) - .post(`/users/${this.data.id}/permissions`) - .matchHeader('Authorization', `Bearer ${this.token}`) + .post(`/users/${data.id}/permissions`) + .matchHeader('Authorization', `Bearer ${token}`) .reply(200); - this.users.assignPermissions(this.data, {}).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await usersManager.assignPermissions(data, {}); + expect(request.isDone()).to.be.true; }); }); describe('#removePermissions', () => { - beforeEach(function () { - this.data = { + /** + * @typedef {object} data + * @property {string} id Id + */ + + /** + * @typedef {object} body + * @property {string} permission_name Permission name + * @property {string} resource_server_identifier Resource server identifier + */ + + /** + * @type {data} + */ + let data; + + /** + * @type {body} + */ + let body; + + /** + * @type {nock} + */ + let scope; + + beforeEach(() => { + data = { id: 'user_id', }; - this.body = { permission_name: 'My Permission', resource_server_identifier: 'test123' }; + body = { permission_name: 'My Permission', resource_server_identifier: 'test123' }; - this.request = nock(API_URL).delete(`/users/${this.data.id}/permissions`, {}).reply(200); + scope = nock(API_URL).delete(`/users/${data.id}/permissions`, {}).reply(200); }); - it('should validate empty user_id', function () { - const _this = this; - expect(function () { - _this.users.removePermissions({ id: null }, this.body, () => {}); + it('should validate empty user_id', () => { + expect(() => { + usersManager.removePermissions({ id: null }, body, () => {}); }).to.throw('The user_id cannot be null or undefined'); }); - it('should validate non-string user_id', function () { - const _this = this; + it('should validate non-string user_id', () => { expect(() => { - _this.users.removePermissions({ id: 123 }, _this.body, () => {}); + usersManager.removePermissions({ id: 123 }, body, () => {}); }).to.throw('The user_id has to be a string'); }); - it('should accept a callback', function (done) { - this.users.removePermissions(this.data, {}, () => { + it('should accept a callback', (done) => { + usersManager.removePermissions(data, {}, () => { done(); }); }); - it('should return a promise if no callback is given', function (done) { - this.users - .removePermissions(this.data, {}) - .then(done.bind(null, null)) - .catch(done.bind(null, null)); + it('should return a promise if no callback is given', () => { + expect(usersManager.removePermissions(data, {})).instanceOf(Promise); }); - it('should pass any errors to the promise catch handler', function (done) { + it('should pass any errors to the promise catch handler', async () => { nock.cleanAll(); - nock(API_URL).post(`/users/${this.data.id}/permissions`).reply(500); + nock(API_URL).post(`/users/${data.id}/permissions`).reply(500); - this.users.removePermissions(this.data, {}).catch((err) => { + try { + await usersManager.removePermissions(data, {}); + } catch (err) { expect(err).to.exist; - - done(); - }); + } }); - it('should perform a DELETE request to /api/v2/users/user_id/permissions', function (done) { - const { request } = this; - - this.users.removePermissions(this.data, {}).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + it('should perform a DELETE request to /api/v2/users/user_id/permissions', async () => { + await usersManager.removePermissions(data, {}); + expect(scope.isDone()).to.be.true; }); - it('should pass the data in the body of the request', function (done) { + it('should pass the data in the body of the request', async () => { nock.cleanAll(); - const request = nock(API_URL) - .delete(`/users/${this.data.id}/permissions`, this.body) - .reply(200); - - this.users.removePermissions(this.data, this.body).then(() => { - expect(request.isDone()).to.be.true; + const request = nock(API_URL).delete(`/users/${data.id}/permissions`, body).reply(200); - done(); - }); + await usersManager.removePermissions(data, body); + expect(request.isDone()).to.be.true; }); - it('should include the token in the Authorization header', function (done) { + it('should include the token in the Authorization header', async () => { nock.cleanAll(); const request = nock(API_URL) - .delete(`/users/${this.data.id}/permissions`) - .matchHeader('Authorization', `Bearer ${this.token}`) + .delete(`/users/${data.id}/permissions`) + .matchHeader('Authorization', `Bearer ${token}`) .reply(200); - this.users.removePermissions(this.data, {}).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await usersManager.removePermissions(data, {}); + expect(request.isDone()).to.be.true; }); }); @@ -1513,53 +1494,50 @@ describe('UsersManager', () => { id: 'user_id', }; - beforeEach(function () { - this.request = nock(API_URL).get(`/users/${data.id}/organizations`).reply(200); - }); + /** + * @type {nock} + */ + let scope; - it('should accept a callback', function (done) { - this.users.getUserOrganizations(data, done.bind(null, null)); + beforeEach(() => { + scope = nock(API_URL).get(`/users/${data.id}/organizations`).reply(200); }); - it('should return a promise when no callback is given', function (done) { - this.users.getUserOrganizations(data).then(done.bind(null, null)); + it('should accept a callback', (done) => { + usersManager.getUserOrganizations(data, done.bind(null, null)); }); - it('should perform a GET request to /api/v2/users/user_id/organizations', function (done) { - const { request } = this; - - this.users.getUserOrganizations(data).then(() => { - expect(request.isDone()).to.be.true; + it('should return a promise when no callback is given', () => { + expect(usersManager.getUserOrganizations(data)).instanceOf(Promise); + }); - done(); - }); + it('should perform a GET request to /api/v2/users/user_id/organizations', async () => { + await usersManager.getUserOrganizations(data); + expect(scope.isDone()).to.be.true; }); - it('should pass any errors to the promise catch handler', function (done) { + it('should pass any errors to the promise catch handler', async () => { nock.cleanAll(); nock(API_URL).get(`/users/${data.id}/organizations`).reply(500); - this.users.getUserOrganizations(data).catch((err) => { + try { + await usersManager.getUserOrganizations(data); + } catch (err) { expect(err).to.exist; - - done(); - }); + } }); - it('should include the token in the authorization header', function (done) { + it('should include the token in the authorization header', async () => { nock.cleanAll(); const request = nock(API_URL) .get(`/users/${data.id}/organizations`) - .matchHeader('authorization', `Bearer ${this.token}`) + .matchHeader('authorization', `Bearer ${token}`) .reply(200); - this.users.getUserOrganizations(data).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await usersManager.getUserOrganizations(data); + expect(request.isDone()).to.be.true; }); }); }); diff --git a/test/retry-rest-client.tests.js b/test/retry-rest-client.tests.js index 01f4ee7ab..dcd2a1300 100644 --- a/test/retry-rest-client.tests.js +++ b/test/retry-rest-client.tests.js @@ -9,8 +9,9 @@ const RetryRestClient = require('../src/RetryRestClient'); const API_URL = 'https://tenant.auth0.com'; describe('RetryRestClient', () => { - before(function () { - this.restClient = new RestClient(API_URL); + let restClient; + before(() => { + restClient = new RestClient(API_URL); }); it('should raise an error when no RestClient is provided', () => { @@ -44,10 +45,10 @@ describe('RetryRestClient', () => { }); }); - it('should pass data to callback when provided', function (done) { + it('should pass data to callback when provided', (done) => { nock(API_URL).get('/').reply(200, { success: true }); - const client = new RetryRestClient(this.restClient); + const client = new RetryRestClient(restClient); client.getAll((err, data) => { expect(err).to.null; expect(data.success).to.be.true; @@ -55,20 +56,18 @@ describe('RetryRestClient', () => { }); }); - it('should return promise for successful request when no callback is provided', function (done) { + it('should return promise for successful request when no callback is provided', async () => { nock(API_URL).get('/').reply(200, { success: true }); - const client = new RetryRestClient(this.restClient); - client.getAll().then((data) => { - expect(data.success).to.be.true; - done(); - }); + const client = new RetryRestClient(restClient); + const data = await client.getAll(); + expect(data.success).to.be.true; }); - it('should pass err to callback when provided', function (done) { + it('should pass err to callback when provided', (done) => { nock(API_URL).get('/').reply(500); - const client = new RetryRestClient(this.restClient); + const client = new RetryRestClient(restClient); client.getAll((err) => { expect(err).to.not.null; expect(err.statusCode).to.be.equal(500); @@ -76,45 +75,42 @@ describe('RetryRestClient', () => { }); }); - it('should return promise for failed request when no callback is provided', function (done) { + it('should return promise for failed request when no callback is provided', async () => { nock(API_URL).get('/').reply(500); - const client = new RetryRestClient(this.restClient); - client.getAll().catch((err) => { + const client = new RetryRestClient(restClient); + try { + await client.getAll(); + } catch (err) { expect(err).to.not.null; expect(err.statusCode).to.be.equal(500); - done(); - }); + } }); - it('should retry once when an error is returned', function (done) { - const self = this; + it('should retry once when an error is returned', async () => { let timesCalled = 0; const restClientSpy = { getAll(...args) { timesCalled += 1; - return self.restClient.getAll(args); + return restClient.getAll(args); }, }; nock(API_URL).get('/').reply(429, { success: false }).get('/').reply(200, { success: true }); const client = new RetryRestClient(restClientSpy); - client.getAll().then((data) => { - expect(data.success).to.be.true; - expect(timesCalled).to.be.equal(2); - done(); - }); + const data = await client.getAll(); + expect(data.success).to.be.true; + expect(timesCalled).to.be.equal(2); }); - it('should try 4 times when request fails 3 times', function (done) { - const self = this; + it('should try 4 times when request fails 3 times', async () => { const clock = sinon.useFakeTimers(); let timesCalled = 0; const restClientSpy = { getAll(...args) { timesCalled += 1; - return self.restClient.getAll(...args).finally(() => { + return restClient.getAll(...args).finally(() => { clock.runAllAsync(); }); }, @@ -128,22 +124,19 @@ describe('RetryRestClient', () => { .reply(200, { success: true }); const client = new RetryRestClient(restClientSpy); - client.getAll().then((data) => { - clock.restore(); - expect(data.success).to.be.true; - expect(timesCalled).to.be.equal(4); - done(); - }); + const data = await client.getAll(); + clock.restore(); + expect(data.success).to.be.true; + expect(timesCalled).to.be.equal(4); }); - it('should retry 2 times and fail when maxRetries is exceeded', function (done) { - const self = this; + it('should retry 2 times and fail when maxRetries is exceeded', async () => { const clock = sinon.useFakeTimers(); let timesCalled = 0; const restClientSpy = { getAll(...args) { timesCalled += 1; - return self.restClient.getAll(...args).finally(() => { + return restClient.getAll(...args).finally(() => { clock.runAllAsync(); }); }, @@ -152,27 +145,28 @@ describe('RetryRestClient', () => { nock(API_URL).get('/').times(4).reply(429, { success: false }); const client = new RetryRestClient(restClientSpy, { maxRetries: 3 }); - client.getAll().catch((err) => { + try { + await client.getAll(); + } catch (err) { clock.restore(); expect(err).to.not.null; expect(timesCalled).to.be.equal(4); // Initial call + 3 retires. - done(); - }); + } }); - it('should not retry when status code is not 429', function (done) { + it('should not retry when status code is not 429', async () => { nock(API_URL).get('/').reply(500); - const client = new RetryRestClient(this.restClient); - client.getAll().catch((err) => { + const client = new RetryRestClient(restClient); + try { + await client.getAll(); + } catch (err) { expect(err).to.not.null; expect(err.statusCode).to.be.equal(500); - done(); - }); + } }); - it('should delay the retry using exponential backoff and succeed after retry', function (done) { - const self = this; + it('should delay the retry using exponential backoff and succeed after retry', async () => { const clock = sinon.useFakeTimers(); const backoffs = []; let prev = 0; @@ -181,7 +175,7 @@ describe('RetryRestClient', () => { const now = new Date().getTime(); backoffs.push(now - prev); prev = now; - return self.restClient.getAll(...args).finally(() => { + return restClient.getAll(...args).finally(() => { clock.runAllAsync(); }); }, @@ -196,42 +190,40 @@ describe('RetryRestClient', () => { const client = new RetryRestClient(restClientSpy, { maxRetries: 10 }); - client.getAll().then((data) => { - clock.restore(); - expect(data.success).to.be.true; - expect(backoffs.length).to.be.equal(10); - - expect(backoffs.shift()).to.be.equal(0, 'first request should happen immediately'); - for (let i = 0; i < backoffs.length; i++) { - expect(backoffs[i] / 1000).to.be.within( - Math.pow(2, i), - 2 * Math.pow(2, i), - `attempt ${i + 1} in secs` - ); - } - done(); - }); + const data = await client.getAll(); + clock.restore(); + expect(data.success).to.be.true; + expect(backoffs.length).to.be.equal(10); + + expect(backoffs.shift()).to.be.equal(0, 'first request should happen immediately'); + for (let i = 0; i < backoffs.length; i++) { + expect(backoffs[i] / 1000).to.be.within( + Math.pow(2, i), + 2 * Math.pow(2, i), + `attempt ${i + 1} in secs` + ); + } }); - it('should not retry when retry functionality is disabled', function (done) { - const self = this; + it('should not retry when retry functionality is disabled', async () => { let timesCalled = 0; const restClientSpy = { getAll(...args) { timesCalled += 1; - return self.restClient.getAll(...args); + return restClient.getAll(...args); }, }; nock(API_URL).get('/').reply(429, { success: false }); const client = new RetryRestClient(restClientSpy, { enabled: false }); - client.getAll().catch((err) => { + try { + await client.getAll(); + } catch (err) { expect(err).to.not.null; expect(err.statusCode).to.be.equal(429); expect(timesCalled).to.be.equal(1); - done(); - }); + } }); it('should remove callback from arguments object if data is passed', (done) => { From fb49243126aab24b997695d4d6a41b87f0cf8259 Mon Sep 17 00:00:00 2001 From: hornta Date: Tue, 5 Oct 2021 11:03:10 +0200 Subject: [PATCH 07/22] Refactor test to use async/await for increased readability --- .eslintrc.js | 3 + src/Auth0RestClient.js | 2 +- src/management/JobsManager.js | 38 ++-- test/auth/database-auth.tests.js | 208 +++++------------- .../oauth-with-idtoken-validation.tests.js | 44 ++-- test/auth0-rest-client.tests.js | 33 ++- test/management/roles.tests.js | 127 ++++------- test/management/rules-configs.tests.js | 94 +++----- test/management/rules.tests.js | 140 +++++------- test/management/stats.tests.js | 62 ++---- test/management/tenant.tests.js | 62 ++---- test/management/tickets.tests.js | 50 ++--- test/management/user-blocks.tests.js | 111 +++------- 13 files changed, 335 insertions(+), 639 deletions(-) diff --git a/.eslintrc.js b/.eslintrc.js index 88e4502bd..a692ef535 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -56,5 +56,8 @@ module.exports = { 'jsdoc/no-undefined-types': 'off', 'jsdoc/require-param': 'off', 'jsdoc/check-param-names': 'off', + + 'promise/catch-or-return': 'off', + 'promise/always-return': 'off', }, }; diff --git a/src/Auth0RestClient.js b/src/Auth0RestClient.js index 134220e36..79aacded3 100644 --- a/src/Auth0RestClient.js +++ b/src/Auth0RestClient.js @@ -45,7 +45,7 @@ class Auth0RestClient { if (callback) { return callback(err); } - return Promise.reject(err); + throw err; }); }; } diff --git a/src/management/JobsManager.js b/src/management/JobsManager.js index cfa684792..05ddcf26c 100644 --- a/src/management/JobsManager.js +++ b/src/management/JobsManager.js @@ -128,24 +128,26 @@ class JobsManager { const headers = { ...options.headers, ...form.getHeaders() }; headers['Content-Type'] = 'multipart/form-data'; - const promise = options.tokenProvider.getAccessToken().then((access_token) => - axios - .post(url, form, { headers: { ...headers, Authorization: `Bearer ${access_token}` } }) - .catch((err) => { - if (!err.response) { - return Promise.reject(err); - } - - const res = err.response; - // `superagent` uses the error parameter in callback on http errors. - // the following code is intended to keep that behaviour (https://github.com/visionmedia/superagent/blob/master/lib/node/response.js#L170) - const error = new Error(`${'cannot POST' + ' '}${url} (${res.status})`); - error.status = res.status; - error.method = 'POST'; - error.text = res.data.message || res.statusText || error.message; - return Promise.reject(error); - }) - ); + const promise = options.tokenProvider.getAccessToken().then((access_token) => { + try { + return axios.post(url, form, { + headers: { ...headers, Authorization: `Bearer ${access_token}` }, + }); + } catch (err) { + if (!err.response) { + throw err; + } + + const res = err.response; + // `superagent` uses the error parameter in callback on http errors. + // the following code is intended to keep that behaviour (https://github.com/visionmedia/superagent/blob/master/lib/node/response.js#L170) + const error = new Error(`${'cannot POST' + ' '}${url} (${res.status})`); + error.status = res.status; + error.method = 'POST'; + error.text = res.data.message || res.statusText || error.message; + throw error; + } + }); // Don't return a promise if a callback was given. if (cb && cb instanceof Function) { diff --git a/test/auth/database-auth.tests.js b/test/auth/database-auth.tests.js index 9ecfcc8a8..c1bfb82a5 100644 --- a/test/auth/database-auth.tests.js +++ b/test/auth/database-auth.tests.js @@ -84,24 +84,18 @@ describe('DatabaseAuthenticator', () => { this.authenticator.signIn(userData, done.bind(null, null)); }); - it('should return a promise when no callback is provided', function (done) { - this.authenticator.signIn(userData).then(done.bind(null, null)).catch(done.bind(null, null)); + it('should return a promise when no callback is provided', function () { + expect(this.authenticator.signIn(userData)).instanceOf(Promise); }); - it(`should perform a POST request to ${path}`, function (done) { + it(`should perform a POST request to ${path}`, async function () { const { request } = this; - this.authenticator - .signIn(userData) - .then(() => { - expect(request.isDone()).to.be.true; - - done(); - }) - .catch(done); + await this.authenticator.signIn(userData); + expect(request.isDone()).to.be.true; }); - it('should include the user data in the request', function (done) { + it('should include the user data in the request', async function () { nock.cleanAll(); const request = nock(API_URL) @@ -116,51 +110,33 @@ describe('DatabaseAuthenticator', () => { }) .reply(200); - this.authenticator - .signIn(userData) - .then(() => { - expect(request.isDone()).to.be.true; - - done(); - }) - .catch(done); + await this.authenticator.signIn(userData); + expect(request.isDone()).to.be.true; }); - it('should include the Auth0 client ID in the request', function (done) { + it('should include the Auth0 client ID in the request', async function () { nock.cleanAll(); const request = nock(API_URL) .post(path, (body) => body.client_id === CLIENT_ID) .reply(200); - this.authenticator - .signIn(userData) - .then(() => { - expect(request.isDone()).to.be.true; - - done(); - }) - .catch(done); + await this.authenticator.signIn(userData); + expect(request.isDone()).to.be.true; }); - it('should use Username-Password-Authentication by default', function (done) { + it('should use Username-Password-Authentication by default', async function () { nock.cleanAll(); const request = nock(API_URL) .post(path, (body) => body.connection === 'Username-Password-Authentication') .reply(200); - this.authenticator - .signIn(userData) - .then(() => { - expect(request.isDone()).to.be.true; - - done(); - }) - .catch(done); + await this.authenticator.signIn(userData); + expect(request.isDone()).to.be.true; }); - it('should allow the user to specify the connection', function (done) { + it('should allow the user to specify the connection', async function () { nock.cleanAll(); const data = { connection: 'TEST_CONNECTION', ...userData }; @@ -168,34 +144,22 @@ describe('DatabaseAuthenticator', () => { .post(path, (body) => body.connection === 'TEST_CONNECTION') .reply(200); - this.authenticator - .signIn(data) - .then(() => { - expect(request.isDone()).to.be.true; - - done(); - }) - .catch(done); + await this.authenticator.signIn(data); + expect(request.isDone()).to.be.true; }); - it('should use password as default grant type', function (done) { + it('should use password as default grant type', async function () { nock.cleanAll(); const request = nock(API_URL) .post(path, (body) => body.grant_type === 'password') .reply(200); - this.authenticator - .signIn(userData) - .then(() => { - expect(request.isDone()).to.be.true; - - done(); - }) - .catch(done); + await this.authenticator.signIn(userData); + expect(request.isDone()).to.be.true; }); - it('should allow the user to specify the grant type', function (done) { + it('should allow the user to specify the grant type', async function () { nock.cleanAll(); const data = { grant_type: 'TEST_GRANT', ...userData }; @@ -203,31 +167,19 @@ describe('DatabaseAuthenticator', () => { .post(path, (body) => body.grant_type === 'TEST_GRANT') .reply(200); - this.authenticator - .signIn(data) - .then(() => { - expect(request.isDone()).to.be.true; - - done(); - }) - .catch(done); + await this.authenticator.signIn(data); + expect(request.isDone()).to.be.true; }); - it('should use the openid scope by default', function (done) { + it('should use the openid scope by default', async function () { nock.cleanAll(); const request = nock(API_URL) .post(path, (body) => body.scope === 'openid') .reply(200); - this.authenticator - .signIn(userData) - .then(() => { - expect(request.isDone()).to.be.true; - - done(); - }) - .catch(done); + await this.authenticator.signIn(userData); + expect(request.isDone()).to.be.true; }); }); @@ -285,20 +237,14 @@ describe('DatabaseAuthenticator', () => { this.authenticator.signUp(userData).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it(`should perform a POST request to ${path}`, function (done) { + it(`should perform a POST request to ${path}`, async function () { const { request } = this; - this.authenticator - .signUp(userData) - .then(() => { - expect(request.isDone()).to.be.true; - - done(); - }) - .catch(done); + await this.authenticator.signUp(userData); + expect(request.isDone()).to.be.true; }); - it('should include the user data in the request', function (done) { + it('should include the user data in the request', async function () { nock.cleanAll(); const request = nock(API_URL) @@ -313,31 +259,19 @@ describe('DatabaseAuthenticator', () => { }) .reply(200); - this.authenticator - .signUp(userData) - .then(() => { - expect(request.isDone()).to.be.true; - - done(); - }) - .catch(done); + await this.authenticator.signUp(userData); + expect(request.isDone()).to.be.true; }); - it('should include the Auth0 client ID in the request', function (done) { + it('should include the Auth0 client ID in the request', async function () { nock.cleanAll(); const request = nock(API_URL) .post(path, (body) => body.client_id === CLIENT_ID) .reply(200); - this.authenticator - .signUp(userData) - .then(() => { - expect(request.isDone()).to.be.true; - - done(); - }) - .catch(done); + await this.authenticator.signUp(userData); + expect(request.isDone()).to.be.true; }); }); @@ -398,20 +332,14 @@ describe('DatabaseAuthenticator', () => { .catch(done.bind(null, null)); }); - it(`should perform a POST request to ${path}`, function (done) { + it(`should perform a POST request to ${path}`, async function () { const { request } = this; - this.authenticator - .changePassword(userData) - .then(() => { - expect(request.isDone()).to.be.true; - - done(); - }) - .catch(done); + await this.authenticator.changePassword(userData); + expect(request.isDone()).to.be.true; }); - it('should include the user data in the request', function (done) { + it('should include the user data in the request', async function () { nock.cleanAll(); const request = nock(API_URL) @@ -426,31 +354,19 @@ describe('DatabaseAuthenticator', () => { }) .reply(200); - this.authenticator - .changePassword(userData) - .then(() => { - expect(request.isDone()).to.be.true; - - done(); - }) - .catch(done); + await this.authenticator.changePassword(userData); + expect(request.isDone()).to.be.true; }); - it('should include the Auth0 client ID in the request', function (done) { + it('should include the Auth0 client ID in the request', async function () { nock.cleanAll(); const request = nock(API_URL) .post(path, (body) => body.client_id === CLIENT_ID) .reply(200); - this.authenticator - .changePassword(userData) - .then(() => { - expect(request.isDone()).to.be.true; - - done(); - }) - .catch(done); + await this.authenticator.changePassword(userData); + expect(request.isDone()).to.be.true; }); }); @@ -498,20 +414,14 @@ describe('DatabaseAuthenticator', () => { .catch(done.bind(null, null)); }); - it(`should perform a POST request to ${path}`, function (done) { + it(`should perform a POST request to ${path}`, async function () { const { request } = this; - this.authenticator - .requestChangePasswordEmail(userData) - .then(() => { - expect(request.isDone()).to.be.true; - - done(); - }) - .catch(done); + await this.authenticator.requestChangePasswordEmail(userData); + expect(request.isDone()).to.be.true; }); - it('should include the user data in the request', function (done) { + it('should include the user data in the request', async function () { nock.cleanAll(); const request = nock(API_URL) @@ -526,31 +436,19 @@ describe('DatabaseAuthenticator', () => { }) .reply(200); - this.authenticator - .requestChangePasswordEmail(userData) - .then(() => { - expect(request.isDone()).to.be.true; - - done(); - }) - .catch(done); + await this.authenticator.requestChangePasswordEmail(userData); + expect(request.isDone()).to.be.true; }); - it('should include the Auth0 client ID in the request', function (done) { + it('should include the Auth0 client ID in the request', async function () { nock.cleanAll(); const request = nock(API_URL) .post(path, (body) => body.client_id === CLIENT_ID) .reply(200); - this.authenticator - .requestChangePasswordEmail(userData) - .then(() => { - expect(request.isDone()).to.be.true; - - done(); - }) - .catch(done); + await this.authenticator.requestChangePasswordEmail(userData); + expect(request.isDone()).to.be.true; }); }); }); diff --git a/test/auth/oauth-with-idtoken-validation.tests.js b/test/auth/oauth-with-idtoken-validation.tests.js index da14493af..3db636fe9 100644 --- a/test/auth/oauth-with-idtoken-validation.tests.js +++ b/test/auth/oauth-with-idtoken-validation.tests.js @@ -70,7 +70,7 @@ describe('OAUthWithIDTokenValidation', () => { it('Does nothing when there is no id_token', (done) => { const oauth = { create() { - return new Promise((res) => res({})); + return new Promise((resolve) => resolve({})); }, }; const oauthWithValidation = new OAUthWithIDTokenValidation(oauth, {}); @@ -79,7 +79,7 @@ describe('OAUthWithIDTokenValidation', () => { it('Bypasses validation when options.__bypassIdTokenValidation is true', (done) => { const oauth = { create() { - return new Promise((res) => res({ id_token: 'foobar' })); + return new Promise((resolve) => resolve({ id_token: 'foobar' })); }, }; const oauthWithValidation = new OAUthWithIDTokenValidation(oauth, { @@ -90,7 +90,7 @@ describe('OAUthWithIDTokenValidation', () => { it('Calls jwt.verify with token and algs', (done) => { const oauth = { create() { - return new Promise((res) => res({ id_token: 'foobar' })); + return new Promise((resolve) => resolve({ id_token: 'foobar' })); }, }; sinon.stub(jwt, 'verify').callsFake((idtoken, getKey, options) => { @@ -111,7 +111,7 @@ describe('OAUthWithIDTokenValidation', () => { it('Returns auth result when verify response is successful', (done) => { const oauth = { create() { - return new Promise((res) => res({ id_token: 'foobar' })); + return new Promise((resolve) => resolve({ id_token: 'foobar' })); }, }; sinon.stub(jwt, 'verify').callsFake((idtoken, getKey, options, callback) => { @@ -133,7 +133,7 @@ describe('OAUthWithIDTokenValidation', () => { it('Returns error when verify response is an error', (done) => { const oauth = { create() { - return new Promise((res) => res({ id_token: 'foobar' })); + return new Promise((resolve) => resolve({ id_token: 'foobar' })); }, }; sinon.stub(jwt, 'verify').callsFake((idtoken, getKey, options, callback) => { @@ -148,7 +148,7 @@ describe('OAUthWithIDTokenValidation', () => { it('Uses `clientSecret` as key when header.alg === HS256 and there is a user secret', (done) => { const oauth = { create() { - return new Promise((res) => res({ id_token: 'foobar' })); + return new Promise((resolve) => resolve({ id_token: 'foobar' })); }, }; sinon.stub(jwt, 'verify').callsFake((idtoken, getKey) => { @@ -165,7 +165,7 @@ describe('OAUthWithIDTokenValidation', () => { it('Returns unvalidated response when header.alg === HS256 and there is no user secret', (done) => { const oauth = { create() { - return new Promise((res) => res({ id_token: 'foobar' })); + return new Promise((resolve) => resolve({ id_token: 'foobar' })); }, }; const OAUthWithIDTokenValidationProxy = proxyquire( @@ -193,7 +193,7 @@ describe('OAUthWithIDTokenValidation', () => { describe('when header.alg !== HS256', () => { it('creates a jwksClient with the correct jwksUri', (done) => { const oauth = { - create: () => new Promise((res) => res({ id_token: 'foobar' })), + create: () => new Promise((resolve) => resolve({ id_token: 'foobar' })), }; const jwksClientStub = sinon.spy(() => ({ @@ -220,7 +220,7 @@ describe('OAUthWithIDTokenValidation', () => { it('returns the error when available', (done) => { const oauth = { create() { - return new Promise((res) => res({ id_token: 'foobar' })); + return new Promise((resolve) => resolve({ id_token: 'foobar' })); }, }; const jwksClientStub = sinon.spy(() => ({ @@ -245,7 +245,7 @@ describe('OAUthWithIDTokenValidation', () => { it('uses the publicKey when available', (done) => { const oauth = { create() { - return new Promise((res) => res({ id_token: 'foobar' })); + return new Promise((resolve) => resolve({ id_token: 'foobar' })); }, }; const jwksClientStub = sinon.spy(() => ({ @@ -271,7 +271,7 @@ describe('OAUthWithIDTokenValidation', () => { it('uses the publicKey when both keys (publicKey and rsaPublicKey) available', (done) => { const oauth = { create() { - return new Promise((res) => res({ id_token: 'foobar' })); + return new Promise((resolve) => resolve({ id_token: 'foobar' })); }, }; const jwksClientStub = sinon.spy(() => ({ @@ -297,7 +297,7 @@ describe('OAUthWithIDTokenValidation', () => { it('uses the rsaPublicKey when there is no publicKey available', (done) => { const oauth = { create() { - return new Promise((res) => res({ id_token: 'foobar' })); + return new Promise((resolve) => resolve({ id_token: 'foobar' })); }, }; const jwksClientStub = sinon.spy(() => ({ @@ -325,8 +325,8 @@ describe('OAUthWithIDTokenValidation', () => { it('fails with a HS256 id_token and `options.supportedAlgorithms===RS256`', (done) => { const oauth = { create() { - return new Promise((res) => - res({ + return new Promise((resolve) => + resolve({ id_token: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuaWNrbmFtZSI6ImpvaG5mb28iLCJuYW1lIjoiam9obmZvb0BnbWFpbC5jb20iLCJwaWN0dXJlIjoiaHR0cHM6Ly9zLmdyYXZhdGFyLmNvbS9hdmF0YXIvMzhmYTAwMjQyM2JkOGM5NDFjNmVkMDU4OGI2MGZmZWQ_cz00ODAmcj1wZyZkPWh0dHBzJTNBJTJGJTJGY2RuLmF1dGgwLmNvbSUyRmF2YXRhcnMlMkZqby5wbmciLCJ1cGRhdGVkX2F0IjoiMjAxOC0wOS0xMlQyMDo1MjoxMS4zMDZaIiwiZW1haWwiOiJqb2huZm9vQGdtYWlsLmNvbSIsImVtYWlsX3ZlcmlmaWVkIjpmYWxzZSwiaXNzIjoiaHR0cHM6Ly9hdXRoLmJydWNrZS5jbHViLyIsInN1YiI6ImF1dGgwfDVhMjA1NGZmNDUxNTc3MTFiZTgxODJmNCIsImF1ZCI6IkVxbjdHTUV3VzhDbmN1S2FhcFRuNWs5VEJ0MzRQdldmIiwiaWF0IjoxNTM2Nzg1NTMxLCJleHAiOjE1MzY4MjE1MzF9.mZGsJyJYyp_mkINcnV0JRJ6QPsTXUE8FrpRTruAIqhE', }) @@ -352,8 +352,8 @@ describe('OAUthWithIDTokenValidation', () => { }); const oauth = { create() { - return new Promise((res) => - res({ + return new Promise((resolve) => + resolve({ id_token: idtoken, }) ); @@ -387,8 +387,8 @@ describe('OAUthWithIDTokenValidation', () => { }); const oauth = { create() { - return new Promise((res) => - res({ + return new Promise((resolve) => + resolve({ id_token: idtoken, }) ); @@ -422,8 +422,8 @@ describe('OAUthWithIDTokenValidation', () => { }); const oauth = { create() { - return new Promise((res) => - res({ + return new Promise((resolve) => + resolve({ id_token: idtoken, }) ); @@ -459,8 +459,8 @@ describe('OAUthWithIDTokenValidation', () => { }); const oauth = { create() { - return new Promise((res) => - res({ + return new Promise((resolve) => + resolve({ id_token: idtoken, }) ); diff --git a/test/auth0-rest-client.tests.js b/test/auth0-rest-client.tests.js index 3f6a1a6a1..a44df6e7c 100644 --- a/test/auth0-rest-client.tests.js +++ b/test/auth0-rest-client.tests.js @@ -84,18 +84,18 @@ describe('Auth0RestClient', () => { nock.cleanAll(); }); }); - it('should return a promise if no callback is provided', function (done) { + it('should return a promise if no callback is provided', async function () { nock(API_URL).get('/some-resource').reply(200, { data: 'value' }); const options = { headers: {}, }; const client = new Auth0RestClient(`${API_URL}/some-resource`, options, this.providerMock); - client.get().then((data) => { - expect(data).to.deep.equal({ data: 'value' }); - done(); - nock.cleanAll(); - }); + const returnValue = client.get(); + expect(returnValue).instanceOf(Promise); + const data = await returnValue; + expect(data).to.deep.equal({ data: 'value' }); + nock.cleanAll(); }); }); @@ -150,7 +150,7 @@ describe('Auth0RestClient', () => { }); }); - it('should return a promise if no callback is given', function (done) { + it('should return a promise if no callback is given', async function () { nock(API_URL).get('/some-resource').reply(200, { data: 'value' }); const options = { @@ -158,11 +158,9 @@ describe('Auth0RestClient', () => { }; const client = new Auth0RestClient(`${API_URL}/some-resource`, options, this.providerMock); - client.getAll().then((data) => { - expect(data).to.deep.equal({ data: 'value' }); - done(); - nock.cleanAll(); - }); + const data = await client.getAll(); + expect(data).to.deep.equal({ data: 'value' }); + nock.cleanAll(); }); it('should accept a callback and handle errors', (done) => { @@ -186,7 +184,7 @@ describe('Auth0RestClient', () => { }); }); - it('should set access token as Authorization header in options object', function (done) { + it('should set access token as Authorization header in options object', async function () { nock(API_URL).get('/some-resource').reply(200); const options = { @@ -194,11 +192,10 @@ describe('Auth0RestClient', () => { }; const client = new Auth0RestClient(`${API_URL}/some-resource`, options, this.providerMock); - client.getAll().then(() => { - expect(client.restClient.options.headers['Authorization']).to.be.equal('Bearer access_token'); - done(); - nock.cleanAll(); - }); + await client.getAll(); + expect(client.restClient.options.headers['Authorization']).to.be.equal('Bearer access_token'); + + nock.cleanAll(); }); it('should sanitize error when access token is in authorization header', function (done) { diff --git a/test/management/roles.tests.js b/test/management/roles.tests.js index 6891caee8..493599541 100644 --- a/test/management/roles.tests.js +++ b/test/management/roles.tests.js @@ -82,33 +82,28 @@ describe('RolesManager', () => { }); }); - it('should pass the body of the response to the "then" handler', function (done) { + it('should pass the body of the response to the "then" handler', async function () { nock.cleanAll(); const data = [{ test: true }]; nock(API_URL).get('/roles').reply(200, data); - this.roles.getAll().then((credentials) => { - expect(credentials).to.be.an.instanceOf(Array); + const credentials = await this.roles.getAll(); + expect(credentials).to.be.an.instanceOf(Array); - expect(credentials.length).to.equal(data.length); + expect(credentials.length).to.equal(data.length); - expect(credentials[0].test).to.equal(data[0].test); - - done(); - }); + expect(credentials[0].test).to.equal(data[0].test); }); - it('should perform a GET request to /api/v2/roles', function (done) { + it('should perform a GET request to /api/v2/roles', async function () { const { request } = this; - this.roles.getAll().then(() => { - expect(request.isDone()).to.be.true; - done(); - }); + await this.roles.getAll(); + expect(request.isDone()).to.be.true; }); - it('should include the token in the Authorization header', function (done) { + it('should include the token in the Authorization header', async function () { nock.cleanAll(); const request = nock(API_URL) @@ -116,13 +111,11 @@ describe('RolesManager', () => { .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.roles.getAll().then(() => { - expect(request.isDone()).to.be.true; - done(); - }); + await this.roles.getAll(); + expect(request.isDone()).to.be.true; }); - it('should pass the parameters in the query-string', function (done) { + it('should pass the parameters in the query-string', async function () { nock.cleanAll(); const params = { @@ -131,11 +124,8 @@ describe('RolesManager', () => { }; const request = nock(API_URL).get('/roles').query(params).reply(200); - this.roles.getAll(params).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await this.roles.getAll(params); + expect(request.isDone()).to.be.true; }); }); @@ -160,14 +150,11 @@ describe('RolesManager', () => { this.roles.get({ id: this.data.id }).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should perform a POST request to /api/v2/roles/rol_ID', function (done) { + it('should perform a POST request to /api/v2/roles/rol_ID', async function () { const { request } = this; - this.roles.get({ id: this.data.id }).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await this.roles.get({ id: this.data.id }); + expect(request.isDone()).to.be.true; }); it('should pass any errors to the promise catch handler', function (done) { @@ -231,26 +218,20 @@ describe('RolesManager', () => { }); }); - it('should perform a POST request to /api/v2/roles', function (done) { + it('should perform a POST request to /api/v2/roles', async function () { const { request } = this; - this.roles.create(data).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await this.roles.create(data); + expect(request.isDone()).to.be.true; }); - it('should pass the data in the body of the request', function (done) { + it('should pass the data in the body of the request', async function () { nock.cleanAll(); const request = nock(API_URL).post('/roles', data).reply(200); - this.roles.create(data).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await this.roles.create(data); + expect(request.isDone()).to.be.true; }); it('should include the token in the Authorization header', function (done) { @@ -297,16 +278,13 @@ describe('RolesManager', () => { }); }); - it('should include the new data in the body of the request', function (done) { + it('should include the new data in the body of the request', async function () { nock.cleanAll(); const request = nock(API_URL).patch(`/roles/${this.data.id}`, this.data).reply(200); - this.roles.update({ id: 'rol_ID' }, this.data).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await this.roles.update({ id: 'rol_ID' }, this.data); + expect(request.isDone()).to.be.true; }); it('should pass any errors to the promise catch handler', function (done) { @@ -333,18 +311,15 @@ describe('RolesManager', () => { this.roles.delete({ id }, done.bind(null, null)); }); - it('should return a promise when no callback is given', function (done) { - this.roles.delete({ id }).then(done.bind(null, null)); + it('should return a promise when no callback is given', function () { + expect(this.roles.delete({ id })).instanceOf(Promise); }); - it(`should perform a delete request to /roles/${id}`, function (done) { + it(`should perform a delete request to /roles/${id}`, async function () { const { request } = this; - this.roles.delete({ id }).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await this.roles.delete({ id }); + expect(request.isDone()).to.be.true; }); it('should pass any errors to the promise catch handler', function (done) { @@ -359,7 +334,7 @@ describe('RolesManager', () => { }); }); - it('should include the token in the authorization header', function (done) { + it('should include the token in the authorization header', async function () { nock.cleanAll(); const request = nock(API_URL) @@ -367,11 +342,8 @@ describe('RolesManager', () => { .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); - this.roles.delete({ id }).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await this.roles.delete({ id }); + expect(request.isDone()).to.be.true; }); }); @@ -388,18 +360,15 @@ describe('RolesManager', () => { this.roles.getPermissions(data, done.bind(null, null)); }); - it('should return a promise when no callback is given', function (done) { - this.roles.getPermissions(data).then(done.bind(null, null)); + it('should return a promise when no callback is given', function () { + expect(this.roles.getPermissions(data)).instanceOf(Promise); }); - it('should perform a GET request to /api/v2/roles/rol_ID/permissions', function (done) { + it('should perform a GET request to /api/v2/roles/rol_ID/permissions', async function () { const { request } = this; - this.roles.getPermissions(data).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await this.roles.getPermissions(data); + expect(request.isDone()).to.be.true; }); it('should pass any errors to the promise catch handler', function (done) { @@ -414,7 +383,7 @@ describe('RolesManager', () => { }); }); - it('should include the token in the authorization header', function (done) { + it('should include the token in the authorization header', async function () { nock.cleanAll(); const request = nock(API_URL) @@ -422,11 +391,8 @@ describe('RolesManager', () => { .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); - this.roles.getPermissions(data).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await this.roles.getPermissions(data); + expect(request.isDone()).to.be.true; }); }); @@ -465,14 +431,11 @@ describe('RolesManager', () => { }); }); - it('should perform a POST request to /api/v2/roles/rol_ID/permissions', function (done) { + it('should perform a POST request to /api/v2/roles/rol_ID/permissions', async function () { const { request } = this; - this.roles.addPermissions(this.data, {}).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await this.roles.addPermissions(this.data, {}); + expect(request.isDone()).to.be.true; }); it('should pass the data in the body of the request', function (done) { diff --git a/test/management/rules-configs.tests.js b/test/management/rules-configs.tests.js index ce6d4c378..4de74bb89 100644 --- a/test/management/rules-configs.tests.js +++ b/test/management/rules-configs.tests.js @@ -67,35 +67,30 @@ describe('RulesConfigsManager', () => { }); }); - it('should pass the body of the response to the "then" handler', function (done) { + it('should pass the body of the response to the "then" handler', async function () { nock.cleanAll(); const data = [{ key: 'dbconnectionstring' }]; nock(API_URL).get('/rules-configs').reply(200, data); - this.rulesConfigs.getAll().then((rulesConfigs) => { - expect(rulesConfigs).to.be.an.instanceOf(Array); + const rulesConfigs = await this.rulesConfigs.getAll(); + expect(rulesConfigs).to.be.an.instanceOf(Array); - expect(rulesConfigs.length).to.equal(data.length); + expect(rulesConfigs.length).to.equal(data.length); - expect(rulesConfigs[0].key).to.equal(data[0].key); - - done(); - }); + expect(rulesConfigs[0].key).to.equal(data[0].key); }); - it('should perform a GET request to rules-configs', function (done) { + it('should perform a GET request to rules-configs', async function () { nock.cleanAll(); const request = nock(API_URL).get('/rules-configs').reply(200); - this.rulesConfigs.getAll().then(() => { - expect(request.isDone()).to.be.true; - done(); - }); + await this.rulesConfigs.getAll(); + expect(request.isDone()).to.be.true; }); - it('should include the token in the Authorization header', function (done) { + it('should include the token in the Authorization header', async function () { nock.cleanAll(); const request = nock(API_URL) @@ -103,13 +98,11 @@ describe('RulesConfigsManager', () => { .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.rulesConfigs.getAll().then(() => { - expect(request.isDone()).to.be.true; - done(); - }); + await this.rulesConfigs.getAll(); + expect(request.isDone()).to.be.true; }); - it('should pass the parameters in the query-string', function (done) { + it('should pass the parameters in the query-string', async function () { nock.cleanAll(); const params = { @@ -118,11 +111,8 @@ describe('RulesConfigsManager', () => { }; const request = nock(API_URL).get('/rules-configs').query(params).reply(200); - this.rulesConfigs.getAll(params).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await this.rulesConfigs.getAll(params); + expect(request.isDone()).to.be.true; }); }); @@ -157,38 +147,25 @@ describe('RulesConfigsManager', () => { }); }); - it('should perform a PUT request to /rules-configs/{KEY}', function (done) { + it('should perform a PUT request to /rules-configs/{KEY}', async function () { nock.cleanAll(); const request = nock(API_URL).put(`/rules-configs/${this.params.key}`, this.data).reply(200); - this.rulesConfigs - .set(this.params, this.data) - .then(() => { - expect(request.isDone()).to.be.true; - - done(); - }) - .catch((err) => { - console.error(err); - expect.fail(); - done(); - }); + await this.rulesConfigs.set(this.params, this.data); + expect(request.isDone()).to.be.true; }); - it('should pass the data in the body of the request', function (done) { + it('should pass the data in the body of the request', async function () { nock.cleanAll(); const request = nock(API_URL).put(`/rules-configs/${this.params.key}`, this.data).reply(200); - this.rulesConfigs.set(this.params, this.data).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await this.rulesConfigs.set(this.params, this.data); + expect(request.isDone()).to.be.true; }); - it('should include the token in the Authorization header', function (done) { + it('should include the token in the Authorization header', async function () { nock.cleanAll(); const request = nock(API_URL) @@ -196,11 +173,8 @@ describe('RulesConfigsManager', () => { .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.rulesConfigs.set(this.params, this.data).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await this.rulesConfigs.set(this.params, this.data); + expect(request.isDone()).to.be.true; }); }); @@ -215,18 +189,15 @@ describe('RulesConfigsManager', () => { this.rulesConfigs.delete({ key }, done.bind(null, null)); }); - it('should return a promise when no callback is given', function (done) { - this.rulesConfigs.delete({ key }).then(done.bind(null, null)); + it('should return a promise when no callback is given', function () { + expect(this.rulesConfigs.delete({ key })).instanceOf(Promise); }); - it(`should perform a delete request to /rules-configs/${key}`, function (done) { + it(`should perform a delete request to /rules-configs/${key}`, async function () { const { request } = this; - this.rulesConfigs.delete({ key }).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await this.rulesConfigs.delete({ key }); + expect(request.isDone()).to.be.true; }); it('should pass any errors to the promise catch handler', function (done) { @@ -241,7 +212,7 @@ describe('RulesConfigsManager', () => { }); }); - it('should include the token in the authorization header', function (done) { + it('should include the token in the authorization header', async function () { nock.cleanAll(); const request = nock(API_URL) @@ -249,11 +220,8 @@ describe('RulesConfigsManager', () => { .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); - this.rulesConfigs.delete({ key }).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await this.rulesConfigs.delete({ key }); + expect(request.isDone()).to.be.true; }); }); }); diff --git a/test/management/rules.tests.js b/test/management/rules.tests.js index 67afffe19..9a2837243 100644 --- a/test/management/rules.tests.js +++ b/test/management/rules.tests.js @@ -65,44 +65,34 @@ describe('RulesManager', () => { nock(API_URL).get('/rules').reply(500); - this.rules - .getAll() - .then((fg) => { - console.log(fg); - }) - .catch((err) => { - expect(err).to.exist; - done(); - }); - }); - - it('should pass the body of the response to the "then" handler', function (done) { + this.rules.getAll().catch((err) => { + expect(err).to.exist; + done(); + }); + }); + + it('should pass the body of the response to the "then" handler', async function () { nock.cleanAll(); const data = [{ test: true }]; nock(API_URL).get('/rules').reply(200, data); - this.rules.getAll().then((credentials) => { - expect(credentials).to.be.an.instanceOf(Array); - - expect(credentials.length).to.equal(data.length); + const credentials = await this.rules.getAll(); + expect(credentials).to.be.an.instanceOf(Array); - expect(credentials[0].test).to.equal(data[0].test); + expect(credentials.length).to.equal(data.length); - done(); - }); + expect(credentials[0].test).to.equal(data[0].test); }); - it('should perform a GET request to /api/v2/rules', function (done) { + it('should perform a GET request to /api/v2/rules', async function () { const { request } = this; - this.rules.getAll().then(() => { - expect(request.isDone()).to.be.true; - done(); - }); + await this.rules.getAll(); + expect(request.isDone()).to.be.true; }); - it('should include the token in the Authorization header', function (done) { + it('should include the token in the Authorization header', async function () { nock.cleanAll(); const request = nock(API_URL) @@ -110,13 +100,11 @@ describe('RulesManager', () => { .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.rules.getAll().then(() => { - expect(request.isDone()).to.be.true; - done(); - }); + await this.rules.getAll(); + expect(request.isDone()).to.be.true; }); - it('should pass the parameters in the query-string', function (done) { + it('should pass the parameters in the query-string', async function () { nock.cleanAll(); const params = { @@ -125,11 +113,8 @@ describe('RulesManager', () => { }; const request = nock(API_URL).get('/rules').query(params).reply(200); - this.rules.getAll(params).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await this.rules.getAll(params); + expect(request.isDone()).to.be.true; }); }); @@ -156,14 +141,11 @@ describe('RulesManager', () => { this.rules.get({ id: this.data.id }).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should perform a POST request to /api/v2/rules/5', function (done) { + it('should perform a POST request to /api/v2/rules/5', async function () { const { request } = this; - this.rules.get({ id: this.data.id }).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await this.rules.get({ id: this.data.id }); + expect(request.isDone()).to.be.true; }); it('should pass any errors to the promise catch handler', function (done) { @@ -178,7 +160,7 @@ describe('RulesManager', () => { }); }); - it('should include the token in the Authorization header', function (done) { + it('should include the token in the Authorization header', async function () { nock.cleanAll(); const request = nock(API_URL) @@ -186,11 +168,8 @@ describe('RulesManager', () => { .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.rules.get({ id: this.data.id }).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await this.rules.get({ id: this.data.id }); + expect(request.isDone()).to.be.true; }); }); @@ -229,29 +208,23 @@ describe('RulesManager', () => { }); }); - it('should perform a POST request to /api/v2/rules', function (done) { + it('should perform a POST request to /api/v2/rules', async function () { const { request } = this; - this.rules.create(data).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await this.rules.create(data); + expect(request.isDone()).to.be.true; }); - it('should pass the data in the body of the request', function (done) { + it('should pass the data in the body of the request', async function () { nock.cleanAll(); const request = nock(API_URL).post('/rules', data).reply(200); - this.rules.create(data).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await this.rules.create(data); + expect(request.isDone()).to.be.true; }); - it('should include the token in the Authorization header', function (done) { + it('should include the token in the Authorization header', async function () { nock.cleanAll(); const request = nock(API_URL) @@ -259,11 +232,8 @@ describe('RulesManager', () => { .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.rules.create(data).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await this.rules.create(data); + expect(request.isDone()).to.be.true; }); }); @@ -282,26 +252,20 @@ describe('RulesManager', () => { this.rules.update({ id: 5 }, {}).then(done.bind(null, null)).catch(done.bind(null, null)); }); - it('should perform a PATCH request to /api/v2/rules/5', function (done) { + it('should perform a PATCH request to /api/v2/rules/5', async function () { const { request } = this; - this.rules.update({ id: 5 }, {}).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await this.rules.update({ id: 5 }, {}); + expect(request.isDone()).to.be.true; }); - it('should include the new data in the body of the request', function (done) { + it('should include the new data in the body of the request', async function () { nock.cleanAll(); const request = nock(API_URL).patch(`/rules/${this.data.id}`, this.data).reply(200); - this.rules.update({ id: 5 }, this.data).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await this.rules.update({ id: 5 }, this.data); + expect(request.isDone()).to.be.true; }); it('should pass any errors to the promise catch handler', function (done) { @@ -328,18 +292,15 @@ describe('RulesManager', () => { this.rules.delete({ id }, done.bind(null, null)); }); - it('should return a promise when no callback is given', function (done) { - this.rules.delete({ id }).then(done.bind(null, null)); + it('should return a promise when no callback is given', function () { + expect(this.rules.delete({ id })).instanceOf(Promise); }); - it(`should perform a delete request to /rules/${id}`, function (done) { + it(`should perform a delete request to /rules/${id}`, async function () { const { request } = this; - this.rules.delete({ id }).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await this.rules.delete({ id }); + expect(request.isDone()).to.be.true; }); it('should pass any errors to the promise catch handler', function (done) { @@ -354,7 +315,7 @@ describe('RulesManager', () => { }); }); - it('should include the token in the authorization header', function (done) { + it('should include the token in the authorization header', async function () { nock.cleanAll(); const request = nock(API_URL) @@ -362,11 +323,8 @@ describe('RulesManager', () => { .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); - this.rules.delete({ id }).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await this.rules.delete({ id }); + expect(request.isDone()).to.be.true; }); }); }); diff --git a/test/management/stats.tests.js b/test/management/stats.tests.js index 2452b0308..d70b43b42 100644 --- a/test/management/stats.tests.js +++ b/test/management/stats.tests.js @@ -71,33 +71,28 @@ describe('StatsManager', () => { }); }); - it('should pass the body of the response to the "then" handler', function (done) { + it('should pass the body of the response to the "then" handler', async function () { nock.cleanAll(); const data = [{ test: true }]; nock(API_URL).get('/stats/daily').reply(200, data); - this.stats.getDaily().then((blacklistedTokens) => { - expect(blacklistedTokens).to.be.an.instanceOf(Array); + const blacklistedTokens = await this.stats.getDaily(); + expect(blacklistedTokens).to.be.an.instanceOf(Array); - expect(blacklistedTokens.length).to.equal(data.length); + expect(blacklistedTokens.length).to.equal(data.length); - expect(blacklistedTokens[0].test).to.equal(data[0].test); - - done(); - }); + expect(blacklistedTokens[0].test).to.equal(data[0].test); }); - it('should perform a GET request to /api/v2/stats/daily', function (done) { + it('should perform a GET request to /api/v2/stats/daily', async function () { const { request } = this; - this.stats.getDaily().then(() => { - expect(request.isDone()).to.be.true; - done(); - }); + await this.stats.getDaily(); + expect(request.isDone()).to.be.true; }); - it('should include the token in the Authorization header', function (done) { + it('should include the token in the Authorization header', async function () { nock.cleanAll(); const request = nock(API_URL) @@ -105,13 +100,11 @@ describe('StatsManager', () => { .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.stats.getDaily().then(() => { - expect(request.isDone()).to.be.true; - done(); - }); + await this.stats.getDaily(); + expect(request.isDone()).to.be.true; }); - it('should pass the parameters in the query-string', function (done) { + it('should pass the parameters in the query-string', async function () { nock.cleanAll(); const request = nock(API_URL) @@ -122,10 +115,8 @@ describe('StatsManager', () => { }) .reply(200); - this.stats.getDaily({ include_fields: true, fields: 'test' }).then(() => { - expect(request.isDone()).to.be.true; - done(); - }); + await this.stats.getDaily({ include_fields: true, fields: 'test' }); + expect(request.isDone()).to.be.true; }); }); @@ -155,28 +146,23 @@ describe('StatsManager', () => { }); }); - it('should perform a GET request to /api/v2/stats/active-users', function (done) { + it('should perform a GET request to /api/v2/stats/active-users', async function () { const { request } = this; - this.stats.getActiveUsersCount().then(() => { - expect(request.isDone()).to.be.true; - done(); - }); + await this.stats.getActiveUsersCount(); + expect(request.isDone()).to.be.true; }); - it('should pass the token data in the body of the request', function (done) { + it('should pass the token data in the body of the request', async function () { nock.cleanAll(); const request = nock(API_URL).get('/stats/active-users').reply(200); - this.stats.getActiveUsersCount().then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await this.stats.getActiveUsersCount(); + expect(request.isDone()).to.be.true; }); - it('should include the token in the Authorization header', function (done) { + it('should include the token in the Authorization header', async function () { nock.cleanAll(); const request = nock(API_URL) @@ -184,10 +170,8 @@ describe('StatsManager', () => { .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.stats.getActiveUsersCount().then(() => { - expect(request.isDone()).to.be.true; - done(); - }); + await this.stats.getActiveUsersCount(); + expect(request.isDone()).to.be.true; }); }); }); diff --git a/test/management/tenant.tests.js b/test/management/tenant.tests.js index 4045f3902..95a182c01 100644 --- a/test/management/tenant.tests.js +++ b/test/management/tenant.tests.js @@ -71,33 +71,28 @@ describe('TenantManager', () => { }); }); - it('should pass the body of the response to the "then" handler', function (done) { + it('should pass the body of the response to the "then" handler', async function () { nock.cleanAll(); const data = [{ test: true }]; nock(API_URL).get('/tenants/settings').reply(200, data); - this.tenant.getSettings().then((blacklistedTokens) => { - expect(blacklistedTokens).to.be.an.instanceOf(Array); + const blacklistedTokens = await this.tenant.getSettings(); + expect(blacklistedTokens).to.be.an.instanceOf(Array); - expect(blacklistedTokens.length).to.equal(data.length); + expect(blacklistedTokens.length).to.equal(data.length); - expect(blacklistedTokens[0].test).to.equal(data[0].test); - - done(); - }); + expect(blacklistedTokens[0].test).to.equal(data[0].test); }); - it('should perform a GET request to /api/v2/tenants/settings', function (done) { + it('should perform a GET request to /api/v2/tenants/settings', async function () { const { request } = this; - this.tenant.getSettings().then(() => { - expect(request.isDone()).to.be.true; - done(); - }); + await this.tenant.getSettings(); + expect(request.isDone()).to.be.true; }); - it('should include the token in the Authorization header', function (done) { + it('should include the token in the Authorization header', async function () { nock.cleanAll(); const request = nock(API_URL) @@ -105,13 +100,11 @@ describe('TenantManager', () => { .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.tenant.getSettings().then(() => { - expect(request.isDone()).to.be.true; - done(); - }); + await this.tenant.getSettings(); + expect(request.isDone()).to.be.true; }); - it('should pass the parameters in the query-string', function (done) { + it('should pass the parameters in the query-string', async function () { nock.cleanAll(); const request = nock(API_URL) @@ -122,10 +115,8 @@ describe('TenantManager', () => { }) .reply(200); - this.tenant.getSettings({ include_fields: true, fields: 'test' }).then(() => { - expect(request.isDone()).to.be.true; - done(); - }); + await this.tenant.getSettings({ include_fields: true, fields: 'test' }); + expect(request.isDone()).to.be.true; }); }); @@ -159,28 +150,23 @@ describe('TenantManager', () => { }); }); - it('should perform a PATCH request to /api/v2/tenants/settings', function (done) { + it('should perform a PATCH request to /api/v2/tenants/settings', async function () { const { request } = this; - this.tenant.updateSettings(data).then(() => { - expect(request.isDone()).to.be.true; - done(); - }); + await this.tenant.updateSettings(data); + expect(request.isDone()).to.be.true; }); - it('should pass the data in the body of the request', function (done) { + it('should pass the data in the body of the request', async function () { nock.cleanAll(); const request = nock(API_URL).patch('/tenants/settings', data).reply(200); - this.tenant.updateSettings(data).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await this.tenant.updateSettings(data); + expect(request.isDone()).to.be.true; }); - it('should include the token in the Authorization header', function (done) { + it('should include the token in the Authorization header', async function () { nock.cleanAll(); const request = nock(API_URL) @@ -188,10 +174,8 @@ describe('TenantManager', () => { .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.tenant.updateSettings(data).then(() => { - expect(request.isDone()).to.be.true; - done(); - }); + await this.tenant.updateSettings(data); + expect(request.isDone()).to.be.true; }); }); }); diff --git a/test/management/tickets.tests.js b/test/management/tickets.tests.js index 54ba811a0..c9ad63ad0 100644 --- a/test/management/tickets.tests.js +++ b/test/management/tickets.tests.js @@ -76,16 +76,14 @@ describe('TicketsManager', () => { }); }); - it('should perform a POST request to /api/v2tickets/email-verification', function (done) { + it('should perform a POST request to /api/v2tickets/email-verification', async function () { const { request } = this; - this.tickets.verifyEmail(data).then(() => { - expect(request.isDone()).to.be.true; - done(); - }); + await this.tickets.verifyEmail(data); + expect(request.isDone()).to.be.true; }); - it('should include the token in the Authorization header', function (done) { + it('should include the token in the Authorization header', async function () { nock.cleanAll(); const request = nock(API_URL) @@ -93,13 +91,11 @@ describe('TicketsManager', () => { .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.tickets.verifyEmail({}).then(() => { - expect(request.isDone()).to.be.true; - done(); - }); + await this.tickets.verifyEmail({}); + expect(request.isDone()).to.be.true; }); - it('should pass the parameters in the query-string', function (done) { + it('should pass the parameters in the query-string', async function () { nock.cleanAll(); const request = nock(API_URL) @@ -109,11 +105,8 @@ describe('TicketsManager', () => { }) .reply(200); - this.tickets.verifyEmail({ include_fields: true, fields: 'test' }).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await this.tickets.verifyEmail({ include_fields: true, fields: 'test' }); + expect(request.isDone()).to.be.true; }); }); @@ -151,28 +144,23 @@ describe('TicketsManager', () => { }); }); - it('should perform a POST request to /api/v2tickets/email-verification', function (done) { + it('should perform a POST request to /api/v2tickets/email-verification', async function () { const { request } = this; - this.tickets.changePassword(data).then(() => { - expect(request.isDone()).to.be.true; - done(); - }); + await this.tickets.changePassword(data); + expect(request.isDone()).to.be.true; }); - it('should pass the data in the body of the request', function (done) { + it('should pass the data in the body of the request', async function () { nock.cleanAll(); const request = nock(API_URL).post('/tickets/password-change', data).reply(200); - this.tickets.changePassword(data).then(() => { - expect(request.isDone()).to.be.true; - - done(); - }); + await this.tickets.changePassword(data); + expect(request.isDone()).to.be.true; }); - it('should include the token in the Authorization header', function (done) { + it('should include the token in the Authorization header', async function () { nock.cleanAll(); const request = nock(API_URL) @@ -180,10 +168,8 @@ describe('TicketsManager', () => { .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); - this.tickets.changePassword(data).then(() => { - expect(request.isDone()).to.be.true; - done(); - }); + await this.tickets.changePassword(data); + expect(request.isDone()).to.be.true; }); }); }); diff --git a/test/management/user-blocks.tests.js b/test/management/user-blocks.tests.js index 67c6c1843..06aff914f 100644 --- a/test/management/user-blocks.tests.js +++ b/test/management/user-blocks.tests.js @@ -68,20 +68,15 @@ describe('UserBlocksManager', () => { this.userBlocks.get({ id }, done.bind(null, null)); }); - it('should return a promise when no callback is given', function (done) { - this.userBlocks.get({ id }).then(done.bind(null, null)); + it('should return a promise when no callback is given', function () { + expect(this.userBlocks.get({ id })).instanceOf(Promise); }); - it(`should perform a get request to /user-blocks/${id}`, function (done) { + it(`should perform a get request to /user-blocks/${id}`, async function () { const { request } = this; - this.userBlocks - .get({ id }) - .then(() => { - expect(request.isDone()).to.be.true; - done(); - }) - .catch(done); + await this.userBlocks.get({ id }); + expect(request.isDone()).to.be.true; }); it('should pass any errors to the promise catch handler', function (done) { @@ -99,7 +94,7 @@ describe('UserBlocksManager', () => { .catch(done); }); - it('should include the token in the authorization header', function (done) { + it('should include the token in the authorization header', async function () { nock.cleanAll(); const request = nock(API_URL) @@ -107,14 +102,8 @@ describe('UserBlocksManager', () => { .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); - this.userBlocks - .get({ id }) - .then(() => { - expect(request.isDone()).to.be.true; - - done(); - }) - .catch(done); + await this.userBlocks.get({ id }); + expect(request.isDone()).to.be.true; }); }); @@ -141,21 +130,15 @@ describe('UserBlocksManager', () => { this.userBlocks.delete({ id }, done.bind(null, null)); }); - it('should return a promise when no callback is given', function (done) { - this.userBlocks.delete({ id }).then(done.bind(null, null)); + it('should return a promise when no callback is given', function () { + expect(this.userBlocks.delete({ id })).instanceOf(Promise); }); - it(`should perform a delete request to /user-blocks/${id}`, function (done) { + it(`should perform a delete request to /user-blocks/${id}`, async function () { const { request } = this; - this.userBlocks - .delete({ id }) - .then(() => { - expect(request.isDone()).to.be.true; - - done(); - }) - .catch(done); + await this.userBlocks.delete({ id }); + expect(request.isDone()).to.be.true; }); it('should pass any errors to the promise catch handler', function (done) { @@ -173,7 +156,7 @@ describe('UserBlocksManager', () => { .catch(done); }); - it('should include the token in the authorization header', function (done) { + it('should include the token in the authorization header', async function () { nock.cleanAll(); const request = nock(API_URL) @@ -181,14 +164,8 @@ describe('UserBlocksManager', () => { .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); - this.userBlocks - .delete({ id }) - .then(() => { - expect(request.isDone()).to.be.true; - - done(); - }) - .catch(done); + await this.userBlocks.delete({ id }); + expect(request.isDone()).to.be.true; }); }); @@ -218,21 +195,15 @@ describe('UserBlocksManager', () => { this.userBlocks.getByIdentifier({ identifier }, done.bind(null, null)); }); - it('should return a promise when no callback is given', function (done) { - this.userBlocks.getByIdentifier({ identifier }).then(done.bind(null, null)); + it('should return a promise when no callback is given', function () { + expect(this.userBlocks.getByIdentifier({ identifier })).instanceOf(Promise); }); - it('should perform a get request to /user-blocks', function (done) { + it('should perform a get request to /user-blocks', async function () { const { request } = this; - this.userBlocks - .getByIdentifier({ identifier }) - .then(() => { - expect(request.isDone()).to.be.true; - - done(); - }) - .catch(done); + await this.userBlocks.getByIdentifier({ identifier }); + expect(request.isDone()).to.be.true; }); it('should pass any errors to the promise catch handler', function (done) { @@ -250,7 +221,7 @@ describe('UserBlocksManager', () => { .catch(done); }); - it('should include the token in the authorization header', function (done) { + it('should include the token in the authorization header', async function () { nock.cleanAll(); const request = nock(API_URL) @@ -259,14 +230,8 @@ describe('UserBlocksManager', () => { .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); - this.userBlocks - .getByIdentifier({ identifier }) - .then(() => { - expect(request.isDone()).to.be.true; - - done(); - }) - .catch(done); + await this.userBlocks.getByIdentifier({ identifier }); + expect(request.isDone()).to.be.true; }); }); @@ -296,21 +261,15 @@ describe('UserBlocksManager', () => { this.userBlocks.deleteByIdentifier({ identifier }, done.bind(null, null)); }); - it('should return a promise when no callback is given', function (done) { - this.userBlocks.deleteByIdentifier({ identifier }).then(done.bind(null, null)); + it('should return a promise when no callback is given', function () { + expect(this.userBlocks.deleteByIdentifier({ identifier })).instanceOf(Promise); }); - it('should perform a delete request to /user-blocks', function (done) { + it('should perform a delete request to /user-blocks', async function () { const { request } = this; - this.userBlocks - .deleteByIdentifier({ identifier }) - .then(() => { - expect(request.isDone()).to.be.true; - - done(); - }) - .catch(done); + await this.userBlocks.deleteByIdentifier({ identifier }); + expect(request.isDone()).to.be.true; }); it('should pass any errors to the promise catch handler', function (done) { @@ -328,7 +287,7 @@ describe('UserBlocksManager', () => { .catch(done); }); - it('should include the token in the authorization header', function (done) { + it('should include the token in the authorization header', async function () { nock.cleanAll(); const request = nock(API_URL) @@ -337,14 +296,8 @@ describe('UserBlocksManager', () => { .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); - this.userBlocks - .deleteByIdentifier({ identifier }) - .then(() => { - expect(request.isDone()).to.be.true; - - done(); - }) - .catch(done); + await this.userBlocks.deleteByIdentifier({ identifier }); + expect(request.isDone()).to.be.true; }); }); }); From 7ed1742115b3533b2371c8bd65ad6d6694aff856 Mon Sep 17 00:00:00 2001 From: hornta Date: Tue, 19 Oct 2021 11:42:51 +0200 Subject: [PATCH 08/22] remove engine requirements --- .circleci/config.yml | 2 +- package.json | 3 --- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 5cb1ce065..4e22484c6 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -4,7 +4,7 @@ orbs: jobs: build-and-test: docker: - - image: circleci/node:12 + - image: circleci/node:10 environment: LANG: en_US.UTF-8 steps: diff --git a/package.json b/package.json index b62bfaf7d..f32add24b 100644 --- a/package.json +++ b/package.json @@ -7,9 +7,6 @@ "files": [ "src" ], - "engines": { - "node": ">=12" - }, "scripts": { "test": "mocha --reporter spec ./test/**/*.tests.js", "test:ci": "nyc npm run test -- --forbid-only --reporter mocha-junit-reporter", From eef7e91399548f915416167cbb91f91ecc48604c Mon Sep 17 00:00:00 2001 From: hornta Date: Tue, 19 Oct 2021 13:43:49 +0200 Subject: [PATCH 09/22] add node v16 to ci --- .circleci/config.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 2c4c43052..457f97e1c 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -44,7 +44,7 @@ workflows: - build-and-test: matrix: parameters: - node-version: ["8", "10", "12", "14"] + node-version: ["8", "10", "12", "14", "16"] - ship/node-publish: pkg-manager: yarn requires: From 1db9d4bc56259b226f67ef75a179999ca64ea169 Mon Sep 17 00:00:00 2001 From: hornta Date: Wed, 20 Oct 2021 13:23:42 +0200 Subject: [PATCH 10/22] set minimum support node version --- package.json | 3 +++ 1 file changed, 3 insertions(+) diff --git a/package.json b/package.json index a7b8ba821..eb755130e 100644 --- a/package.json +++ b/package.json @@ -20,6 +20,9 @@ "type": "git", "url": "https://github.com/auth0/node-auth0" }, + "engines": { + "node": ">=8.3.0" + }, "keywords": [ "auth0", "api" From 042003acff1aaa6329a2c93e1178796566130970 Mon Sep 17 00:00:00 2001 From: hornta Date: Wed, 20 Oct 2021 13:33:10 +0200 Subject: [PATCH 11/22] run ci on node 8 and 10 without eslint --- .circleci/config.yml | 45 ++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 43 insertions(+), 2 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 457f97e1c..93ed53c2c 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -37,18 +37,59 @@ jobs: - run: name: Generate Coverage command: yarn test:coverage - + build-and-test-no-lint: + parameters: + node-version: + type: string + default: "8" + docker: + - image: circleci/node:<< parameters.node-version >> + environment: + LANG: en_US.UTF-8 + steps: + - checkout + - restore_cache: + name: Restore Yarn Package Cache + key: yarn-packages-{{ checksum "yarn.lock" }} + - run: + name: Install Dependencies + command: yarn install --ignore-engines + - save_cache: + name: Save Yarn Package Cache + key: yarn-packages-{{ checksum "yarn.lock" }} + paths: + - ~/.cache/yarn + - run: + name: ESLint + command: yarn lint + - run: + name: Tests + command: yarn test:ci + - when: + condition: + equal: [ "12", << parameters.node-version >> ] + steps: + - run: + name: Generate Coverage + command: yarn test:coverage workflows: build-test-report: jobs: - build-and-test: matrix: parameters: - node-version: ["8", "10", "12", "14", "16"] + node-version: ["12", "14", "16"] + + # ESLint has dropped support for version 8 and 10. + - build-and-test-no-lint: + matrix: + parameters: + node-version: ["8", "10"] - ship/node-publish: pkg-manager: yarn requires: - build-and-test + - build-and-test-no-lint context: - publish-npm - publish-gh From 6e2a0e758df828b18c5f2f43900aaff7dbfb40a5 Mon Sep 17 00:00:00 2001 From: hornta Date: Wed, 20 Oct 2021 13:34:58 +0200 Subject: [PATCH 12/22] remove eslint for the no-lint script, duh... --- .circleci/config.yml | 3 --- 1 file changed, 3 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 93ed53c2c..67442a2bd 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -59,9 +59,6 @@ jobs: key: yarn-packages-{{ checksum "yarn.lock" }} paths: - ~/.cache/yarn - - run: - name: ESLint - command: yarn lint - run: name: Tests command: yarn test:ci From 79f5423b2c98807c1ade8eace6d284ee3c7cbc8d Mon Sep 17 00:00:00 2001 From: hornta Date: Wed, 20 Oct 2021 13:40:07 +0200 Subject: [PATCH 13/22] disable running test on 8 and 10 because mocha has no support for version 8 and 10 --- .circleci/config.yml | 16 +++------------- 1 file changed, 3 insertions(+), 13 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 67442a2bd..b2759f659 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -37,7 +37,7 @@ jobs: - run: name: Generate Coverage command: yarn test:coverage - build-and-test-no-lint: + build-no-test-no-lint: parameters: node-version: type: string @@ -59,16 +59,6 @@ jobs: key: yarn-packages-{{ checksum "yarn.lock" }} paths: - ~/.cache/yarn - - run: - name: Tests - command: yarn test:ci - - when: - condition: - equal: [ "12", << parameters.node-version >> ] - steps: - - run: - name: Generate Coverage - command: yarn test:coverage workflows: build-test-report: jobs: @@ -77,8 +67,8 @@ workflows: parameters: node-version: ["12", "14", "16"] - # ESLint has dropped support for version 8 and 10. - - build-and-test-no-lint: + # ESLint & mocha has dropped support for version 8 and 10. + - build-no-test-no-lint: matrix: parameters: node-version: ["8", "10"] From 7afa69fd13c7523c1dc679a35e75ff3072aeb486 Mon Sep 17 00:00:00 2001 From: hornta Date: Wed, 20 Oct 2021 14:05:06 +0200 Subject: [PATCH 14/22] test downgrading mocha to 8 --- .circleci/config.yml | 9 ++- package.json | 2 +- yarn.lock | 151 +++++++++++++++++++++++++++---------------- 3 files changed, 102 insertions(+), 60 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index b2759f659..b6e9604b9 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -37,7 +37,7 @@ jobs: - run: name: Generate Coverage command: yarn test:coverage - build-no-test-no-lint: + build-and-test-no-lint: parameters: node-version: type: string @@ -59,6 +59,9 @@ jobs: key: yarn-packages-{{ checksum "yarn.lock" }} paths: - ~/.cache/yarn + - run: + name: Tests + command: yarn test:ci workflows: build-test-report: jobs: @@ -67,8 +70,8 @@ workflows: parameters: node-version: ["12", "14", "16"] - # ESLint & mocha has dropped support for version 8 and 10. - - build-no-test-no-lint: + # ESLint has dropped support for version 8 and 10. + - build-and-test-no-lint: matrix: parameters: node-version: ["8", "10"] diff --git a/package.json b/package.json index eb755130e..d8c9e830e 100644 --- a/package.json +++ b/package.json @@ -57,7 +57,7 @@ "json-loader": "^0.5.7", "jws": "^3.2.2", "minami": "^1.2.3", - "mocha": "^9.1.2", + "mocha": "^8.4.0", "mocha-junit-reporter": "^2.0.0", "nock": "^10.0.6", "nyc": "^14.1.1", diff --git a/yarn.lock b/yarn.lock index 226d77b8e..8f7c2bfd9 100644 --- a/yarn.lock +++ b/yarn.lock @@ -518,7 +518,7 @@ anymatch@^2.0.0: micromatch "^3.1.4" normalize-path "^2.1.1" -anymatch@~3.1.2: +anymatch@~3.1.1, anymatch@~3.1.2: version "3.1.2" resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-3.1.2.tgz#c0557c096af32f106198f4f4e2a383537e378716" integrity sha512-P43ePfOAIupkguHUycrc4qJ9kz8ZiuOUijaETwX7THt0Y/GNK7v0aa8rY816xWjZ7rJdA5XdMcpVFTKMq+RvWg== @@ -982,7 +982,7 @@ chalk@^2.0.0, chalk@^2.3.0, chalk@^2.4.2: escape-string-regexp "^1.0.5" supports-color "^5.3.0" -chalk@^4.0.0, chalk@^4.1.0: +chalk@^4.0.0: version "4.1.2" resolved "https://registry.yarnpkg.com/chalk/-/chalk-4.1.2.tgz#aac4e2b7734a740867aeb16bf02aad556a1e7a01" integrity sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA== @@ -1022,20 +1022,20 @@ check-error@^1.0.2: resolved "https://registry.yarnpkg.com/check-error/-/check-error-1.0.2.tgz#574d312edd88bb5dd8912e9286dd6c0aed4aac82" integrity sha1-V00xLt2Iu13YkS6Sht1sCu1KrII= -chokidar@3.5.2, chokidar@^3.4.1: - version "3.5.2" - resolved "https://registry.yarnpkg.com/chokidar/-/chokidar-3.5.2.tgz#dba3976fcadb016f66fd365021d91600d01c1e75" - integrity sha512-ekGhOnNVPgT77r4K/U3GDhu+FQ2S8TnK/s2KbIGXi0SZWuwkZ2QNyfWdZW+TVfn84DpEP7rLeCt2UI6bJ8GwbQ== +chokidar@3.5.1: + version "3.5.1" + resolved "https://registry.yarnpkg.com/chokidar/-/chokidar-3.5.1.tgz#ee9ce7bbebd2b79f49f304799d5468e31e14e68a" + integrity sha512-9+s+Od+W0VJJzawDma/gvBNQqkTiqYTWLuZoyAsivsI4AaWTCzHG06/TMjsf1cYe9Cb97UCEhjz7HvnPk2p/tw== dependencies: - anymatch "~3.1.2" + anymatch "~3.1.1" braces "~3.0.2" - glob-parent "~5.1.2" + glob-parent "~5.1.0" is-binary-path "~2.1.0" is-glob "~4.0.1" normalize-path "~3.0.0" - readdirp "~3.6.0" + readdirp "~3.5.0" optionalDependencies: - fsevents "~2.3.2" + fsevents "~2.3.1" chokidar@^2.1.8: version "2.1.8" @@ -1056,6 +1056,21 @@ chokidar@^2.1.8: optionalDependencies: fsevents "^1.2.7" +chokidar@^3.4.1: + version "3.5.2" + resolved "https://registry.yarnpkg.com/chokidar/-/chokidar-3.5.2.tgz#dba3976fcadb016f66fd365021d91600d01c1e75" + integrity sha512-ekGhOnNVPgT77r4K/U3GDhu+FQ2S8TnK/s2KbIGXi0SZWuwkZ2QNyfWdZW+TVfn84DpEP7rLeCt2UI6bJ8GwbQ== + dependencies: + anymatch "~3.1.2" + braces "~3.0.2" + glob-parent "~5.1.2" + is-binary-path "~2.1.0" + is-glob "~4.0.1" + normalize-path "~3.0.0" + readdirp "~3.6.0" + optionalDependencies: + fsevents "~2.3.2" + chownr@^1.1.1: version "1.1.4" resolved "https://registry.yarnpkg.com/chownr/-/chownr-1.1.4.tgz#6fc9d7b42d32a583596337666e7d08084da2cc6b" @@ -1381,13 +1396,20 @@ cyclist@^1.0.1: resolved "https://registry.yarnpkg.com/cyclist/-/cyclist-1.0.1.tgz#596e9698fd0c80e12038c2b82d6eb1b35b6224d9" integrity sha1-WW6WmP0MgOEgOMK4LW6xs1tiJNk= -debug@4, debug@4.3.2, debug@^4.0.1, debug@^4.1.0, debug@^4.1.1, debug@^4.3.2: +debug@4, debug@^4.0.1, debug@^4.1.0, debug@^4.1.1, debug@^4.3.2: version "4.3.2" resolved "https://registry.yarnpkg.com/debug/-/debug-4.3.2.tgz#f0a49c18ac8779e31d4a0c6029dfb76873c7428b" integrity sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw== dependencies: ms "2.1.2" +debug@4.3.1: + version "4.3.1" + resolved "https://registry.yarnpkg.com/debug/-/debug-4.3.1.tgz#f0d229c505e0c6d8c49ac553d1b13dc183f6b2ee" + integrity sha512-doEwdvm4PCeK4K3RQN2ZC2BYUBaxwLARCqZmMjtF8a51J2Rb0xpVloFRnCODwqjpwnAoao4pelN8l3RJdv3gRQ== + dependencies: + ms "2.1.2" + debug@^2.2.0, debug@^2.3.3: version "2.6.9" resolved "https://registry.yarnpkg.com/debug/-/debug-2.6.9.tgz#5d128515df134ff327e90a4c93f4e077a536341f" @@ -2114,7 +2136,7 @@ fsevents@^1.2.7: bindings "^1.5.0" nan "^2.12.1" -fsevents@~2.3.2: +fsevents@~2.3.1, fsevents@~2.3.2: version "2.3.2" resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-2.3.2.tgz#8a526f78b8fdf4623b709e0b975c52c24c02fd1a" integrity sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA== @@ -2178,17 +2200,17 @@ glob-parent@^3.1.0: is-glob "^3.1.0" path-dirname "^1.0.0" -glob-parent@^5.1.2, glob-parent@~5.1.2: +glob-parent@^5.1.2, glob-parent@~5.1.0, glob-parent@~5.1.2: version "5.1.2" resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-5.1.2.tgz#869832c58034fe68a4093c17dc15e8340d8401c4" integrity sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow== dependencies: is-glob "^4.0.1" -glob@7.1.7: - version "7.1.7" - resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.7.tgz#3b193e9233f01d42d0b3f78294bbeeb418f94a90" - integrity sha512-OvD9ENzPLbegENnYP5UUfJIirTg4+XwMWGaQfQTY0JenxNvvIKP3U3/tAQSPIu/lHxXYSZmpXlUHeqAIdKzBLQ== +glob@7.1.6: + version "7.1.6" + resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.6.tgz#141f33b81a7c2492e125594307480c46679278a6" + integrity sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA== dependencies: fs.realpath "^1.0.0" inflight "^1.0.4" @@ -2646,11 +2668,6 @@ is-stream@^1.0.1, is-stream@^1.1.0: resolved "https://registry.yarnpkg.com/is-stream/-/is-stream-1.1.0.tgz#12d4a3dd4e68e0b79ceb8dbc84173ae80d91ca44" integrity sha1-EtSj3U5o4Lec6428hBc66A2RykQ= -is-unicode-supported@^0.1.0: - version "0.1.0" - resolved "https://registry.yarnpkg.com/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz#3f26c76a809593b52bfa2ecb5710ed2779b522a7" - integrity sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw== - is-upper-case@^1.1.0: version "1.1.2" resolved "https://registry.yarnpkg.com/is-upper-case/-/is-upper-case-1.1.2.tgz#8d0b1fa7e7933a1e58483600ec7d9661cbaf756f" @@ -2760,10 +2777,10 @@ js-yaml@3.14.1, js-yaml@^3.13.1: argparse "^1.0.7" esprima "^4.0.0" -js-yaml@4.1.0: - version "4.1.0" - resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-4.1.0.tgz#c1fb65f8f5017901cdd2c951864ba18458a10602" - integrity sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA== +js-yaml@4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-4.0.0.tgz#f426bc0ff4b4051926cd588c71113183409a121f" + integrity sha512-pqon0s+4ScYUvX30wxQi3PogGFAlUyH0awepWvwkj4jD4v+ova3RiYw8bmA6x2rDrEaj8i/oWKoRxpVNW+Re8Q== dependencies: argparse "^2.0.1" @@ -3095,13 +3112,12 @@ lodash@^4.17.14, lodash@^4.17.15, lodash@^4.17.21, lodash@^4.17.5: resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.21.tgz#679591c564c3bffaae8454cf0b3df370c3d6911c" integrity sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg== -log-symbols@4.1.0: - version "4.1.0" - resolved "https://registry.yarnpkg.com/log-symbols/-/log-symbols-4.1.0.tgz#3fbdbb95b4683ac9fc785111e792e558d4abd503" - integrity sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg== +log-symbols@4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/log-symbols/-/log-symbols-4.0.0.tgz#69b3cc46d20f448eccdb75ea1fa733d9e821c920" + integrity sha512-FN8JBzLx6CzeMrB0tg6pqlGU1wCrXW+ZXGH481kfsBqer0hToTIiHdjH4Mq8xJUbvATujKCvaREGWpGUionraA== dependencies: - chalk "^4.1.0" - is-unicode-supported "^0.1.0" + chalk "^4.0.0" lower-case-first@^1.0.0: version "1.0.2" @@ -3368,32 +3384,33 @@ mocha-junit-reporter@^2.0.0: strip-ansi "^4.0.0" xml "^1.0.0" -mocha@^9.1.2: - version "9.1.2" - resolved "https://registry.yarnpkg.com/mocha/-/mocha-9.1.2.tgz#93f53175b0f0dc4014bd2d612218fccfcf3534d3" - integrity sha512-ta3LtJ+63RIBP03VBjMGtSqbe6cWXRejF9SyM9Zyli1CKZJZ+vfCTj3oW24V7wAphMJdpOFLoMI3hjJ1LWbs0w== +mocha@^8.4.0: + version "8.4.0" + resolved "https://registry.yarnpkg.com/mocha/-/mocha-8.4.0.tgz#677be88bf15980a3cae03a73e10a0fc3997f0cff" + integrity sha512-hJaO0mwDXmZS4ghXsvPVriOhsxQ7ofcpQdm8dE+jISUOKopitvnXFQmpRR7jd2K6VBG6E26gU3IAbXXGIbu4sQ== dependencies: "@ungap/promise-all-settled" "1.1.2" ansi-colors "4.1.1" browser-stdout "1.3.1" - chokidar "3.5.2" - debug "4.3.2" + chokidar "3.5.1" + debug "4.3.1" diff "5.0.0" escape-string-regexp "4.0.0" find-up "5.0.0" - glob "7.1.7" + glob "7.1.6" growl "1.10.5" he "1.2.0" - js-yaml "4.1.0" - log-symbols "4.1.0" + js-yaml "4.0.0" + log-symbols "4.0.0" minimatch "3.0.4" ms "2.1.3" - nanoid "3.1.25" - serialize-javascript "6.0.0" + nanoid "3.1.20" + serialize-javascript "5.0.1" strip-json-comments "3.1.1" supports-color "8.1.1" which "2.0.2" - workerpool "6.1.5" + wide-align "1.1.3" + workerpool "6.1.0" yargs "16.2.0" yargs-parser "20.2.4" yargs-unparser "2.0.0" @@ -3450,10 +3467,10 @@ nan@^2.12.1: resolved "https://registry.yarnpkg.com/nan/-/nan-2.15.0.tgz#3f34a473ff18e15c1b5626b62903b5ad6e665fee" integrity sha512-8ZtvEnA2c5aYCZYd1cvgdnU6cqwixRoYg70xPLWUws5ORTa/lnw+u4amixRS/Ac5U5mQVgp9pnlSUnbNWFaWZQ== -nanoid@3.1.25: - version "3.1.25" - resolved "https://registry.yarnpkg.com/nanoid/-/nanoid-3.1.25.tgz#09ca32747c0e543f0e1814b7d3793477f9c8e152" - integrity sha512-rdwtIXaXCLFAQbnfqDRnI6jaRHp9fTcYBjtFKE8eezcZ7LuLjhUaQGNeMXf1HmRoCH32CLz6XwX0TtxEOS/A3Q== +nanoid@3.1.20: + version "3.1.20" + resolved "https://registry.yarnpkg.com/nanoid/-/nanoid-3.1.20.tgz#badc263c6b1dcf14b71efaa85f6ab4c1d6cfc788" + integrity sha512-a1cQNyczgKbLX9jwbS/+d7W8fX/RfgYR7lVWwWOGIPNgK2m0MWvrGF6/m4kk6U3QcFMnZf3RIhL0v2Jgh/0Uxw== nanomatch@^1.2.9: version "1.2.13" @@ -4191,6 +4208,13 @@ readdirp@^2.2.1: micromatch "^3.1.10" readable-stream "^2.0.2" +readdirp@~3.5.0: + version "3.5.0" + resolved "https://registry.yarnpkg.com/readdirp/-/readdirp-3.5.0.tgz#9ba74c019b15d365278d2e91bb8c48d7b4d42c9e" + integrity sha512-cMhu7c/8rdhkHXWsY+osBhfSy0JikwpHK/5+imo+LpeasTF8ouErHrlYkwT0++njiyuDvc7OFY5T3ukvZ8qmFQ== + dependencies: + picomatch "^2.2.1" + readdirp@~3.6.0: version "3.6.0" resolved "https://registry.yarnpkg.com/readdirp/-/readdirp-3.6.0.tgz#74a370bd857116e245b29cc97340cd431a02a6c7" @@ -4405,10 +4429,10 @@ sentence-case@^1.1.1, sentence-case@^1.1.2: dependencies: lower-case "^1.1.1" -serialize-javascript@6.0.0: - version "6.0.0" - resolved "https://registry.yarnpkg.com/serialize-javascript/-/serialize-javascript-6.0.0.tgz#efae5d88f45d7924141da8b5c3a7a7e663fefeb8" - integrity sha512-Qr3TosvguFt8ePWqsvRfrKyQXIiW+nGbYpy8XK24NQHE83caxWt+mIymTT19DGFbNWNLfEwsrkSmN64lVWB9ag== +serialize-javascript@5.0.1: + version "5.0.1" + resolved "https://registry.yarnpkg.com/serialize-javascript/-/serialize-javascript-5.0.1.tgz#7886ec848049a462467a97d3d918ebb2aaf934f4" + integrity sha512-SaaNal9imEO737H2c05Og0/8LUXG7EnsZyMa8MzkmuHoELfT6txuj0cMqRj6zfPKnmQ1yasR4PCJc8x+M4JSPA== dependencies: randombytes "^2.1.0" @@ -4710,6 +4734,14 @@ string-replace-webpack-plugin@0.1.3: file-loader "^0.8.1" style-loader "^0.8.3" +"string-width@^1.0.2 || 2": + version "2.1.1" + resolved "https://registry.yarnpkg.com/string-width/-/string-width-2.1.1.tgz#ab93f27a8dc13d28cac815c462143a6d9012ae9e" + integrity sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw== + dependencies: + is-fullwidth-code-point "^2.0.0" + strip-ansi "^4.0.0" + string-width@^3.0.0, string-width@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/string-width/-/string-width-3.1.0.tgz#22767be21b62af1081574306f69ac51b62203961" @@ -5242,6 +5274,13 @@ which@^1.2.9, which@^1.3.0: dependencies: isexe "^2.0.0" +wide-align@1.1.3: + version "1.1.3" + resolved "https://registry.yarnpkg.com/wide-align/-/wide-align-1.1.3.tgz#ae074e6bdc0c14a431e804e624549c633b000457" + integrity sha512-QGkOQc8XL6Bt5PwnsExKBPuMKBxnGxWWW3fU55Xt4feHozMUhdUMaBCk290qpm/wG5u/RSKzwdAC4i51YigihA== + dependencies: + string-width "^1.0.2 || 2" + word-wrap@^1.2.3: version "1.2.3" resolved "https://registry.yarnpkg.com/word-wrap/-/word-wrap-1.2.3.tgz#610636f6b1f703891bd34771ccb17fb93b47079c" @@ -5254,10 +5293,10 @@ worker-farm@^1.7.0: dependencies: errno "~0.1.7" -workerpool@6.1.5: - version "6.1.5" - resolved "https://registry.yarnpkg.com/workerpool/-/workerpool-6.1.5.tgz#0f7cf076b6215fd7e1da903ff6f22ddd1886b581" - integrity sha512-XdKkCK0Zqc6w3iTxLckiuJ81tiD/o5rBE/m+nXpRCB+/Sq4DqkfXZ/x0jW02DG1tGsfUGXbTJyZDP+eu67haSw== +workerpool@6.1.0: + version "6.1.0" + resolved "https://registry.yarnpkg.com/workerpool/-/workerpool-6.1.0.tgz#a8e038b4c94569596852de7a8ea4228eefdeb37b" + integrity sha512-toV7q9rWNYha963Pl/qyeZ6wG+3nnsyvolaNUS8+R5Wtw6qJPTxIlOP1ZSvcGhEJw+l3HMMmtiNo9Gl61G4GVg== wrap-ansi@^5.1.0: version "5.1.0" From 44139127b46524cb66a18c98662e2e8222437539 Mon Sep 17 00:00:00 2001 From: hornta Date: Wed, 20 Oct 2021 21:47:06 +0200 Subject: [PATCH 15/22] run eslint conditionally in job --- .circleci/config.yml | 49 ++++++++++++-------------------------------- 1 file changed, 13 insertions(+), 36 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index b6e9604b9..238a484b3 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -24,9 +24,18 @@ jobs: key: yarn-packages-{{ checksum "yarn.lock" }} paths: - ~/.cache/yarn - - run: - name: ESLint - command: yarn lint + - when: + condition: + # ESLint has dropped support for version 8 and 10. + and: + - not: + equal: [ "8", << parameters.node-version >> ] + - not: + equal: [ "10", << parameters.node-version >> ] + steps: + - run: + name: ESLint + command: yarn lint - run: name: Tests command: yarn test:ci @@ -37,49 +46,17 @@ jobs: - run: name: Generate Coverage command: yarn test:coverage - build-and-test-no-lint: - parameters: - node-version: - type: string - default: "8" - docker: - - image: circleci/node:<< parameters.node-version >> - environment: - LANG: en_US.UTF-8 - steps: - - checkout - - restore_cache: - name: Restore Yarn Package Cache - key: yarn-packages-{{ checksum "yarn.lock" }} - - run: - name: Install Dependencies - command: yarn install --ignore-engines - - save_cache: - name: Save Yarn Package Cache - key: yarn-packages-{{ checksum "yarn.lock" }} - paths: - - ~/.cache/yarn - - run: - name: Tests - command: yarn test:ci workflows: build-test-report: jobs: - build-and-test: matrix: parameters: - node-version: ["12", "14", "16"] - - # ESLint has dropped support for version 8 and 10. - - build-and-test-no-lint: - matrix: - parameters: - node-version: ["8", "10"] + node-version: ["8", "10", "12", "14", "16"] - ship/node-publish: pkg-manager: yarn requires: - build-and-test - - build-and-test-no-lint context: - publish-npm - publish-gh From 1f301ac81f08e2590e4dd1ac868535f44f156eb3 Mon Sep 17 00:00:00 2001 From: hornta Date: Fri, 22 Oct 2021 13:40:23 +0200 Subject: [PATCH 16/22] update husky hooks placement --- package.json | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index d8c9e830e..747bdeebe 100644 --- a/package.json +++ b/package.json @@ -13,7 +13,6 @@ "test:coverage": "codecov", "test:watch": "cross-env NODE_ENV=test mocha --timeout 5000 ./test/**/*.tests.js ./test/*.tests.js --watch", "jsdoc:generate": "jsdoc --configure .jsdoc.json --verbose", - "precommit": "pretty-quick --staged", "lint": "eslint ." }, "repository": { @@ -68,5 +67,10 @@ "sinon": "^11.1.2", "string-replace-webpack-plugin": "0.1.3", "webpack": "^4.36.1" + }, + "husky": { + "hooks": { + "pre-commit": "pretty-quick --staged" + } } } From e45438f73a0220aac081e6c56f7bc291ead79c76 Mon Sep 17 00:00:00 2001 From: hornta Date: Fri, 22 Oct 2021 13:40:32 +0200 Subject: [PATCH 17/22] run the tests on node 8 in mocha 6 with npx --- .circleci/config.yml | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 238a484b3..447652b53 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -36,9 +36,23 @@ jobs: - run: name: ESLint command: yarn lint - - run: - name: Tests - command: yarn test:ci + - when: + condition: + # mocha@>=6 doesn't support node 8 so we use mocha@6 with npx to run the tests + equal: ["8", << parameters.node-version >>] + steps: + - run: + name: Tests + command: npx mocha@6 --reporter spec ./test/**/*.tests.js + - when: + condition: + and: + - not: + equal: ["8", << parameters.node-version >>] + steps: + - run: + name: Tests + command: yarn test:ci - when: condition: equal: [ "12", << parameters.node-version >> ] From 9dd4d305a3e22d4197119efe489c9c21d6036cd3 Mon Sep 17 00:00:00 2001 From: hornta <4553604+hornta@users.noreply.github.com> Date: Thu, 28 Oct 2021 20:55:05 +0200 Subject: [PATCH 18/22] Update src/management/ConnectionsManager.js Co-authored-by: Adam Mcgrath --- src/management/ConnectionsManager.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/management/ConnectionsManager.js b/src/management/ConnectionsManager.js index 42650da5d..b4d3e4d6c 100644 --- a/src/management/ConnectionsManager.js +++ b/src/management/ConnectionsManager.js @@ -43,7 +43,7 @@ class ConnectionsManager { * @type {external:RestClient} */ const auth0RestClient = new Auth0RestClient( - `${options.baseUrl}/connections/:id `, + `${options.baseUrl}/connections/:id`, clientOptions, options.tokenProvider ); From 64146b893f383252d2786913f81541a8882ce335 Mon Sep 17 00:00:00 2001 From: hornta <4553604+hornta@users.noreply.github.com> Date: Thu, 28 Oct 2021 20:56:34 +0200 Subject: [PATCH 19/22] Update src/management/LogsManager.js Co-authored-by: Adam Mcgrath --- src/management/LogsManager.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/management/LogsManager.js b/src/management/LogsManager.js index 62973a70b..4b61b4d24 100644 --- a/src/management/LogsManager.js +++ b/src/management/LogsManager.js @@ -43,7 +43,7 @@ class LogsManager { * @type {external:RestClient} */ const auth0RestClient = new Auth0RestClient( - `${options.baseUrl}/logs/:id `, + `${options.baseUrl}/logs/:id`, clientOptions, options.tokenProvider ); From 18f79a772c3d2408e9a9f0a117d9bb95996f1c0d Mon Sep 17 00:00:00 2001 From: hornta Date: Thu, 28 Oct 2021 22:31:04 +0200 Subject: [PATCH 20/22] cleanup --- .circleci/config.yml | 2 +- .eslintrc.js | 8 -- package.json | 18 +-- src/management/RolesManager.js | 2 - src/management/UsersManager.js | 4 - yarn.lock | 225 ++++++++++++++------------------- 6 files changed, 101 insertions(+), 158 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 447652b53..2683ba0fe 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -43,7 +43,7 @@ jobs: steps: - run: name: Tests - command: npx mocha@6 --reporter spec ./test/**/*.tests.js + command: "npx mocha@6 --reporter spec './test/**/*.tests.js'" - when: condition: and: diff --git a/.eslintrc.js b/.eslintrc.js index a692ef535..31e3bfa06 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -17,21 +17,14 @@ module.exports = { ecmaVersion: 9, }, rules: { - // https://eslint.org/docs/rules/#ecmascript-6 'arrow-body-style': 'error', 'arrow-parens': 'error', 'arrow-spacing': 'error', - 'constructor-super': 'error', 'generator-star-spacing': 'error', - 'no-class-assign': 'error', 'no-confusing-arrow': 'error', - 'no-const-assign': 'error', - 'no-dupe-class-members': 'error', 'no-duplicate-imports': 'error', - 'no-new-symbol': 'error', 'no-restricted-exports': 'error', 'no-restricted-imports': 'error', - 'no-this-before-super': 'error', 'no-useless-computed-key': 'error', 'no-useless-constructor': 'error', 'no-useless-rename': 'error', @@ -44,7 +37,6 @@ module.exports = { 'prefer-rest-params': 'error', 'prefer-spread': 'error', 'prefer-template': 'error', - 'require-yield': 'error', 'rest-spread-spacing': 'error', 'sort-imports': 'error', 'symbol-description': 'error', diff --git a/package.json b/package.json index 747bdeebe..9699c7d55 100644 --- a/package.json +++ b/package.json @@ -8,11 +8,12 @@ "src" ], "scripts": { - "test": "mocha --reporter spec ./test/**/*.tests.js", + "test": "mocha --reporter spec './test/**/*.tests.js'", "test:ci": "nyc npm run test -- --forbid-only --reporter mocha-junit-reporter", "test:coverage": "codecov", - "test:watch": "cross-env NODE_ENV=test mocha --timeout 5000 ./test/**/*.tests.js ./test/*.tests.js --watch", + "test:watch": "cross-env NODE_ENV=test mocha --timeout 5000 './test/**/*.tests.js' './test/*.tests.js' --watch", "jsdoc:generate": "jsdoc --configure .jsdoc.json --verbose", + "precommit": "pretty-quick --staged", "lint": "eslint ." }, "repository": { @@ -45,14 +46,14 @@ "chai": "^4.2.0", "codecov": "^3.7.2", "cross-env": "^5.2.0", - "eslint": "^7.32.0", + "eslint": "^8.1.0", "eslint-config-prettier": "^8.3.0", - "eslint-plugin-jsdoc": "^36.1.0", + "eslint-plugin-jsdoc": "^37.0.3", "eslint-plugin-node": "^11.1.0", "eslint-plugin-prettier": "^4.0.0", - "eslint-plugin-promise": "^5.1.0", + "eslint-plugin-promise": "^5.1.1", "husky": "^3.0.1", - "jsdoc": "^3.6.3", + "jsdoc": "^3.6.7", "json-loader": "^0.5.7", "jws": "^3.2.2", "minami": "^1.2.3", @@ -67,10 +68,5 @@ "sinon": "^11.1.2", "string-replace-webpack-plugin": "0.1.3", "webpack": "^4.36.1" - }, - "husky": { - "hooks": { - "pre-commit": "pretty-quick --staged" - } } } diff --git a/src/management/RolesManager.js b/src/management/RolesManager.js index 181b56dde..36424f384 100644 --- a/src/management/RolesManager.js +++ b/src/management/RolesManager.js @@ -298,8 +298,6 @@ class RolesManager { * var params = { * roleId: 'ROLE_ID', * per_page: 50, - * @param params - * @param callback * page: 0 * }; * @example diff --git a/src/management/UsersManager.js b/src/management/UsersManager.js index 7972b9076..20df90f0e 100644 --- a/src/management/UsersManager.js +++ b/src/management/UsersManager.js @@ -191,7 +191,6 @@ class UsersManager { * * @example * This method takes an optional object as first argument that may be used to - * @param {...any} args * specify pagination settings and the search query. If pagination options are * not present, the first page of a limited number of results will be returned. * @@ -243,7 +242,6 @@ class UsersManager { * Get a user by its id. * * @example - * @param {...any} args * management.users.get({ id: USER_ID }, function (err, user) { * console.log(user); * }); @@ -261,7 +259,6 @@ class UsersManager { * * @example * var params = { id: USER_ID }; - * @param {...any} args * * management.users.update(params, data, function (err, user) { * if (err) { @@ -824,7 +821,6 @@ class UsersManager { * Get a list of organizations for a user. * * @example - * @param {...any} args * management.users.getUserOrganizations({ id: USER_ID }, function (err, orgs) { * console.log(orgs); * }); diff --git a/yarn.lock b/yarn.lock index 8f7c2bfd9..5c4dd6d9c 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2,13 +2,6 @@ # yarn lockfile v1 -"@babel/code-frame@7.12.11": - version "7.12.11" - resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.12.11.tgz#f4ad435aa263db935b8f10f2c552d23fb716a63f" - integrity sha512-Zt1yodBx1UcyiePMSkWnU4hPqhwq7hGi2nFL1LeA3EUl+q2LQx16MISgJ0+z7dnmgvP9QtIleuETGOiOH1RcIw== - dependencies: - "@babel/highlight" "^7.10.4" - "@babel/code-frame@^7.0.0", "@babel/code-frame@^7.14.5": version "7.14.5" resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.14.5.tgz#23b08d740e83f49c5e59945fbf1b43e80bbf4edb" @@ -60,7 +53,7 @@ resolved "https://registry.yarnpkg.com/@babel/helper-validator-identifier/-/helper-validator-identifier-7.15.7.tgz#220df993bfe904a4a6b02ab4f3385a5ebf6e2389" integrity sha512-K4JvCtQqad9OY2+yTU8w+E82ywk/fe+ELNlt1G8z3bVGlZfn/hOcQQsUhGhW/N+tb3fxK800wLtKOE/aM0m72w== -"@babel/highlight@^7.10.4", "@babel/highlight@^7.14.5": +"@babel/highlight@^7.14.5": version "7.14.5" resolved "https://registry.yarnpkg.com/@babel/highlight/-/highlight-7.14.5.tgz#6861a52f03966405001f6aa534a01a24d99e8cd9" integrity sha512-qf9u2WFWVV0MppaL877j2dBtQIDgmidgjGk5VIMw3OadXvYaXn66U1BFlH2t4+t3i+8PhedppRv+i40ABzd+gg== @@ -106,23 +99,23 @@ "@babel/helper-validator-identifier" "^7.14.9" to-fast-properties "^2.0.0" -"@es-joy/jsdoccomment@0.10.8": - version "0.10.8" - resolved "https://registry.yarnpkg.com/@es-joy/jsdoccomment/-/jsdoccomment-0.10.8.tgz#b3152887e25246410ed4ea569a55926ec13b2b05" - integrity sha512-3P1JiGL4xaR9PoTKUHa2N/LKwa2/eUdRqGwijMWWgBqbFEqJUVpmaOi2TcjcemrsRMgFLBzQCK4ToPhrSVDiFQ== +"@es-joy/jsdoccomment@0.12.0": + version "0.12.0" + resolved "https://registry.yarnpkg.com/@es-joy/jsdoccomment/-/jsdoccomment-0.12.0.tgz#47de05d86e9728ae3a5f1c57d6e9b63b07c6dc98" + integrity sha512-Gw4/j9v36IKY8ET+W0GoOzrRw17xjf21EIFFRL3zx21fF5MnqmeNpNi+PU/LKjqLpPb2Pw2XdlJbYM31VVo/PQ== dependencies: comment-parser "1.2.4" esquery "^1.4.0" - jsdoc-type-pratt-parser "1.1.1" + jsdoc-type-pratt-parser "2.0.0" -"@eslint/eslintrc@^0.4.3": - version "0.4.3" - resolved "https://registry.yarnpkg.com/@eslint/eslintrc/-/eslintrc-0.4.3.tgz#9e42981ef035beb3dd49add17acb96e8ff6f394c" - integrity sha512-J6KFFz5QCYUJq3pf0mjEcCJVERbzv71PUIDczuh9JkwGEzced6CO5ADLHB1rbf/+oPBtoPfMYNOpGDzCANlbXw== +"@eslint/eslintrc@^1.0.3": + version "1.0.3" + resolved "https://registry.yarnpkg.com/@eslint/eslintrc/-/eslintrc-1.0.3.tgz#41f08c597025605f672251dcc4e8be66b5ed7366" + integrity sha512-DHI1wDPoKCBPoLZA3qDR91+3te/wDSc1YhKg3jR8NxKKRJq2hwHwcWv31cSwSYvIBrmbENoYMWcenW8uproQqg== dependencies: ajv "^6.12.4" - debug "^4.1.1" - espree "^7.3.0" + debug "^4.3.2" + espree "^9.0.0" globals "^13.9.0" ignore "^4.0.6" import-fresh "^3.2.1" @@ -130,10 +123,10 @@ minimatch "^3.0.4" strip-json-comments "^3.1.1" -"@humanwhocodes/config-array@^0.5.0": - version "0.5.0" - resolved "https://registry.yarnpkg.com/@humanwhocodes/config-array/-/config-array-0.5.0.tgz#1407967d4c6eecd7388f83acf1eaf4d0c6e58ef9" - integrity sha512-FagtKFz74XrTl7y6HCzQpwDfXP0yhxe9lHLD1UZxjvZIcbyRz8zTFF/yYNfSfzU414eDwZ1SrO0Qvtyf+wFMQg== +"@humanwhocodes/config-array@^0.6.0": + version "0.6.0" + resolved "https://registry.yarnpkg.com/@humanwhocodes/config-array/-/config-array-0.6.0.tgz#b5621fdb3b32309d2d16575456cbc277fa8f021a" + integrity sha512-JQlEKbcgEUjBFhLIF4iqM7u/9lwgHRBcpHrmUNCALK0Q3amXN6lxdoXLnF0sm11E9VqTmBALR87IlUg1bZ8A9A== dependencies: "@humanwhocodes/object-schema" "^1.2.0" debug "^4.1.1" @@ -429,10 +422,10 @@ acorn@^6.4.1: resolved "https://registry.yarnpkg.com/acorn/-/acorn-6.4.2.tgz#35866fd710528e92de10cf06016498e47e39e1e6" integrity sha512-XtGIhXwF8YM8bJhGxG5kXgjkEuNGLTkoYqVE+KMR+aspr4KGYmKYg7yUe3KghyQ9yheNwLnjmzh/7+gfDBmHCQ== -acorn@^7.4.0: - version "7.4.1" - resolved "https://registry.yarnpkg.com/acorn/-/acorn-7.4.1.tgz#feaed255973d2e77555b83dbc08851a6c63520fa" - integrity sha512-nQyp0o1/mNdbTO1PO6kHkwSrmgZ0MT/jCCpNiwbUjGoRN4dlBhqJtoQuCnEOKzgTVwg0ZWiCoQy6SxMebQVh8A== +acorn@^8.5.0: + version "8.5.0" + resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.5.0.tgz#4512ccb99b3698c752591e9bb4472e38ad43cee2" + integrity sha512-yXbYeFy+jUuYd3/CDcg2NkIYE991XYX/bje7LmjJigUciaeO1JR4XxXgCIV1/Zc/dRuFEyw1L0pbA+qynJkW5Q== agent-base@6: version "6.0.2" @@ -461,16 +454,6 @@ ajv@^6.1.0, ajv@^6.10.0, ajv@^6.10.2, ajv@^6.12.4: json-schema-traverse "^0.4.1" uri-js "^4.2.2" -ajv@^8.0.1: - version "8.6.3" - resolved "https://registry.yarnpkg.com/ajv/-/ajv-8.6.3.tgz#11a66527761dc3e9a3845ea775d2d3c0414e8764" - integrity sha512-SMJOdDP6LqTkD0Uq8qLi+gMwSt0imXLSV080qFVwJCpH9U6Mb+SUGHAXM0KNbcBPguytWyvFxcHgMLe2D2XSpw== - dependencies: - fast-deep-equal "^3.1.1" - json-schema-traverse "^1.0.0" - require-from-string "^2.0.2" - uri-js "^4.2.2" - amdefine@>=0.0.4: version "1.0.1" resolved "https://registry.yarnpkg.com/amdefine/-/amdefine-1.0.1.tgz#4a5282ac164729e93619bcfd3ad151f817ce91f5" @@ -630,11 +613,6 @@ assign-symbols@^1.0.0: resolved "https://registry.yarnpkg.com/assign-symbols/-/assign-symbols-1.0.0.tgz#59667f41fadd4f20ccbc2bb96b8d4f7f78ec0367" integrity sha1-WWZ/QfrdTyDMvCu5a41Pf3jsA2c= -astral-regex@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/astral-regex/-/astral-regex-2.0.0.tgz#483143c567aeed4785759c0865786dc77d7d2e31" - integrity sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ== - async-each@^1.0.1: version "1.0.3" resolved "https://registry.yarnpkg.com/async-each/-/async-each-1.0.3.tgz#b727dbf87d7651602f06f4d4ac387f47d91b0cbf" @@ -1396,7 +1374,7 @@ cyclist@^1.0.1: resolved "https://registry.yarnpkg.com/cyclist/-/cyclist-1.0.1.tgz#596e9698fd0c80e12038c2b82d6eb1b35b6224d9" integrity sha1-WW6WmP0MgOEgOMK4LW6xs1tiJNk= -debug@4, debug@^4.0.1, debug@^4.1.0, debug@^4.1.1, debug@^4.3.2: +debug@4, debug@^4.1.0, debug@^4.1.1, debug@^4.3.2: version "4.3.2" resolved "https://registry.yarnpkg.com/debug/-/debug-4.3.2.tgz#f0a49c18ac8779e31d4a0c6029dfb76873c7428b" integrity sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw== @@ -1678,16 +1656,16 @@ eslint-plugin-es@^3.0.0: eslint-utils "^2.0.0" regexpp "^3.0.0" -eslint-plugin-jsdoc@^36.1.0: - version "36.1.0" - resolved "https://registry.yarnpkg.com/eslint-plugin-jsdoc/-/eslint-plugin-jsdoc-36.1.0.tgz#8dfe5f27edfb6aa3812e6d86ccaea849ddc86b03" - integrity sha512-Qpied2AJCQcScxfzTObLKRiP5QgLXjMU/ITjBagEV5p2Q/HpumD1EQtazdRYdjDSwPmXhwOl2yquwOGQ4HOJNw== +eslint-plugin-jsdoc@^37.0.3: + version "37.0.3" + resolved "https://registry.yarnpkg.com/eslint-plugin-jsdoc/-/eslint-plugin-jsdoc-37.0.3.tgz#42ddd0393c166c2724a7fdee808b94ab1d9dfb00" + integrity sha512-Qg/gIZAfcrM4Qu/JzcnxPGD45Je6wPLFzMZQboeqit/CL4aY6wuzBTkgUMiWXfw/PaPl+sb0GF1XdBlV23ReDA== dependencies: - "@es-joy/jsdoccomment" "0.10.8" + "@es-joy/jsdoccomment" "0.12.0" comment-parser "1.2.4" debug "^4.3.2" esquery "^1.4.0" - jsdoc-type-pratt-parser "^1.1.1" + jsdoc-type-pratt-parser "^2.0.0" lodash "^4.17.21" regextras "^0.8.0" semver "^7.3.5" @@ -1712,10 +1690,10 @@ eslint-plugin-prettier@^4.0.0: dependencies: prettier-linter-helpers "^1.0.0" -eslint-plugin-promise@^5.1.0: - version "5.1.0" - resolved "https://registry.yarnpkg.com/eslint-plugin-promise/-/eslint-plugin-promise-5.1.0.tgz#fb2188fb734e4557993733b41aa1a688f46c6f24" - integrity sha512-NGmI6BH5L12pl7ScQHbg7tvtk4wPxxj8yPHH47NvSmMtFneC077PSeY3huFj06ZWZvtbfxSPt3RuOQD5XcR4ng== +eslint-plugin-promise@^5.1.1: + version "5.1.1" + resolved "https://registry.yarnpkg.com/eslint-plugin-promise/-/eslint-plugin-promise-5.1.1.tgz#9674d11c056d1bafac38e4a3a9060be740988d90" + integrity sha512-XgdcdyNzHfmlQyweOPTxmc7pIsS6dE4MvwhXWMQ2Dxs1XAL2GJDilUsjWen6TWik0aSI+zD/PqocZBblcm9rdA== eslint-scope@^4.0.3: version "4.0.3" @@ -1725,22 +1703,29 @@ eslint-scope@^4.0.3: esrecurse "^4.1.0" estraverse "^4.1.1" -eslint-scope@^5.1.1: - version "5.1.1" - resolved "https://registry.yarnpkg.com/eslint-scope/-/eslint-scope-5.1.1.tgz#e786e59a66cb92b3f6c1fb0d508aab174848f48c" - integrity sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw== +eslint-scope@^6.0.0: + version "6.0.0" + resolved "https://registry.yarnpkg.com/eslint-scope/-/eslint-scope-6.0.0.tgz#9cf45b13c5ac8f3d4c50f46a5121f61b3e318978" + integrity sha512-uRDL9MWmQCkaFus8RF5K9/L/2fn+80yoW3jkD53l4shjCh26fCtvJGasxjUqP5OT87SYTxCVA3BwTUzuELx9kA== dependencies: esrecurse "^4.3.0" - estraverse "^4.1.1" + estraverse "^5.2.0" -eslint-utils@^2.0.0, eslint-utils@^2.1.0: +eslint-utils@^2.0.0: version "2.1.0" resolved "https://registry.yarnpkg.com/eslint-utils/-/eslint-utils-2.1.0.tgz#d2de5e03424e707dc10c74068ddedae708741b27" integrity sha512-w94dQYoauyvlDc43XnGB8lU3Zt713vNChgt4EWwhXAP2XkBvndfxF0AgIqKOOasjPIPzj9JqgwkwbCYD0/V3Zg== dependencies: eslint-visitor-keys "^1.1.0" -eslint-visitor-keys@^1.1.0, eslint-visitor-keys@^1.3.0: +eslint-utils@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/eslint-utils/-/eslint-utils-3.0.0.tgz#8aebaface7345bb33559db0a1f13a1d2d48c3672" + integrity sha512-uuQC43IGctw68pJA1RgbQS8/NP7rch6Cwd4j3ZBtgo4/8Flj4eGE7ZYSZRN3iq5pVUv6GPdW5Z1RFleo84uLDA== + dependencies: + eslint-visitor-keys "^2.0.0" + +eslint-visitor-keys@^1.1.0: version "1.3.0" resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz#30ebd1ef7c2fdff01c3a4f151044af25fab0523e" integrity sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ== @@ -1750,37 +1735,41 @@ eslint-visitor-keys@^2.0.0: resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-2.1.0.tgz#f65328259305927392c938ed44eb0a5c9b2bd303" integrity sha512-0rSmRBzXgDzIsD6mGdJgevzgezI534Cer5L/vyMX0kHzT/jiB43jRhd9YUlMGYLQy2zprNmoT8qasCGtY+QaKw== -eslint@^7.32.0: - version "7.32.0" - resolved "https://registry.yarnpkg.com/eslint/-/eslint-7.32.0.tgz#c6d328a14be3fb08c8d1d21e12c02fdb7a2a812d" - integrity sha512-VHZ8gX+EDfz+97jGcgyGCyRia/dPOd6Xh9yPv8Bl1+SoaIwD+a/vlrOmGRUyOYu7MwUhc7CxqeaDZU13S4+EpA== +eslint-visitor-keys@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-3.0.0.tgz#e32e99c6cdc2eb063f204eda5db67bfe58bb4186" + integrity sha512-mJOZa35trBTb3IyRmo8xmKBZlxf+N7OnUl4+ZhJHs/r+0770Wh/LEACE2pqMGMe27G/4y8P2bYGk4J70IC5k1Q== + +eslint@^8.1.0: + version "8.1.0" + resolved "https://registry.yarnpkg.com/eslint/-/eslint-8.1.0.tgz#00f1f7dbf4134f26588e6c9f2efe970760f64664" + integrity sha512-JZvNneArGSUsluHWJ8g8MMs3CfIEzwaLx9KyH4tZ2i+R2/rPWzL8c0zg3rHdwYVpN/1sB9gqnjHwz9HoeJpGHw== dependencies: - "@babel/code-frame" "7.12.11" - "@eslint/eslintrc" "^0.4.3" - "@humanwhocodes/config-array" "^0.5.0" + "@eslint/eslintrc" "^1.0.3" + "@humanwhocodes/config-array" "^0.6.0" ajv "^6.10.0" chalk "^4.0.0" cross-spawn "^7.0.2" - debug "^4.0.1" + debug "^4.3.2" doctrine "^3.0.0" enquirer "^2.3.5" escape-string-regexp "^4.0.0" - eslint-scope "^5.1.1" - eslint-utils "^2.1.0" - eslint-visitor-keys "^2.0.0" - espree "^7.3.1" + eslint-scope "^6.0.0" + eslint-utils "^3.0.0" + eslint-visitor-keys "^3.0.0" + espree "^9.0.0" esquery "^1.4.0" esutils "^2.0.2" fast-deep-equal "^3.1.3" file-entry-cache "^6.0.1" functional-red-black-tree "^1.0.1" - glob-parent "^5.1.2" + glob-parent "^6.0.1" globals "^13.6.0" ignore "^4.0.6" import-fresh "^3.0.0" imurmurhash "^0.1.4" is-glob "^4.0.0" - js-yaml "^3.13.1" + js-yaml "^4.1.0" json-stable-stringify-without-jsonify "^1.0.1" levn "^0.4.1" lodash.merge "^4.6.2" @@ -1788,22 +1777,21 @@ eslint@^7.32.0: natural-compare "^1.4.0" optionator "^0.9.1" progress "^2.0.0" - regexpp "^3.1.0" + regexpp "^3.2.0" semver "^7.2.1" strip-ansi "^6.0.0" strip-json-comments "^3.1.0" - table "^6.0.9" text-table "^0.2.0" v8-compile-cache "^2.0.3" -espree@^7.3.0, espree@^7.3.1: - version "7.3.1" - resolved "https://registry.yarnpkg.com/espree/-/espree-7.3.1.tgz#f2df330b752c6f55019f8bd89b7660039c1bbbb6" - integrity sha512-v3JCNCE64umkFpmkFGqzVKsOT0tN1Zr+ueqLZfpV1Ob8e+CEgPWa+OxCoGH3tnhimMKIaBm4m/vaRpJ/krRz2g== +espree@^9.0.0: + version "9.0.0" + resolved "https://registry.yarnpkg.com/espree/-/espree-9.0.0.tgz#e90a2965698228502e771c7a58489b1a9d107090" + integrity sha512-r5EQJcYZ2oaGbeR0jR0fFVijGOcwai07/690YRXLINuhmVeRY4UKSAsQPe/0BNuDgwP7Ophoc1PRsr2E3tkbdQ== dependencies: - acorn "^7.4.0" + acorn "^8.5.0" acorn-jsx "^5.3.1" - eslint-visitor-keys "^1.3.0" + eslint-visitor-keys "^3.0.0" esprima@^4.0.0: version "4.0.1" @@ -2200,7 +2188,14 @@ glob-parent@^3.1.0: is-glob "^3.1.0" path-dirname "^1.0.0" -glob-parent@^5.1.2, glob-parent@~5.1.0, glob-parent@~5.1.2: +glob-parent@^6.0.1: + version "6.0.2" + resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-6.0.2.tgz#6d237d99083950c79290f24c7642a3de9a28f9e3" + integrity sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A== + dependencies: + is-glob "^4.0.3" + +glob-parent@~5.1.0, glob-parent@~5.1.2: version "5.1.2" resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-5.1.2.tgz#869832c58034fe68a4093c17dc15e8340d8401c4" integrity sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow== @@ -2612,7 +2607,7 @@ is-glob@^3.1.0: dependencies: is-extglob "^2.1.0" -is-glob@^4.0.0, is-glob@^4.0.1, is-glob@~4.0.1: +is-glob@^4.0.0, is-glob@^4.0.1, is-glob@^4.0.3, is-glob@~4.0.1: version "4.0.3" resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-4.0.3.tgz#64f61e42cbbb2eec2071a9dac0b28ba1e65d5084" integrity sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg== @@ -2784,6 +2779,13 @@ js-yaml@4.0.0: dependencies: argparse "^2.0.1" +js-yaml@^4.1.0: + version "4.1.0" + resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-4.1.0.tgz#c1fb65f8f5017901cdd2c951864ba18458a10602" + integrity sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA== + dependencies: + argparse "^2.0.1" + js2xmlparser@^4.0.1: version "4.0.1" resolved "https://registry.yarnpkg.com/js2xmlparser/-/js2xmlparser-4.0.1.tgz#670ef71bc5661f089cc90481b99a05a1227ae3bd" @@ -2791,17 +2793,12 @@ js2xmlparser@^4.0.1: dependencies: xmlcreate "^2.0.3" -jsdoc-type-pratt-parser@1.1.1: - version "1.1.1" - resolved "https://registry.yarnpkg.com/jsdoc-type-pratt-parser/-/jsdoc-type-pratt-parser-1.1.1.tgz#10fe5e409ba38de22a48b555598955a26ff0160f" - integrity sha512-uelRmpghNwPBuZScwgBG/OzodaFk5RbO5xaivBdsAY70icWfShwZ7PCMO0x1zSkOa8T1FzHThmrdoyg/0AwV5g== - -jsdoc-type-pratt-parser@^1.1.1: - version "1.2.0" - resolved "https://registry.yarnpkg.com/jsdoc-type-pratt-parser/-/jsdoc-type-pratt-parser-1.2.0.tgz#3482a3833b74a88c95a6ba7253f0c0de3b77b9f5" - integrity sha512-4STjeF14jp4bqha44nKMY1OUI6d2/g6uclHWUCZ7B4DoLzaB5bmpTkQrpqU+vSVzMD0LsKAOskcnI3I3VfIpmg== +jsdoc-type-pratt-parser@2.0.0, jsdoc-type-pratt-parser@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/jsdoc-type-pratt-parser/-/jsdoc-type-pratt-parser-2.0.0.tgz#ec739a0868922515fcb179852e990e89b52b9044" + integrity sha512-sUuj2j48wxrEpbFjDp1sAesAxPiLT+z0SWVmMafyIINs6Lj5gIPKh3VrkBZu4E/Dv+wHpOot0m6H8zlHQjwqeQ== -jsdoc@^3.6.3: +jsdoc@^3.6.7: version "3.6.7" resolved "https://registry.yarnpkg.com/jsdoc/-/jsdoc-3.6.7.tgz#00431e376bed7f9de4716c6f15caa80e64492b89" integrity sha512-sxKt7h0vzCd+3Y81Ey2qinupL6DpRSZJclS04ugHDNmRUXGzqicMJ6iwayhSA0S0DwwX30c5ozyUthr1QKF6uw== @@ -2846,11 +2843,6 @@ json-schema-traverse@^0.4.1: resolved "https://registry.yarnpkg.com/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz#69f6a87d9513ab8bb8fe63bdb0979c448e684660" integrity sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg== -json-schema-traverse@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz#ae7bcb3656ab77a73ba5c49bf654f38e6b6860e2" - integrity sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug== - json-stable-stringify-without-jsonify@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz#9db7b59496ad3f3cfef30a75142d2d930ad72651" @@ -3102,11 +3094,6 @@ lodash.once@^4.0.0: resolved "https://registry.yarnpkg.com/lodash.once/-/lodash.once-4.1.1.tgz#0dd3971213c7c56df880977d504c88fb471a97ac" integrity sha1-DdOXEhPHxW34gJd9UEyI+0cal6w= -lodash.truncate@^4.4.2: - version "4.4.2" - resolved "https://registry.yarnpkg.com/lodash.truncate/-/lodash.truncate-4.4.2.tgz#5a350da0b1113b837ecfffd5812cbe58d6eae193" - integrity sha1-WjUNoLERO4N+z//VgSy+WNbq4ZM= - lodash@^4.17.14, lodash@^4.17.15, lodash@^4.17.21, lodash@^4.17.5: version "4.17.21" resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.21.tgz#679591c564c3bffaae8454cf0b3df370c3d6911c" @@ -4238,7 +4225,7 @@ regexp.prototype.flags@^1.2.0: call-bind "^1.0.2" define-properties "^1.1.3" -regexpp@^3.0.0, regexpp@^3.1.0: +regexpp@^3.0.0, regexpp@^3.2.0: version "3.2.0" resolved "https://registry.yarnpkg.com/regexpp/-/regexpp-3.2.0.tgz#0425a2768d8f23bad70ca4b90461fa2f1213e1b2" integrity sha512-pq2bWo9mVD43nbts2wGv17XLiNLya+GklZ8kaDLV2Z08gDCsGpnKn9BFMepvWuHCbyVvY7J5o5+BVvoQbmlJLg== @@ -4275,11 +4262,6 @@ require-directory@^2.1.1: resolved "https://registry.yarnpkg.com/require-directory/-/require-directory-2.1.1.tgz#8c64ad5fd30dab1c976e2344ffe7f792a6a6df42" integrity sha1-jGStX9MNqxyXbiNE/+f3kqam30I= -require-from-string@^2.0.2: - version "2.0.2" - resolved "https://registry.yarnpkg.com/require-from-string/-/require-from-string-2.0.2.tgz#89a7fdd938261267318eafe14f9c32e598c36909" - integrity sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw== - require-main-filename@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/require-main-filename/-/require-main-filename-2.0.0.tgz#d0b329ecc7cc0f61649f62215be69af54aa8989b" @@ -4526,15 +4508,6 @@ slash@^3.0.0: resolved "https://registry.yarnpkg.com/slash/-/slash-3.0.0.tgz#6539be870c165adbd5240220dbe361f1bc4d4634" integrity sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q== -slice-ansi@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/slice-ansi/-/slice-ansi-4.0.0.tgz#500e8dd0fd55b05815086255b3195adf2a45fe6b" - integrity sha512-qMCMfhY040cVHT43K9BFygqYbUPFZKHOg7K73mtTWJRb8pyP3fzf4Ixd5SzdEJQ6MRUg/WBnOLxghZtKKurENQ== - dependencies: - ansi-styles "^4.0.0" - astral-regex "^2.0.0" - is-fullwidth-code-point "^3.0.0" - snake-case@^1.1.0: version "1.1.2" resolved "https://registry.yarnpkg.com/snake-case/-/snake-case-1.1.2.tgz#0c2f25e305158d9a18d3d977066187fef8a5a66a" @@ -4751,7 +4724,7 @@ string-width@^3.0.0, string-width@^3.1.0: is-fullwidth-code-point "^2.0.0" strip-ansi "^5.1.0" -string-width@^4.1.0, string-width@^4.2.0, string-width@^4.2.3: +string-width@^4.1.0, string-width@^4.2.0: version "4.2.3" resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010" integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g== @@ -4875,18 +4848,6 @@ swap-case@^1.1.0: lower-case "^1.1.1" upper-case "^1.1.1" -table@^6.0.9: - version "6.7.2" - resolved "https://registry.yarnpkg.com/table/-/table-6.7.2.tgz#a8d39b9f5966693ca8b0feba270a78722cbaf3b0" - integrity sha512-UFZK67uvyNivLeQbVtkiUs8Uuuxv24aSL4/Vil2PJVtMgU8Lx0CYkP12uCGa3kjyQzOSgV1+z9Wkb82fCGsO0g== - dependencies: - ajv "^8.0.1" - lodash.clonedeep "^4.5.0" - lodash.truncate "^4.4.2" - slice-ansi "^4.0.0" - string-width "^4.2.3" - strip-ansi "^6.0.1" - taffydb@2.6.2: version "2.6.2" resolved "https://registry.yarnpkg.com/taffydb/-/taffydb-2.6.2.tgz#7cbcb64b5a141b6a2efc2c5d2c67b4e150b2a268" From 4dfb600ea12f5ee177334ba2510bb89f471e2378 Mon Sep 17 00:00:00 2001 From: hornta Date: Sat, 30 Oct 2021 13:02:54 +0200 Subject: [PATCH 21/22] Revert back to using proxyquire and --- src/auth/OAUthWithIDTokenValidation.js | 3 +- .../oauth-with-idtoken-validation.tests.js | 105 ++++++++++++++---- 2 files changed, 87 insertions(+), 21 deletions(-) diff --git a/src/auth/OAUthWithIDTokenValidation.js b/src/auth/OAUthWithIDTokenValidation.js index 26913dddf..5c716327f 100644 --- a/src/auth/OAUthWithIDTokenValidation.js +++ b/src/auth/OAUthWithIDTokenValidation.js @@ -18,7 +18,6 @@ class OAUthWithIDTokenValidation { * @param {string} [options.clientSecret] Default client Secret. * @param {string} [options.supportedAlgorithms] Algorithms that your application expects to receive * @param {boolean} [options.__bypassIdTokenValidation] Whether the id_token should be validated or not - * @param {Function} [options.jwksClient] Dependency injected `jwks-rsa` */ constructor(oauth, options) { if (!oauth) { @@ -39,7 +38,7 @@ class OAUthWithIDTokenValidation { this.clientSecret = options.clientSecret; this.domain = options.domain; this.supportedAlgorithms = options.supportedAlgorithms || ['HS256', 'RS256']; - this._jwksClient = (options.jwksClient || jwksClient)({ + this._jwksClient = jwksClient({ jwksUri: `https://${options.domain}/.well-known/jwks.json`, }); } diff --git a/test/auth/oauth-with-idtoken-validation.tests.js b/test/auth/oauth-with-idtoken-validation.tests.js index 3db636fe9..4c290fcc5 100644 --- a/test/auth/oauth-with-idtoken-validation.tests.js +++ b/test/auth/oauth-with-idtoken-validation.tests.js @@ -1,7 +1,6 @@ const { expect } = require('chai'); const sinon = require('sinon'); const proxyquire = require('proxyquire'); - const jwt = require('jsonwebtoken'); const jwksClient = require('jwks-rsa'); const pem = require('pem'); @@ -130,6 +129,7 @@ describe('OAUthWithIDTokenValidation', () => { done(); }); }); + it('Returns error when verify response is an error', (done) => { const oauth = { create() { @@ -145,6 +145,7 @@ describe('OAUthWithIDTokenValidation', () => { done(); }); }); + it('Uses `clientSecret` as key when header.alg === HS256 and there is a user secret', (done) => { const oauth = { create() { @@ -190,6 +191,7 @@ describe('OAUthWithIDTokenValidation', () => { done(); }); }); + describe('when header.alg !== HS256', () => { it('creates a jwksClient with the correct jwksUri', (done) => { const oauth = { @@ -201,6 +203,14 @@ describe('OAUthWithIDTokenValidation', () => { cb(null, { publicKey: 'publicKey' }); }, })); + jwksClientStub.prototype = {}; + + const OAUthWithIDTokenValidationProxy = proxyquire( + '../../src/auth/OAUthWithIDTokenValidation', + { + 'jwks-rsa': jwksClientStub, + } + ); sinon.stub(jwt, 'verify').callsFake((idtoken, getKey) => { getKey({ alg: 'RS256' }, () => { @@ -210,13 +220,13 @@ describe('OAUthWithIDTokenValidation', () => { done(); }); }); - const oauthWithValidation = new OAUthWithIDTokenValidation(oauth, { + const oauthWithValidation = new OAUthWithIDTokenValidationProxy(oauth, { domain: DOMAIN, clientSecret: CLIENT_SECRET, - jwksClient: jwksClientStub, }); oauthWithValidation.create(PARAMS, DATA); }); + it('returns the error when available', (done) => { const oauth = { create() { @@ -228,6 +238,14 @@ describe('OAUthWithIDTokenValidation', () => { cb({ the: 'error' }); }, })); + jwksClientStub.prototype = {}; + + const OAUthWithIDTokenValidationProxy = proxyquire( + '../../src/auth/OAUthWithIDTokenValidation', + { + 'jwks-rsa': jwksClientStub, + } + ); sinon.stub(jwt, 'verify').callsFake((idtoken, getKey) => { getKey({ kid: 'kid', alg: 'RS256' }, (err) => { @@ -235,13 +253,13 @@ describe('OAUthWithIDTokenValidation', () => { done(); }); }); - const oauthWithValidation = new OAUthWithIDTokenValidation(oauth, { + const oauthWithValidation = new OAUthWithIDTokenValidationProxy(oauth, { domain: DOMAIN, clientSecret: CLIENT_SECRET, - jwksClient: jwksClientStub, }); oauthWithValidation.create(PARAMS, DATA); }); + it('uses the publicKey when available', (done) => { const oauth = { create() { @@ -254,6 +272,13 @@ describe('OAUthWithIDTokenValidation', () => { cb(null, { publicKey: 'publicKey' }); }, })); + jwksClientStub.prototype = {}; + const OAUthWithIDTokenValidationProxy = proxyquire( + '../../src/auth/OAUthWithIDTokenValidation', + { + 'jwks-rsa': jwksClientStub, + } + ); sinon.stub(jwt, 'verify').callsFake((idtoken, getKey) => { getKey({ kid: 'kid', alg: 'RS256' }, (err, key) => { @@ -261,13 +286,13 @@ describe('OAUthWithIDTokenValidation', () => { done(); }); }); - const oauthWithValidation = new OAUthWithIDTokenValidation(oauth, { + const oauthWithValidation = new OAUthWithIDTokenValidationProxy(oauth, { domain: DOMAIN, clientSecret: CLIENT_SECRET, - jwksClient: jwksClientStub, }); oauthWithValidation.create(PARAMS, DATA); }); + it('uses the publicKey when both keys (publicKey and rsaPublicKey) available', (done) => { const oauth = { create() { @@ -280,6 +305,13 @@ describe('OAUthWithIDTokenValidation', () => { cb(null, { publicKey: 'publicKey', rsaPublicKey: 'rsaPublicKey' }); }, })); + jwksClientStub.prototype = {}; + const OAUthWithIDTokenValidationProxy = proxyquire( + '../../src/auth/OAUthWithIDTokenValidation', + { + 'jwks-rsa': jwksClientStub, + } + ); sinon.stub(jwt, 'verify').callsFake((idtoken, getKey) => { getKey({ kid: 'kid', alg: 'RS256' }, (err, key) => { @@ -287,13 +319,13 @@ describe('OAUthWithIDTokenValidation', () => { done(); }); }); - const oauthWithValidation = new OAUthWithIDTokenValidation(oauth, { + const oauthWithValidation = new OAUthWithIDTokenValidationProxy(oauth, { domain: DOMAIN, clientSecret: CLIENT_SECRET, - jwksClient: jwksClientStub, }); oauthWithValidation.create(PARAMS, DATA); }); + it('uses the rsaPublicKey when there is no publicKey available', (done) => { const oauth = { create() { @@ -306,6 +338,13 @@ describe('OAUthWithIDTokenValidation', () => { cb(null, { rsaPublicKey: 'rsaPublicKey' }); }, })); + jwksClientStub.prototype = {}; + const OAUthWithIDTokenValidationProxy = proxyquire( + '../../src/auth/OAUthWithIDTokenValidation', + { + 'jwks-rsa': jwksClientStub, + } + ); sinon.stub(jwt, 'verify').callsFake((idtoken, getKey) => { getKey({ kid: 'kid', alg: 'RS256' }, (err, key) => { @@ -313,14 +352,14 @@ describe('OAUthWithIDTokenValidation', () => { done(); }); }); - const oauthWithValidation = new OAUthWithIDTokenValidation(oauth, { + const oauthWithValidation = new OAUthWithIDTokenValidationProxy(oauth, { domain: DOMAIN, clientSecret: CLIENT_SECRET, - jwksClient: jwksClientStub, }); oauthWithValidation.create(PARAMS, DATA); }); }); + describe('#integration', () => { it('fails with a HS256 id_token and `options.supportedAlgorithms===RS256`', (done) => { const oauth = { @@ -342,6 +381,7 @@ describe('OAUthWithIDTokenValidation', () => { done(); }); }); + it('fails with a RS256 id_token and `options.supportedAlgorithms===HS256`', (done) => { createCertificate((c) => { const idtoken = jwt.sign({ foo: 'bar' }, c.serviceKey, { @@ -364,12 +404,18 @@ describe('OAUthWithIDTokenValidation', () => { cb(null, { publicKey: c.publicKey }); }, })); + jwksClientStub.prototype = {}; + const OAUthWithIDTokenValidationProxy = proxyquire( + '../../src/auth/OAUthWithIDTokenValidation', + { + 'jwks-rsa': jwksClientStub, + } + ); - const oauthWithValidation = new OAUthWithIDTokenValidation(oauth, { + const oauthWithValidation = new OAUthWithIDTokenValidationProxy(oauth, { clientSecret: CLIENT_SECRET, domain: 'auth.brucke.club', supportedAlgorithms: ['HS256'], - jwksClient: jwksClientStub, }); oauthWithValidation.create(PARAMS, DATA, (e) => { expect(e.message).to.eq('invalid algorithm'); @@ -377,6 +423,7 @@ describe('OAUthWithIDTokenValidation', () => { }); }); }); + it('fails when `token.exp` is expired', (done) => { createCertificate((c) => { const idtoken = jwt.sign({ foo: 'bar' }, c.serviceKey, { @@ -399,12 +446,18 @@ describe('OAUthWithIDTokenValidation', () => { cb(null, { publicKey: c.publicKey }); }, })); + jwksClientStub.prototype = {}; + const OAUthWithIDTokenValidationProxy = proxyquire( + '../../src/auth/OAUthWithIDTokenValidation', + { + 'jwks-rsa': jwksClientStub, + } + ); - const oauthWithValidation = new OAUthWithIDTokenValidation(oauth, { + const oauthWithValidation = new OAUthWithIDTokenValidationProxy(oauth, { clientSecret: CLIENT_SECRET, domain: 'auth.brucke.club', supportedAlgorithms: ['RS256'], - jwksClient: jwksClientStub, }); oauthWithValidation.create(PARAMS, DATA, (e) => { expect(e.message).to.eq('jwt expired'); @@ -412,6 +465,7 @@ describe('OAUthWithIDTokenValidation', () => { }); }); }); + describe('when using a valid certificate to generate an invalid id_token', () => { it('fails when `token.aud` is invalid', (done) => { createCertificate((c) => { @@ -434,13 +488,19 @@ describe('OAUthWithIDTokenValidation', () => { cb(null, { publicKey: c.publicKey }); }, })); + jwksClientStub.prototype = {}; + const OAUthWithIDTokenValidationProxy = proxyquire( + '../../src/auth/OAUthWithIDTokenValidation', + { + 'jwks-rsa': jwksClientStub, + } + ); - const oauthWithValidation = new OAUthWithIDTokenValidation(oauth, { + const oauthWithValidation = new OAUthWithIDTokenValidationProxy(oauth, { clientId: 'foobar', clientSecret: CLIENT_SECRET, domain: 'brucke.auth0.com', supportedAlgorithms: ['RS256'], - jwksClient: jwksClientStub, }); oauthWithValidation.create(PARAMS, DATA, (e) => { expect(e.message).to.eq('jwt audience invalid. expected: foobar'); @@ -448,6 +508,7 @@ describe('OAUthWithIDTokenValidation', () => { }); }); }); + it('fails when `token.iss` is invalid', (done) => { const TEST_AUDIENCE = 'foobar'; createCertificate((c) => { @@ -471,13 +532,19 @@ describe('OAUthWithIDTokenValidation', () => { cb(null, { publicKey: c.publicKey }); }, })); + jwksClientStub.prototype = {}; + const OAUthWithIDTokenValidationProxy = proxyquire( + '../../src/auth/OAUthWithIDTokenValidation', + { + 'jwks-rsa': jwksClientStub, + } + ); - const oauthWithValidation = new OAUthWithIDTokenValidation(oauth, { + const oauthWithValidation = new OAUthWithIDTokenValidationProxy(oauth, { clientId: 'foobar', clientSecret: CLIENT_SECRET, domain: 'brucke.auth0.com', supportedAlgorithms: ['RS256'], - jwksClient: jwksClientStub, }); oauthWithValidation.create(PARAMS, DATA, (e) => { expect(e.message).to.eq('jwt issuer invalid. expected: https://brucke.auth0.com/'); From 9f395f28633e11400aaf8d8857bbe09624a8a590 Mon Sep 17 00:00:00 2001 From: hornta Date: Sat, 30 Oct 2021 13:03:29 +0200 Subject: [PATCH 22/22] Made the `getCachedAccessToken` a promise again --- src/management/ManagementTokenProvider.js | 81 +++++++++++------------ 1 file changed, 39 insertions(+), 42 deletions(-) diff --git a/src/management/ManagementTokenProvider.js b/src/management/ManagementTokenProvider.js index 5f196e8b4..dbd207872 100644 --- a/src/management/ManagementTokenProvider.js +++ b/src/management/ManagementTokenProvider.js @@ -1,6 +1,7 @@ const { ArgumentError } = require('rest-facade'); const AuthenticationClient = require('../auth'); const memoizer = require('lru-memoizer'); +const util = require('util'); /** * Auth0 Management API Token Provider. @@ -70,36 +71,38 @@ class ManagementTokenProvider { this.authenticationClient = new AuthenticationClient(authenticationClientOptions); const self = this; - this.getCachedAccessToken = memoizer({ - load(options, callback) { - self - .clientCredentialsGrant(options.domain, options.scope, options.audience) - .then((data) => { - callback(null, data); - }) - .catch((err) => { - callback(err); - }); - }, - hash(options) { - return `${options.domain}-${options.clientId}-${options.scope}`; - }, - itemMaxAge(options, data) { - if (options.cacheTTLInSeconds) { - return options.cacheTTLInSeconds * 1000; - } - - // if the expires_in is lower or equal to than 10 seconds, do not subtract 10 additional seconds. - if (data.expires_in && data.expires_in <= 10 /* seconds */) { - return data.expires_in * 1000; - } else if (data.expires_in) { - // Subtract 10 seconds from expires_in to fetch a new one, before it expires. - return data.expires_in * 1000 - 10000 /* milliseconds */; - } - return 60 * 60 * 1000; //1h - }, - max: 100, - }); + this.getCachedAccessToken = util.promisify( + memoizer({ + load(options, callback) { + self + .clientCredentialsGrant(options.domain, options.scope, options.audience) + .then((data) => { + callback(null, data); + }) + .catch((err) => { + callback(err); + }); + }, + hash(options) { + return `${options.domain}-${options.clientId}-${options.scope}`; + }, + itemMaxAge(options, data) { + if (options.cacheTTLInSeconds) { + return options.cacheTTLInSeconds * 1000; + } + + // if the expires_in is lower or equal to than 10 seconds, do not subtract 10 additional seconds. + if (data.expires_in && data.expires_in <= 10 /* seconds */) { + return data.expires_in * 1000; + } else if (data.expires_in) { + // Subtract 10 seconds from expires_in to fetch a new one, before it expires. + return data.expires_in * 1000 - 10000 /* milliseconds */; + } + return 60 * 60 * 1000; //1h + }, + max: 100, + }) + ); } /** @@ -107,23 +110,17 @@ class ManagementTokenProvider { * * @returns {Promise} Promise returning an access_token. */ - getAccessToken() { + async getAccessToken() { if (this.options.enableCache) { - return new Promise((resolve, reject) => { - this.getCachedAccessToken(this.options, (error, data) => { - if (error) { - reject(error); - } else { - resolve(data.access_token); - } - }); - }); + const data = await this.getCachedAccessToken(this.options); + return data.access_token; } else { - return this.clientCredentialsGrant( + const data = await this.clientCredentialsGrant( this.options.domain, this.options.scope, this.options.audience - ).then((data) => data.access_token); + ); + return data.access_token; } }