diff --git a/.circleci/config.yml b/.circleci/config.yml
index 07a3ef12d..2683ba0fe 100644
--- a/.circleci/config.yml
+++ b/.circleci/config.yml
@@ -24,9 +24,35 @@ jobs:
key: yarn-packages-{{ checksum "yarn.lock" }}
paths:
- ~/.cache/yarn
- - run:
- name: Tests
- command: yarn test:ci
+ - 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
+ - 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 >> ]
@@ -34,14 +60,13 @@ jobs:
- run:
name: Generate Coverage
command: yarn test:coverage
-
workflows:
build-test-report:
jobs:
- 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:
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..31e3bfa06
--- /dev/null
+++ b/.eslintrc.js
@@ -0,0 +1,55 @@
+module.exports = {
+ env: {
+ node: true,
+ commonjs: true,
+ es2017: true,
+ mocha: true,
+ },
+ extends: [
+ 'eslint:recommended',
+ 'plugin:jsdoc/recommended',
+ 'plugin:node/recommended',
+ 'plugin:promise/recommended',
+ 'plugin:prettier/recommended',
+ ],
+ plugins: ['jsdoc'],
+ parserOptions: {
+ ecmaVersion: 9,
+ },
+ rules: {
+ 'arrow-body-style': 'error',
+ 'arrow-parens': 'error',
+ 'arrow-spacing': 'error',
+ 'generator-star-spacing': 'error',
+ 'no-confusing-arrow': 'error',
+ 'no-duplicate-imports': 'error',
+ 'no-restricted-exports': 'error',
+ 'no-restricted-imports': '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',
+ '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',
+ 'jsdoc/check-param-names': 'off',
+
+ 'promise/catch-or-return': 'off',
+ 'promise/always-return': '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/README.md b/README.md
index 87d4cd0c9..203773333 100644
--- a/README.md
+++ b/README.md
@@ -36,7 +36,7 @@ var AuthenticationClient = require('auth0').AuthenticationClient;
var auth0 = new AuthenticationClient({
domain: '{YOUR_ACCOUNT}.auth0.com',
- clientId: '{OPTIONAL_CLIENT_ID}'
+ clientId: '{OPTIONAL_CLIENT_ID}',
});
```
@@ -51,7 +51,7 @@ var ManagementClient = require('auth0').ManagementClient;
var management = new ManagementClient({
token: '{YOUR_API_V2_TOKEN}',
- domain: '{YOUR_ACCOUNT}.auth0.com'
+ domain: '{YOUR_ACCOUNT}.auth0.com',
});
```
@@ -66,7 +66,7 @@ var auth0 = new ManagementClient({
domain: '{YOUR_ACCOUNT}.auth0.com',
clientId: '{YOUR_NON_INTERACTIVE_CLIENT_ID}',
clientSecret: '{YOUR_NON_INTERACTIVE_CLIENT_SECRET}',
- scope: 'read:users update:users'
+ scope: 'read:users update:users',
});
```
@@ -80,15 +80,15 @@ var AuthenticationClient = require('auth0').AuthenticationClient;
var auth0 = new AuthenticationClient({
domain: '{YOUR_ACCOUNT}.auth0.com',
clientId: '{CLIENT_ID}',
- clientSecret: '{CLIENT_SECRET}'
+ clientSecret: '{CLIENT_SECRET}',
});
auth0.clientCredentialsGrant(
{
audience: 'https://{YOUR_ACCOUNT}.auth0.com/api/v2/',
- scope: '{MANAGEMENT_API_SCOPES}'
+ scope: '{MANAGEMENT_API_SCOPES}',
},
- function(err, response) {
+ function (err, response) {
if (err) {
// Handle error.
}
@@ -105,7 +105,7 @@ Be aware that all methods can be used with promises or callbacks. However, when
```js
// Using callbacks.
-management.getUsers(function(err, users) {
+management.getUsers(function (err, users) {
if (err) {
// handle error.
}
@@ -115,10 +115,10 @@ management.getUsers(function(err, users) {
// Using promises.
management
.getUsers()
- .then(function(users) {
+ .then(function (users) {
console.log(users);
})
- .catch(function(err) {
+ .catch(function (err) {
// Handle error.
});
```
diff --git a/package.json b/package.json
index d10c30fdc..9699c7d55 100644
--- a/package.json
+++ b/package.json
@@ -8,17 +8,21 @@
"src"
],
"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",
+ "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",
"url": "https://github.com/auth0/node-auth0"
},
+ "engines": {
+ "node": ">=8.3.0"
+ },
"keywords": [
"auth0",
"api"
@@ -31,7 +35,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",
@@ -43,21 +46,26 @@
"chai": "^4.2.0",
"codecov": "^3.7.2",
"cross-env": "^5.2.0",
+ "eslint": "^8.1.0",
+ "eslint-config-prettier": "^8.3.0",
+ "eslint-plugin-jsdoc": "^37.0.3",
+ "eslint-plugin-node": "^11.1.0",
+ "eslint-plugin-prettier": "^4.0.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",
- "mocha": "^6.2.0",
- "mocha-junit-reporter": "^1.23.1",
- "moment": "^2.24.0",
+ "mocha": "^8.4.0",
+ "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..79aacded3 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);
+ }
+ throw 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..cebb038a8 100644
--- a/src/auth/DatabaseAuthenticator.js
+++ b/src/auth/DatabaseAuthenticator.js
@@ -1,297 +1,280 @@
-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 {
+ /**
+ * @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.
+ *
+ * @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.
+ *
+ * @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..5c716327f 100644
--- a/src/auth/OAUthWithIDTokenValidation.js
+++ b/src/auth/OAUthWithIDTokenValidation.js
@@ -1,128 +1,124 @@
-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
*/
-var 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
+ */
+ 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 = 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 = 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}
- */
-OAUthWithIDTokenValidation.prototype.create = function(params, data, cb) {
- const _this = this;
- 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'));
+ /**
+ * 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) {
+ 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'));
}
- return new Promise((res, rej) => {
- var options = {
- algorithms: this.supportedAlgorithms,
- audience: this.clientId,
- issuer: 'https://' + this.domain + '/'
- };
-
- if (data.organization) {
- options.organization = data.organization;
+ _this._jwksClient.getSigningKey(header.kid, (err, key) => {
+ if (err) {
+ return callback(err);
}
+ const signingKey = key.publicKey || key.rsaPublicKey;
+ return callback(null, signingKey);
+ });
+ }
+ 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, function(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 b73719bf7..f3f981003 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,371 @@ 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 {
+ /**
+ * @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.
+ *
+ * @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
+ *
+ * @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
+ *
+ * @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.
+ *
+ * @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
+ *
+ * @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..c380e08ff 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,270 @@ 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.
+ *
+ * @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.
+ *
+ * @example
+ * Given the user `email` address, it will send an email with:
+ *
+ *
+ * - A link (default, `send:"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.
+ *
+ * -
+ * A verification code (`send:"code"`). You can then authenticate with
+ * this user using the `/oauth/ro` endpoint specifying `email` as
+ * `username` and `code` as `password`.
+ *
+ *
+ *
+ * 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:
- *
- *
- * - A link (default, `send:"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.
- *
- * -
- * A verification code (`send:"code"`). You can then authenticate with
- * this user using the `/oauth/ro` endpoint specifying `email` as
- * `username` and `code` as `password`.
- *
- *
- *
- * 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.
+ *
+ * @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..b7f4164ba 100644
--- a/src/auth/TokensManager.js
+++ b/src/auth/TokensManager.js
@@ -1,257 +1,242 @@
-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.
+ *
+ * @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).
+ *
+ * @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.
+ *
+ * @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..2d2393b4d 100644
--- a/src/auth/UsersManager.js
+++ b/src/auth/UsersManager.js
@@ -1,172 +1,161 @@
-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.
+ *
+ * @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.
+ *
+ * @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 885ca5caf..67743b07d 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 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 {object} 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..8a174ce56 100644
--- a/src/auth/index.js
+++ b/src/auth/index.js
@@ -1,29 +1,23 @@
-/** @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
* Authentication API SDK.
*
- * This client must used to access Auth0's
- * Authentication API.
- * @constructor
- * @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
@@ -36,605 +30,538 @@ 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.
*/
-var 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');
+ }
- var defaultHeaders = {
- 'User-Agent': 'node.js/' + process.version.replace('v', ''),
- 'Content-Type': 'application/json'
- };
-
- var 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) {
- var clientInfo = options.clientInfo || utils.generateClientInfo();
- if ('string' === typeof clientInfo.name && clientInfo.name) {
- var 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
+ *
+ *
+ * var data = {
+ * email: '{EMAIL}',
+ * authParams: {} // Optional auth params.
+ * };
*
- * @type {OAuthAuthenticator}
+ * 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.
+ *
+ * @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
+ *
*
- * @type {DatabaseAuthenticator}
+ * 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`.
+ *
*
- * @type {PasswordlessAuthenticator}
+ * 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}
*/
- 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.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-AuthenticationClient.prototype.requestMagicLink = function(data, cb) {
- data.send = 'link';
-
- return this.passwordless.sendEmail(data, cb);
-};
-
-/**
- * Start passwordless flow sending an email.
- *
- * @method 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.
- *
- * @return {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.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-AuthenticationClient.prototype.verifyEmailCode = function(data, cb) {
- var translatedData = {
- username: data.email,
- realm: 'email',
- otp: data.otp
- };
-
- return this.passwordless.signIn(translatedData, cb);
-};
-
-/**
- * Start passwordless flow sending an SMS.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-AuthenticationClient.prototype.requestSMSCode = function(data, cb) {
- var 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.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-AuthenticationClient.prototype.verifySMSCode = function(data, cb) {
- var 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).
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-AuthenticationClient.prototype.getDelegationToken = function(data, cb) {
- var 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.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-AuthenticationClient.prototype.changePassword = function(data, cb) {
- var translatedData = {
- connection: data.connection,
- email: data.email || data.username,
- password: data.password
- };
-
- return this.database.changePassword(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).
+ *
+ * @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);
+ }
-/**
- * Request a change password email using a database or active directory service.
- *
- * @method 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}',
+ * 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);
+ }
- return this.database.requestChangePasswordEmail(data, cb);
-};
+ /**
+ * Request a change password email using a database or active directory service.
+ *
+ * @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.
- *
- *
- * auth0.getProfile(data, function (err, userInfo) {
- * if (err) {
- * // Handle error.
- * }
- *
- * console.log(userInfo);
- * });
- *
- * @param {String} accessToken The user access token.
- *
- * @return {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.
- *
- * @method 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
- *
- * @return {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
- *
- * @method 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
- *
- * @return {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
- *
- * @method 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.
- *
- * @return {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/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..ad3d0e4ca 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
+ * {@link 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..218419419 100644
--- a/src/management/ActionsManager.js
+++ b/src/management/ActionsManager.js
@@ -1,661 +1,579 @@
-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
- */
-
-/**
- * @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}
+ * @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.
*
- * @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.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 .
+ *
+ * @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 .
+ *
+ * @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.
+ *
+ * @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.
+ *
+ * @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.
+ *
+ * @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.
+ *
+ * @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
+ *
+ * @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.
+ *
+ * @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.
+ *
+ * @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
+ *
+ * @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.
+ *
+ * @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).
+ *
+ * @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.
+ *
+ * @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.
+ *
+ * @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..a1a8d4eb9 100644
--- a/src/management/BlacklistedTokensManager.js
+++ b/src/management/BlacklistedTokensManager.js
@@ -1,102 +1,95 @@
-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.
+ *
+ * @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}
+ * @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..58c6955f1 100644
--- a/src/management/BrandingManager.js
+++ b/src/management/BrandingManager.js
@@ -1,183 +1,161 @@
-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
- */
-
-/**
- * @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
*/
-var 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);
- var 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}
*/
- var 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}
*/
- var brandingTemplateAuth0RestClient = new Auth0RestClient(
- options.baseUrl + '/branding/templates/universal-login',
- clientOptions,
- options.tokenProvider
- );
- this.brandingTemplates = new RetryRestClient(brandingTemplateAuth0RestClient, options.retry);
-};
-
-/**
- * Update the branding settings.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(BrandingManager, 'updateSettings', 'resource.patch');
-
-/**
- * Get the branding settings..
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(BrandingManager, 'getSettings', 'resource.get');
+ getSettings(...args) {
+ return this.resource.get(...args);
+ }
-/**
- * Get the new universal login template.
- *
- * @method 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.
- *
- * @return {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.
- *
- * @method 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.
- *
- * @return {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).
- *
- * @method 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.
- *
- * @return {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 7cafa6df3..6ddd50202 100644
--- a/src/management/ClientGrantsManager.js
+++ b/src/management/ClientGrantsManager.js
@@ -1,165 +1,152 @@
-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 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
*/
-var 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}
*/
- var 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.
+ *
*
- * @type {external:RestClient}
+ * // 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}
*/
- var auth0RestClient = new Auth0RestClient(
- options.baseUrl + '/client-grants/:id',
- clientOptions,
- options.tokenProvider
- );
- this.resource = new RetryRestClient(auth0RestClient, options.retry);
-};
-
-/**
- * Create an Auth0 client grant.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ClientGrantsManager, 'create', 'resource.create');
-
-/**
- * Get all Auth0 Client Grants.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ClientGrantsManager, 'getAll', 'resource.getAll');
+ getAll(...args) {
+ return this.resource.getAll(...args);
+ }
-/**
- * Update an Auth0 client grant.
- *
- * @method 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.
- *
- * @return {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.
- *
- * @method 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.
- *
- * @return {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 4acf3ce3a..bf66e1970 100644
--- a/src/management/ClientsManager.js
+++ b/src/management/ClientsManager.js
@@ -1,10 +1,8 @@
-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 ClientsManager
* Auth0 Clients Manager.
*
* {@link https://auth0.com/docs/api/v2#!/Clients Clients} represent
@@ -12,176 +10,162 @@ 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
*/
-var 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.
*
- * @type {Object}
+ * @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}
*/
- var 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.
*
- * @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.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}
*/
- var auth0RestClient = new Auth0RestClient(
- options.baseUrl + '/clients/:client_id',
- clientOptions,
- options.tokenProvider
- );
- this.resource = new RetryRestClient(auth0RestClient, options.retry);
-};
-
-/**
- * Create an Auth0 client.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ClientsManager, 'create', 'resource.create');
-
-/**
- * Get all Auth0 clients.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ClientsManager, 'getAll', 'resource.getAll');
+ getAll(...args) {
+ return this.resource.getAll(...args);
+ }
-/**
- * Get an Auth0 client.
- *
- * @method 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.
- *
- * @return {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.
- *
- * @method 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.
- *
- * @return {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.
- *
- * @method 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.
- *
- * @return {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 f10f291c0..b4d3e4d6c 100644
--- a/src/management/ConnectionsManager.js
+++ b/src/management/ConnectionsManager.js
@@ -1,268 +1,244 @@
-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 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
*/
-var 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 ('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);
+
+ 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);
}
- if (options.baseUrl === null || options.baseUrl === undefined) {
- throw new ArgumentError('Must provide a base URL for the API');
+ /**
+ * Create a new connection.
+ *
+ * @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}
+ */
+ 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 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.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}
+ */
+ getAll(...args) {
+ return this.resource.getAll(...args);
}
/**
- * Options object for the Rest Client instance.
+ * Get an Auth0 connection.
+ *
+ * @example
+ * management.connections.get({ id: CONNECTION_ID }, function (err, connection) {
+ * if (err) {
+ * // Handle error.
+ * }
*
- * @type {Object}
+ * console.log(connection);
+ * });
+ * @param {object} params Connection parameters.
+ * @param {string} params.id Connection ID.
+ * @param {Function} [cb] Callback function.
+ * @returns {Promise|undefined}
*/
- var 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#!/ConnectionsManagers Auth0
- * Connections}.
+ * Update an existing connection.
*
- * @type {external:RestClient}
+ * @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}
*/
- var auth0RestClient = new Auth0RestClient(
- options.baseUrl + '/connections/:id ',
- clientOptions,
- options.tokenProvider
- );
- this.resource = new RetryRestClient(auth0RestClient, options.retry);
-
- var statusClient = new Auth0RestClient(
- options.baseUrl + '/connections/:id/status',
- clientOptions,
- options.tokenProvider
- );
- this.status = new RetryRestClient(statusClient, options.retry);
+ update(...args) {
+ return this.resource.patch(...args);
+ }
/**
- * Provides an abstraction layer for consuming the
- * {@link https://auth0.com/docs/api/management/v2#!/Connections/delete_users_by_email
- * endpoint}.
+ * Delete an existing connection.
+ *
+ * @example
+ * management.connections.delete({ id: CONNECTION_ID }, function (err) {
+ * if (err) {
+ * // Handle error.
+ * }
*
- * @type {external:RestClient}
+ * // Connection deleted.
+ * });
+ * @param {object} params Connection parameters.
+ * @param {string} params.id Connection ID.
+ * @param {Function} [cb] Callback function.
+ * @returns {Promise|undefined}
*/
- var userAuth0RestClient = new Auth0RestClient(
- options.baseUrl + '/connections/:id/users',
- clientOptions,
- options.tokenProvider
- );
- this.user = new RetryRestClient(userAuth0RestClient, options.retry);
-};
-
-/**
- * Create a new connection.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ConnectionsManager, 'create', 'resource.create');
-
-/**
- * Get all connections.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ConnectionsManager, 'getAll', 'resource.getAll');
-
-/**
- * Get an Auth0 connection.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ConnectionsManager, 'get', 'resource.get');
-
-/**
- * Update an existing connection.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ConnectionsManager, 'update', 'resource.patch');
+ delete(...args) {
+ return this.resource.delete(...args);
+ }
-/**
- * Delete an existing connection.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ConnectionsManager, 'delete', 'resource.delete');
+ /**
+ * Checks the status of an ad/ldap connection referenced by its ID.
+ *
+ * @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);
+ }
-/**
- * Checks the status of an ad/ldap connection referenced by its ID.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ConnectionsManager, 'checkStatus', 'status.get');
+ /**
+ * Delete a connection user by email.
+ *
+ * @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.
- *
- * @method 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.
- *
- * @return {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/src/management/CustomDomainsManager.js b/src/management/CustomDomainsManager.js
index fea099afc..296ed61aa 100644
--- a/src/management/CustomDomainsManager.js
+++ b/src/management/CustomDomainsManager.js
@@ -1,10 +1,8 @@
-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 CustomDomainsManager
* Auth0 Custom Domains Manager.
*
* {@link https://auth0.com/docs/api/management/v2#!/Custom_Domains/get_custom_domains CustomDomains} represent
@@ -12,179 +10,164 @@ 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
*/
-var 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 },
+ };
+
+ /**
+ * 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);
- 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 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.
*
- * @type {Object}
+ * @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}
*/
- var 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}
*/
- var 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}
*/
- var auth0VerifyRestClient = new Auth0RestClient(
- options.baseUrl + '/custom-domains/:id/verify',
- clientOptions,
- options.tokenProvider
- );
- this.vefifyResource = new RetryRestClient(auth0VerifyRestClient, options.retry);
-};
-
-/**
- * Create an Auth0 Custom Domain.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(CustomDomainsManager, 'create', 'resource.create');
+ get(...args) {
+ return this.resource.get(...args);
+ }
-/**
- * Get all Auth0 CustomDomains.
- *
- * @method getAll
- * @memberOf module:management.CustomDomainsManager.prototype
- *
- * @example
- * management.customDomains.getAll(function (err, customDomains) {
- * console.log(customDomains.length);
- * });
- *
- * @return {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.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(CustomDomainsManager, 'get', 'resource.get');
+ if (cb && cb instanceof Function) {
+ return this.vefifyResource.create(params, {}, cb);
+ }
-/**
- * Verify a Custom Domain.
- *
- * @method 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.
- *
- * @return {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.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(CustomDomainsManager, 'delete', 'resource.delete');
+}
module.exports = CustomDomainsManager;
diff --git a/src/management/DeviceCredentialsManager.js b/src/management/DeviceCredentialsManager.js
index 1cff47c31..0143059a8 100644
--- a/src/management/DeviceCredentialsManager.js
+++ b/src/management/DeviceCredentialsManager.js
@@ -1,129 +1,113 @@
-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
- */
-
-/**
- * @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
*/
-var 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}
*/
- var 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}
*/
- var auth0RestClient = new Auth0RestClient(
- options.baseUrl + '/device-credentials/:id',
- clientOptions,
- options.tokenProvider
- );
- this.resource = new RetryRestClient(auth0RestClient, options.retry);
-};
-
-/**
- * Create an Auth0 credential.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(DeviceCredentialsManager, 'createPublicKey', 'resource.create');
-
-/**
- * Get all Auth0 credentials.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(DeviceCredentialsManager, 'getAll', 'resource.getAll');
+ getAll(...args) {
+ return this.resource.getAll(...args);
+ }
-/**
- * Delete an Auth0 device credential.
- *
- * @method 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.
- *
- * @return {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 b99d9fd25..2905b0d9f 100644
--- a/src/management/EmailProviderManager.js
+++ b/src/management/EmailProviderManager.js
@@ -1,147 +1,129 @@
-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
- */
-
-/**
- * @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
*/
-var 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');
+ }
+
+ /**
+ * 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
+ * [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.
*
- * @type {Object}
+ * @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}
*/
- var 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}
*/
- var auth0RestClient = new Auth0RestClient(
- options.baseUrl + '/emails/provider',
- clientOptions,
- options.tokenProvider
- );
- this.resource = new RetryRestClient(auth0RestClient, options.retry);
-};
-
-/**
- * Configure the email provider.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(EmailProviderManager, 'configure', 'resource.create');
-
-/**
- * Get the email provider.
- *
- * @method 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}
- */
-utils.wrapPropertyMethod(EmailProviderManager, 'get', 'resource.getAll');
+ get(...args) {
+ return this.resource.getAll(...args);
+ }
-/**
- * Update the email provider.
- *
- * @method 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.
- *
- * @return {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.
- *
- * @method delete
- * @memberOf module:management.EmailProviderManager.prototype
- *
- * @example
- * management.emailProvider.delete(function (err) {
- * if (err) {
- * // Handle error.
- * }
- *
- * // Email provider configured.
- * });
- *
- * @param {Function} [cb] Callback function.
- *
- * @return {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 c92ea85c8..3ff1cd1c7 100644
--- a/src/management/EmailTemplatesManager.js
+++ b/src/management/EmailTemplatesManager.js
@@ -1,129 +1,113 @@
-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
- */
-
-/**
- * @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
+ * on Auth0's Email Templates. {@link https://auth0.com/docs/api/management/v2#!/Email_Templates/get_email_templates_by_templateName}
*/
-var 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}
*/
- var 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}
*/
- var auth0RestClient = new Auth0RestClient(
- options.baseUrl + '/email-templates/:name',
- clientOptions,
- options.tokenProvider
- );
- this.resource = new RetryRestClient(auth0RestClient, options.retry);
-};
-
-/**
- * Create a new Email Template.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(EmailTemplatesManager, 'create', 'resource.create');
-
-/**
- * Get an Auth0 Email Template.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(EmailTemplatesManager, 'get', 'resource.get');
+ get(...args) {
+ return this.resource.get(...args);
+ }
-/**
- * Update an existing Email Template.
- *
- * @method 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.
- *
- * @return {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 9ccaf09a7..bc5d3f2d2 100644
--- a/src/management/GrantsManager.js
+++ b/src/management/GrantsManager.js
@@ -1,119 +1,112 @@
-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 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
*/
-var 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}
*/
- var 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.
+ *
+ * @example
+ * var params = {
+ * id: 'GRANT_ID',
+ * user_id: 'USER_ID'
+ * };
*
- * @type {external:RestClient}
+ * 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}
*/
- var auth0RestClient = new Auth0RestClient(
- options.baseUrl + '/grants/:id',
- clientOptions,
- options.tokenProvider
- );
- this.resource = new RetryRestClient(auth0RestClient, options.retry);
-};
-
-/**
- * Get all Auth0 Grants.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(GrantsManager, 'getAll', 'resource.getAll');
-
-/**
- * Delete an Auth0 grant.
- *
- * @method 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.
- *
- * @return {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 12393a338..89d7de5a5 100644
--- a/src/management/GuardianManager.js
+++ b/src/management/GuardianManager.js
@@ -1,508 +1,434 @@
-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
- */
-
-/**
- * @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
*/
-var 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);
}
- var 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}
*/
- var 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}
*/
- var 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}
*/
- var 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}
*/
- var 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}
*/
- var 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}
*/
- var 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}
*/
- var 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}
*/
- var 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}
*/
- var 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.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(GuardianManager, 'getGuardianEnrollment', 'enrollments.get');
-
-/**
- * Delete a Guardian enrollment.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(GuardianManager, 'deleteGuardianEnrollment', 'enrollments.delete');
-
-/**
- * Create a Guardian enrollment ticket.
- *
- * @method createEnrollmentTicket
- * @memberOf module:management.GuardianManager.prototype
- *
- * @example
- * management.guardian.createEnrollmentTicket(function (err, ticket) {
- * console.log(ticket);
- * });
- *
- * @param {Function} [cb] Callback function.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(GuardianManager, 'createEnrollmentTicket', 'tickets.create');
-
-/**
- * Get a list of factors and statuses.
- *
- * @method 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}
- */
-utils.wrapPropertyMethod(GuardianManager, 'getFactors', 'factors.getAll');
-
-/**
- * Get Guardian factor configuration
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(GuardianManager, 'getFactorSettings', 'factorSettings.get');
-
-/**
- * Update Guardian factor configuration
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(GuardianManager, 'updateFactorSettings', 'factorSettings.update');
-
-/**
- * Get Guardian factor provider configuration
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(GuardianManager, 'getFactorProvider', 'factorsProviders.get');
-
-/**
- * Update Guardian's factor provider
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(GuardianManager, 'updateFactorProvider', 'factorsProviders.update');
-
-/**
- * Get Guardian enrollment and verification factor templates
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(GuardianManager, 'getFactorTemplates', 'factorsTemplates.get');
-
-/**
- * Update Guardian enrollment and verification factor templates
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(GuardianManager, 'updateFactorTemplates', 'factorsTemplates.update');
-
-/**
- * Update Guardian Factor
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(GuardianManager, 'updateFactor', 'factors.update');
+ updateFactor(...args) {
+ return this.factors.update(...args);
+ }
-/**
- * Get enabled Guardian policies
- *
- * @method getPolicies
- * @memberOf module:management.GuardianManager.prototype
- *
- * @example
- * management.guardian.getPolicies(function (err, policies) {
- * console.log(policies);
- * });
- *
- * @param {Function} [cb] Callback function.
- *
- * @return {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
- *
- * @method 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.
- *
- * @return {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
- *
- * @method getPhoneFactorSelectedProvider
- * @memberOf module:management.GuardianManager.prototype
- *
- * @example
- * management.guardian.getPhoneFactorSelectedProvider(function (err, selectedProvider) {
- * console.log(selectedProvider);
- * });
- *
- * @param {Function} [cb] Callback function.
- *
- * @return {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
- *
- * @method 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.
- *
- * @return {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
- *
- * @method getPhoneFactorMessageTypes
- * @memberOf module:management.GuardianManager.prototype
- *
- * @example
- * management.guardian.getPhoneFactorMessageTypes(function (err, messageTypes) {
- * console.log(messageTypes);
- * });
- *
- * @param {Function} [cb] Callback function.
- *
- * @return {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
- *
- * @method 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.
- *
- * @return {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 53276ac03..1d40910ee 100644
--- a/src/management/HooksManager.js
+++ b/src/management/HooksManager.js
@@ -1,368 +1,327 @@
-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
- */
-
-/**
- * @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
*/
-var 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}
*/
- var 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}
*/
- var 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',
- clientOptions,
- options.tokenProvider
- );
- this.secrets = new RetryRestClient(hookSecretsClient, options.retry);
-};
-
-/**
- * Create a new hook.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(HooksManager, 'create', 'resource.create');
-
-/**
- * Get all hooks.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(HooksManager, 'getAll', 'resource.getAll');
-
-/**
- * Get an Auth0 hook.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(HooksManager, 'get', 'resource.get');
+ update(...args) {
+ return this.resource.patch(...args);
+ }
-/**
- * Update an existing hook.
- *
- * @method 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.
- *
- * @return {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.
- *
- * @method 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.
- *
- * @return {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
- *
- * @method getSecrets
- * @memberOf module:management.HooksManager.prototype
- *
- * @example
- * 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.
- *
- * @return {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
- *
- * @method 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.
- *
- * @return {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
- *
- * @method 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.
- *
- * @return {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
- *
- * @method 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.
- *
- * @return {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 cca9c74c5..f394f536d 100644
--- a/src/management/JobsManager.js
+++ b/src/management/JobsManager.js
@@ -1,389 +1,356 @@
-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
- */
-
-/**
- * @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
*/
-var 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');
- }
-
- var 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
*/
- var 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}
- */
- var 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}'
+ * };
+ *
+ * management.jobs.get(params, function (err, job) {
+ * if (err) {
+ * // Handle error.
+ * }
*
- * @type {external:RestClient}
+ * // 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.
- *
- * @method 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.
- *
- * @return {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) {
- 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;
-
- var 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() };
- headers['Content-Type'] = 'multipart/form-data';
-
- var promise = options.tokenProvider.getAccessToken().then(function(access_token) {
- return axios
- .post(url, form, { headers: { ...headers, Authorization: `Bearer ${access_token}` } })
- .catch(function(err) {
+ _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(async (access_token) => {
+ try {
+ return await axios.post(url, form, {
+ headers: { ...headers, Authorization: `Bearer ${access_token}` },
+ });
+ } catch (err) {
if (!err.response) {
- return Promise.reject(err);
+ throw 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);
- });
- });
+ throw error;
+ }
+ });
+
+ // 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;
-};
+ /**
+ * 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.
- *
- * @method 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.
- *
- * @return {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.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-JobsManager.prototype.importUsersJob = function(data, cb) {
- var 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.
- *
- * @method 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.
- *
- * @return {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
- *
- * @method 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.
- *
- * @return {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.
- *
- * @method 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.
- *
- * @return {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 43cae1f4c..086235463 100644
--- a/src/management/LogStreamsManager.js
+++ b/src/management/LogStreamsManager.js
@@ -1,179 +1,163 @@
-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 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
*/
-var 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}
*/
- var 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}
*/
- var auth0RestClient = new Auth0RestClient(
- options.baseUrl + '/log-streams/:id ',
- clientOptions,
- options.tokenProvider
- );
- this.resource = new RetryRestClient(auth0RestClient, options.retry);
-};
-
-/**
- * Get all Log Streams.
- *
- * @method 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}
- */
-utils.wrapPropertyMethod(LogStreamsManager, 'getAll', 'resource.getAll');
-
-/**
- * Get an Auth0 Log Streams.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(LogStreamsManager, 'get', 'resource.get');
+ get(...args) {
+ return this.resource.get(...args);
+ }
-/**
- * Create an Auth0 Log Stream.
- *
- * @method 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.
- *
- * @return {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.
- *
- * @method 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.
- *
- * @return {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.
- *
- * @method 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.
- *
- * @return {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 85b1e2186..4b61b4d24 100644
--- a/src/management/LogsManager.js
+++ b/src/management/LogsManager.js
@@ -1,116 +1,109 @@
-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 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
*/
-var 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}
*/
- var 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}
*/
- var auth0RestClient = new Auth0RestClient(
- options.baseUrl + '/logs/:id ',
- clientOptions,
- options.tokenProvider
- );
- this.resource = new RetryRestClient(auth0RestClient, options.retry);
-};
-
-/**
- * Get all logs.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(LogsManager, 'getAll', 'resource.getAll');
-
-/**
- * Get an Auth0 log.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(LogsManager, 'get', 'resource.get');
+ get(...args) {
+ return this.resource.get(...args);
+ }
+}
module.exports = LogsManager;
diff --git a/src/management/ManagementTokenProvider.js b/src/management/ManagementTokenProvider.js
index 85081fcad..dbd207872 100644
--- a/src/management/ManagementTokenProvider.js
+++ b/src/management/ManagementTokenProvider.js
@@ -1,143 +1,135 @@
-var ArgumentError = require('rest-facade').ArgumentError;
-var AuthenticationClient = require('../auth');
-var memoizer = require('lru-memoizer');
-var es6Promisify = require('es6-promisify');
-
-var DEFAULT_OPTIONS = { enableCache: true };
+const { ArgumentError } = require('rest-facade');
+const AuthenticationClient = require('../auth');
+const memoizer = require('lru-memoizer');
+const util = require('util');
/**
- * @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.
- *
*/
-var ManagementTokenProvider = function(options) {
- if (!options || typeof options !== 'object') {
- throw new ArgumentError('Options must be an object');
- }
+class ManagementTokenProvider {
+ /**
+ * @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.
+ */
+ constructor(options) {
+ if (!options || typeof options !== 'object') {
+ throw new ArgumentError('Options must be an object');
+ }
- var params = Object.assign({}, DEFAULT_OPTIONS, options);
+ const params = { enableCache: true, ...options };
- if (!params.domain || params.domain.length === 0) {
- throw new ArgumentError('Must provide a domain');
- }
+ if (!params.domain || params.domain.length === 0) {
+ throw new ArgumentError('Must provide a domain');
+ }
- if (!params.clientId || params.clientId.length === 0) {
- throw new ArgumentError('Must provide a clientId');
- }
+ if (!params.clientId || params.clientId.length === 0) {
+ throw new ArgumentError('Must provide a clientId');
+ }
- if (!params.clientSecret || params.clientSecret.length === 0) {
- throw new ArgumentError('Must provide a clientSecret');
- }
+ if (!params.clientSecret || params.clientSecret.length === 0) {
+ throw new ArgumentError('Must provide a clientSecret');
+ }
- if (!params.audience || params.audience.length === 0) {
- throw new ArgumentError('Must provide a audience');
- }
+ if (!params.audience || params.audience.length === 0) {
+ throw new ArgumentError('Must provide a audience');
+ }
- if (typeof params.enableCache !== 'boolean') {
- throw new ArgumentError('enableCache must be a boolean');
- }
+ if (typeof params.enableCache !== 'boolean') {
+ throw new ArgumentError('enableCache must be a boolean');
+ }
+
+ if (params.enableCache && params.cacheTTLInSeconds) {
+ if (typeof params.cacheTTLInSeconds !== 'number') {
+ throw new ArgumentError('cacheTTLInSeconds must be a number');
+ }
- if (params.enableCache && params.cacheTTLInSeconds) {
- if (typeof params.cacheTTLInSeconds !== 'number') {
- throw new ArgumentError('cacheTTLInSeconds must be a number');
+ if (params.cacheTTLInSeconds <= 0) {
+ throw new ArgumentError('cacheTTLInSeconds must be a greater than 0');
+ }
}
- if (params.cacheTTLInSeconds <= 0) {
- throw new ArgumentError('cacheTTLInSeconds must be a greater than 0');
+ if (params.scope && typeof params.scope !== 'string') {
+ throw new ArgumentError('scope must be a string');
}
- }
- if (params.scope && typeof params.scope !== 'string') {
- throw new ArgumentError('scope must be a string');
+ this.options = params;
+ 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,
+ };
+ this.authenticationClient = new AuthenticationClient(authenticationClientOptions);
+
+ const self = this;
+ 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,
+ })
+ );
}
- this.options = params;
- var 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
- };
- this.authenticationClient = new AuthenticationClient(authenticationClientOptions);
-
- var self = this;
- this.getCachedAccessToken = es6Promisify.promisify(
- memoizer({
- load: function(options, callback) {
- self
- .clientCredentialsGrant(options.domain, options.scope, options.audience)
- .then(function(data) {
- callback(null, data);
- })
- .catch(function(err) {
- callback(err);
- });
- },
- hash: function(options) {
- return options.domain + '-' + options.clientId + '-' + options.scope;
- },
- itemMaxAge: function(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
- })
- );
-};
-
-/**
- * Returns the access_token.
- *
- * @method getAccessToken
- * @memberOf module:management.ManagementTokenProvider.prototype
- *
- * @return {Promise} Promise returning an access_token.
- */
-ManagementTokenProvider.prototype.getAccessToken = function() {
- if (this.options.enableCache) {
- return this.getCachedAccessToken(this.options).then(function(data) {
+ /**
+ * Returns the access_token.
+ *
+ * @returns {Promise} Promise returning an access_token.
+ */
+ async getAccessToken() {
+ if (this.options.enableCache) {
+ const data = await this.getCachedAccessToken(this.options);
return data.access_token;
- });
- } else {
- return this.clientCredentialsGrant(
- this.options.domain,
- this.options.scope,
- this.options.audience
- ).then(function(data) {
+ } else {
+ const data = await this.clientCredentialsGrant(
+ this.options.domain,
+ this.options.scope,
+ this.options.audience
+ );
return data.access_token;
+ }
+ }
+
+ clientCredentialsGrant(domain, scope, audience) {
+ return this.authenticationClient.clientCredentialsGrant({
+ audience,
+ scope,
});
}
-};
-
-ManagementTokenProvider.prototype.clientCredentialsGrant = function(domain, scope, audience) {
- return this.authenticationClient.clientCredentialsGrant({
- audience: audience,
- scope: scope
- });
-};
+}
module.exports = ManagementTokenProvider;
diff --git a/src/management/MigrationsManager.js b/src/management/MigrationsManager.js
index b051deecb..fb9b94330 100644
--- a/src/management/MigrationsManager.js
+++ b/src/management/MigrationsManager.js
@@ -1,108 +1,99 @@
-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
*/
-var 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');
+ }
- 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 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}
*/
- var 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.
- *
- * @method 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.
- *
- * @return {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.
- *
- * @method getMigrations
- * @memberOf module:management.MigrationsManager.prototype
- *
- * @example
- * management.migrations.getMigrations(function (err, migrations) {
- * if (err) {
- * // Handle error.
- * }
- *
- * console.log(migrations.flags);
- * });
- *
- * @param {Function} [cb] Callback function.
- *
- * @return {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 c54184eda..e282585e7 100644
--- a/src/management/OrganizationsManager.js
+++ b/src/management/OrganizationsManager.js
@@ -1,870 +1,777 @@
-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
- */
-
-/**
- * @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
*/
-var 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}
*/
- var 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}
*/
- var 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',
- clientOptions,
- options.tokenProvider
- );
- this.connections = new RetryRestClient(connectionsInRoleClient, options.retry);
-
- var 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',
- clientOptions,
- options.tokenProvider
- );
- this.invitations = new RetryRestClient(invitationClient, options.retry);
-
- var 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',
- clientOptions,
- options.tokenProvider
- );
- this.organizationsByName = new RetryRestClient(organizationByNameClient, options.retry);
-};
-
-/**
- * Create a new organization.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(OrganizationsManager, 'create', 'organizations.create');
-
-/**
- * Get all organizations.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(OrganizationsManager, 'getAll', 'organizations.getAll');
-
-/**
- * Get an Auth0 organization.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(OrganizationsManager, 'getByID', 'organizations.get');
-
-/**
- * Get an Auth0 organization.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(OrganizationsManager, 'getByName', 'organizationsByName.get');
-
-/**
- * Update an existing organization.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(OrganizationsManager, 'update', 'organizations.patch');
-
-/**
- * Delete an existing organization.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(OrganizationsManager, 'delete', 'organizations.delete');
-
-/**
- **** Organization Connections
- */
-
-/**
- * Get Enabled Connections in a Organization
- *
- * @method getEnabledConnections
- * @memberOf module:management.OrganizationsManager.prototype
- *
- * @example
- * 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.
- *
- * @return {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
- *
- * @method getEnabledConnection
- * @memberOf module:management.OrganizationsManager.prototype
- *
- * @example
- * var params = {id : 'ORGANIZATION_ID', connection_id: 'CONNECTION_ID'}
- * @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.
- *
- * @return {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
- *
- * @method 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.
- *
- * @return {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
- *
- * @method 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.
- *
- * @return {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
- *
- * @method 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.
- *
- * @return {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
- *
- * @method getMembers
- * @memberOf module:management.OrganizationsManager.prototype
- *
- * @example
- * var params = {id : 'ORGANIZATION_ID'}
- * @example
- * 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.
- *
- * @return {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
- *
- * @method 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.
- *
- * @return {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
- *
- * @method 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.
- *
- * @return {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
- *
- * @method 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 {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}
- */
-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
- *
- * @method getInvitation
- * @memberOf module:management.OrganizationsManager.prototype
- *
- * @example
- * var params = {id : 'ORGANIZATION_ID', invitation_id: 'INVITATION_ID'}
- * @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.
- *
- * @return {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
- *
- * @method 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.
- *
- * @return {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
- *
- * @method 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.
- *
- * @return {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
- *
- * @method getMemberRoles
- * @memberOf module:management.OrganizationsManager.prototype
- *
- * @example
- * var params = {id : 'ORGANIZATION_ID', user_id: 'user_id'}
- * @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.
- *
- * @return {Promise|undefined}
- */
-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
- *
- * @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.
- *
- * @return {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
- *
- * @method 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.
- *
- * @return {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 8065002f6..31ebaf7b1 100644
--- a/src/management/PromptsManager.js
+++ b/src/management/PromptsManager.js
@@ -1,214 +1,192 @@
-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
- */
-
-/**
- * @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
*/
-var 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);
}
- var 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}
*/
- var 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}
*/
- var customTextByLanguageAuth0RestClient = new Auth0RestClient(
- options.baseUrl + '/prompts/:prompt/custom-text/:language',
- clientOptions,
- options.tokenProvider
- );
- this.customTextByLanguage = new RetryRestClient(
- customTextByLanguageAuth0RestClient,
- options.retry
- );
-};
-
-/**
- * Update the prompts settings.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(PromptsManager, 'updateSettings', 'resource.patch');
+ getCustomTextByLanguage(params, cb) {
+ params = params || {};
-/**
- * Get the prompts settings..
- *
- * @method 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.
- *
- * @return {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.
- *
- * @method 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
- *
- * @return {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.
- *
- * @method 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
- *
- * @return {Promise|undefined}
- */
-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');
+ }
- 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,
+ };
- options.prompt = params.prompt;
- options.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 480423aed..219eb385e 100644
--- a/src/management/ResourceServersManager.js
+++ b/src/management/ResourceServersManager.js
@@ -1,10 +1,8 @@
-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 ResourceServersManager
* Auth0 Resource Servers Manager.
*
* {@link https://auth0.com/docs/api/management/v2#!/Resource_Servers Resource Servers} represents
@@ -12,176 +10,161 @@ 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 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');
+ }
-var 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}
*/
- var 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.
+ *
+ * @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.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}
*/
- var auth0RestClient = new Auth0RestClient(
- options.baseUrl + '/resource-servers/:id',
- clientOptions,
- options.tokenProvider
- );
- this.resource = new RetryRestClient(auth0RestClient, options.retry);
-};
-
-/**
- * Create an API (Resource Server).
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ResourceServersManager, 'create', 'resource.create');
-
-/**
- * Get all resource servers.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ResourceServersManager, 'getAll', 'resource.getAll');
+ getAll(...args) {
+ return this.resource.getAll(...args);
+ }
-/**
- * Get a Resource Server.
- *
- * @method 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.
- *
- * @return {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.
- *
- * @method 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.
- *
- * @return {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.
- *
- * @method 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.
- *
- * @return {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 2f49ae865..36424f384 100644
--- a/src/management/RolesManager.js
+++ b/src/management/RolesManager.js
@@ -1,411 +1,365 @@
-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
- */
-
-/**
- * @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
*/
-var 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}
*/
- var 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}
*/
- var 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',
- clientOptions,
- options.tokenProvider
- );
- this.permissions = new RetryRestClient(permissionsInRoleClient, options.retry);
-
- var 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.
- *
- * @method 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.
- *
- * @return {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.
- *
- * @method 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.
- *
- * @return {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.
- *
- * @method 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.
- *
- * @return {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.
- *
- * @method 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.
- *
- * @return {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.
- *
- * @method 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.
- *
- * @return {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
- *
- * @method getPermissionsInRole
- * @memberOf module:management.RolesManager.prototype
- *
- * @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.
- *
- * @return {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
- *
- * @method 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.
- *
- * @return {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
- *
- * @method 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.
- *
- * @return {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,
+ * 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
- *
- * @method getUsers
- * @memberOf module:management.RolesManager.prototype
- *
- * @example
- * var params = {
- * roleId: '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.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.
- *
- * @return {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
- *
- * @method 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.
- *
- * @return {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 d48ef71b3..eb0585a95 100644
--- a/src/management/RulesConfigsManager.js
+++ b/src/management/RulesConfigsManager.js
@@ -1,129 +1,113 @@
-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
- */
-
-/**
- * @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
*/
-var 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}
*/
- var 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}
*/
- var auth0RestClient = new Auth0RestClient(
- options.baseUrl + '/rules-configs/:key',
- clientOptions,
- options.tokenProvider
- );
- this.resource = new RetryRestClient(auth0RestClient, options.retry);
-};
-
-/**
- * Set a new rules config.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(RulesConfigsManager, 'set', 'resource.update');
-
-/**
- * Get all rules configs.
- *
- * @method 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}
- */
-utils.wrapPropertyMethod(RulesConfigsManager, 'getAll', 'resource.getAll');
+ getAll(...args) {
+ return this.resource.getAll(...args);
+ }
-/**
- * Delete an existing rules config.
- *
- * @method 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.
- *
- * @return {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 61d578dfa..cfe43574d 100644
--- a/src/management/RulesManager.js
+++ b/src/management/RulesManager.js
@@ -1,197 +1,175 @@
-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
- */
-
-/**
- * @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
*/
-var 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}
*/
- var 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}
*/
- var auth0RestClient = new Auth0RestClient(
- options.baseUrl + '/rules/:id',
- clientOptions,
- options.tokenProvider
- );
- this.resource = new RetryRestClient(auth0RestClient, options.retry);
-};
-
-/**
- * Create a new rule.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(RulesManager, 'create', 'resource.create');
-
-/**
- * Get all rules.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(RulesManager, 'getAll', 'resource.getAll');
+ getAll(...args) {
+ return this.resource.getAll(...args);
+ }
-/**
- * Get an Auth0 rule.
- *
- * @method 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.
- *
- * @return {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.
- *
- * @method 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.
- *
- * @return {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.
- *
- * @method 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.
- *
- * @return {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 2254a83be..3dcd84359 100644
--- a/src/management/StatsManager.js
+++ b/src/management/StatsManager.js
@@ -1,123 +1,107 @@
-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 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
*/
-var 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');
+ }
- 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}/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}
*/
- var 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.
- *
- * @method 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.
- *
- * @return {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.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-StatsManager.prototype.getActiveUsersCount = function(cb) {
- var 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 e8d081633..ecbd87a7d 100644
--- a/src/management/TenantManager.js
+++ b/src/management/TenantManager.js
@@ -1,115 +1,99 @@
-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}
+ * @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..
+ *
+ * @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..3058fcdb6 100644
--- a/src/management/UserBlocksManager.js
+++ b/src/management/UserBlocksManager.js
@@ -1,178 +1,151 @@
-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.
+ *
+ * @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');
+ /**
+ * Unblock an user by its id.
+ *
+ * @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.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');
- }
-
- 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.
+ *
+ * @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.
+ *
+ * @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..20df90f0e 100644
--- a/src/management/UsersManager.js
+++ b/src/management/UsersManager.js
@@ -1,960 +1,837 @@
-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
+ * 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
+ * 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 };
*
- * @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 {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}
+ */
- 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
+ * 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..1d80c2355 100644
--- a/src/management/index.js
+++ b/src/management/index.js
@@ -1,55 +1,49 @@
-/** @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, 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
* 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.
- * @constructor
- * @memberOf module:management
*
* @example
* Initialize your client class with an API v2 token (you can generate one
@@ -61,8 +55,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,3818 +72,3295 @@ var 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.
- *
*/
-var 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);
- var baseUrl = util.format(BASE_URL_FORMAT, options.domain);
- var userAgent = options.userAgent || 'node.js/' + process.version.replace('v', '');
+ const defaultHeaders = {
+ 'User-Agent': `node.js/${process.version.replace('v', '')}`,
+ 'Content-Type': 'application/json',
+ };
- var defaultHeaders = {
- 'User-Agent': 'node.js/' + process.version.replace('v', ''),
- 'Content-Type': 'application/json'
- };
+ const managerOptions = {
+ headers: Object.assign(defaultHeaders, options.headers || {}),
+ baseUrl,
+ };
- var managerOptions = {
- headers: Object.assign(defaultHeaders, options.headers || {}),
- baseUrl: baseUrl
- };
+ if (options.token === undefined) {
+ const config = Object.assign(
+ { audience: util.format(MANAGEMENT_API_AUD_FORMAT, options.domain) },
+ options
+ );
- if (options.token === undefined) {
- var 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;
+ }
- 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}`;
}
- 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: function() {
- return Promise.resolve(options.token);
+ 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;
}
- };
- 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);
+ }
+
+ /**
+ * 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.tokenProvider = this.tokenProvider;
+ /**
+ * 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}
+ */
- if (options.telemetry !== false) {
- var clientInfo = options.clientInfo || generateClientInfo();
- if ('string' === typeof clientInfo.name && clientInfo.name.length > 0) {
- var telemetry = jsonToBase64(clientInfo);
- managerOptions.headers['Auth0-Client'] = telemetry;
- }
+ createConnection(...args) {
+ return this.connections.create(...args);
}
- managerOptions.retry = options.retry;
+ /**
+ * Get an Auth0 connection.
+ *
+ * @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}
+ */
+ getConnection(...args) {
+ return this.connections.get(...args);
+ }
/**
- * Simple abstraction for performing CRUD operations on the
- * clients endpoint.
+ * Delete an existing connection.
*
- * @type {ClientsManager}
+ * @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}
*/
- this.clients = new ClientsManager(managerOptions);
+ deleteConnection(...args) {
+ return this.connections.delete(...args);
+ }
/**
- * Simple abstraction for performing CRUD operations on the client grants
- * endpoint.
+ * Update an existing connection.
+ *
+ * @example
+ * var data = { name: 'newConnectionName' };
+ * var params = { id: CONNECTION_ID };
+ *
+ * management.updateConnection(params, data, function (err, connection) {
+ * if (err) {
+ * // Handle error.
+ * }
*
- * @type {ClientGrantsManager}
+ * 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.clientGrants = new ClientGrantsManager(managerOptions);
+ updateConnection(...args) {
+ return this.connections.update(...args);
+ }
/**
- * Simple abstraction for performing CRUD operations on the grants
- * 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.
+ *
*
- * @type {GrantsManager}
+ * // 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.grants = new GrantsManager(managerOptions);
+ getClients(...args) {
+ return this.clients.getAll(...args);
+ }
/**
- * Simple abstraction for performing CRUD operations on the
- * users endpoint.
+ * Get an Auth0 client.
*
- * @type {UsersManager}
+ * @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}
*/
- this.users = new UsersManager(managerOptions);
+ getClient(...args) {
+ return this.clients.get(...args);
+ }
/**
- * Simple abstraction for performing CRUD operations on the
- * user-blocks endpoint.
+ * Create an Auth0 client.
*
- * @type {UserBlocksManager}
+ * @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}
*/
- this.userBlocks = new UserBlocksManager(managerOptions);
+ createClient(...args) {
+ return this.clients.create(...args);
+ }
/**
- * Simple abstraction for performing CRUD operations on the
- * guardian endpoint.
+ * Update an Auth0 client.
*
- * @type {GuardianManager}
+ * @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}
*/
- this.guardian = new GuardianManager(managerOptions);
+ updateClient(...args) {
+ return this.clients.update(...args);
+ }
/**
- * Simple abstraction for performing CRUD operations on the
- * custom domains endpoint.
+ * Delete an Auth0 client.
+ *
+ * @example
+ * management.deleteClient({ client_id: CLIENT_ID }, function (err) {
+ * if (err) {
+ * // Handle error.
+ * }
*
- * @type {CustomDomainsManager}
+ * // Client deleted.
+ * });
+ * @param {object} params Client parameters.
+ * @param {string} params.client_id Application client ID.
+ * @param {Function} [cb] Callback function.
+ * @returns {Promise|undefined}
*/
- this.customDomains = new CustomDomainsManager(managerOptions);
+ deleteClient(...args) {
+ return this.clients.delete(...args);
+ }
/**
- * Simple abstraction for performing CRUD operations on the
- * connections 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.
+ *
*
- * @type {ConnectionsManager}
+ * // 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.connections = new ConnectionsManager(managerOptions);
+ getClientGrants(...args) {
+ return this.clientGrants.getAll(...args);
+ }
/**
- * Simple abstraction for performing CRUD operations on the
- * device credentials endpoint.
+ * Create an Auth0 client grant.
*
- * @type {DeviceCredentialsManager}
+ * @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}
*/
- this.deviceCredentials = new DeviceCredentialsManager(managerOptions);
+ createClientGrant(...args) {
+ return this.clientGrants.create(...args);
+ }
/**
- * Simple abstraction for performing CRUD operations on the
- * rules endpoint.
+ * 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.
+ * }
*
- * @type {RulesManager}
+ * 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.rules = new RulesManager(managerOptions);
+ updateClientGrant(...args) {
+ return this.clientGrants.update(...args);
+ }
/**
- * Simple abstraction for performing CRUD operations on the
- * blacklisted tokens endpoint.
+ * Delete an Auth0 client grant.
+ *
+ * @example
+ * management.clientGrants.delete({ id: GRANT_ID }, function (err) {
+ * if (err) {
+ * // Handle error.
+ * }
*
- * @type {BlacklistedtokensManager}
+ * // Grant deleted.
+ * });
+ * @param {object} params Client parameters.
+ * @param {string} params.id Client grant ID.
+ * @param {Function} [cb] Callback function.
+ * @returns {Promise|undefined}
*/
- this.blacklistedTokens = new BlacklistedTokensManager(managerOptions);
+ deleteClientGrant(...args) {
+ return this.clientGrants.delete(...args);
+ }
/**
- * Simple abstraction for performing CRUD operations on the
- * email provider endpoint.
+ * 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 {EmailProviderManager}
+ * 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.emailProvider = new EmailProviderManager(managerOptions);
+ getGrants(...args) {
+ return this.grants.getAll(...args);
+ }
/**
- * ManagementClient account statistics manager.
+ * Delete an Auth0 grant.
+ *
+ * @example
+ * var params = {
+ * id: GRANT_ID,
+ * user_id: USER_ID
+ * };
*
- * @type {StatsManager}
+ * 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.stats = new StatsManager(managerOptions);
+ deleteGrant(...args) {
+ return this.grants.delete(...args);
+ }
/**
- * ManagementClient tenant settings manager.
+ * Create an Auth0 credential.
*
- * @type {TenantManager}
+ * @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}
*/
- this.tenant = new TenantManager(managerOptions);
+ createDevicePublicKey(...args) {
+ return this.deviceCredentials.createPublicKey(...args);
+ }
/**
- * Jobs manager.
+ * Get all Auth0 credentials.
*
- * @type {JobsManager}
+ * @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}
*/
- this.jobs = new JobsManager(managerOptions);
+ getDeviceCredentials(...args) {
+ return this.deviceCredentials.getAll(...args);
+ }
/**
- * Tickets manager.
+ * Delete an Auth0 device credential.
*
- * @type {TicketsManager}
+ * @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}
*/
- this.tickets = new TicketsManager(managerOptions);
+ deleteDeviceCredential(...args) {
+ return this.deviceCredentials.delete(...args);
+ }
/**
- * Logs 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.
+ *
*
- * @type {LogsManager}
+ * // 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}
*/
- this.logs = new LogsManager(managerOptions);
+ getRules(...args) {
+ return this.rules.getAll(...args);
+ }
/**
- * Log Streams manager.
+ * Create a new rule.
*
- * @type {LogStreamsManager}
+ * @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}
*/
- this.logStreams = new LogStreamsManager(managerOptions);
+ createRule(...args) {
+ return this.rules.create(...args);
+ }
/**
- * Simple abstraction for performing CRUD operations on the
- * resource servers endpoint.
+ * Get an Auth0 rule.
*
- * @type {ResourceServersManager}
+ * @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}
*/
- this.resourceServers = new ResourceServersManager(managerOptions);
+ getRule(...args) {
+ return this.rules.get(...args);
+ }
/**
- * Simple abstraction for performing CRUD operations on
- * Auth0's Email Templates
+ * Delete an existing rule.
*
- * @type {EmailTemplatesManager}
+ * @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}
*/
- this.emailTemplates = new EmailTemplatesManager(managerOptions);
+ deleteRule(...args) {
+ return this.rules.delete(...args);
+ }
/**
- * RulesConfigs manager.
+ * Update an existing rule.
*
- * @type {RulesConfigsManager}
+ * @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}
*/
- this.rulesConfigs = new RulesConfigsManager(managerOptions);
+ updateRule(...args) {
+ return this.rules.update(...args);
+ }
/**
- * Simple abstraction for performing CRUD operations on the
- * roles 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.
+ *
+ *
+ * // Pagination settings.
+ * var params = {
+ * search_engine: 'v3',
+ * q: 'name:*jane*',
+ * per_page: 10,
+ * page: 0
+ * };
*
- * @type {RolesManager}
+ * 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.roles = new RolesManager(managerOptions);
+ getUsers(...args) {
+ return this.users.getAll(...args);
+ }
/**
- * Simple abstraction for performing CRUD operations on the
- * hooks endpoint.
+ * Get users for a given email address
+ *
+ * @example
+ * This method takes an email address as the first argument,
+ * and returns all users with that email address
+ *
*
- * @type {HooksManager}
+ * 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.hooks = new HooksManager(managerOptions);
+ getUsersByEmail(...args) {
+ return this.users.getByEmail(...args);
+ }
/**
- * Simple abstraction for performing CRUD operations on the
- * branding endpoint.
+ * Get a user by its id.
*
- * @type {HooksManager}
+ * @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.branding = new BrandingManager(managerOptions);
+ getUser(...args) {
+ return this.users.get(...args);
+ }
/**
- * ManagementClient migrations manager.
+ * Delete all users.
*
- * @type {MigrationsManager}
+ * @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.
*/
- this.migrations = new MigrationsManager(managerOptions);
+ deleteAllUsers(...args) {
+ return this.users.deleteAll(...args);
+ }
/**
- * Prompts Manager
+ * Delete a user by its id.
*
- * @type {PromptsManager}
+ * @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}
*/
- this.prompts = new PromptsManager(managerOptions);
+ deleteUser(...args) {
+ return this.users.delete(...args);
+ }
/**
- * Simple abstraction for performing CRUD operations on the
- * actions endpoint.
+ * Create a new user.
*
- * @type {ActionsManager}
+ * @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}
*/
- this.actions = new ActionsManager(managerOptions);
+ createUser(...args) {
+ return this.users.create(...args);
+ }
/**
- * Organizations Manager
+ * Update a user by its id.
+ *
+ * @example
+ * var params = { id: USER_ID };
+ *
+ * management.updateUser(params, data, function (err, user) {
+ * if (err) {
+ * // Handle error.
+ * }
*
- * @type {OrganizationsManager}
+ * // 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}
*/
- this.organizations = new OrganizationsManager(managerOptions);
-};
+ updateUser(...args) {
+ return this.users.update(...args);
+ }
-/**
- * Get all connections.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'getConnections', 'connections.getAll');
+ /**
+ * 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);
+ }
-/**
- * Create a new connection.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'createConnection', 'connections.create');
+ /**
+ * 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);
+ }
-/**
- * Get an Auth0 connection.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'getConnection', 'connections.get');
+ /**
+ * 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);
+ }
-/**
- * Delete an existing connection.
- *
- * @method 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.
- *
- * @return {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.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);
+ }
-/**
- * Update an existing connection.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'updateConnection', 'connections.update');
+ /**
+ * 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 all Auth0 clients.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'getClients', 'clients.getAll');
+ /**
+ * 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);
+ }
-/**
- * Get an Auth0 client.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'getClient', 'clients.get');
+ /**
+ * 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);
+ }
-/**
- * Create an Auth0 client.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'createClient', 'clients.create');
+ /**
+ * 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);
+ }
-/**
- * Update an Auth0 client.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'updateClient', 'clients.update');
+ /**
+ * 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);
+ }
-/**
- * Delete an Auth0 client.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'deleteClient', 'clients.delete');
+ /**
+ * 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);
+ }
-/**
- * Get all Auth0 Client Grants.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'getClientGrants', 'clientGrants.getAll');
+ /**
+ * 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);
+ }
-/**
- * Create an Auth0 client grant.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'createClientGrant', 'clientGrants.create');
+ /**
+ * 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);
+ }
-/**
- * Update an Auth0 client grant.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'updateClientGrant', 'clientGrants.update');
+ /**
+ * 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);
+ }
-/**
- * Delete an Auth0 client grant.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'deleteClientGrant', 'clientGrants.delete');
+ /**
+ * 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);
+ }
-/**
- * Get all Auth0 Grants.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'getGrants', 'grants.getAll');
+ /**
+ * 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);
+ }
-/**
- * Delete an Auth0 grant.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'deleteGrant', 'grants.delete');
+ /**
+ * 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);
+ }
-/**
- * Create an Auth0 credential.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(
- ManagementClient,
- 'createDevicePublicKey',
- 'deviceCredentials.createPublicKey'
-);
+ /**
+ * 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);
+ }
-/**
- * Get all Auth0 credentials.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'getDeviceCredentials', 'deviceCredentials.getAll');
+ /**
+ * 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);
+ }
-/**
- * Delete an Auth0 device credential.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'deleteDeviceCredential', 'deviceCredentials.delete');
+ /**
+ * 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);
+ }
-/**
- * Get all rules.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'getRules', 'rules.getAll');
+ /**
+ * 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);
+ }
-/**
- * Create a new rule.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'createRule', 'rules.create');
+ /**
+ * 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);
+ }
-/**
- * Get an Auth0 rule.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'getRule', 'rules.get');
+ /**
+ * 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);
+ }
-/**
- * Delete an existing rule.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'deleteRule', 'rules.delete');
+ /**
+ * 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);
+ }
-/**
- * Update an existing rule.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'updateRule', 'rules.update');
+ /**
+ * 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 all users.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'getUsers', 'users.getAll');
+ /**
+ * 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 users for a given email address
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'getUsersByEmail', 'users.getByEmail');
+ /**
+ * 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);
+ }
-/**
- * Get a user by its id.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'getUser', 'users.get');
+ /**
+ * 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 all users.
- *
- * @method deleteAllUsers
- * @memberOf module:management.ManagementClient.prototype
- *
- * @example
- * management.deleteAllUsers(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.
- */
-utils.wrapPropertyMethod(ManagementClient, 'deleteAllUsers', 'users.deleteAll');
+ /**
+ * 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);
+ }
-/**
- * Delete a user by its id.
- *
- * @method 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
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'deleteUser', 'users.delete');
+ /**
+ * 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);
+ }
-/**
- * Create a new user.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'createUser', 'users.create');
-
-/**
- * Update a user by its id.
- *
- * @method 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
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'updateUser', 'users.update');
-
-/**
- * Update the user metadata for a user.
- *
- * @method 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
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'updateUserMetadata', 'users.updateUserMetadata');
-
-/**
- * Update the app metadata for a user.
- *
- * @method 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
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'updateAppMetadata', 'users.updateAppMetadata');
-
-/**
- * Delete a multifactor provider for a user.
- *
- * @method 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
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(
- ManagementClient,
- 'deleteUserMultifactor',
- 'users.deleteMultifactorProvider'
-);
-
-/**
- * Delete a multifactor provider for a user.
- *
- * @method 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
- *
- * @return {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'
-);
-
-/**
- * Unlink the given accounts.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'unlinkUsers', 'users.unlink');
-
-/**
- * Link the user with another account.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'linkUsers', 'users.link');
-
-/**
- * Get user's log events.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'getUserLogs', 'users.logs');
-
-/**
- * Get user's roles
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'getUserRoles', 'users.getRoles');
-
-/**
- * Assign roles to a user
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'assignRolestoUser', 'users.assignRoles');
-
-/**
- * Assign users to a role
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'assignUsersToRole', 'roles.assignUsers');
-
-/**
- * Remove roles from a user
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'removeRolesFromUser', 'users.removeRoles');
-
-/**
- * Get user's permissions
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'getUserPermissions', 'users.getPermissions');
-
-/**
- * Assign permissions to a user
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'assignPermissionsToUser', 'users.assignPermissions');
-
-/**
- * Remove permissions from a user
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'removePermissionsFromUser', 'users.removePermissions');
-
-/**
- * Get a list of a user's Guardian enrollments.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(
- ManagementClient,
- 'getGuardianEnrollments',
- 'users.getGuardianEnrollments'
-);
-
-/**
- * Generate new Guardian recovery code.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(
- ManagementClient,
- 'regenerateRecoveryCode',
- 'users.regenerateRecoveryCode'
-);
-
-/**
- * Invalidate all remembered browsers for MFA.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(
- ManagementClient,
- 'invalidateRememberBrowser',
- 'users.invalidateRememberBrowser'
-);
-
-/**
- * Get user blocks by its id.
- *
- * @method 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
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'getUserBlocks', 'userBlocks.get');
-
-/**
- * Unblock an user by its id.
- *
- * @method 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
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'unblockUser', 'userBlocks.delete');
-
-/**
- * Get user blocks by its identifier.
- *
- * @method 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
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(
- ManagementClient,
- 'getUserBlocksByIdentifier',
- 'userBlocks.getByIdentifier'
-);
-
-/**
- * Unblock an user by its id.
- *
- * @method 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
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(
- ManagementClient,
- 'unblockUserByIdentifier',
- 'userBlocks.deleteByIdentifier'
-);
-
-/**
- * Get a single Guardian enrollment.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(
- ManagementClient,
- 'getGuardianEnrollment',
- 'guardian.getGuardianEnrollment'
-);
-
-/**
- * Delete a user's Guardian enrollment.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(
- ManagementClient,
- 'deleteGuardianEnrollment',
- 'guardian.deleteGuardianEnrollment'
-);
-
-/**
- * Get all blacklisted tokens.
- *
- * @method getBlacklistedTokens
- * @memberOf module:management.ManagementClient.prototype
- *
- * @example
- * management.getBlacklistedTokens(function (err, tokens) {
- * console.log(tokens.length);
- * });
- *
- * @param {Function} [cb] Callback function.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'getBlacklistedTokens', 'blacklistedTokens.getAll');
-
-/**
- * Blacklist a new token.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'blacklistToken', 'blacklistedTokens.add');
-
-/**
- * Create a new Email Template.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'createEmailTemplate', 'emailTemplates.create');
-
-/**
- * Get an Auth0 Email Template.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'getEmailTemplate', 'emailTemplates.get');
-
-/**
- * Update an existing Email Template.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'updateEmailTemplate', 'emailTemplates.update');
-
-/**
- * Get the email provider.
- *
- * @method 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}
- */
-utils.wrapPropertyMethod(ManagementClient, 'getEmailProvider', 'emailProvider.get');
-
-/**
- * Configure the email provider.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'configureEmailProvider', 'emailProvider.configure');
-
-/**
- * Delete email provider.
- *
- * @method deleteEmailProvider
- * @memberOf module:management.ManagementClient.prototype
- *
- * @example
- * management.deleteEmailProvider(function (err) {
- * if (err) {
- * // Handle error.
- * }
- *
- * // Email provider deleted.
- * });
- *
- * @param {Function} [cb] Callback function.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'deleteEmailProvider', 'emailProvider.delete');
-
-/**
- * Update the email provider.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'updateEmailProvider', 'emailProvider.update');
-
-/**
- * Get a the active users count.
- *
- * @method getActiveUsersCount
- * @memberOf module:management.ManagementClient.prototype
- *
- * @example
- * management.getActiveUsersCount(function (err, usersCount) {
- * if (err) {
- * // Handle error.
- * }
- *
- * console.log(usersCount);
- * });
- *
- * @param {Function} [cb] Callback function.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'getActiveUsersCount', 'stats.getActiveUsersCount');
-
-/**
- * Get the daily stats.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'getDailyStats', 'stats.getDaily');
-
-/**
- * Get the tenant settings..
- *
- * @method getTenantSettings
- * @memberOf module:management.ManagementClient.prototype
- *
- * @example
- * management.getSettings(function (err, settings) {
- * if (err) {
- * // Handle error.
- * }
- *
- * console.log(settings);
- * });
- *
- * @param {Function} [cb] Callback function.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'getTenantSettings', 'tenant.getSettings');
-
-/**
- * Update the tenant settings.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'updateTenantSettings', 'tenant.updateSettings');
-
-/**
- * Get a job by its ID.
- *
- * @method 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.
- *
- * @return {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.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'importUsers', 'jobs.importUsers');
+ /**
+ * 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);
+ }
-/**
- * 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.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'importUsersJob', 'jobs.importUsersJob');
+ /**
+ * 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);
+ }
-/**
- * Export all users to a file using a long running job.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'exportUsers', 'jobs.exportUsers');
+ /**
+ * 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);
+ }
-/**
- * Given a job ID, retrieve the failed/errored items
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'getJobErrors', 'jobs.errors');
+ /**
+ * 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);
+ }
-/**
- * Send a verification email to a user.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'sendEmailVerification', 'jobs.verifyEmail');
+ /**
+ * 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);
+ }
-/**
- * Create a new password change ticket.
- *
- * @method 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.
- * @return {Promise}
- */
-utils.wrapPropertyMethod(ManagementClient, 'createPasswordChangeTicket', 'tickets.changePassword');
+ /**
+ * 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);
+ }
-/**
- * Create an email verification ticket.
- *
- * @method 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.
- * @return {Promise}
- */
-utils.wrapPropertyMethod(ManagementClient, 'createEmailVerificationTicket', 'tickets.verifyEmail');
+ /**
+ * 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 an Auth0 log.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'getLog', 'logs.get');
+ /**
+ * 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 all logs.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'getLogs', 'logs.getAll');
+ /**
+ * 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);
+ }
-/**
- * Get all Log Streams.
- *
- * @method getLogStreams
- * @memberOf module:management.ManagementClient.prototype
- *
- *
- *
- * management.getLogStreams( function (err, logStreams) {
- * console.log(logStreams.length);
- * });
- *
- * @param {Function} [cb] Callback function.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'getLogStreams', 'logStreams.getAll');
+ /**
+ * 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);
+ }
-/**
- * Create a new Log Stream.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'createLogStream', 'logStreams.create');
+ /**
+ * 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 an Auth0 Log Stream.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'getLogStream', 'logStreams.get');
+ /**
+ * 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);
+ }
-/**
- * Delete an existing Log Stream.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'deleteLogStream', 'logStreams.delete');
+ /**
+ * 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);
+ }
-/**
- * Update an existing Log Stream.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'updateLogStream', 'logStreams.update');
+ /**
+ * 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);
+ }
-/**
- * Create a new resource server.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'createResourceServer', 'resourceServers.create');
+ /**
+ * 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);
+ }
-/**
- * Get all resource servers.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'getResourceServers', 'resourceServers.getAll');
+ /**
+ * 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);
+ }
-/**
- * Get a Resource Server.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'getResourceServer', 'resourceServers.get');
+ /**
+ * 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);
+ }
-/**
- * Delete an existing resource server.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'deleteResourceServer', 'resourceServers.delete');
+ /**
+ * 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);
+ }
-/**
- * Update an existing resource server.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'updateResourceServer', 'resourceServers.update');
+ /**
+ * 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);
+ }
-/**
- * Set a new rules config.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'setRulesConfig', 'rulesConfigs.set');
+ /**
+ * 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);
+ }
-/**
- * Get rules config.
- *
- * @method getRulesConfigs
- * @memberOf module:management.ManagementClient.prototype
- * @param {Function} [cb] Callback function.
- *
- * @example
- *
- * management.getRulesConfigs(function (err, rulesConfigs) {
- * if (err) {
- * // Handle error.
- * }
- *
- * // Get Rules Configs.
- * });
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'getRulesConfigs', 'rulesConfigs.getAll');
+ /**
+ * 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);
+ }
-/**
- * Delete rules config.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'deleteRulesConfig', 'rulesConfigs.delete');
+ /**
+ * 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);
+ }
-/**
- * Create an Auth0 Custom Domain.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'createCustomDomain', 'customDomains.create');
+ /**
+ * 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 all Auth0 CustomDomains.
- *
- * @method getCustomDomains
- * @memberOf module:management.ManagementClient.prototype
- *
- * @example
- * management.getCustomDomains(function (err, customDomains) {
- * console.log(customDomains.length);
- * });
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'getCustomDomains', 'customDomains.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);
+ }
-/**
- * Get a Custom Domain.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'getCustomDomain', 'customDomains.get');
+ /**
+ * 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);
+ }
-/**
- * Verify a Custom Domain.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'verifyCustomDomain', 'customDomains.verify');
+ /**
+ * 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);
+ }
-/**
- * Delete a Custom Domain.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'deleteCustomDomain', 'customDomains.delete');
+ /**
+ * 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);
+ }
-/**
- * Create a Guardian enrollment ticket.
- *
- * @method createGuardianEnrollmentTicket
- * @memberOf module:management.ManagementClient.prototype
- *
- * @example
- * management.createGuardianEnrollmentTicket(function (err, ticket) {
- * console.log(ticket);
- * });
- *
- * @param {Function} [cb] Callback function.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(
- ManagementClient,
- 'createGuardianEnrollmentTicket',
- 'guardian.createEnrollmentTicket'
-);
+ /**
+ * 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);
+ }
-/**
- * Get a list of Guardian factors and statuses.
- *
- * @method getGuardianFactors
- * @memberOf module:management.ManagementClient.prototype
- *
- * @example
- * management.getGuardianFactors(function (err, factors) {
- * console.log(factors.length);
- * });
- *
- * @param {Function} [cb] Callback function.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'getGuardianFactors', 'guardian.getFactors');
+ /**
+ * 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);
+ }
-/**
- * Get the settings of a Guardian factor.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(
- ManagementClient,
- 'getGuardianFactorSettings',
- 'guardian.getFactorSettings'
-);
+ /**
+ * 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);
+ }
-/**
- * Get Guardian factor provider configuration
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(
- ManagementClient,
- 'getGuardianFactorProvider',
- 'guardian.getFactorProvider'
-);
+ /**
+ * 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);
+ }
-/**
- * Update Guardian's factor provider
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(
- ManagementClient,
- 'updateGuardianFactorProvider',
- 'guardian.updateFactorProvider'
-);
+ /**
+ * Get all Auth0 CustomDomains.
+ *
+ * @example
+ * management.getCustomDomains(function (err, customDomains) {
+ * console.log(customDomains.length);
+ * });
+ * @returns {Promise|undefined}
+ */
+ getCustomDomains(...args) {
+ return this.customDomains.getAll(...args);
+ }
-/**
- * Update a Guardian's factor settings
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(
- ManagementClient,
- 'updateGuardianFactorSettings',
- 'guardian.updateFactorSettings'
-);
+ /**
+ * 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 enrollment and verification factor templates
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(
- ManagementClient,
- 'getGuardianFactorTemplates',
- 'guardian.getFactorTemplates'
-);
+ /**
+ * 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);
+ }
+
+ /**
+ * 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 Guardian enrollment and verification factor templates
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(
- ManagementClient,
- 'updateGuardianFactorTemplates',
- 'guardian.updateFactorTemplates'
-);
+ /**
+ * 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);
+ }
-/**
- * Update Guardian Factor
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'updateGuardianFactor', 'guardian.updateFactor');
+ /**
+ * 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);
+ }
-/**
- * Get enabled Guardian policies
- *
- * @method getGuardianPolicies
- * @memberOf module:management.ManagementClient.prototype
- *
- * @example
- * management.getGuardianPolicies(function (err, policies) {
- * console.log(policies);
- * });
- *
- * @param {Function} [cb] Callback function.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'getGuardianPolicies', 'guardian.getPolicies');
+ /**
+ * 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 enabled Guardian policies
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'updateGuardianPolicies', 'guardian.updatePolicies');
+ /**
+ * 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 the Guardian phone factor's selected provider
- *
- * @method getGuardianPhoneFactorSelectedProvider
- * @memberOf module:management.ManagementClient.prototype
- *
- * @example
- * management.getGuardianPhoneFactorSelectedProvider(function (err, selectedProvider) {
- * console.log(selectedProvider);
- * });
- *
- * @param {Function} [cb] Callback function.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(
- ManagementClient,
- 'getGuardianPhoneFactorSelectedProvider',
- 'guardian.getPhoneFactorSelectedProvider'
-);
+ /**
+ * 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 the Guardian phone factor's selected provider
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(
- ManagementClient,
- 'updateGuardianPhoneFactorSelectedProvider',
- 'guardian.updatePhoneFactorSelectedProvider'
-);
+ /**
+ * 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 message types
- *
- * @method getGuardianPhoneFactorMessageTypes
- * @memberOf module:management.ManagementClient.prototype
- *
- * @example
- * management.getGuardianPhoneFactorMessageTypes(function (err, messageTypes) {
- * console.log(messageTypes);
- * });
- *
- * @param {Function} [cb] Callback function.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(
- ManagementClient,
- 'getGuardianPhoneFactorMessageTypes',
- 'guardian.getPhoneFactorMessageTypes'
-);
+ /**
+ * 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 message types
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(
- ManagementClient,
- 'updateGuardianPhoneFactorMessageTypes',
- 'guardian.updatePhoneFactorMessageTypes'
-);
+ /**
+ * 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 all roles.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'getRoles', 'roles.getAll');
+ /**
+ * 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);
+ }
-/**
- * Create a new role.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'createRole', 'roles.create');
+ /**
+ * 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 an Auth0 role.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'getRole', 'roles.get');
+ /**
+ * 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);
+ }
-/**
- * Delete an existing role.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'deleteRole', 'roles.delete');
+ /**
+ * 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);
+ }
-/**
- * Update an existing role.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'updateRole', 'roles.update');
+ /**
+ * 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);
+ }
-/**
- * Get permissions for a given role
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'getPermissionsInRole', 'roles.getPermissions');
+ /**
+ * 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);
+ }
-/**
- * Add permissions in a role
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'addPermissionsInRole', 'roles.addPermissions');
+ /**
+ * 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);
+ }
-/**
- * Remove permissions from a role
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'removePermissionsFromRole', 'roles.removePermissions');
+ /**
+ * 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);
+ }
-/**
- * Get users in a given role
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'getUsersInRole', 'roles.getUsers');
+ /**
+ * 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);
+ }
-/**
- * Get all hooks.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'getHooks', 'hooks.getAll');
+ /**
+ * 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 an Auth0 hook.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'getHook', 'hooks.get');
+ /**
+ * 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);
+ }
-/**
- * Create a new hook.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'createHook', 'hooks.create');
+ /**
+ * 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 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);
+ }
-/**
- * Update an existing hook.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'updateHook', 'hooks.update');
+ /**
+ * 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);
+ }
-/**
- * Delete an existing hook.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'deleteHook', 'hooks.delete');
+ /**
+ * 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);
+ }
-/**
- * Get an Auth0 hook's secrets.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'getHookSecrets', 'hooks.getSecrets');
+ /**
+ * 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);
+ }
-/**
- * Add hook screts.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'addHookSecrets', 'hooks.addSecrets');
+ /**
+ * 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);
+ }
-/**
- * Update an existing hook.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'updateHookSecrets', 'hooks.updateSecrets');
+ /**
+ * 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);
+ }
-/**
- * Delete an existing hook.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'removeHookSecrets', 'hooks.removeSecrets');
+ /**
+ * 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);
+ }
-/**
- * Returns the access_token.
- *
- * @method getAccessToken
- * @memberOf module:management.ManagementClient.prototype
- *
- * @return {Promise} Promise returning an access_token.
- */
-utils.wrapPropertyMethod(ManagementClient, 'getAccessToken', 'tokenProvider.getAccessToken');
+ /**
+ * 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);
+ }
-/**
- * Update the branding settings.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'updateBrandingSettings', 'branding.updateSettings');
+ /**
+ * 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);
+ }
-/**
- * Get the branding settings..
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'getBrandingSettings', 'branding.getSettings');
+ /**
+ * 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 new universal login template.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(
- ManagementClient,
- 'getBrandingUniversalLoginTemplate',
- 'branding.getUniversalLoginTemplate'
-);
+ /**
+ * 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.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(
- ManagementClient,
- 'setBrandingUniversalLoginTemplate',
- 'branding.setUniversalLoginTemplate'
-);
+ /**
+ * 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);
+ }
-/**
- * Delete the new universal login template.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(
- ManagementClient,
- 'deleteBrandingUniversalLoginTemplate',
- 'branding.deleteUniversalLoginTemplate'
-);
+ /**
+ * 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);
+ }
-/**
- * Update the tenant migrations.
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'updateMigrations', 'migrations.updateMigrations');
+ /**
+ * Returns the access_token.
+ *
+ * @returns {Promise} Promise returning an access_token.
+ */
+ getAccessToken(...args) {
+ return this.tokenProvider.getAccessToken(...args);
+ }
-/**
- * Get migrations flags
- *
- * @method 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.
- *
- * @return {Promise|undefined}
- */
-utils.wrapPropertyMethod(ManagementClient, 'getMigrations', 'migrations.getMigrations');
+ /**
+ * 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 prompts settings..
- *
- * @method getPromptsSettings
- * @memberOf module:management.ManagementClient.prototype
- *
- * @example
- * management.getPromptsSettings(function (err, settings) {
- * * console.log(settings);
- * });
- *
- * @param {Function} [cb] Callback function.
- *
- * @return {Promise|undefined}
- */
+ /**
+ * 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 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.
- *
- * @method 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.
- *
- * @return {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.
- *
- * @method 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
- *
- * @return {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.
- *
- * @method 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
- *
- * @return {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 fe545b9df..e553250ee 100644
--- a/src/utils.js
+++ b/src/utils.js
@@ -1,89 +1,60 @@
-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', '')
- }
- };
-};
-
-/**
- * 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('.');
- if (path.length > 2) {
- throw new Error('wrapPropertyMethod() only supports one level of nesting for propertyMethod');
- }
- var property = path.shift();
- var method = path.pop();
-
- Object.defineProperty(Parent.prototype, name, {
- enumerable: false,
- get: function() {
- return this[property][method].bind(this[property]);
- }
- });
-};
-
-utils.containsUnsafeChars = s => {
+const generateClientInfo = () => ({
+ name: 'node-auth0',
+ version: pkg.version,
+ env: {
+ node: process.version.replace('v', ''),
+ },
+});
+
+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,
+ containsUnsafeChars,
+ maybeDecode,
+ sanitizeArguments,
+};
diff --git a/test/auth/authentication-client.tests.js b/test/auth/authentication-client.tests.js
index 4f0a744e9..dd97adcdc 100644
--- a/test/auth/authentication-client.tests.js
+++ b/test/auth/authentication-client.tests.js
@@ -1,90 +1,87 @@
-var expect = require('chai').expect;
-var sinon = require('sinon');
-var proxyquire = require('proxyquire');
-
-var ArgumentError = require('rest-facade').ArgumentError;
-
-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');
-
-var ensureProperty = require('../utils').ensureProperty;
-
-describe('AuthenticationClient', function() {
- describe('#constructor', function() {
- it('should raise an error when no options object is provided', function() {
- expect(AuthenticationClient).to.throw(
- ArgumentError,
- 'Authentication Client SDK options must be an object'
- );
+const { expect } = require('chai');
+const sinon = require('sinon');
+const proxyquire = require('proxyquire');
+
+const { ArgumentError } = require('rest-facade');
+
+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');
+
+const { ensureProperty } = require('../utils');
+
+describe('AuthenticationClient', () => {
+ describe('#constructor', () => {
+ it('should raise an error when no options object is provided', () => {
+ 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', function() {
- var client = AuthenticationClient.bind(null, { token: 'token', domain: '' });
-
- expect(client).to.throw(ArgumentError, 'Must provide a domain');
+ it('should raise an error when the domain is not valid', () => {
+ expect(() => {
+ new AuthenticationClient({ token: 'token', domain: '' });
+ }).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 +90,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 +110,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 +125,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 +140,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 +156,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 +176,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..c1bfb82a5 100644
--- a/test/auth/database-auth.tests.js
+++ b/test/auth/database-auth.tests.js
@@ -1,117 +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/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 () {
+ expect(this.authenticator.signIn(userData)).instanceOf(Promise);
});
- it('should perform a POST request to ' + path, function(done) {
- var request = this.request;
+ it(`should perform a POST request to ${path}`, async function () {
+ const { request } = this;
- this.authenticator
- .signIn(userData)
- .then(function() {
- 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();
- 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;
}
@@ -121,206 +110,146 @@ describe('DatabaseAuthenticator', function() {
})
.reply(200);
- this.authenticator
- .signIn(userData)
- .then(function() {
- 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();
- 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() {
- 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();
- 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() {
- 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();
- 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() {
- 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();
- 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() {
- 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();
- 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() {
- 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();
- 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() {
- expect(request.isDone()).to.be.true;
-
- done();
- })
- .catch(done);
+ await this.authenticator.signIn(userData);
+ expect(request.isDone()).to.be.true;
});
});
- 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}`, async function () {
+ const { request } = this;
- this.authenticator
- .signUp(userData)
- .then(function() {
- 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();
- 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;
}
@@ -330,109 +259,92 @@ describe('DatabaseAuthenticator', function() {
})
.reply(200);
- this.authenticator
- .signUp(userData)
- .then(function() {
- 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();
- 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() {
- expect(request.isDone()).to.be.true;
-
- done();
- })
- .catch(done);
+ await this.authenticator.signUp(userData);
+ expect(request.isDone()).to.be.true;
});
});
- 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}`, async function () {
+ const { request } = this;
- this.authenticator
- .changePassword(userData)
- .then(function() {
- 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();
- 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;
}
@@ -442,103 +354,79 @@ describe('DatabaseAuthenticator', function() {
})
.reply(200);
- this.authenticator
- .changePassword(userData)
- .then(function() {
- 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();
- 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() {
- expect(request.isDone()).to.be.true;
-
- done();
- })
- .catch(done);
+ await this.authenticator.changePassword(userData);
+ expect(request.isDone()).to.be.true;
});
});
- 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}`, async function () {
+ const { request } = this;
- this.authenticator
- .requestChangePasswordEmail(userData)
- .then(function() {
- 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();
- 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;
}
@@ -548,33 +436,19 @@ describe('DatabaseAuthenticator', function() {
})
.reply(200);
- this.authenticator
- .requestChangePasswordEmail(userData)
- .then(function() {
- 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();
- 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() {
- 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 f43b4202d..4c290fcc5 100644
--- a/test/auth/oauth-with-idtoken-validation.tests.js
+++ b/test/auth/oauth-with-idtoken-validation.tests.js
@@ -1,26 +1,25 @@
-var expect = require('chai').expect;
-var sinon = require('sinon');
-var proxyquire = require('proxyquire');
-
-var jwt = require('jsonwebtoken');
-var jwksClient = require('jwks-rsa');
-var pem = require('pem');
+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');
// 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 +28,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 +55,498 @@ 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({}));
- }
+ done();
+ },
};
- var oauthWithValidation = new OAUthWithIDTokenValidation(oauth, {});
- oauthWithValidation.create(PARAMS, DATA, done);
+ const oauthWithValidation = new OAUthWithIDTokenValidation(oauth, {});
+ oauthWithValidation.create(PARAMS, DATA);
});
- 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((resolve) => resolve({}));
+ },
};
- 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((resolve) => resolve({ 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((resolve) => resolve({ 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((resolve) => resolve({ 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((resolve) => resolve({ 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((resolve) => resolve({ 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((resolve) => resolve({ 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((resolve) => resolve({ 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' });
+ },
+ }));
+ jwksClientStub.prototype = {};
+
+ const OAUthWithIDTokenValidationProxy = proxyquire(
+ '../../src/auth/OAUthWithIDTokenValidation',
+ {
+ 'jwks-rsa': jwksClientStub,
+ }
+ );
+
+ 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 OAUthWithIDTokenValidationProxy(oauth, {
domain: DOMAIN,
- clientSecret: CLIENT_SECRET
+ clientSecret: CLIENT_SECRET,
});
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((resolve) => resolve({ 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' });
+ },
+ }));
+ jwksClientStub.prototype = {};
+
+ const OAUthWithIDTokenValidationProxy = proxyquire(
+ '../../src/auth/OAUthWithIDTokenValidation',
+ {
+ 'jwks-rsa': jwksClientStub,
+ }
+ );
- 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 OAUthWithIDTokenValidationProxy(oauth, {
domain: DOMAIN,
- clientSecret: CLIENT_SECRET
+ clientSecret: CLIENT_SECRET,
});
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((resolve) => resolve({ 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' });
+ },
+ }));
+ jwksClientStub.prototype = {};
+ const OAUthWithIDTokenValidationProxy = proxyquire(
+ '../../src/auth/OAUthWithIDTokenValidation',
+ {
+ 'jwks-rsa': jwksClientStub,
+ }
+ );
- 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 OAUthWithIDTokenValidationProxy(oauth, {
domain: DOMAIN,
- clientSecret: CLIENT_SECRET
+ clientSecret: CLIENT_SECRET,
});
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((resolve) => resolve({ 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' });
+ },
+ }));
+ jwksClientStub.prototype = {};
+ const OAUthWithIDTokenValidationProxy = proxyquire(
+ '../../src/auth/OAUthWithIDTokenValidation',
+ {
+ 'jwks-rsa': jwksClientStub,
+ }
+ );
- 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 OAUthWithIDTokenValidationProxy(oauth, {
domain: DOMAIN,
- clientSecret: CLIENT_SECRET
+ clientSecret: CLIENT_SECRET,
});
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((resolve) => resolve({ 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' });
+ },
+ }));
+ jwksClientStub.prototype = {};
+ const OAUthWithIDTokenValidationProxy = proxyquire(
+ '../../src/auth/OAUthWithIDTokenValidation',
+ {
+ 'jwks-rsa': jwksClientStub,
+ }
+ );
- 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 OAUthWithIDTokenValidationProxy(oauth, {
domain: DOMAIN,
- clientSecret: CLIENT_SECRET
+ clientSecret: CLIENT_SECRET,
});
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 =>
- res({
+
+ describe('#integration', () => {
+ it('fails with a HS256 id_token and `options.supportedAlgorithms===RS256`', (done) => {
+ const oauth = {
+ create() {
+ return new Promise((resolve) =>
+ resolve({
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 =>
- res({
- id_token: idtoken
+ const oauth = {
+ create() {
+ return new Promise((resolve) =>
+ resolve({
+ id_token: idtoken,
})
);
- }
+ },
};
- var jwksClientStub = sinon.spy(function() {
- return {
- getSigningKey: function(kid, cb) {
- cb(null, { publicKey: c.publicKey });
- }
- };
- });
- OAUthWithIDTokenValidationProxy = proxyquire(
+ const jwksClientStub = sinon.spy(() => ({
+ getSigningKey(kid, cb) {
+ cb(null, { publicKey: c.publicKey });
+ },
+ }));
+ jwksClientStub.prototype = {};
+ const OAUthWithIDTokenValidationProxy = proxyquire(
'../../src/auth/OAUthWithIDTokenValidation',
{
- 'jwks-rsa': jwksClientStub
+ 'jwks-rsa': jwksClientStub,
}
);
- var oauthWithValidation = new OAUthWithIDTokenValidationProxy(oauth, {
+
+ const oauthWithValidation = new OAUthWithIDTokenValidationProxy(oauth, {
clientSecret: CLIENT_SECRET,
domain: 'auth.brucke.club',
- supportedAlgorithms: ['HS256']
+ supportedAlgorithms: ['HS256'],
});
- 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 =>
- res({
- id_token: idtoken
+ const oauth = {
+ create() {
+ return new Promise((resolve) =>
+ resolve({
+ id_token: idtoken,
})
);
- }
+ },
};
- var jwksClientStub = sinon.spy(function() {
- return {
- getSigningKey: function(kid, cb) {
- cb(null, { publicKey: c.publicKey });
- }
- };
- });
- OAUthWithIDTokenValidationProxy = proxyquire(
+ const jwksClientStub = sinon.spy(() => ({
+ getSigningKey(kid, cb) {
+ cb(null, { publicKey: c.publicKey });
+ },
+ }));
+ jwksClientStub.prototype = {};
+ const OAUthWithIDTokenValidationProxy = proxyquire(
'../../src/auth/OAUthWithIDTokenValidation',
{
- 'jwks-rsa': jwksClientStub
+ 'jwks-rsa': jwksClientStub,
}
);
- var oauthWithValidation = new OAUthWithIDTokenValidationProxy(oauth, {
+
+ const oauthWithValidation = new OAUthWithIDTokenValidationProxy(oauth, {
clientSecret: CLIENT_SECRET,
domain: 'auth.brucke.club',
- supportedAlgorithms: ['RS256']
+ supportedAlgorithms: ['RS256'],
});
- 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 =>
- res({
- id_token: idtoken
+ const oauth = {
+ create() {
+ return new Promise((resolve) =>
+ resolve({
+ id_token: idtoken,
})
);
- }
+ },
};
- var jwksClientStub = sinon.spy(function() {
- return {
- getSigningKey: function(kid, cb) {
- cb(null, { publicKey: c.publicKey });
- }
- };
- });
- OAUthWithIDTokenValidationProxy = proxyquire(
+ const jwksClientStub = sinon.spy(() => ({
+ getSigningKey(kid, cb) {
+ cb(null, { publicKey: c.publicKey });
+ },
+ }));
+ jwksClientStub.prototype = {};
+ const OAUthWithIDTokenValidationProxy = proxyquire(
'../../src/auth/OAUthWithIDTokenValidation',
{
- 'jwks-rsa': jwksClientStub
+ 'jwks-rsa': jwksClientStub,
}
);
- var oauthWithValidation = new OAUthWithIDTokenValidationProxy(oauth, {
+
+ const oauthWithValidation = new OAUthWithIDTokenValidationProxy(oauth, {
clientId: 'foobar',
clientSecret: CLIENT_SECRET,
domain: 'brucke.auth0.com',
- supportedAlgorithms: ['RS256']
+ supportedAlgorithms: ['RS256'],
});
- 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 =>
- res({
- id_token: idtoken
+ const oauth = {
+ create() {
+ return new Promise((resolve) =>
+ resolve({
+ id_token: idtoken,
})
);
- }
+ },
};
- var jwksClientStub = sinon.spy(function() {
- return {
- getSigningKey: function(kid, cb) {
- cb(null, { publicKey: c.publicKey });
- }
- };
- });
- OAUthWithIDTokenValidationProxy = proxyquire(
+ const jwksClientStub = sinon.spy(() => ({
+ getSigningKey(kid, cb) {
+ cb(null, { publicKey: c.publicKey });
+ },
+ }));
+ jwksClientStub.prototype = {};
+ const OAUthWithIDTokenValidationProxy = proxyquire(
'../../src/auth/OAUthWithIDTokenValidation',
{
- 'jwks-rsa': jwksClientStub
+ 'jwks-rsa': jwksClientStub,
}
);
- var oauthWithValidation = new OAUthWithIDTokenValidationProxy(oauth, {
+
+ const oauthWithValidation = new OAUthWithIDTokenValidationProxy(oauth, {
clientId: 'foobar',
clientSecret: CLIENT_SECRET,
domain: 'brucke.auth0.com',
- supportedAlgorithms: ['RS256']
+ supportedAlgorithms: ['RS256'],
});
- 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 6e1f16224..3d3db40ec 100644
--- a/test/auth/tokens-manager.tests.js
+++ b/test/auth/tokens-manager.tests.js
@@ -1,129 +1,127 @@
-var expect = require('chai').expect;
-var nock = require('nock');
+const { expect } = require('chai');
+const nock = require('nock');
-const isPromise = thing => thing && typeof thing.then === 'function';
+const isPromise = (thing) => thing && typeof thing.then === 'function';
-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(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();
@@ -131,25 +129,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,
@@ -157,9 +153,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,
@@ -167,83 +163,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(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;
}
@@ -253,76 +249,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();
@@ -330,43 +322,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,
@@ -374,43 +364,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(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;
}
@@ -420,108 +410,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 fd8fbfd7e..3d9717f39 100644
--- a/test/auth/users-manager.tests.js
+++ b/test/auth/users-manager.tests.js
@@ -1,98 +1,100 @@
-var expect = require('chai').expect;
-var nock = require('nock');
+const { expect } = require('chai');
+const nock = require('nock');
-const isPromise = thing => thing && typeof thing.then === 'function';
+const isPromise = (thing) => thing && typeof thing.then === 'function';
-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(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();
@@ -100,17 +102,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();
@@ -118,17 +120,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();
@@ -137,104 +139,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(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();
@@ -242,107 +242,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..a44df6e7c 100644
--- a/test/auth0-rest-client.tests.js
+++ b/test/auth0-rest-client.tests.js
@@ -1,111 +1,114 @@
-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', async function () {
+ 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 => {
- expect(data).to.deep.equal({ data: 'value' });
- done();
- nock.cleanAll();
- });
+ const client = new Auth0RestClient(`${API_URL}/some-resource`, options, this.providerMock);
+ const returnValue = client.get();
+ expect(returnValue).instanceOf(Promise);
+ const data = await returnValue;
+ expect(data).to.deep.equal({ data: 'value' });
+ nock.cleanAll();
});
});
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,33 @@ 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', async function () {
+ 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) {
- expect(data).to.deep.equal({ data: 'value' });
- done();
- nock.cleanAll();
- });
+ const client = new Auth0RestClient(`${API_URL}/some-resource`, options, this.providerMock);
+ const data = await client.getAll();
+ expect(data).to.deep.equal({ data: 'value' });
+ 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 +184,29 @@ 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', async function () {
+ 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) {
- expect(client.restClient.options.headers['Authorization']).to.be.equal('Bearer access_token');
- done();
- nock.cleanAll();
- });
+ const client = new Auth0RestClient(`${API_URL}/some-resource`, options, this.providerMock);
+ 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) {
- 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 +214,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..398ac8d25 100644
--- a/test/management/branding.tests.js
+++ b/test/management/branding.tests.js
@@ -1,147 +1,136 @@
-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() {
- expect(BrandingManager).to.throw(ArgumentError, 'Must provide manager options');
+ describe('#constructor', () => {
+ it('should error when no options are provided', () => {
+ expect(() => {
+ new 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, {});
-
- 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 BrandingManager({});
+ }).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: '' });
-
- expect(client).to.throw(ArgumentError, 'The provided base URL is invalid');
+ it('should throw an error when the base URL is invalid', () => {
+ expect(() => {
+ new BrandingManager({ baseUrl: '' });
+ }).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 +138,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 +217,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 +291,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 +365,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..f67f4f1a6 100644
--- a/test/management/client-grants.tests.js
+++ b/test/management/client-grants.tests.js
@@ -1,97 +1,89 @@
-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() {
- expect(ClientGrantsManager).to.throw(ArgumentError, 'Must provide client options');
+ describe('#constructor', () => {
+ it('should error when no options are provided', () => {
+ expect(() => {
+ new 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, {});
-
- expect(grants).to.throw(ArgumentError, 'Must provide a base URL for the API');
+ it('should throw an error when no base URL is provided', () => {
+ 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', function() {
- var grants = ClientGrantsManager.bind(null, { baseUrl: '' });
-
- expect(grants).to.throw(ArgumentError, 'The provided base URL is invalid');
+ it('should throw an error when the base URL is invalid', () => {
+ expect(() => {
+ new ClientGrantsManager({ baseUrl: '' });
+ }).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 +94,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 +192,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 +230,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..1720202ad 100644
--- a/test/management/client.tests.js
+++ b/test/management/client.tests.js
@@ -1,97 +1,89 @@
-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() {
- expect(ClientsManager).to.throw(ArgumentError, 'Must provide client options');
+ describe('#constructor', () => {
+ it('should error when no options are provided', () => {
+ expect(() => {
+ new 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, {});
-
- 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 ClientsManager({});
+ }).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: '' });
-
- expect(client).to.throw(ArgumentError, 'The provided base URL is invalid');
+ it('should throw an error when the base URL is invalid', () => {
+ expect(() => {
+ new ClientsManager({ baseUrl: '' });
+ }).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 +94,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 +188,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 +223,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 +264,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 6c983fdf8..39234304a 100644
--- a/test/management/connections.tests.js
+++ b/test/management/connections.tests.js
@@ -1,92 +1,84 @@
-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() {
- expect(ConnectionsManager).to.throw(ArgumentError, 'Must provide client options');
+ describe('#constructor', () => {
+ it('should error when no options are provided', () => {
+ expect(() => {
+ new 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, {});
-
- 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 ConnectionsManager({});
+ }).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: '' });
-
- expect(client).to.throw(ArgumentError, 'The provided base URL is invalid');
+ it('should throw an error when the base URL is invalid', () => {
+ expect(() => {
+ new ConnectionsManager({ baseUrl: '' });
+ }).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 +89,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 +132,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 +221,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 +291,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 +366,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,53 +419,44 @@ describe('ConnectionsManager', function() {
});
});
- describe('#checkStatus', function() {
- var params = { id: 5 };
- var data = {
+ describe('#checkStatus', () => {
+ 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 + '/status')
- .reply(200);
+ 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, function() {
+ 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 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) {
+ it('should report success', function (done) {
nock.cleanAll();
- var request = nock(API_URL)
- .get('/connections/' + params.id + '/status')
- .reply(200);
+ nock(API_URL).get(`/connections/${params.id}/status`).reply(200);
- this.connections.checkStatus(params).then(function(response) {
+ this.connections.checkStatus(params).then((response) => {
expect(response).to.exist;
done();
});
});
- it('should report failure', function(done) {
+ it('should report failure', function (done) {
nock.cleanAll();
- var request = nock(API_URL)
- .get('/connections/' + params.id + '/status')
- .reply(500);
+ nock(API_URL).get(`/connections/${params.id}/status`).reply(500);
- this.connections.checkStatus(params).catch(function(err) {
+ this.connections.checkStatus(params).catch((err) => {
expect(err).to.exist;
done();
@@ -509,72 +464,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..e9b57e80c 100644
--- a/test/management/custom-domains.tests.js
+++ b/test/management/custom-domains.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 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() {
- expect(CustomDomainsManager).to.throw(ArgumentError, 'Must provide manager options');
+ describe('#constructor', () => {
+ it('should error when no options are provided', () => {
+ expect(() => {
+ new 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, {});
-
- 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 CustomDomainsManager({});
+ }).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: '' });
-
- expect(client).to.throw(ArgumentError, 'The provided base URL is invalid');
+ it('should throw an error when the base URL is invalid', () => {
+ expect(() => {
+ new CustomDomainsManager({ baseUrl: '' });
+ }).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 +88,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 +123,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 +184,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 +193,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 +261,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 +314,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..10cd533f9 100644
--- a/test/management/device-credentials.tests.js
+++ b/test/management/device-credentials.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 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() {
- expect(DeviceCredentialsManager).to.throw(ArgumentError, 'Must provide manager options');
+ describe('#constructor', () => {
+ it('should error when no options are provided', () => {
+ expect(() => {
+ new 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, {});
-
- 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 DeviceCredentialsManager({});
+ }).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: '' });
-
- expect(client).to.throw(ArgumentError, 'The provided base URL is invalid');
+ it('should throw an error when the base URL is invalid', () => {
+ expect(() => {
+ new DeviceCredentialsManager({ baseUrl: '' });
+ }).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 +88,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 +128,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 +202,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..977f9bb11 100644
--- a/test/management/email-provider.tests.js
+++ b/test/management/email-provider.tests.js
@@ -1,141 +1,130 @@
-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() {
- expect(EmailProviderManager).to.throw(ArgumentError, 'Must provide client options');
+ describe('#constructor', () => {
+ it('should error when no options are provided', () => {
+ expect(() => {
+ new 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, {});
-
- 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 EmailProviderManager({});
+ }).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: '' });
-
- expect(client).to.throw(ArgumentError, 'The provided base URL is invalid');
+ it('should throw an error when the base URL is invalid', () => {
+ expect(() => {
+ new EmailProviderManager({ baseUrl: '' });
+ }).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 +132,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 +202,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 +272,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..8c3acd18d 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,95 @@ 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() {
- expect(EmailTemplatesManager).to.throw(ArgumentError, 'Must provide manager options');
+ describe('#constructor', () => {
+ it('should error when no options are provided', () => {
+ expect(() => {
+ new 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, {});
-
- expect(client).to.throw(ArgumentError, 'Must provide a valid string as base URL for the API');
+ it('should throw an error when no base URL is provided', () => {
+ 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', function() {
- var client = EmailTemplatesManager.bind(null, { baseUrl: '' });
-
- 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', () => {
+ expect(() => {
+ new EmailTemplatesManager({ baseUrl: '' });
+ }).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 +110,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 +178,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..11222d68d 100644
--- a/test/management/grants.tests.js
+++ b/test/management/grants.tests.js
@@ -1,97 +1,89 @@
-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() {
- expect(GrantsManager).to.throw(ArgumentError, 'Must provide client options');
+ describe('#constructor', () => {
+ it('should error when no options are provided', () => {
+ expect(() => {
+ new 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, {});
-
- expect(grants).to.throw(ArgumentError, 'Must provide a base URL for the API');
+ it('should throw an error when no base URL is provided', () => {
+ 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', function() {
- var grants = GrantsManager.bind(null, { baseUrl: '' });
-
- expect(grants).to.throw(ArgumentError, 'The provided base URL is invalid');
+ it('should throw an error when the base URL is invalid', () => {
+ expect(() => {
+ new GrantsManager({ baseUrl: '' });
+ }).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 +94,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..fd5f19e08 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,161 @@ 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() {
- expect(GuardianManager).to.throw(ArgumentError, 'Must provide manager options');
+ describe('#constructor', () => {
+ it('should error when no options are provided', () => {
+ expect(() => {
+ new 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, {});
-
- 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 GuardianManager({});
+ }).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: '' });
-
- expect(manager).to.throw(ArgumentError, 'The provided base URL is invalid');
+ it('should throw an error when the base URL is invalid', () => {
+ expect(() => {
+ new GuardianManager({ baseUrl: '' });
+ }).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 +192,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 +266,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 +325,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 +386,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 +452,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 +530,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 +592,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 +667,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 +740,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 +814,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 +867,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 +934,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 +945,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 +994,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 +1010,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 +1071,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 +1082,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 +1131,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..fca141c39 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,69 @@ 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() {
- expect(HookManager).to.throw(ArgumentError, 'Must provide manager options');
+ describe('#constructor', () => {
+ it('should error when no options are provided', () => {
+ expect(() => {
+ new 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, {});
-
- 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 HookManager({});
+ }).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: '' });
-
- expect(client).to.throw(ArgumentError, 'The provided base URL is invalid');
+ it('should throw an error when the base URL is invalid', () => {
+ expect(() => {
+ new HookManager({ baseUrl: '' });
+ }).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 +98,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 +138,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 +199,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 +272,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 +322,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 +375,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 +430,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 +500,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 +573,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..e1b7b8c74 100644
--- a/test/management/jobs.tests.js
+++ b/test/management/jobs.tests.js
@@ -1,110 +1,102 @@
-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() {
- expect(JobsManager).to.throw(ArgumentError, 'Must provide client options');
+ describe('#constructor', () => {
+ it('should error when no options are provided', () => {
+ expect(() => {
+ new 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, {});
-
- 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 JobsManager({});
+ }).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: '' });
-
- expect(client).to.throw(ArgumentError, 'The provided base URL is invalid');
+ it('should throw an error when the base URL is invalid', () => {
+ expect(() => {
+ new JobsManager({ baseUrl: '' });
+ }).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 +107,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 +150,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 +202,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 +246,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 +276,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 +313,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 +336,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 +397,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 +474,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 +511,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 +519,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 +550,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..781ff921e 100644
--- a/test/management/log-streams.tests.js
+++ b/test/management/log-streams.tests.js
@@ -1,92 +1,84 @@
-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() {
- expect(LogStreamsManager).to.throw(ArgumentError, 'Must provide client options');
+ describe('#constructor', () => {
+ it('should error when no options are provided', () => {
+ expect(() => {
+ new 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, {});
-
- 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 LogStreamsManager({});
+ }).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: '' });
-
- expect(client).to.throw(ArgumentError, 'The provided base URL is invalid');
+ it('should throw an error when the base URL is invalid', () => {
+ expect(() => {
+ new LogStreamsManager({ baseUrl: '' });
+ }).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 +89,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 +203,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 +271,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 +324,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..d5ee44995 100644
--- a/test/management/logs.tests.js
+++ b/test/management/logs.tests.js
@@ -1,92 +1,84 @@
-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() {
- expect(LogsManager).to.throw(ArgumentError, 'Must provide client options');
+ describe('#constructor', () => {
+ it('should error when no options are provided', () => {
+ expect(() => {
+ new 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, {});
-
- 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 LogsManager({});
+ }).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: '' });
-
- expect(client).to.throw(ArgumentError, 'The provided base URL is invalid');
+ it('should throw an error when the base URL is invalid', () => {
+ expect(() => {
+ new LogsManager({ baseUrl: '' });
+ }).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 +89,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 +132,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..619e91c23 100644
--- a/test/management/management-client.tests.js
+++ b/test/management/management-client.tests.js
@@ -1,133 +1,137 @@
-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() {
- expect(ManagementClient).to.throw(
- ArgumentError,
- 'Management API SDK options must be an object'
- );
+ it('should raise an error when no options object is provided', () => {
+ 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', function() {
- var config = Object.assign({}, withTokenConfig);
- delete config.domain;
- var client = ManagementClient.bind(null, config);
+ it('should raise an error when the domain is not set', () => {
+ 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', function() {
- var config = Object.assign({}, withTokenConfig);
- config.domain = '';
- var client = ManagementClient.bind(null, config);
+ it('should raise an error when the domain is not valid', () => {
+ 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', function() {
- var config = Object.assign({}, withTokenConfig);
- config.token = '';
- var client = ManagementClient.bind(null, config);
+ it('should raise an error when the token is not valid', () => {
+ 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', function() {
- var config = Object.assign({}, withTokenProviderConfig);
- delete config.clientId;
- var client = ManagementClient.bind(null, config);
+ it('should raise an error when the token and clientId are not set', () => {
+ 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', function() {
- var config = Object.assign({}, withTokenProviderConfig);
- delete config.clientSecret;
- var client = ManagementClient.bind(null, config);
+ it('should raise an error when the token and clientSecret are not set', () => {
+ 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', 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 +139,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 +386,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 +534,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 +684,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 +834,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 +920,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..0435bdf3a 100644
--- a/test/management/management-token-provider.tests.js
+++ b/test/management/management-token-provider.tests.js
@@ -1,456 +1,453 @@
-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 sinon = require('sinon');
+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 defaultOptions = {
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() {
- expect(new ManagementTokenProvider(defaultConfig)).to.exist.to.be.an.instanceOf(
+ it('should expose an instance of ManagementTokenProvider', () => {
+ expect(new ManagementTokenProvider(defaultOptions)).to.exist.to.be.an.instanceOf(
ManagementTokenProvider
);
});
- it('should raise an error when no options object is provided', function() {
- expect(ManagementTokenProvider).to.throw(ArgumentError, 'Options must be an object');
+ it('should raise an error when no options object is provided', () => {
+ expect(() => {
+ new 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);
- delete config.domain;
- var provider = ManagementTokenProvider.bind(null, config);
+ it('should raise an error when domain is not set', () => {
+ const options = Object.assign({}, defaultOptions);
+ delete options.domain;
- expect(provider).to.throw(ArgumentError, 'Must provide a domain');
+ expect(() => {
+ new ManagementTokenProvider(options);
+ }).to.throw(ArgumentError, 'Must provide a domain');
});
- it('should raise an error when domain is not valid', function() {
- var config = Object.assign({}, defaultConfig);
- config.domain = '';
- var provider = ManagementTokenProvider.bind(null, config);
+ it('should raise an error when domain is not valid', () => {
+ const options = { ...defaultOptions, domain: '' };
- expect(provider).to.throw(ArgumentError, 'Must provide a domain');
+ expect(() => {
+ new ManagementTokenProvider(options);
+ }).to.throw(ArgumentError, 'Must provide a domain');
});
- it('should raise an error when clientId is not set', function() {
- var config = Object.assign({}, defaultConfig);
- delete config.clientId;
- var provider = ManagementTokenProvider.bind(null, config);
+ it('should raise an error when clientId is not set', () => {
+ const options = { ...defaultOptions };
+ delete options.clientId;
- expect(provider).to.throw(ArgumentError, 'Must provide a clientId');
+ expect(() => {
+ new ManagementTokenProvider(options);
+ }).to.throw(ArgumentError, 'Must provide a clientId');
});
- it('should raise an error when clientId is not valid', function() {
- var config = Object.assign({}, defaultConfig);
- config.clientId = '';
- var provider = ManagementTokenProvider.bind(null, config);
+ it('should raise an error when clientId is not valid', () => {
+ const options = { ...defaultOptions, clientId: '' };
- expect(provider).to.throw(ArgumentError, 'Must provide a clientId');
+ expect(() => {
+ new ManagementTokenProvider(options);
+ }).to.throw(ArgumentError, 'Must provide a clientId');
});
- it('should raise an error when clientSecret is not set', function() {
- var config = Object.assign({}, defaultConfig);
- delete config.clientSecret;
- var provider = ManagementTokenProvider.bind(null, config);
+ it('should raise an error when clientSecret is not set', () => {
+ const options = Object.assign({}, defaultOptions);
+ delete options.clientSecret;
- expect(provider).to.throw(ArgumentError, 'Must provide a clientSecret');
+ expect(() => {
+ new ManagementTokenProvider(options);
+ }).to.throw(ArgumentError, 'Must provide a clientSecret');
});
- it('should raise an error when clientSecret is not valid', function() {
- var config = Object.assign({}, defaultConfig);
- config.clientSecret = '';
- var provider = ManagementTokenProvider.bind(null, config);
+ it('should raise an error when clientSecret is not valid', () => {
+ const options = { ...defaultOptions, clientSecret: '' };
- expect(provider).to.throw(ArgumentError, 'Must provide a clientSecret');
+ expect(() => {
+ new ManagementTokenProvider(options);
+ }).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);
- config.enableCache = 'string';
- var provider = ManagementTokenProvider.bind(null, config);
+ it('should raise an error when enableCache is not of type boolean', () => {
+ const options = { ...defaultOptions, enableCache: 'string' };
- expect(provider).to.throw(ArgumentError, 'enableCache must be a boolean');
+ expect(() => {
+ new ManagementTokenProvider(options);
+ }).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);
- config.scope = ['foo', 'bar'];
- var provider = ManagementTokenProvider.bind(null, config);
+ it('should raise an error when scope is not of type string', () => {
+ const options = { ...defaultOptions, scope: ['foo', 'bar'] };
- expect(provider).to.throw(ArgumentError, 'scope must be a string');
+ expect(() => {
+ new ManagementTokenProvider(options);
+ }).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);
- config.scope = 'read:users';
- var provider = new ManagementTokenProvider(config);
+ it('should set scope to read:users when passed as read:users', () => {
+ const options = Object.assign({}, defaultOptions);
+ options.scope = 'read:users';
+ const provider = new ManagementTokenProvider(options);
expect(provider.options.scope).to.be.equal('read:users');
});
- it('should set enableCache to true when not specified', function() {
- var config = Object.assign({}, defaultConfig);
- delete config.enableCache;
- var provider = new ManagementTokenProvider(config);
+ it('should set enableCache to true when not specified', () => {
+ const options = Object.assign({}, defaultOptions);
+ delete options.enableCache;
+ const provider = new ManagementTokenProvider(options);
expect(provider.options.enableCache).to.be.true;
});
- it('should set enableCache to true when passed as true', function() {
- var config = Object.assign({}, defaultConfig);
- config.enableCache = true;
- var provider = new ManagementTokenProvider(config);
+ it('should set enableCache to true when passed as true', () => {
+ const options = Object.assign({}, defaultOptions);
+ options.enableCache = true;
+ const provider = new ManagementTokenProvider(options);
expect(provider.options.enableCache).to.be.true;
});
- it('should set enableCache to false when passed as false', function() {
- var config = Object.assign({}, defaultConfig);
- config.enableCache = false;
- var provider = new ManagementTokenProvider(config);
+ it('should set enableCache to false when passed as false', () => {
+ const options = Object.assign({}, defaultOptions);
+ options.enableCache = false;
+ const provider = new ManagementTokenProvider(options);
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);
- config.cacheTTLInSeconds = 'string';
- var provider = ManagementTokenProvider.bind(null, config);
+ it('should raise an error when the cacheTTLInSeconds is not of type number', () => {
+ const options = { ...defaultOptions, cacheTTLInSeconds: 'string' };
- expect(provider).to.throw(ArgumentError, 'cacheTTLInSeconds must be a number');
+ expect(() => {
+ new ManagementTokenProvider(options);
+ }).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);
- config.cacheTTLInSeconds = -1;
- var provider = ManagementTokenProvider.bind(null, config);
+ it('should raise an error when the cacheTTLInSeconds is not a greater than 0', () => {
+ const options = { ...defaultOptions, cacheTTLInSeconds: -1 };
- expect(provider).to.throw(ArgumentError, 'cacheTTLInSeconds must be a greater than 0');
+ expect(() => {
+ new ManagementTokenProvider(options);
+ }).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);
- config.cacheTTLInSeconds = 15;
- var provider = new ManagementTokenProvider(config);
+ it('should set cacheTTLInSeconds to 15 when passed as 15', () => {
+ const options = Object.assign({}, defaultOptions);
+ options.cacheTTLInSeconds = 15;
+ const provider = new ManagementTokenProvider(options);
expect(provider.options.cacheTTLInSeconds).to.be.equal(15);
});
- it('should set headers when passed into options', function() {
- var config = Object.assign({}, defaultConfig);
- config.headers = {
+ it('should set headers when passed into options', () => {
+ const options = Object.assign({}, defaultOptions);
+ options.headers = {
'User-Agent': 'node.js',
- 'Content-Type': 'application/json'
+ 'Content-Type': 'application/json',
};
- var provider = new ManagementTokenProvider(config);
- expect(provider.options.headers).to.be.equal(config.headers);
+ const provider = new ManagementTokenProvider(options);
+ expect(provider.options.headers).to.be.equal(options.headers);
});
- it('should handle network errors correctly', function(done) {
- var config = Object.assign({}, defaultConfig);
- config.domain = 'domain';
- var client = new ManagementTokenProvider(config);
+ it('should handle network errors correctly', async () => {
+ const options = Object.assign({}, defaultOptions);
+ options.domain = 'domain';
+ const client = new ManagementTokenProvider(options);
- nock('https://' + config.domain)
- .post('/oauth/token')
- .reply(401);
+ nock(`https://${options.domain}`).post('/oauth/token').reply(401);
- client.getAccessToken().catch(function(err) {
+ try {
+ await 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', async () => {
+ const client = new ManagementTokenProvider(defaultOptions);
+ nock(`https://${defaultOptions.domain}`).post('/oauth/token').reply(401);
- client.getAccessToken().catch(function(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();
- });
+ }
});
- function timeout(ms) {
- return new Promise(resolve => setTimeout(resolve, ms));
- }
- 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);
- config.domain = 'auth0-node-sdk-1.auth0.com';
- var client = new ManagementTokenProvider(config);
+ it('should expire access token from cache by the expires_in setting', async () => {
+ const clock = sinon.useFakeTimers();
+ const options = Object.assign({}, defaultOptions);
+ options.domain = 'auth0-node-sdk-1.auth0.com';
+ const client = new ManagementTokenProvider(options);
- nock('https://' + config.domain)
- .post('/oauth/token')
- .reply(200, {
- access_token: 'token',
- expires_in: 10
- });
+ nock(`https://${options.domain}`).post('/oauth/token').reply(200, {
+ access_token: 'token',
+ expires_in: 10,
+ });
- const access_token = await client.getAccessToken();
+ let getAccessTokenPromise = client.getAccessToken();
+ await clock.runAllAsync();
+ await clock.runAllAsync();
+ await clock.runAllAsync();
+ const access_token = await getAccessTokenPromise;
expect(access_token).to.exist;
expect(access_token).to.be.equal('token');
- await client.getAccessToken();
- await timeout(10000);
-
- nock('https://' + config.domain)
- .post('/oauth/token')
- .reply(200, {
- access_token: 'token2',
- expires_in: 10
- });
- const access_token2 = await client.getAccessToken();
+ getAccessTokenPromise = client.getAccessToken();
+ await clock.runAllAsync();
+ await getAccessTokenPromise;
+ await clock.tickAsync(10000 + 1); // + 1 ms so that the first mocked request can expire
+
+ nock(`https://${options.domain}`).post('/oauth/token').reply(200, {
+ access_token: 'token2',
+ expires_in: 10,
+ });
+ getAccessTokenPromise = client.getAccessToken();
+ await clock.runAllAsync();
+ await clock.runAllAsync();
+ await clock.runAllAsync();
+ const access_token2 = await getAccessTokenPromise;
expect(access_token2).to.exist;
expect(access_token2).to.be.equal('token2');
nock.cleanAll();
+ clock.restore();
});
- it('should return access token', function(done) {
- var config = Object.assign({}, defaultConfig);
- config.domain = 'auth0-node-sdk-1.auth0.com';
- var client = new ManagementTokenProvider(config);
+ it('should return access token', async () => {
+ const options = Object.assign({}, defaultOptions);
+ options.domain = 'auth0-node-sdk-1.auth0.com';
+ const client = new ManagementTokenProvider(options);
- nock('https://' + config.domain)
- .post('/oauth/token')
- .reply(200, {
- access_token: 'token',
- expires_in: 3600
- });
-
- client.getAccessToken().then(function(access_token) {
- expect(access_token).to.exist;
- expect(access_token).to.be.equal('token');
- done();
- nock.cleanAll();
+ nock(`https://${options.domain}`).post('/oauth/token').reply(200, {
+ access_token: 'token',
+ expires_in: 3600,
});
+
+ const accessToken = await client.getAccessToken();
+ expect(accessToken).to.exist;
+ expect(accessToken).to.be.equal('token');
});
- it('should contain correct body payload', function(done) {
- var config = Object.assign({}, defaultConfig);
- config.domain = 'auth0-node-sdk-2.auth0.com';
- var client = new ManagementTokenProvider(config);
+ it('should contain correct body payload', (done) => {
+ const options = Object.assign({}, defaultOptions);
+ options.domain = 'auth0-node-sdk-2.auth0.com';
+ const client = new ManagementTokenProvider(options);
- nock('https://' + config.domain)
- .post('/oauth/token', function(body) {
+ nock(`https://${options.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');
+ nock.cleanAll();
+ done();
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) {
- done();
- nock.cleanAll();
- });
+ client.getAccessToken();
});
- it('should return access token from the cache the second call', function(done) {
- var config = Object.assign({}, defaultConfig);
- config.domain = 'auth0-node-sdk-3.auth0.com';
- var client = new ManagementTokenProvider(config);
+ 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);
- nock('https://' + config.domain)
- .post('/oauth/token')
- .once()
- .reply(200, {
- access_token: 'access_token',
- expires_in: 3600
- });
-
- client.getAccessToken().then(function(access_token) {
- expect(access_token).to.exist;
- expect(access_token).to.be.equal('access_token');
-
- setTimeout(function() {
- client
- .getAccessToken()
- .then(function(access_token) {
- expect(access_token).to.exist;
- expect(access_token).to.be.equal('access_token');
- done();
- nock.cleanAll();
- })
- .catch(function(err) {
- expect.fail();
- done();
- nock.cleanAll();
- });
- }, 40); // 40ms
+ nock(`https://${options.domain}`).post('/oauth/token').once().reply(200, {
+ access_token: 'access_token',
+ expires_in: 3600,
});
+
+ 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');
+
+ 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', function(done) {
- var config = Object.assign({}, defaultConfig);
- config.domain = 'auth0-node-sdk-4.auth0.com';
- var client = new ManagementTokenProvider(config);
+ it('should request new access token when cache is expired', (done) => {
+ const options = Object.assign({}, defaultOptions);
+ options.domain = 'auth0-node-sdk-4.auth0.com';
+ const client = new ManagementTokenProvider(options);
- nock('https://' + config.domain)
+ nock(`https://${options.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);
- config.enableCache = false;
- config.domain = 'auth0-node-sdk-3.auth0.com';
- var client = new ManagementTokenProvider(config);
+ it('should return new access token on the second call when cache is disabled', (done) => {
+ const options = Object.assign({}, defaultOptions);
+ options.enableCache = false;
+ options.domain = 'auth0-node-sdk-3.auth0.com';
+ const client = new ManagementTokenProvider(options);
- nock('https://' + config.domain)
+ nock(`https://${options.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);
- config.domain = 'auth0-node-sdk-5.auth0.com';
- config.cacheTTLInSeconds = 10; // 1sec / 40 = 25ms;
- var client = new ManagementTokenProvider(config);
+ it('should return cached access token on the second call when cacheTTLInSeconds is not passed', (done) => {
+ const options = Object.assign({}, defaultOptions);
+ options.domain = 'auth0-node-sdk-5.auth0.com';
+ options.cacheTTLInSeconds = 10; // 1sec / 40 = 25ms;
+ const client = new ManagementTokenProvider(options);
- nock('https://' + config.domain)
+ nock(`https://${options.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);
- config.domain = 'auth0-node-sdk-6.auth0.com';
- config.cacheTTLInSeconds = 1 / 40; // 1sec / 40 = 25ms
- var client = new ManagementTokenProvider(config);
+ it('should return new access token on the second call when cacheTTLInSeconds is passed', (done) => {
+ const options = Object.assign({}, defaultOptions);
+ options.domain = 'auth0-node-sdk-6.auth0.com';
+ options.cacheTTLInSeconds = 1 / 40; // 1sec / 40 = 25ms
+ const client = new ManagementTokenProvider(options);
- nock('https://' + config.domain)
+ nock(`https://${options.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 options = Object.assign({}, defaultOptions);
+ const client = new ManagementTokenProvider(options);
- nock('https://' + config.domain)
- .post('/oauth/token', function(payload) {
+ nock(`https://${options.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 +456,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);
- config.enableCache = false;
- var client = new ManagementTokenProvider(config);
+ it('should pass the correct payload in the body of the oauth/token request with cache disabled', (done) => {
+ const options = Object.assign({}, defaultOptions);
+ options.enableCache = false;
+ const client = new ManagementTokenProvider(options);
- nock('https://' + config.domain)
- .post('/oauth/token', function(payload) {
+ nock(`https://${options.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 +477,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..7563eb351 100644
--- a/test/management/migrations.tests.js
+++ b/test/management/migrations.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 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() {
- expect(MigrationsManager).to.throw(ArgumentError, 'Must provide manager options');
+ describe('#constructor', () => {
+ it('should error when no options are provided', () => {
+ expect(() => {
+ new 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, {});
-
- 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 MigrationsManager({});
+ }).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: '' });
-
- expect(manager).to.throw(ArgumentError, 'The provided base URL is invalid');
+ it('should throw an error when the base URL is invalid', () => {
+ expect(() => {
+ new MigrationsManager({ baseUrl: '' });
+ }).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 +86,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 +197,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..d811c1c95 100644
--- a/test/management/organizations.tests.js
+++ b/test/management/organizations.tests.js
@@ -1,23 +1,32 @@
-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() {
- this.token = 'TOKEN';
- this.organizations = new OrganizationsManager({
- headers: { authorization: 'Bearer ' + this.token },
- baseUrl: API_URL
+describe('OrganizationsManager', () => {
+ /**
+ * @type {OrganizationsManager}
+ */
+ let organizations;
+
+ /**
+ * @type {string}
+ */
+ let token;
+
+ before(() => {
+ token = 'TOKEN';
+ organizations = new OrganizationsManager({
+ headers: { authorization: `Bearer ${token}` },
+ baseUrl: API_URL,
});
});
- describe('instance', function() {
- var methods = [
+ describe('instance', () => {
+ const methods = [
'getByID',
'getByName',
'getAll',
@@ -38,76 +47,69 @@ describe('OrganizationsManager', function() {
'getInvitations',
'getInvitation',
'createInvitation',
- 'deleteInvitation'
+ 'deleteInvitation',
];
- methods.forEach(function(method) {
- it('should have a ' + method + ' method', function() {
- expect(this.organizations[method]).to.exist.to.be.an.instanceOf(Function);
+ methods.forEach((method) => {
+ it(`should have a ${method} method`, () => {
+ expect(organizations[method]).to.exist.to.be.an.instanceOf(Function);
});
});
});
- describe('#constructor', function() {
- it('should error when no options are provided', function() {
- expect(OrganizationsManager).to.throw(ArgumentError, 'Must provide manager options');
+ describe('#constructor', () => {
+ it('should error when no options are provided', () => {
+ expect(() => {
+ new 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, {});
-
- 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 OrganizationsManager({});
+ }).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: '' });
-
- expect(client).to.throw(ArgumentError, 'The provided base URL is invalid');
+ it('should throw an error when the base URL is invalid', () => {
+ expect(() => {
+ new OrganizationsManager({ baseUrl: '' });
+ }).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', (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();
- var request = nock(API_URL)
- .get('/organizations')
- .reply(500);
+ nock(API_URL).get('/organizations').reply(500);
- this.organizations.getAll().catch(function(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();
- 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) {
+ organizations.getAll().then((credentials) => {
expect(credentials).to.be.an.instanceOf(Array);
expect(credentials.length).to.equal(data.length);
@@ -118,42 +120,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() {
+ 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();
- var request = nock(API_URL)
+ const request = nock(API_URL)
.get('/organizations')
- .matchHeader('Authorization', 'Bearer ' + this.token)
+ .matchHeader('Authorization', `Bearer ${token}`)
.reply(200);
- this.organizations.getAll().then(function() {
+ 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();
- 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() {
+ organizations.getAll(params).then(() => {
expect(request.isDone()).to.be.true;
done();
@@ -161,65 +160,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));
+ organizations.getByID(params, 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', function (done) {
+ 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() {
+ 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) {
+ 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 ${token}`)
.reply(200);
- this.organizations.getByID({ id: this.data.id }).then(function() {
+ organizations.getByID({ id: this.data.id }).then(() => {
expect(request.isDone()).to.be.true;
done();
@@ -227,65 +222,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));
+ organizations.getByName(params, 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', function (done) {
+ 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() {
+ 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) {
+ 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 ${token}`)
.reply(200);
- this.organizations.getByName({ name: this.data.name }).then(function() {
+ organizations.getByName({ name: this.data.name }).then(() => {
expect(request.isDone()).to.be.true;
done();
@@ -293,79 +286,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', (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();
- var request = nock(API_URL)
- .post('/organizations')
- .reply(500);
+ nock(API_URL).post('/organizations').reply(500);
- this.organizations.create(data).catch(function(err) {
+ 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() {
+ 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();
- 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() {
+ 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();
- var request = nock(API_URL)
+ const request = nock(API_URL)
.post('/organizations')
- .matchHeader('Authorization', 'Bearer ' + this.token)
+ .matchHeader('Authorization', `Bearer ${token}`)
.reply(200);
- this.organizations.create(data).then(function() {
+ organizations.create(data).then(() => {
expect(request.isDone()).to.be.true;
done();
@@ -373,58 +357,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) {
- 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));
});
- 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() {
+ 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() {
+ 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) {
+ organizations.update({ id: this.data.id }, this.data).catch((err) => {
expect(err).to.exist;
done();
@@ -432,56 +410,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', (done) => {
+ 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', (done) => {
+ 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() {
+ 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();
- 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) {
+ 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();
- var request = nock(API_URL)
- .delete('/organizations/' + id)
- .matchHeader('authorization', 'Bearer ' + this.token)
+ const request = nock(API_URL)
+ .delete(`/organizations/${id}`)
+ .matchHeader('authorization', `Bearer ${token}`)
.reply(200);
- this.organizations.delete({ id: id }).then(function() {
+ organizations.delete({ id }).then(() => {
expect(request.isDone()).to.be.true;
done();
@@ -490,58 +464,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) {
- 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) {
- 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() {
+ 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();
- 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) {
+ 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();
- 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 ${token}`)
.reply(200);
- this.organizations.getEnabledConnections(data).then(function() {
+ organizations.getEnabledConnections(data).then(() => {
expect(request.isDone()).to.be.true;
done();
@@ -549,59 +519,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) {
- 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) {
- 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() {
+ 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();
- 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) {
+ 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();
- 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 ${token}`)
.reply(200);
- this.organizations.getEnabledConnection(data).then(function() {
+ organizations.getEnabledConnection(data).then(() => {
expect(request.isDone()).to.be.true;
done();
@@ -609,92 +579,88 @@ 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) {
+ organizations.addEnabledConnection(this.data, {}, () => {
done();
});
});
- it('should return a promise if no callback is given', function(done) {
- this.organizations
+ it('should return a promise if no callback is given', function (done) {
+ 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) {
+ 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() {
+ 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', () => {
+ expect(() => {
+ 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', () => {
+ expect(() => {
+ 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() {
+ 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 ${token}`)
.reply(200);
- this.organizations.addEnabledConnection(this.data, {}).then(function() {
+ organizations.addEnabledConnection(this.data, {}).then(() => {
expect(request.isDone()).to.be.true;
done();
@@ -702,118 +668,106 @@ 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) {
+ organizations.updateEnabledConnection(this.data, this.body, () => {
done();
});
});
- it('should return a promise if no callback is given', function(done) {
- this.organizations
+ it('should return a promise if no callback is given', function (done) {
+ 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) {
+ 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() {
+ 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', () => {
+ expect(() => {
+ 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', () => {
+ expect(() => {
+ 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() {
- _this.organizations.updateEnabledConnection(
- { id: 'org_123', connection_id: null },
- {},
- function() {}
- );
+ it('should return error when connection_id is not sent', () => {
+ expect(() => {
+ 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() {
- var _this = this;
- expect(function() {
- _this.organizations.updateEnabledConnection(
- { id: 'org_123', connection_id: 123 },
- {},
- function() {}
- );
+ it('should return error when connection_id is not a string', () => {
+ expect(() => {
+ organizations.updateEnabledConnection({ id: 'org_123', connection_id: 123 }, {}, () => {});
}).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() {
+ 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 ${token}`)
.reply(200);
- this.organizations.updateEnabledConnection(this.data, this.body).then(function() {
+ organizations.updateEnabledConnection(this.data, this.body).then(() => {
expect(request.isDone()).to.be.true;
done();
@@ -821,102 +775,90 @@ 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', () => {
+ expect(() => {
+ 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(() => {
+ 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', () => {
+ expect(() => {
+ 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() {
- _this.organizations.removeEnabledConnection(
- { id: _this.data.id, connection_id: 123 },
- function() {}
- );
+ it('should validate non-string connectionId', function () {
+ const _this = this;
+ expect(() => {
+ 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, function() {
+ it('should accept a callback', function (done) {
+ organizations.removeEnabledConnection(this.data, () => {
done();
});
});
- it('should return a promise if no callback is given', function(done) {
- this.organizations
+ it('should return a promise if no callback is given', function (done) {
+ 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) {
+ 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() {
+ 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 ${token}`)
.reply(200);
- this.organizations.removeEnabledConnection(this.data, {}).then(function() {
+ organizations.removeEnabledConnection(this.data, {}).then(() => {
expect(request.isDone()).to.be.true;
done();
@@ -925,58 +867,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) {
- 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) {
- 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() {
+ 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();
- 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) {
+ 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();
- 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 ${token}`)
.reply(200);
- this.organizations.getMembers(data).then(function() {
+ organizations.getMembers(data).then(() => {
expect(request.isDone()).to.be.true;
done();
@@ -984,92 +922,86 @@ 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) {
+ organizations.addMembers(this.data, {}, () => {
done();
});
});
- it('should return a promise if no callback is given', function(done) {
- this.organizations
+ it('should return a promise if no callback is given', function (done) {
+ 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) {
+ 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() {
+ 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', () => {
+ expect(() => {
+ 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', () => {
+ expect(() => {
+ 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() {
+ 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 ${token}`)
.reply(200);
- this.organizations.addMembers(this.data, {}).then(function() {
+ organizations.addMembers(this.data, {}).then(() => {
expect(request.isDone()).to.be.true;
done();
@@ -1077,77 +1009,70 @@ 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', () => {
+ expect(function () {
+ 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(() => {
+ 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
+ it('should return a promise if no callback is given', function (done) {
+ 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) {
+ 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() {
+ 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 ${token}`)
.reply(200);
- this.organizations.removeMembers(this.data, this.body).then(function() {
+ organizations.removeMembers(this.data, this.body).then(() => {
expect(request.isDone()).to.be.true;
done();
@@ -1156,59 +1081,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) {
- 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) {
- 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() {
+ 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();
- 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) {
+ 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();
- 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 ${token}`)
.reply(200);
- this.organizations.getMemberRoles(data).then(function() {
+ organizations.getMemberRoles(data).then(() => {
expect(request.isDone()).to.be.true;
done();
@@ -1216,113 +1139,103 @@ 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) {
+ organizations.addMemberRoles(this.data, this.body, () => {
done();
});
});
- it('should return a promise if no callback is given', function(done) {
- this.organizations
+ it('should return a promise if no callback is given', function (done) {
+ 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) {
+ 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() {
+ 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', () => {
+ expect(() => {
+ 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', () => {
+ expect(() => {
+ 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', () => {
+ expect(() => {
+ 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', () => {
+ expect(() => {
+ 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() {
+ 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 ${token}`)
.reply(200);
- this.organizations.addMemberRoles(this.data, {}).then(function() {
+ organizations.addMemberRoles(this.data, {}).then(() => {
expect(request.isDone()).to.be.true;
done();
@@ -1330,98 +1243,87 @@ 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', () => {
+ expect(function () {
+ 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(() => {
+ 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
+ it('should return a promise if no callback is given', function (done) {
+ 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) {
+ 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', () => {
+ expect(() => {
+ 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', () => {
+ expect(() => {
+ 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() {
+ 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 ${token}`)
.reply(200);
- this.organizations.removeMemberRoles(this.data, this.body).then(function() {
+ organizations.removeMemberRoles(this.data, this.body).then(() => {
expect(request.isDone()).to.be.true;
done();
@@ -1430,58 +1332,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) {
- 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) {
- 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() {
+ 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();
- 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) {
+ 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();
- 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 ${token}`)
.reply(200);
- this.organizations.getInvitations(data).then(function() {
+ organizations.getInvitations(data).then(() => {
expect(request.isDone()).to.be.true;
done();
@@ -1489,87 +1387,81 @@ 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) {
- 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) {
- 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() {
+ 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();
- 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) {
+ 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', () => {
+ expect(() => {
+ 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', () => {
+ expect(() => {
+ 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', () => {
+ expect(() => {
+ 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', () => {
+ expect(() => {
+ 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();
- 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 ${token}`)
.reply(200);
- this.organizations.getInvitation(data).then(function() {
+ organizations.getInvitation(data).then(() => {
expect(request.isDone()).to.be.true;
done();
@@ -1577,95 +1469,91 @@ 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) {
+ organizations.createInvitation(this.data, {}, () => {
done();
});
});
- it('should return a promise if no callback is given', function(done) {
- this.organizations
+ it('should return a promise if no callback is given', function (done) {
+ 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) {
+ 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() {
+ 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', () => {
+ expect(() => {
+ 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', () => {
+ expect(() => {
+ 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() {
+ 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 ${token}`)
.reply(200);
- this.organizations.createInvitation(this.data, {}).then(function() {
+ organizations.createInvitation(this.data, {}).then(() => {
expect(request.isDone()).to.be.true;
done();
@@ -1673,90 +1561,86 @@ 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', () => {
+ expect(() => {
+ 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', () => {
+ expect(() => {
+ 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
+ it('should return a promise if no callback is given', function (done) {
+ 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) {
+ 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) {
+ 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', () => {
+ expect(() => {
+ 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', () => {
+ expect(() => {
+ 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 ${token}`)
.reply(200);
- this.organizations.deleteInvitation(this.data).then(function() {
+ 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..b1bd439d2 100644
--- a/test/management/prompts.tests.js
+++ b/test/management/prompts.tests.js
@@ -1,140 +1,129 @@
-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() {
- expect(PromptsManager).to.throw(ArgumentError, 'Must provide manager options');
+ describe('#constructor', () => {
+ it('should error when no options are provided', () => {
+ expect(() => {
+ new 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, {});
-
- 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 PromptsManager({});
+ }).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: '' });
-
- expect(client).to.throw(ArgumentError, 'The provided base URL is invalid');
+ it('should throw an error when the base URL is invalid', () => {
+ expect(() => {
+ new PromptsManager({ baseUrl: '' });
+ }).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 +131,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 +203,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 +277,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..fe391244b 100644
--- a/test/management/resource-servers.tests.js
+++ b/test/management/resource-servers.tests.js
@@ -1,101 +1,90 @@
-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() {
- expect(ResourceServersManager).to.throw(
- ArgumentError,
- 'Must provide resource server options'
- );
+ describe('#constructor', () => {
+ it('should error when no options are provided', () => {
+ expect(() => {
+ new 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, {});
-
- expect(resourceServerManager).to.throw(ArgumentError, 'Must provide a base URL for the API');
+ it('should throw an error when no base URL is provided', () => {
+ 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', function() {
- var resourceServerManager = ResourceServersManager.bind(null, { baseUrl: '' });
-
- expect(resourceServerManager).to.throw(ArgumentError, 'The provided base URL is invalid');
+ it('should throw an error when the base URL is invalid', () => {
+ expect(() => {
+ new ResourceServersManager({ baseUrl: '' });
+ }).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 +95,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 +191,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 +261,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 +336,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..493599541 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,188 +26,158 @@ 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() {
- expect(RolesManager).to.throw(ArgumentError, 'Must provide manager options');
+ describe('#constructor', () => {
+ it('should error when no options are provided', () => {
+ expect(() => {
+ new 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, {});
-
- 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 RolesManager({});
+ }).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: '' });
-
- expect(client).to.throw(ArgumentError, 'The provided base URL is invalid');
+ it('should throw an error when the base URL is invalid', () => {
+ expect(() => {
+ new RolesManager({ baseUrl: '' });
+ }).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', async function () {
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) {
- 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) {
- var request = this.request;
+ it('should perform a GET request to /api/v2/roles', async function () {
+ const { request } = this;
- this.roles.getAll().then(function() {
- 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();
- 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() {
- 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();
- 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() {
- expect(request.isDone()).to.be.true;
-
- done();
- });
+ await this.roles.getAll(params);
+ expect(request.isDone()).to.be.true;
});
});
- 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;
-
- this.roles.get({ id: this.data.id }).then(function() {
- expect(request.isDone()).to.be.true;
+ it('should perform a POST request to /api/v2/roles/rol_ID', async function () {
+ const { request } = this;
- 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) {
+ 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 +185,64 @@ 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;
-
- this.roles.create(data).then(function() {
- expect(request.isDone()).to.be.true;
+ it('should perform a POST request to /api/v2/roles', async function () {
+ const { request } = this;
- 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();
- var request = nock(API_URL)
- .post('/roles', data)
- .reply(200);
-
- this.roles.create(data).then(function() {
- expect(request.isDone()).to.be.true;
+ const request = nock(API_URL).post('/roles', data).reply(200);
- done();
- });
+ await this.roles.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', 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 +250,49 @@ 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', async function () {
nock.cleanAll();
- var request = nock(API_URL)
- .patch('/roles/' + this.data.id, this.data)
- .reply(200);
-
- this.roles.update({ id: 'rol_ID' }, this.data).then(function() {
- expect(request.isDone()).to.be.true;
+ const request = nock(API_URL).patch(`/roles/${this.data.id}`, this.data).reply(200);
- 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) {
+ 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,194 +300,167 @@ 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 () {
+ expect(this.roles.delete({ id })).instanceOf(Promise);
});
- it('should perform a delete request to /roles/' + id, function(done) {
- var request = this.request;
-
- this.roles.delete({ id: id }).then(function() {
- expect(request.isDone()).to.be.true;
+ it(`should perform a delete request to /roles/${id}`, async function () {
+ const { request } = this;
- done();
- });
+ await this.roles.delete({ id });
+ 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', 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', async function () {
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() {
- expect(request.isDone()).to.be.true;
-
- done();
- });
+ await this.roles.delete({ id });
+ expect(request.isDone()).to.be.true;
});
});
- 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) {
- 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) {
- var request = this.request;
+ it('should perform a GET request to /api/v2/roles/rol_ID/permissions', async function () {
+ const { request } = this;
- this.roles.getPermissions(data).then(function() {
- 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) {
+ 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', async function () {
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() {
- expect(request.isDone()).to.be.true;
-
- done();
- });
+ await this.roles.getPermissions(data);
+ expect(request.isDone()).to.be.true;
});
});
- 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', async function () {
+ const { request } = this;
- this.roles.addPermissions(this.data, {}).then(function() {
- 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) {
+ 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 +468,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 +557,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 +612,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..4de74bb89 100644
--- a/test/management/rules-configs.tests.js
+++ b/test/management/rules-configs.tests.js
@@ -1,280 +1,227 @@
-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() {
- expect(RulesConfigsManager).to.throw(ArgumentError, 'Must provide manager options');
+ describe('#constructor', () => {
+ it('should error when no options are provided', () => {
+ expect(() => {
+ new 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, {});
-
- 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 RulesConfigsManager({});
+ }).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: '' });
-
- expect(client).to.throw(ArgumentError, 'The provided base URL is invalid');
+ it('should throw an error when the base URL is invalid', () => {
+ expect(() => {
+ new RulesConfigsManager({ baseUrl: '' });
+ }).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', async function () {
nock.cleanAll();
- var data = [{ key: 'dbconnectionstring' }];
- var request = nock(API_URL)
- .get('/rules-configs')
- .reply(200, data);
-
- this.rulesConfigs.getAll().then(function(rulesConfigs) {
- expect(rulesConfigs).to.be.an.instanceOf(Array);
+ const data = [{ key: 'dbconnectionstring' }];
+ nock(API_URL).get('/rules-configs').reply(200, data);
- expect(rulesConfigs.length).to.equal(data.length);
+ const rulesConfigs = await this.rulesConfigs.getAll();
+ expect(rulesConfigs).to.be.an.instanceOf(Array);
- expect(rulesConfigs[0].key).to.equal(data[0].key);
+ expect(rulesConfigs.length).to.equal(data.length);
- 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();
- 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() {
- 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();
- 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() {
- 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();
- var params = {
+ const params = {
include_fields: true,
- fields: 'test'
+ fields: 'test',
};
- var request = nock(API_URL)
- .get('/rules-configs')
- .query(params)
- .reply(200);
-
- this.rulesConfigs.getAll(params).then(function() {
- expect(request.isDone()).to.be.true;
+ const request = nock(API_URL).get('/rules-configs').query(params).reply(200);
- done();
- });
+ await this.rulesConfigs.getAll(params);
+ expect(request.isDone()).to.be.true;
});
});
- 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}', async function () {
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() {
- expect(request.isDone()).to.be.true;
-
- done();
- })
- .catch(function(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();
- var request = nock(API_URL)
- .put('/rules-configs/' + this.params.key, this.data)
- .reply(200);
-
- this.rulesConfigs.set(this.params, this.data).then(function() {
- expect(request.isDone()).to.be.true;
+ const request = nock(API_URL).put(`/rules-configs/${this.params.key}`, this.data).reply(200);
- 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();
- 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() {
- expect(request.isDone()).to.be.true;
-
- done();
- });
+ await this.rulesConfigs.set(this.params, this.data);
+ expect(request.isDone()).to.be.true;
});
});
- 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 () {
+ expect(this.rulesConfigs.delete({ key })).instanceOf(Promise);
});
- 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}`, async function () {
+ const { request } = this;
- this.rulesConfigs.delete({ key: key }).then(function() {
- 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) {
+ 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', async function () {
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() {
- 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 dcf900952..9a2837243 100644
--- a/test/management/rules.tests.js
+++ b/test/management/rules.tests.js
@@ -1,346 +1,279 @@
-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() {
- expect(RulesManager).to.throw(ArgumentError, 'Must provide manager options');
+ describe('#constructor', () => {
+ it('should error when no options are provided', () => {
+ expect(() => {
+ new 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, {});
-
- 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 RulesManager({});
+ }).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: '' });
-
- expect(client).to.throw(ArgumentError, 'The provided base URL is invalid');
+ it('should throw an error when the base URL is invalid', () => {
+ expect(() => {
+ new RulesManager({ baseUrl: '' });
+ }).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) {
+ this.rules.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 function () {
nock.cleanAll();
- var data = [{ test: true }];
- var request = nock(API_URL)
- .get('/rules')
- .reply(200, data);
-
- this.rules.getAll().then(function(credentials) {
- expect(credentials).to.be.an.instanceOf(Array);
+ const data = [{ test: true }];
+ nock(API_URL).get('/rules').reply(200, data);
- 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) {
- var request = this.request;
+ it('should perform a GET request to /api/v2/rules', async function () {
+ const { request } = this;
- this.rules.getAll().then(function() {
- 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();
- 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() {
- 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();
- 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() {
- expect(request.isDone()).to.be.true;
-
- done();
- });
+ await this.rules.getAll(params);
+ expect(request.isDone()).to.be.true;
});
});
- 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;
-
- this.rules.get({ id: this.data.id }).then(function() {
- expect(request.isDone()).to.be.true;
+ it('should perform a POST request to /api/v2/rules/5', async function () {
+ const { request } = this;
- 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) {
+ 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', async function () {
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() {
- expect(request.isDone()).to.be.true;
-
- done();
- });
+ await this.rules.get({ id: this.data.id });
+ expect(request.isDone()).to.be.true;
});
});
- 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;
-
- this.rules.create(data).then(function() {
- expect(request.isDone()).to.be.true;
+ it('should perform a POST request to /api/v2/rules', async function () {
+ const { request } = this;
- 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();
- var request = nock(API_URL)
- .post('/rules', data)
- .reply(200);
-
- this.rules.create(data).then(function() {
- expect(request.isDone()).to.be.true;
+ const request = nock(API_URL).post('/rules', data).reply(200);
- 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();
- 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() {
- expect(request.isDone()).to.be.true;
-
- done();
- });
+ await this.rules.create(data);
+ expect(request.isDone()).to.be.true;
});
});
- 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;
-
- this.rules.update({ id: 5 }, {}).then(function() {
- expect(request.isDone()).to.be.true;
+ it('should perform a PATCH request to /api/v2/rules/5', async function () {
+ const { request } = this;
- 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();
- var request = nock(API_URL)
- .patch('/rules/' + this.data.id, this.data)
- .reply(200);
-
- this.rules.update({ id: 5 }, this.data).then(function() {
- expect(request.isDone()).to.be.true;
+ const request = nock(API_URL).patch(`/rules/${this.data.id}`, this.data).reply(200);
- 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) {
+ 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,60 +281,50 @@ 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 () {
+ expect(this.rules.delete({ id })).instanceOf(Promise);
});
- it('should perform a delete request to /rules/' + id, function(done) {
- var request = this.request;
+ it(`should perform a delete request to /rules/${id}`, async function () {
+ const { request } = this;
- this.rules.delete({ id: id }).then(function() {
- 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) {
+ 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', async function () {
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() {
- 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 eac10c623..d70b43b42 100644
--- a/test/management/stats.tests.js
+++ b/test/management/stats.tests.js
@@ -1,210 +1,177 @@
-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() {
- expect(StatsManager).to.throw(ArgumentError, 'Must provide manager options');
+ describe('#constructor', () => {
+ it('should error when no options are provided', () => {
+ expect(() => {
+ new 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, {});
-
- 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 StatsManager({});
+ }).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: '' });
-
- expect(client).to.throw(ArgumentError, 'The provided base URL is invalid');
+ it('should throw an error when the base URL is invalid', () => {
+ expect(() => {
+ new StatsManager({ baseUrl: '' });
+ }).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', async function () {
nock.cleanAll();
- var data = [{ test: true }];
- var request = nock(API_URL)
- .get('/stats/daily')
- .reply(200, data);
-
- this.stats.getDaily().then(function(blacklistedTokens) {
- expect(blacklistedTokens).to.be.an.instanceOf(Array);
+ const data = [{ test: true }];
+ nock(API_URL).get('/stats/daily').reply(200, data);
- expect(blacklistedTokens.length).to.equal(data.length);
+ const blacklistedTokens = await this.stats.getDaily();
+ expect(blacklistedTokens).to.be.an.instanceOf(Array);
- expect(blacklistedTokens[0].test).to.equal(data[0].test);
+ expect(blacklistedTokens.length).to.equal(data.length);
- done();
- });
+ expect(blacklistedTokens[0].test).to.equal(data[0].test);
});
- 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', async function () {
+ const { request } = this;
- this.stats.getDaily().then(function() {
- 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();
- 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() {
- 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();
- 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() {
- expect(request.isDone()).to.be.true;
- done();
- });
+ await this.stats.getDaily({ include_fields: true, fields: 'test' });
+ expect(request.isDone()).to.be.true;
});
});
- 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', async function () {
+ const { request } = this;
- this.stats.getActiveUsersCount().then(function() {
- 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();
- var request = nock(API_URL)
- .get('/stats/active-users')
- .reply(200);
-
- this.stats.getActiveUsersCount().then(function() {
- expect(request.isDone()).to.be.true;
+ const request = nock(API_URL).get('/stats/active-users').reply(200);
- 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();
- 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() {
- 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 0b541a6a4..95a182c01 100644
--- a/test/management/tenant.tests.js
+++ b/test/management/tenant.tests.js
@@ -1,214 +1,181 @@
-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', async function () {
nock.cleanAll();
- var data = [{ test: true }];
- var request = nock(API_URL)
- .get('/tenants/settings')
- .reply(200, data);
-
- this.tenant.getSettings().then(function(blacklistedTokens) {
- expect(blacklistedTokens).to.be.an.instanceOf(Array);
+ const data = [{ test: true }];
+ nock(API_URL).get('/tenants/settings').reply(200, data);
- expect(blacklistedTokens.length).to.equal(data.length);
+ const blacklistedTokens = await this.tenant.getSettings();
+ expect(blacklistedTokens).to.be.an.instanceOf(Array);
- expect(blacklistedTokens[0].test).to.equal(data[0].test);
+ expect(blacklistedTokens.length).to.equal(data.length);
- done();
- });
+ expect(blacklistedTokens[0].test).to.equal(data[0].test);
});
- 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', async function () {
+ const { request } = this;
- this.tenant.getSettings().then(function() {
- 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();
- 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() {
- 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();
- 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() {
- expect(request.isDone()).to.be.true;
- done();
- });
+ await this.tenant.getSettings({ include_fields: true, fields: 'test' });
+ expect(request.isDone()).to.be.true;
});
});
- 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', async function () {
+ const { request } = this;
- this.tenant.updateSettings(data).then(function() {
- 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();
- var request = nock(API_URL)
- .patch('/tenants/settings', data)
- .reply(200);
-
- this.tenant.updateSettings(data).then(function() {
- expect(request.isDone()).to.be.true;
+ const request = nock(API_URL).patch('/tenants/settings', data).reply(200);
- 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();
- 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() {
- 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 072a0fe39..c9ad63ad0 100644
--- a/test/management/tickets.tests.js
+++ b/test/management/tickets.tests.js
@@ -1,204 +1,175 @@
-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', async function () {
+ const { request } = this;
- this.tickets.verifyEmail(data).then(function() {
- 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();
- 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() {
- 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();
- 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() {
- expect(request.isDone()).to.be.true;
-
- done();
- });
+ await this.tickets.verifyEmail({ include_fields: true, fields: 'test' });
+ expect(request.isDone()).to.be.true;
});
});
- 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', async function () {
+ const { request } = this;
- this.tickets.changePassword(data).then(function() {
- 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();
- 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() {
- 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();
- 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() {
- 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 decf9c491..06aff914f 100644
--- a/test/management/user-blocks.tests.js
+++ b/test/management/user-blocks.tests.js
@@ -1,100 +1,92 @@
-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) {
- 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) {
- var request = this.request;
+ it(`should perform a get request to /user-blocks/${id}`, async function () {
+ const { request } = this;
- this.userBlocks
- .get({ id })
- .then(function() {
- 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) {
+ 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,77 +94,61 @@ 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', async function () {
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() {
- expect(request.isDone()).to.be.true;
-
- done();
- })
- .catch(done);
+ await this.userBlocks.get({ id });
+ expect(request.isDone()).to.be.true;
});
});
- 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) {
- 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) {
- var request = this.request;
+ it(`should perform a delete request to /user-blocks/${id}`, async function () {
+ const { request } = this;
- this.userBlocks
- .delete({ id })
- .then(function() {
- 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) {
+ 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,43 +156,34 @@ 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', async function () {
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() {
- expect(request.isDone()).to.be.true;
-
- done();
- })
- .catch(done);
+ await this.userBlocks.delete({ id });
+ expect(request.isDone()).to.be.true;
});
});
- 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,38 +191,29 @@ 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) {
- 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) {
- var request = this.request;
+ it('should perform a get request to /user-blocks', async function () {
+ const { request } = this;
- this.userBlocks
- .getByIdentifier({ identifier })
- .then(function() {
- 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) {
+ 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,44 +221,35 @@ 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', async function () {
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() {
- expect(request.isDone()).to.be.true;
-
- done();
- })
- .catch(done);
+ await this.userBlocks.getByIdentifier({ identifier });
+ expect(request.isDone()).to.be.true;
});
});
- 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,38 +257,29 @@ 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) {
- 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) {
- var request = this.request;
-
- this.userBlocks
- .deleteByIdentifier({ identifier })
- .then(function() {
- expect(request.isDone()).to.be.true;
+ it('should perform a delete request to /user-blocks', async function () {
+ const { request } = this;
- 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) {
+ 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,23 +287,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', async function () {
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() {
- expect(request.isDone()).to.be.true;
-
- done();
- })
- .catch(done);
+ await this.userBlocks.deleteByIdentifier({ identifier });
+ expect(request.isDone()).to.be.true;
});
});
});
diff --git a/test/management/users.tests.js b/test/management/users.tests.js
index 32613b97c..7d0cbbf15 100644
--- a/test/management/users.tests.js
+++ b/test/management/users.tests.js
@@ -1,23 +1,31 @@
-var expect = require('chai').expect;
-var nock = require('nock');
-
-var SRC_DIR = '../../src';
-var API_URL = 'https://tenants.auth0.com';
-
-var UsersManager = require(SRC_DIR + '/management/UsersManager');
-var ArgumentError = require('rest-facade').ArgumentError;
-
-describe('UsersManager', function() {
- before(function() {
- this.token = 'TOKEN';
- this.users = new UsersManager({
- headers: { authorization: 'Bearer ' + this.token },
- baseUrl: API_URL
+const { expect } = require('chai');
+const nock = require('nock');
+
+const API_URL = 'https://tenants.auth0.com';
+
+const UsersManager = require(`../../src/management/UsersManager`);
+const { ArgumentError } = require('rest-facade');
+
+describe('UsersManager', () => {
+ /**
+ * @type {string}
+ */
+ let token;
+
+ /**
+ * @type {UsersManager}
+ */
+ let usersManager;
+ before(() => {
+ token = 'TOKEN';
+ usersManager = new UsersManager({
+ headers: { authorization: `Bearer ${token}` },
+ baseUrl: API_URL,
});
});
- describe('instance', function() {
- var methods = [
+ describe('instance', () => {
+ const methods = [
'get',
'getAll',
'create',
@@ -39,1652 +47,1497 @@ describe('UsersManager', function() {
'getPermissions',
'assignPermissions',
'removePermissions',
- 'getUserOrganizations'
+ 'getUserOrganizations',
];
- methods.forEach(function(method) {
- it('should have a ' + method + ' method', function() {
- expect(this.users[method]).to.exist.to.be.an.instanceOf(Function);
+ methods.forEach((method) => {
+ it(`should have a ${method} method`, () => {
+ expect(usersManager[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', () => {
+ /**
+ * @type {nock}
+ */
+ let scope;
+ beforeEach(() => {
+ scope = nock(API_URL).get('/users').reply(200);
});
- it('should accept a callback', function(done) {
- this.users.getAll(function() {
+ 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();
- var request = nock(API_URL)
- .get('/users')
- .reply(500);
+ nock(API_URL).get('/users').reply(500);
- this.users.getAll().catch(function(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();
- var data = [{ test: true }];
- var request = nock(API_URL)
- .get('/users')
- .reply(200, data);
-
- this.users.getAll().then(function(users) {
- expect(users).to.be.an.instanceOf(Array);
+ const data = [{ test: true }];
+ nock(API_URL).get('/users').reply(200, data);
- 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) {
- var request = this.request;
-
- this.users.getAll().then(function() {
- 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();
- var request = nock(API_URL)
+ const request = nock(API_URL)
.get('/users')
- .matchHeader('Authorization', 'Bearer ' + this.token)
+ .matchHeader('Authorization', `Bearer ${token}`)
.reply(200);
- this.users.getAll().then(function() {
- 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();
- var params = {
+ const params = {
include_fields: true,
- fields: 'test'
+ fields: 'test',
};
- var request = nock(API_URL)
- .get('/users')
- .query(params)
- .reply(200);
-
- this.users.getAll(params).then(function() {
- expect(request.isDone()).to.be.true;
+ const request = nock(API_URL).get('/users').query(params).reply(200);
- done();
- });
+ await usersManager.getAll(params);
+ expect(request.isDone()).to.be.true;
});
});
- describe('#getByEmail', function() {
- beforeEach(function() {
- this.request = nock(API_URL)
- .get('/users-by-email')
- .reply(200);
+ describe('#getByEmail', () => {
+ /**
+ * @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', function() {
+ 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();
- 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) {
+ 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();
- var data = [{ test: true }];
- var request = nock(API_URL)
- .get('/users-by-email')
- .reply(200, data);
-
- this.users.getByEmail().then(function(users) {
- expect(users).to.be.an.instanceOf(Array);
-
- expect(users.length).to.equal(data.length);
-
- expect(users[0].test).to.equal(data[0].test);
+ const data = [{ test: true }];
+ nock(API_URL).get('/users-by-email').reply(200, data);
- 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) {
- var request = this.request;
-
- this.users.getByEmail().then(function() {
- 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();
- var request = nock(API_URL)
+ const request = nock(API_URL)
.get('/users-by-email')
- .matchHeader('Authorization', 'Bearer ' + this.token)
+ .matchHeader('Authorization', `Bearer ${token}`)
.reply(200);
- this.users.getByEmail().then(function() {
- 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();
- 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);
-
- this.users.getByEmail(params.email).then(function() {
- expect(request.isDone()).to.be.true;
+ const request = nock(API_URL).get('/users-by-email').query(params).reply(200);
- 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();
- 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);
-
- this.users.getByEmail(params.email, additionalOptions).then(function() {
- expect(request.isDone()).to.be.true;
+ const request = nock(API_URL).get('/users-by-email').query(params).reply(200);
- done();
- });
+ await usersManager.getByEmail(params.email, additionalOptions);
+ expect(request.isDone()).to.be.true;
});
});
- describe('#get', function() {
- beforeEach(function() {
- this.data = {
+ describe('#get', () => {
+ /**
+ * @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,
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);
+ scope = nock(API_URL).get(`/users/${data.id}`).reply(200, data);
});
- it('should accept a callback', function(done) {
- var 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) {
- var request = this.request;
-
- this.users.get({ id: this.data.id }).then(function() {
- 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();
- var request = 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(function(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();
- var request = nock(API_URL)
- .get('/users/' + this.data.id)
- .matchHeader('Authorization', 'Bearer ' + this.token)
+ const request = nock(API_URL)
+ .get(`/users/${data.id}`)
+ .matchHeader('Authorization', `Bearer ${token}`)
.reply(200);
- this.users.get({ id: this.data.id }).then(function() {
- expect(request.isDone()).to.be.true;
-
- done();
- });
+ await usersManager.get({ id: data.id });
+ expect(request.isDone()).to.be.true;
});
});
- 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);
+ /**
+ * @type {nock}
+ */
+ let scope;
+ beforeEach(() => {
+ scope = nock(API_URL).post('/users').reply(200);
});
- it('should accept a callback', function(done) {
- this.users.create(data, function() {
+ 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();
- var request = nock(API_URL)
- .post('/users')
- .reply(500);
+ nock(API_URL).post('/users').reply(500);
- this.users.create(data).catch(function(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) {
- var request = this.request;
-
- this.users.create(data).then(function() {
- 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();
- var request = nock(API_URL)
- .post('/users', data)
- .reply(200);
-
- this.users.create(data).then(function() {
- expect(request.isDone()).to.be.true;
+ const request = nock(API_URL).post('/users', data).reply(200);
- 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();
- var request = nock(API_URL)
+ const request = nock(API_URL)
.post('/users')
- .matchHeader('Authorization', 'Bearer ' + this.token)
+ .matchHeader('Authorization', `Bearer ${token}`)
.reply(200);
- this.users.create(data).then(function() {
- expect(request.isDone()).to.be.true;
-
- done();
- });
+ await usersManager.create(data);
+ expect(request.isDone()).to.be.true;
});
});
- describe('#update', function() {
- beforeEach(function() {
- this.data = { id: 5 };
+ describe('#update', () => {
+ /**
+ * @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) {
- var request = this.request;
+ it('should accept a callback', (done) => {
+ usersManager.update({ id: 5 }, {}, done.bind(null, null));
+ });
- this.users.update({ id: 5 }, {}).then(function() {
- 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();
- var 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(function() {
- 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();
- var request = 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(function(err) {
+ try {
+ await usersManager.update({ id: data.id }, data);
+ } catch (err) {
expect(err).to.exist;
-
- done();
- });
+ }
});
});
- 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);
- });
+ /**
+ * @type {nock}
+ */
+ let scope;
- it('should accept a callback', function(done) {
- this.users.delete({ id: 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: 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) {
- var request = this.request;
-
- this.users.delete({ id: id }).then(function() {
- 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();
- 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) {
+ 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();
- var request = nock(API_URL)
- .delete('/users/' + id)
- .matchHeader('authorization', 'Bearer ' + this.token)
+ const request = nock(API_URL)
+ .delete(`/users/${id}`)
+ .matchHeader('authorization', `Bearer ${token}`)
.reply(200);
- this.users.delete({ id: id }).then(function() {
- expect(request.isDone()).to.be.true;
-
- done();
- });
+ await usersManager.delete({ id });
+ expect(request.isDone()).to.be.true;
});
});
- 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);
+ /**
+ * @type {nock}
+ */
+ let scope;
+
+ beforeEach(() => {
+ scope = 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', () => {
+ expect(() => {
+ usersManager.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', () => {
+ expect(() => {
+ 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, function() {
+ 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();
- 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) {
+ 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) {
- var request = this.request;
-
- this.users.link(userId, data).then(function() {
- 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();
- 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() {
- 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();
- 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 ${token}`)
.reply(200);
- this.users.link(userId, data).then(function() {
- expect(request.isDone()).to.be.true;
-
- done();
- });
+ await usersManager.link(userId, data);
+ expect(request.isDone()).to.be.true;
});
});
- 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);
- });
+ /**
+ * @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) {
- var request = this.request;
-
- this.users.unlink(data).then(function() {
- 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();
- var request = nock(API_URL)
- .delete(url)
- .reply(500);
+ nock(API_URL).delete(url).reply(500);
- this.users.unlink(data).catch(function(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();
- var request = nock(API_URL)
+ const request = nock(API_URL)
.delete(url)
- .matchHeader('authorization', 'Bearer ' + this.token)
+ .matchHeader('authorization', `Bearer ${token}`)
.reply(200);
- this.users.unlink(data).then(function() {
- expect(request.isDone()).to.be.true;
-
- done();
- });
+ await usersManager.unlink(data);
+ expect(request.isDone()).to.be.true;
});
});
- 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);
- });
+ /**
+ * @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) {
- var request = this.request;
-
- this.users.deleteMultifactorProvider(data).then(function() {
- 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();
- var request = nock(API_URL)
- .delete(url)
- .reply(500);
+ nock(API_URL).delete(url).reply(500);
- this.users.deleteMultifactorProvider(data).catch(function(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();
- var request = nock(API_URL)
+ const request = nock(API_URL)
.delete(url)
- .matchHeader('authorization', 'Bearer ' + this.token)
+ .matchHeader('authorization', `Bearer ${token}`)
.reply(200);
- this.users.deleteMultifactorProvider(data).then(function() {
- expect(request.isDone()).to.be.true;
-
- done();
- });
+ await usersManager.deleteMultifactorProvider(data);
+ expect(request.isDone()).to.be.true;
});
});
- describe('#updateUserMetadata', function() {
- beforeEach(function() {
- this.data = {
+ describe('#updateUserMetadata', () => {
+ /**
+ * @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'
+ 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) {
- var request = this.request;
-
- this.users.updateUserMetadata({ id: 5 }, {}).then(function() {
- 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();
- var request = nock(API_URL)
- .patch('/users/' + this.data.id, {
- user_metadata: this.data
+ const request = nock(API_URL)
+ .patch(`/users/${data.id}`, {
+ user_metadata: data,
})
.reply(200);
- this.users
- .updateUserMetadata({ id: 5 }, this.data)
- .then(function() {
- 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();
- var request = 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(function(err) {
+ try {
+ await usersManager.updateUserMetadata({ id: data.id }, data);
+ } catch (err) {
expect(err).to.exist;
-
- done();
- });
+ }
});
});
- 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);
- });
+ /**
+ * @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) {
- var request = this.request;
-
- this.users.logs(data).then(function() {
- 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();
- var request = nock(API_URL)
- .get(url)
- .reply(500);
+ nock(API_URL).get(url).reply(500);
- this.users.logs(data).catch(function(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();
- var request = nock(API_URL)
+ const request = nock(API_URL)
.get(url)
- .matchHeader('authorization', 'Bearer ' + this.token)
+ .matchHeader('authorization', `Bearer ${token}`)
.reply(200);
- this.users.logs(data).then(function() {
- 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();
- 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) {
- expect(logs).to.be.an.instanceOf(Array);
+ const logs = await usersManager.logs(data);
+ expect(logs).to.be.an.instanceOf(Array);
- expect(logs.length).to.equal(response.length);
+ expect(logs.length).to.equal(response.length);
- expect(logs[0].test).to.equal(response[0].test);
-
- 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();
- 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;
+ const ownData = { ...data };
+ ownData.page = params.page;
+ ownData.per_page = params.per_page;
- this.users.logs(data).then(function() {
- expect(request.isDone()).to.be.true;
-
- done();
- });
+ await usersManager.logs(ownData);
+ expect(request.isDone()).to.be.true;
});
});
- 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);
- });
+ /**
+ * @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) {
- var request = this.request;
-
- this.users.getGuardianEnrollments(data).then(function() {
- 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();
- 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) {
+ 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();
- 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 ${token}`)
.reply(200);
- this.users.getGuardianEnrollments(data).then(function() {
- expect(request.isDone()).to.be.true;
-
- done();
- });
+ await usersManager.getGuardianEnrollments(data);
+ expect(request.isDone()).to.be.true;
});
});
- 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);
+ /**
+ * @type {nock}
+ */
+ let scope;
+
+ beforeEach(() => {
+ scope = 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', () => {
+ expect(() => {
+ usersManager.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', (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();
- 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) {
+ 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) {
- var request = this.request;
-
- this.users.regenerateRecoveryCode(data).then(function() {
- 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();
- 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 ${token}`)
.reply(200);
- this.users.regenerateRecoveryCode(data).then(function() {
- expect(request.isDone()).to.be.true;
-
- done();
- });
+ await usersManager.regenerateRecoveryCode(data);
+ expect(request.isDone()).to.be.true;
});
});
- describe('#invalidateRememberBrowser', function() {
- var data = {
- id: 'USER_ID'
+ describe('#invalidateRememberBrowser', () => {
+ const data = {
+ id: 'USER_ID',
};
- beforeEach(function() {
- this.request = nock(API_URL)
- .post('/users/' + data.id + '/multifactor/actions/invalidate-remember-browser')
+ /**
+ * @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() {
- var _this = this;
- expect(function() {
- _this.users.invalidateRememberBrowser(null, function() {});
+ it('should validate empty userId', () => {
+ expect(() => {
+ usersManager.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', (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();
- 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) {
+ 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) {
- var request = this.request;
-
- this.users.invalidateRememberBrowser(data).then(function() {
- 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();
- 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 ${token}`)
.reply(200);
- this.users.invalidateRememberBrowser(data).then(function() {
- expect(request.isDone()).to.be.true;
-
- done();
- });
+ await usersManager.invalidateRememberBrowser(data);
+ expect(request.isDone()).to.be.true;
});
});
- 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);
- });
+ /**
+ * @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) {
- var request = this.request;
-
- this.users.getRoles(data).then(function() {
- 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();
- 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) {
+ 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();
- 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 ${token}`)
.reply(200);
- this.users.getRoles(data).then(function() {
- expect(request.isDone()).to.be.true;
-
- done();
- });
+ await usersManager.getRoles(data);
+ expect(request.isDone()).to.be.true;
});
});
- describe('#assignRoles', function() {
- beforeEach(function() {
- this.data = {
- id: 'user_id'
+ describe('#assignRoles', () => {
+ /**
+ * @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() {
- var _this = this;
- expect(function() {
- _this.users.assignRoles({ id: null }, _this.body, function() {});
+ it('should validate empty user_id', () => {
+ expect(() => {
+ usersManager.assignRoles({ id: null }, 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', () => {
+ expect(() => {
+ 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, {}, function() {
+ 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();
- var request = 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(function(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) {
- var request = this.request;
-
- this.users.assignRoles(this.data, {}).then(function() {
- 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();
- var request = nock(API_URL)
- .post('/users/' + this.data.id + '/roles', this.body)
- .reply(200);
-
- this.users.assignRoles(this.data, this.body).then(function() {
- 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();
- var request = nock(API_URL)
- .post('/users/' + this.data.id + '/roles')
- .matchHeader('Authorization', 'Bearer ' + this.token)
+ const request = nock(API_URL)
+ .post(`/users/${data.id}/roles`)
+ .matchHeader('Authorization', `Bearer ${token}`)
.reply(200);
- this.users.assignRoles(this.data, {}).then(function() {
- expect(request.isDone()).to.be.true;
-
- done();
- });
+ await usersManager.assignRoles(data, {});
+ expect(request.isDone()).to.be.true;
});
});
- describe('#removeRoles', function() {
- beforeEach(function() {
- this.data = {
- id: 'user_id'
+ describe('#removeRoles', () => {
+ /**
+ * @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() {
- var _this = this;
- expect(function() {
- _this.users.removeRoles({ id: null }, this.body, function() {});
+ 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() {
- var _this = this;
- expect(function() {
- _this.users.removeRoles({ id: 123 }, _this.body, function() {});
+ it('should validate non-string user_id', () => {
+ expect(() => {
+ 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, {}, function() {
+ 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();
- var request = 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(function(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) {
- var request = this.request;
-
- this.users.removeRoles(this.data, {}).then(function() {
- 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();
- var request = nock(API_URL)
- .delete('/users/' + this.data.id + '/roles', this.body)
- .reply(200);
-
- this.users.removeRoles(this.data, this.body).then(function() {
- expect(request.isDone()).to.be.true;
+ const request = nock(API_URL).delete(`/users/${data.id}/roles`, body).reply(200);
- 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();
- var request = nock(API_URL)
- .delete('/users/' + this.data.id + '/roles')
- .matchHeader('Authorization', 'Bearer ' + this.token)
+ const request = nock(API_URL)
+ .delete(`/users/${data.id}/roles`)
+ .matchHeader('Authorization', `Bearer ${token}`)
.reply(200);
- this.users.removeRoles(this.data, {}).then(function() {
- expect(request.isDone()).to.be.true;
-
- done();
- });
+ await usersManager.removeRoles(data, {});
+ expect(request.isDone()).to.be.true;
});
});
- 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);
- });
+ /**
+ * @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) {
- var request = this.request;
-
- this.users.getPermissions(data).then(function() {
- 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();
- 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) {
+ 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();
- 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 ${token}`)
.reply(200);
- this.users.getPermissions(data).then(function() {
- expect(request.isDone()).to.be.true;
-
- done();
- });
+ await usersManager.getPermissions(data);
+ expect(request.isDone()).to.be.true;
});
});
- describe('#assignPermissions', function() {
- beforeEach(function() {
- this.data = {
- id: 'user_id'
+ describe('#assignPermissions', () => {
+ /**
+ * @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() {
- var _this = this;
- expect(function() {
- _this.users.assignPermissions({ id: null }, this.body, function() {});
+ 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() {
- var _this = this;
- expect(function() {
- _this.users.assignPermissions({ id: 123 }, _this.body, function() {});
+ it('should validate non-string user_id', () => {
+ expect(() => {
+ 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, {}, function() {
+ 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();
- var request = 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(function(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) {
- var request = this.request;
-
- this.users.assignPermissions(this.data, {}).then(function() {
- 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();
- var request = nock(API_URL)
- .post('/users/' + this.data.id + '/permissions', this.body)
- .reply(200);
-
- this.users.assignPermissions(this.data, this.body).then(function() {
- expect(request.isDone()).to.be.true;
+ const request = nock(API_URL).post(`/users/${data.id}/permissions`, body).reply(200);
- 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();
- var request = nock(API_URL)
- .post('/users/' + this.data.id + '/permissions')
- .matchHeader('Authorization', 'Bearer ' + this.token)
+ const request = nock(API_URL)
+ .post(`/users/${data.id}/permissions`)
+ .matchHeader('Authorization', `Bearer ${token}`)
.reply(200);
- this.users.assignPermissions(this.data, {}).then(function() {
- expect(request.isDone()).to.be.true;
-
- done();
- });
+ await usersManager.assignPermissions(data, {});
+ expect(request.isDone()).to.be.true;
});
});
- describe('#removePermissions', function() {
- beforeEach(function() {
- this.data = {
- id: 'user_id'
+ describe('#removePermissions', () => {
+ /**
+ * @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() {
- var _this = this;
- expect(function() {
- _this.users.removePermissions({ id: null }, this.body, function() {});
+ 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() {
- var _this = this;
- expect(function() {
- _this.users.removePermissions({ id: 123 }, _this.body, function() {});
+ it('should validate non-string user_id', () => {
+ expect(() => {
+ 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, {}, function() {
+ 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();
- var request = 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(function(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) {
- var request = this.request;
-
- this.users.removePermissions(this.data, {}).then(function() {
- 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();
- var request = nock(API_URL)
- .delete('/users/' + this.data.id + '/permissions', this.body)
- .reply(200);
-
- this.users.removePermissions(this.data, this.body).then(function() {
- 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();
- var request = nock(API_URL)
- .delete('/users/' + this.data.id + '/permissions')
- .matchHeader('Authorization', 'Bearer ' + this.token)
+ const request = nock(API_URL)
+ .delete(`/users/${data.id}/permissions`)
+ .matchHeader('Authorization', `Bearer ${token}`)
.reply(200);
- this.users.removePermissions(this.data, {}).then(function() {
- expect(request.isDone()).to.be.true;
-
- done();
- });
+ await usersManager.removePermissions(data, {});
+ expect(request.isDone()).to.be.true;
});
});
- 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);
- });
+ /**
+ * @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) {
- var request = this.request;
-
- this.users.getUserOrganizations(data).then(function() {
- 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();
- 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) {
+ 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();
- 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 ${token}`)
.reply(200);
- this.users.getUserOrganizations(data).then(function() {
- 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 3b7122e58..75a93ebf6 100644
--- a/test/retry-rest-client.tests.js
+++ b/test/retry-rest-client.tests.js
@@ -1,141 +1,129 @@
-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';
Promise.prototype.finally =
Promise.prototype.finally ||
- function(fn) {
- const onFinally = callback => Promise.resolve(fn()).then(callback);
+ function (fn) {
+ const onFinally = (callback) => Promise.resolve(fn()).then(callback);
return this.then(
- result => onFinally(() => result),
- reason => onFinally(() => Promise.reject(reason))
+ (result) => onFinally(() => result),
+ (reason) => onFinally(() => Promise.reject(reason))
);
};
-describe('RetryRestClient', function() {
- before(function() {
- this.restClient = new RestClient(API_URL);
+describe('RetryRestClient', () => {
+ let restClient;
+ before(() => {
+ 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', (done) => {
+ nock(API_URL).get('/').reply(200, { success: true });
- var client = new RetryRestClient(this.restClient);
- client.getAll(function(err, data) {
+ const client = new RetryRestClient(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', async () => {
+ nock(API_URL).get('/').reply(200, { success: true });
- var client = new RetryRestClient(this.restClient);
- client.getAll().then(function(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) {
- nock(API_URL)
- .get('/')
- .reply(500);
+ it('should pass err to callback when provided', (done) => {
+ nock(API_URL).get('/').reply(500);
- var client = new RetryRestClient(this.restClient);
- client.getAll(function(err) {
+ const client = new RetryRestClient(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', async () => {
+ nock(API_URL).get('/').reply(500);
- var client = new RetryRestClient(this.restClient);
- client.getAll().catch(function(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) {
- var self = this;
- var timesCalled = 0;
- var restClientSpy = {
- getAll: function() {
+ it('should retry once when an error is returned', async () => {
+ let timesCalled = 0;
+ const restClientSpy = {
+ getAll(...args) {
timesCalled += 1;
- return self.restClient.getAll(arguments);
- }
+ return 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) {
- expect(data.success).to.be.true;
- expect(timesCalled).to.be.equal(2);
- done();
- });
+ const client = new RetryRestClient(restClientSpy);
+ 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) {
- var self = this;
- var clock = sinon.useFakeTimers();
- var timesCalled = 0;
- var restClientSpy = {
- getAll: function() {
+ 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(arguments).finally(() => {
+ return restClient.getAll(...args).finally(() => {
clock.runAllAsync();
});
- }
+ },
};
nock(API_URL)
@@ -145,69 +133,62 @@ describe('RetryRestClient', function() {
.get('/')
.reply(200, { success: true });
- var client = new RetryRestClient(restClientSpy);
- client.getAll().then(function(data) {
- clock.restore();
- expect(data.success).to.be.true;
- expect(timesCalled).to.be.equal(4);
- done();
- });
+ const client = new RetryRestClient(restClientSpy);
+ 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) {
- 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', async () => {
+ const clock = sinon.useFakeTimers();
+ let timesCalled = 0;
+ const restClientSpy = {
+ getAll(...args) {
timesCalled += 1;
- return self.restClient.getAll(arguments).finally(() => {
+ return 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 });
+ 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) {
- nock(API_URL)
- .get('/')
- .reply(500);
+ it('should not retry when status code is not 429', async () => {
+ nock(API_URL).get('/').reply(500);
- var client = new RetryRestClient(this.restClient);
- client.getAll().catch(function(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) {
- 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', async () => {
+ 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 restClient.getAll(...args).finally(() => {
clock.runAllAsync();
});
- }
+ },
};
nock(API_URL)
@@ -217,106 +198,96 @@ describe('RetryRestClient', function() {
.get('/')
.reply(200, { success: true });
- var client = new RetryRestClient(restClientSpy, { maxRetries: 10 });
-
- client.getAll().then(function(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++) {
- expect(backoffs[i] / 1000).to.be.within(
- Math.pow(2, i),
- 2 * Math.pow(2, i),
- 'attempt ' + (i + 1) + ' in secs'
- );
- }
- done();
- });
+ const client = new RetryRestClient(restClientSpy, { maxRetries: 10 });
+
+ 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) {
- var self = this;
- var timesCalled = 0;
- var restClientSpy = {
- getAll: function() {
+ it('should not retry when retry functionality is disabled', async () => {
+ let timesCalled = 0;
+ const restClientSpy = {
+ getAll(...args) {
timesCalled += 1;
- return self.restClient.getAll(arguments);
- }
+ return 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 });
+ 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', 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 9d620dbdd..5c4dd6d9c 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -99,24 +99,62 @@
"@babel/helper-validator-identifier" "^7.14.9"
to-fast-properties "^2.0.0"
-"@sinonjs/commons@^1.6.0", "@sinonjs/commons@^1.7.0", "@sinonjs/commons@^1.8.1":
+"@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 "2.0.0"
+
+"@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.3.2"
+ espree "^9.0.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"
+
+"@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"
+ minimatch "^3.0.4"
+
+"@humanwhocodes/object-schema@^1.2.0":
+ version "1.2.0"
+ resolved "https://registry.yarnpkg.com/@humanwhocodes/object-schema/-/object-schema-1.2.0.tgz#87de7af9c231826fdd68ac7258f77c429e0e5fcf"
+ 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.yarnpkg.com/@sinonjs/commons/-/commons-1.8.3.tgz#3802ddd21a50a949b6721ddd72da36e67e7f1b2d"
integrity sha512-xkNcLAn/wZaX14RPlwizcKicDk9G3F8m2nU3L7Ukm5zBgTwiT0wsoFAHx9Jq56fJA1z/7uKGtCRu16sOUCLIHQ==
dependencies:
type-detect "4.0.8"
-"@sinonjs/fake-timers@^6.0.0", "@sinonjs/fake-timers@^6.0.1":
- version "6.0.1"
- resolved "https://registry.yarnpkg.com/@sinonjs/fake-timers/-/fake-timers-6.0.1.tgz#293674fccb3262ac782c7aadfdeca86b10c75c40"
- integrity sha512-MZPUxrmFubI36XS1DI3qmI0YdN1gks62JtFZvxR67ljjSNCeK6U08Zx4msEWOXuofgqUt6zPHSi1H9fbjR/NRA==
+"@sinonjs/fake-timers@^7.0.4", "@sinonjs/fake-timers@^7.1.2":
+ version "7.1.2"
+ resolved "https://registry.yarnpkg.com/@sinonjs/fake-timers/-/fake-timers-7.1.2.tgz#2524eae70c4910edccf99b2f4e6efc5894aff7b5"
+ integrity sha512-iQADsW4LBMISqZ6Ci1dupJL9pprqwcVFTcOsEmQOEhW+KLCVn/Y4Jrvg2k19fIHCp+iFprriYPTdRcQR8NbUPg==
dependencies:
"@sinonjs/commons" "^1.7.0"
-"@sinonjs/samsam@^5.3.1":
- version "5.3.1"
- resolved "https://registry.yarnpkg.com/@sinonjs/samsam/-/samsam-5.3.1.tgz#375a45fe6ed4e92fca2fb920e007c48232a6507f"
- integrity sha512-1Hc0b1TtyfBu8ixF/tpfSHTVWKwCBLY4QJbkgnE7HcwyvT2xArDxb4K7dMgqRm3szI+LJbzmW/s4xxEhv6hwDg==
+"@sinonjs/samsam@^6.0.2":
+ version "6.0.2"
+ resolved "https://registry.yarnpkg.com/@sinonjs/samsam/-/samsam-6.0.2.tgz#a0117d823260f282c04bff5f8704bdc2ac6910bb"
+ integrity sha512-jxPRPp9n93ci7b8hMfJOFDPRLFYadN6FSpeROFTR4UNF4i5b+EK6m4QXPO46BDhFgRy1JuS87zAnFOzCUwMJcQ==
dependencies:
"@sinonjs/commons" "^1.6.0"
lodash.get "^4.4.2"
@@ -214,6 +252,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.yarnpkg.com/@webassemblyjs/ast/-/ast-1.9.0.tgz#bd850604b4042459a5a41cd7d338cbed695ed964"
@@ -369,11 +412,21 @@
resolved "https://registry.yarnpkg.com/@xtuc/long/-/long-4.2.2.tgz#d291c6a4e97989b5c61d9acf396ae4fe133a718d"
integrity sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==
+acorn-jsx@^5.3.1:
+ version "5.3.2"
+ resolved "https://registry.yarnpkg.com/acorn-jsx/-/acorn-jsx-5.3.2.tgz#7ed5bb55908b3b2f1bc55c6af1653bada7f07937"
+ integrity sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==
+
acorn@^6.4.1:
version "6.4.2"
resolved "https://registry.yarnpkg.com/acorn/-/acorn-6.4.2.tgz#35866fd710528e92de10cf06016498e47e39e1e6"
integrity sha512-XtGIhXwF8YM8bJhGxG5kXgjkEuNGLTkoYqVE+KMR+aspr4KGYmKYg7yUe3KghyQ9yheNwLnjmzh/7+gfDBmHCQ==
+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"
resolved "https://registry.yarnpkg.com/agent-base/-/agent-base-6.0.2.tgz#49fff58577cfee3f37176feab4c22e00f86d7f77"
@@ -391,7 +444,7 @@ ajv-keywords@^3.1.0, ajv-keywords@^3.4.1:
resolved "https://registry.yarnpkg.com/ajv-keywords/-/ajv-keywords-3.5.2.tgz#31f29da5ab6e00d1c2d329acf7b5929614d5014d"
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.yarnpkg.com/ajv/-/ajv-6.12.6.tgz#baf5a62e802b07d977034586f8c3baf5adf26df4"
integrity sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==
@@ -406,10 +459,10 @@ amdefine@>=0.0.4:
resolved "https://registry.yarnpkg.com/amdefine/-/amdefine-1.0.1.tgz#4a5282ac164729e93619bcfd3ad151f817ce91f5"
integrity sha1-SlKCrBZHKek2Gbz9OtFR+BfOkfU=
-ansi-colors@3.2.3:
- version "3.2.3"
- resolved "https://registry.yarnpkg.com/ansi-colors/-/ansi-colors-3.2.3.tgz#57d35b8686e851e2cc04c403f1c00203976a1813"
- integrity sha512-LEHHyuhlPY3TmuUYMh2oz89lTShfvgbmzaBcxve9t/9Wuy7Dwf4yoAKcND7KFT1HAQfqZ12qtc+DUrBMeKF9nw==
+ansi-colors@4.1.1, ansi-colors@^4.1.1:
+ version "4.1.1"
+ resolved "https://registry.yarnpkg.com/ansi-colors/-/ansi-colors-4.1.1.tgz#cbb9ae256bf750af1eab344f229aa27fe94ba348"
+ integrity sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA==
ansi-regex@^3.0.0:
version "3.0.0"
@@ -421,6 +474,11 @@ ansi-regex@^4.1.0:
resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-4.1.0.tgz#8b9f8f08cf1acb843756a839ca8c7e3168c51997"
integrity sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==
+ansi-regex@^5.0.1:
+ version "5.0.1"
+ resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-5.0.1.tgz#082cb2c89c9fe8659a311a53bd6a4dc5301db304"
+ integrity sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==
+
ansi-styles@^3.2.0, ansi-styles@^3.2.1:
version "3.2.1"
resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-3.2.1.tgz#41fbb20243e50b12be0f04b8dedbf07520ce841d"
@@ -428,6 +486,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.yarnpkg.com/ansi-styles/-/ansi-styles-4.3.0.tgz#edd803628ae71c04c85ae7a0906edad34b648937"
+ integrity sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==
+ dependencies:
+ color-convert "^2.0.1"
+
anymatch@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-2.0.0.tgz#bcb24b4f37934d9aa7ac17b4adaf89e7c76ef2eb"
@@ -436,7 +501,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==
@@ -468,6 +533,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.yarnpkg.com/argv/-/argv-0.0.2.tgz#ecbd16f8949b157183711b1bda334f37840185ab"
@@ -839,6 +909,11 @@ callsites@^2.0.0:
resolved "https://registry.yarnpkg.com/callsites/-/callsites-2.0.0.tgz#06eb84f00eea413da86affefacbffb36093b3c50"
integrity sha1-BuuE8A7qQT2oav/vrL/7Ngk7PFA=
+callsites@^3.0.0:
+ version "3.1.0"
+ resolved "https://registry.yarnpkg.com/callsites/-/callsites-3.1.0.tgz#b3630abd8943432f54b3f0519238e33cd7df2f73"
+ integrity sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==
+
camel-case@^1.1.1:
version "1.2.2"
resolved "https://registry.yarnpkg.com/camel-case/-/camel-case-1.2.2.tgz#1aca7c4d195359a2ce9955793433c6e5542511f2"
@@ -852,6 +927,11 @@ camelcase@^5.0.0:
resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-5.3.1.tgz#e3c9b31569e106811df242f715725a1f4c494320"
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.yarnpkg.com/catharsis/-/catharsis-0.9.0.tgz#40382a168be0e6da308c277d3a2b3eb40c7d2121"
@@ -871,7 +951,7 @@ chai@^4.1.2, chai@^4.2.0:
pathval "^1.1.1"
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.yarnpkg.com/chalk/-/chalk-2.4.2.tgz#cd42541677a54333cf541a49108c1432b44c9424"
integrity sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==
@@ -880,6 +960,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:
+ version "4.1.2"
+ resolved "https://registry.yarnpkg.com/chalk/-/chalk-4.1.2.tgz#aac4e2b7734a740867aeb16bf02aad556a1e7a01"
+ 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.yarnpkg.com/change-case/-/change-case-2.3.1.tgz#2c4fde3f063bb41d00cd68e0d5a09db61cbe894f"
@@ -912,6 +1000,21 @@ 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.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.1"
+ braces "~3.0.2"
+ glob-parent "~5.1.0"
+ is-binary-path "~2.1.0"
+ is-glob "~4.0.1"
+ normalize-path "~3.0.0"
+ readdirp "~3.5.0"
+ optionalDependencies:
+ fsevents "~2.3.1"
+
chokidar@^2.1.8:
version "2.1.8"
resolved "https://registry.yarnpkg.com/chokidar/-/chokidar-2.1.8.tgz#804b3a7b6a99358c3c5c61e71d8728f041cff917"
@@ -988,6 +1091,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.3"
resolved "https://registry.yarnpkg.com/codecov/-/codecov-3.8.3.tgz#9c3e364b8a700c597346ae98418d09880a3fdbe7"
@@ -1014,11 +1126,23 @@ color-convert@^1.9.0:
dependencies:
color-name "1.1.3"
+color-convert@^2.0.1:
+ version "2.0.1"
+ resolved "https://registry.yarnpkg.com/color-convert/-/color-convert-2.0.1.tgz#72d3a68d598c9bdb3af2ad1e84f21d896abd4de3"
+ 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.yarnpkg.com/color-name/-/color-name-1.1.3.tgz#a7d0558bd89c42f795dd42328f740831ca53bc25"
integrity sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=
+color-name@~1.1.4:
+ version "1.1.4"
+ resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.4.tgz#c2a09a87acbde69543de6f63fa3995c826c536a2"
+ integrity sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==
+
combined-stream@^1.0.8:
version "1.0.8"
resolved "https://registry.yarnpkg.com/combined-stream/-/combined-stream-1.0.8.tgz#c3d45a8b34fd730631a110a8a2520682b31d5a7f"
@@ -1031,6 +1155,11 @@ commander@^2.20.0:
resolved "https://registry.yarnpkg.com/commander/-/commander-2.20.3.tgz#fd485e84c03eb4881c20722ba48035e8531aeb33"
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.yarnpkg.com/commondir/-/commondir-1.0.1.tgz#ddd800da0c66127393cca5950ea968a3aaf1253b"
@@ -1195,6 +1324,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.yarnpkg.com/cross-spawn/-/cross-spawn-7.0.3.tgz#f73a85b9d5d41d045551c177e2882d4ac85728a6"
+ 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.yarnpkg.com/crypt/-/crypt-0.0.2.tgz#88d7ff7ec0dfb86f713dc87bbb42d044d3e6c41b"
@@ -1236,20 +1374,20 @@ cyclist@^1.0.1:
resolved "https://registry.yarnpkg.com/cyclist/-/cyclist-1.0.1.tgz#596e9698fd0c80e12038c2b82d6eb1b35b6224d9"
integrity sha1-WW6WmP0MgOEgOMK4LW6xs1tiJNk=
-debug@3.2.6:
- version "3.2.6"
- resolved "https://registry.yarnpkg.com/debug/-/debug-3.2.6.tgz#e83d17de16d8a7efb7717edbe5fb10135eee629b"
- integrity sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==
- dependencies:
- ms "^2.1.1"
-
-debug@4, debug@^4.1.0, debug@^4.1.1:
+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==
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"
@@ -1262,6 +1400,11 @@ decamelize@^1.2.0:
resolved "https://registry.yarnpkg.com/decamelize/-/decamelize-1.2.0.tgz#f6534d15148269b20352e7bee26f501f9a191290"
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.yarnpkg.com/decode-uri-component/-/decode-uri-component-0.2.0.tgz#eb3913333458775cb84cd1a1fae062106bb87545"
@@ -1286,6 +1429,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.yarnpkg.com/deep-is/-/deep-is-0.1.4.tgz#a6f2dce612fadd2ef1f519b73551f17e85199831"
+ integrity sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==
+
deepmerge@^3.2.0:
version "3.3.0"
resolved "https://registry.yarnpkg.com/deepmerge/-/deepmerge-3.3.0.tgz#d3c47fd6f3a93d517b14426b0628a17b0125f5f7"
@@ -1298,7 +1446,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.yarnpkg.com/define-properties/-/define-properties-1.1.3.tgz#cf88da6cbee26fe6db7094f61d870cbd84cee9f1"
integrity sha512-3MqfYKj2lLzdMSf8ZIZE/V+Zuy+BgD6f164e8K2w7dgnpKArBDerGYpM46IYYcjnkdPNMjPk9A6VFB8+3SKlXQ==
@@ -1340,15 +1488,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.yarnpkg.com/diff/-/diff-3.5.0.tgz#800c0dd1e0a8bfbc95835c202ad220fe317e5a12"
- integrity sha512-A46qtFgd+g7pDZinpnwiRJtxbC1hpgf0uzP3iG89scHk0AUC7A1TGxf5OiiOUv/JMZR8GOt8hL900hV0bOy5xA==
-
-diff@^4.0.2:
- version "4.0.2"
- resolved "https://registry.yarnpkg.com/diff/-/diff-4.0.2.tgz#60f3aecb89d5fae520c11aa19efc2bb982aade7d"
- 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"
@@ -1359,6 +1502,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.yarnpkg.com/doctrine/-/doctrine-3.0.0.tgz#addebead72a6574db783639dc87a121773973961"
+ integrity sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==
+ dependencies:
+ esutils "^2.0.2"
+
domain-browser@^1.1.1:
version "1.2.0"
resolved "https://registry.yarnpkg.com/domain-browser/-/domain-browser-1.2.0.tgz#3d31f50191a6749dd1375a7f522e823d42e54eda"
@@ -1406,6 +1556,11 @@ emoji-regex@^7.0.1:
resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-7.0.3.tgz#933a04052860c85e83c122479c4748a8e4c72156"
integrity sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==
+emoji-regex@^8.0.0:
+ version "8.0.0"
+ resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-8.0.0.tgz#e818fd69ce5ccfcb404594f842963bf53164cc37"
+ integrity sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==
+
emojis-list@^2.0.0:
version "2.1.0"
resolved "https://registry.yarnpkg.com/emojis-list/-/emojis-list-2.1.0.tgz#4daa4d9db00f9819880c79fa457ae5b09a1fd389"
@@ -1432,6 +1587,13 @@ enhanced-resolve@^4.5.0:
memory-fs "^0.5.0"
tapable "^1.0.0"
+enquirer@^2.3.5:
+ version "2.3.6"
+ resolved "https://registry.yarnpkg.com/enquirer/-/enquirer-2.3.6.tgz#2a7fe5dd634a1e4125a975ec994ff5456dc3734d"
+ integrity sha512-yjNnPr315/FjS4zIsUxYguYUPP2e1NK4d7E7ZOLiyYCcbFBiTMyID+2wvm2w6+pZ/odMA7cRkjhsPbltwBOrLg==
+ dependencies:
+ ansi-colors "^4.1.1"
+
entities@~2.0.0:
version "2.0.3"
resolved "https://registry.yarnpkg.com/entities/-/entities-2.0.3.tgz#5c487e5742ab93c15abb5da22759b8590ec03b7f"
@@ -1451,52 +1613,27 @@ error-ex@^1.3.1:
dependencies:
is-arrayish "^0.2.1"
-es-abstract@^1.19.1:
- version "1.19.1"
- resolved "https://registry.yarnpkg.com/es-abstract/-/es-abstract-1.19.1.tgz#d4885796876916959de78edaa0df456627115ec3"
- integrity sha512-2vJ6tjA/UfqLm2MPs7jxVybLoB8i1t1Jd9R3kISld20sIxPcTbLuggQOUxeWeAvIUkduv/CfMjuh4WmiXr2v9w==
- dependencies:
- call-bind "^1.0.2"
- es-to-primitive "^1.2.1"
- function-bind "^1.1.1"
- get-intrinsic "^1.1.1"
- get-symbol-description "^1.0.0"
- has "^1.0.3"
- has-symbols "^1.0.2"
- internal-slot "^1.0.3"
- is-callable "^1.2.4"
- is-negative-zero "^2.0.1"
- is-regex "^1.1.4"
- is-shared-array-buffer "^1.0.1"
- is-string "^1.0.7"
- is-weakref "^1.0.1"
- object-inspect "^1.11.0"
- object-keys "^1.1.1"
- object.assign "^4.1.2"
- string.prototype.trimend "^1.0.4"
- string.prototype.trimstart "^1.0.4"
- unbox-primitive "^1.0.1"
-
-es-to-primitive@^1.2.1:
- version "1.2.1"
- resolved "https://registry.yarnpkg.com/es-to-primitive/-/es-to-primitive-1.2.1.tgz#e55cd4c9cdc188bcefb03b366c736323fc5c898a"
- 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.yarnpkg.com/es6-error/-/es6-error-4.1.1.tgz#9e3af407459deed47e9a91f9b885a84eb05c561d"
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.yarnpkg.com/es6-promisify/-/es6-promisify-6.1.1.tgz#46837651b7b06bf6fff893d03f29393668d01621"
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.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz#14ba83a5d373e3d311e5afca29cf5bfad965bf34"
+ integrity sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==
+
+escape-string-regexp@^1.0.5:
version "1.0.5"
resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz#1b61c0562190a8dff6ae3bb2cf0200ca130b86d4"
integrity sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=
@@ -1506,6 +1643,58 @@ escape-string-regexp@^2.0.0:
resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz#a30304e99daa32e23b2fd20f51babd07cffca344"
integrity sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==
+eslint-config-prettier@^8.3.0:
+ version "8.3.0"
+ resolved "https://registry.yarnpkg.com/eslint-config-prettier/-/eslint-config-prettier-8.3.0.tgz#f7471b20b6fe8a9a9254cc684454202886a2dd7a"
+ 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@^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.12.0"
+ comment-parser "1.2.4"
+ debug "^4.3.2"
+ esquery "^1.4.0"
+ jsdoc-type-pratt-parser "^2.0.0"
+ 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.yarnpkg.com/eslint-plugin-prettier/-/eslint-plugin-prettier-4.0.0.tgz#8b99d1e4b8b24a762472b4567992023619cb98e0"
+ integrity sha512-98MqmCJ7vJodoQK359bqQWaxOE0CS8paAz/GgjaZLyex4TTk3g9HugoO89EqWCrFiOqn9EVvcoo7gZzONCWVwQ==
+ dependencies:
+ prettier-linter-helpers "^1.0.0"
+
+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"
resolved "https://registry.yarnpkg.com/eslint-scope/-/eslint-scope-4.0.3.tgz#ca03833310f6889a3264781aa82e63eb9cfe7848"
@@ -1514,12 +1703,109 @@ eslint-scope@^4.0.3:
esrecurse "^4.1.0"
estraverse "^4.1.1"
+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 "^5.2.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-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==
+
+eslint-visitor-keys@^2.0.0:
+ version "2.1.0"
+ resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-2.1.0.tgz#f65328259305927392c938ed44eb0a5c9b2bd303"
+ integrity sha512-0rSmRBzXgDzIsD6mGdJgevzgezI534Cer5L/vyMX0kHzT/jiB43jRhd9YUlMGYLQy2zprNmoT8qasCGtY+QaKw==
+
+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:
+ "@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.3.2"
+ doctrine "^3.0.0"
+ enquirer "^2.3.5"
+ escape-string-regexp "^4.0.0"
+ 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 "^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 "^4.1.0"
+ 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.2.0"
+ semver "^7.2.1"
+ strip-ansi "^6.0.0"
+ strip-json-comments "^3.1.0"
+ text-table "^0.2.0"
+ v8-compile-cache "^2.0.3"
+
+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 "^8.5.0"
+ acorn-jsx "^5.3.1"
+ eslint-visitor-keys "^3.0.0"
+
esprima@^4.0.0:
version "4.0.1"
resolved "https://registry.yarnpkg.com/esprima/-/esprima-4.0.1.tgz#13b04cdb3e6c5d19df91ab6987a8695619b0aa71"
integrity sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==
-esrecurse@^4.1.0:
+esquery@^1.4.0:
+ version "1.4.0"
+ resolved "https://registry.yarnpkg.com/esquery/-/esquery-1.4.0.tgz#2148ffc38b82e8c7057dfed48425b3e61f0f24a5"
+ integrity sha512-cCDispWt5vHHtwMY2YrAQ4ibFkAL8RbH5YGBnZBc90MolvvfkkQcJro/aZiAQUlQ3qgrYS6D6v8Gc5G5CQsc9w==
+ dependencies:
+ estraverse "^5.1.0"
+
+esrecurse@^4.1.0, esrecurse@^4.3.0:
version "4.3.0"
resolved "https://registry.yarnpkg.com/esrecurse/-/esrecurse-4.3.0.tgz#7ad7964d679abb28bee72cec63758b1c5d2c9921"
integrity sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==
@@ -1531,11 +1817,16 @@ estraverse@^4.1.1:
resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-4.3.0.tgz#398ad3f3c5a24948be7725e83d11a7de28cdbd1d"
integrity sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==
-estraverse@^5.2.0:
+estraverse@^5.1.0, estraverse@^5.2.0:
version "5.2.0"
resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-5.2.0.tgz#307df42547e6cc7324d3cf03c155d5cdb8c53880"
integrity sha512-BxbNGGNm0RyRYvUdHpIwv9IWzeM9XClbOxwoATuFdOE7ZE6wHL+HQ5T8hoPM+zHvmKzzsEqhgy0GrQ5X13afiQ==
+esutils@^2.0.2:
+ version "2.0.3"
+ resolved "https://registry.yarnpkg.com/esutils/-/esutils-2.0.3.tgz#74d2eb4de0b8da1293711910d50775b9b710ef64"
+ integrity sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==
+
events@^3.0.0:
version "3.3.0"
resolved "https://registry.yarnpkg.com/events/-/events-3.3.0.tgz#31a95ad0a924e2d2c419a813aeb2c4e878ea7400"
@@ -1617,16 +1908,26 @@ 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.yarnpkg.com/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz#3a7d56b559d6cbc3eb512325244e619a65c6c525"
integrity sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==
+fast-diff@^1.1.2:
+ version "1.2.0"
+ resolved "https://registry.yarnpkg.com/fast-diff/-/fast-diff-1.2.0.tgz#73ee11982d86caaf7959828d519cfe927fac5f03"
+ integrity sha512-xJuoT5+L99XlZ8twedaRf6Ax2TgQVxvgZOYoPKqZufmJib0tL2tegPBOZb1pVNgIhlqDlA0eO0c3wBvQcmzx4w==
+
fast-json-stable-stringify@^2.0.0:
version "2.1.0"
resolved "https://registry.yarnpkg.com/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz#874bf69c6f404c2b5d99c481341399fd55892633"
integrity sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==
+fast-levenshtein@^2.0.6:
+ version "2.0.6"
+ resolved "https://registry.yarnpkg.com/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz#3d8a5c66883a16a30ca8643e851f19baa7797917"
+ integrity sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=
+
fast-safe-stringify@^2.0.7:
version "2.1.1"
resolved "https://registry.yarnpkg.com/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz#c406a83b6e70d9e35ce3b30a81141df30aeba884"
@@ -1644,6 +1945,13 @@ figgy-pudding@^3.5.1:
resolved "https://registry.yarnpkg.com/figgy-pudding/-/figgy-pudding-3.5.2.tgz#b4eee8148abb01dcf1d1ac34367d59e12fa61d6e"
integrity sha512-0btnI/H8f2pavGMN8w40mlSKOfTK2SVJmBfBeVIj3kNw0swwgzyRq0d5TJVOwodFmtvpPeWPN/MCcfuWF0Ezbw==
+file-entry-cache@^6.0.1:
+ version "6.0.1"
+ resolved "https://registry.yarnpkg.com/file-entry-cache/-/file-entry-cache-6.0.1.tgz#211b2dd9659cb0394b073e7323ac3c933d522027"
+ integrity sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==
+ dependencies:
+ flat-cache "^3.0.4"
+
file-loader@^0.8.1:
version "0.8.5"
resolved "https://registry.yarnpkg.com/file-loader/-/file-loader-0.8.5.tgz#9275d031fe780f27d47f5f4af02bd43713cc151b"
@@ -1690,12 +1998,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.yarnpkg.com/find-up/-/find-up-3.0.0.tgz#49169f1d7993430646da61ecc5ae355c21c97b73"
- 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"
@@ -1704,6 +2013,13 @@ find-up@^2.1.0:
dependencies:
locate-path "^2.0.0"
+find-up@^3.0.0:
+ version "3.0.0"
+ resolved "https://registry.yarnpkg.com/find-up/-/find-up-3.0.0.tgz#49169f1d7993430646da61ecc5ae355c21c97b73"
+ integrity sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==
+ dependencies:
+ locate-path "^3.0.0"
+
find-up@^4.0.0:
version "4.1.0"
resolved "https://registry.yarnpkg.com/find-up/-/find-up-4.1.0.tgz#97afe7d6cdc0bc5928584b7c8d7b16e8a9aa5d19"
@@ -1712,12 +2028,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.yarnpkg.com/flat/-/flat-4.1.1.tgz#a392059cc382881ff98642f5da4dde0a959f309b"
- integrity sha512-FmTtBsHskrU6FJ2VxCnsDb84wu9zhmO3cUX2kGFb5tuwhfXxGciiT0oRY+cck35QmG+NmGh5eLz6lLCpWTqwpA==
+flat-cache@^3.0.4:
+ version "3.0.4"
+ resolved "https://registry.yarnpkg.com/flat-cache/-/flat-cache-3.0.4.tgz#61b0338302b2fe9f957dcc32fc2a87f1c3048b11"
+ 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.yarnpkg.com/flatted/-/flatted-3.2.2.tgz#64bfed5cb68fe3ca78b3eb214ad97b63bedce561"
+ integrity sha512-JaTY/wtrcSyvXJl4IMFHPKyFur1sE9AUqc0QnhOaJ0CxHtAoIV8pYDzeEfAaNEtGkOfq4gr3LBFmdXW5mOQFnA==
flush-write-stream@^1.0.0:
version "1.1.1"
@@ -1797,7 +2124,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==
@@ -1807,7 +2134,12 @@ function-bind@^1.1.1:
resolved "https://registry.yarnpkg.com/function-bind/-/function-bind-1.1.1.tgz#a56899d3ea3c9bab874bb9773b7c5ede92f4895d"
integrity sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==
-get-caller-file@^2.0.1:
+functional-red-black-tree@^1.0.1:
+ version "1.0.1"
+ resolved "https://registry.yarnpkg.com/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz#1b0ab3bd553b2a0d6399d29c0e3ea0b252078327"
+ integrity sha1-GwqzvVU7Kg1jmdKcDj6gslIHgyc=
+
+get-caller-file@^2.0.1, get-caller-file@^2.0.5:
version "2.0.5"
resolved "https://registry.yarnpkg.com/get-caller-file/-/get-caller-file-2.0.5.tgz#4f94412a82db32f36e3b0b9741f8a97feb031f7e"
integrity sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==
@@ -1817,7 +2149,7 @@ get-func-name@^2.0.0:
resolved "https://registry.yarnpkg.com/get-func-name/-/get-func-name-2.0.0.tgz#ead774abee72e20409433a066366023dd6887a41"
integrity sha1-6td0q+5y4gQJQzoGY2YCPdaIekE=
-get-intrinsic@^1.0.2, get-intrinsic@^1.1.0, get-intrinsic@^1.1.1:
+get-intrinsic@^1.0.2:
version "1.1.1"
resolved "https://registry.yarnpkg.com/get-intrinsic/-/get-intrinsic-1.1.1.tgz#15f59f376f855c446963948f0d24cd3637b4abc6"
integrity sha512-kWZrnVM42QCiEA2Ig1bG8zjoIMOgxWwYCEeNdwY6Tv/cOSeGpcoX4pXHfKUxNKVoArnrEr2e9srnAxxGIraS9Q==
@@ -1843,14 +2175,6 @@ get-stream@^4.0.0:
dependencies:
pump "^3.0.0"
-get-symbol-description@^1.0.0:
- version "1.0.0"
- resolved "https://registry.yarnpkg.com/get-symbol-description/-/get-symbol-description-1.0.0.tgz#7fdb81c900101fbd564dd5f1a30af5aadc1e58d6"
- integrity sha512-2EmdH1YvIQiZpltCNgkuiUnyukzxM/R6NDJX31Ke3BG1Nq5b0S2PhX59UKi9vZpPDQVdqn+1IcaAwnzTT5vCjw==
- dependencies:
- call-bind "^1.0.2"
- get-intrinsic "^1.1.1"
-
get-value@^2.0.3, get-value@^2.0.6:
version "2.0.6"
resolved "https://registry.yarnpkg.com/get-value/-/get-value-2.0.6.tgz#dc15ca1c672387ca76bd37ac0a395ba2042a2c28"
@@ -1864,17 +2188,24 @@ glob-parent@^3.1.0:
is-glob "^3.1.0"
path-dirname "^1.0.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==
dependencies:
is-glob "^4.0.1"
-glob@7.1.3:
- version "7.1.3"
- resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.3.tgz#3960832d3f1574108342dafd3a67b332c0969df1"
- integrity sha512-vcfuiIxogLV4DlGBHIUOwI0IbrJ8HWPc4MU7HzviGeNho/UJDfi6B5p3sHeWIQ0KGIU0Jpxi5ZHxemQfLkkAwQ==
+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"
@@ -1900,6 +2231,13 @@ globals@^11.1.0:
resolved "https://registry.yarnpkg.com/globals/-/globals-11.12.0.tgz#ab8795338868a0babd8525758018c2a7eb95c42e"
integrity sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==
+globals@^13.6.0, globals@^13.9.0:
+ version "13.11.0"
+ resolved "https://registry.yarnpkg.com/globals/-/globals-13.11.0.tgz#40ef678da117fe7bd2e28f1fab24951bd0255be7"
+ 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.9:
version "4.2.8"
resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.8.tgz#e412b8d33f5e006593cbd3cee6df9f2cebbe802a"
@@ -1910,11 +2248,6 @@ growl@1.10.5:
resolved "https://registry.yarnpkg.com/growl/-/growl-1.10.5.tgz#f2735dc2283674fa67478b10181059355c369e5e"
integrity sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA==
-has-bigints@^1.0.1:
- version "1.0.1"
- resolved "https://registry.yarnpkg.com/has-bigints/-/has-bigints-1.0.1.tgz#64fe6acb020673e3b78db035a5af69aa9d07b113"
- integrity sha512-LSBS2LjbNBTf6287JEbEzvJgftkF5qFkmCo9hDRpAzKhUOlJ+hx8dd4USs00SgsUNwc4617J9ki5YtEClM2ffA==
-
has-flag@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-3.0.0.tgz#b5d454dc2199ae225699f3467e5a07f3b955bafd"
@@ -1925,7 +2258,7 @@ has-flag@^4.0.0:
resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-4.0.0.tgz#944771fd9c81c81265c4d6941860da06bb59479b"
integrity sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==
-has-symbols@^1.0.0, has-symbols@^1.0.1, has-symbols@^1.0.2:
+has-symbols@^1.0.1, has-symbols@^1.0.2:
version "1.0.2"
resolved "https://registry.yarnpkg.com/has-symbols/-/has-symbols-1.0.2.tgz#165d3070c00309752a1236a479331e3ac56f1423"
integrity sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==
@@ -2084,6 +2417,16 @@ ignore@^3.3.7:
resolved "https://registry.yarnpkg.com/ignore/-/ignore-3.3.10.tgz#0a97fb876986e8081c631160f8f9f389157f0043"
integrity sha512-Pgs951kaMm5GXP7MOvxERINe3gsaVjUWFm+UZPSq9xYriQAksyhg0csnS0KXSNRD5NmNdapXEpjxG49+AKh/ug==
+ignore@^4.0.6:
+ version "4.0.6"
+ resolved "https://registry.yarnpkg.com/ignore/-/ignore-4.0.6.tgz#750e3db5862087b4737ebac8207ffd1ef27b25fc"
+ 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.yarnpkg.com/import-fresh/-/import-fresh-2.0.0.tgz#d81355c15612d386c61f9ddd3922d4304822a546"
@@ -2092,6 +2435,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.yarnpkg.com/import-fresh/-/import-fresh-3.3.0.tgz#37162c25fcb9ebaa2e6e53d5b4d88ce17d9e0c2b"
+ 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.yarnpkg.com/imurmurhash/-/imurmurhash-0.1.4.tgz#9218b9b2b928a238b13dc4fb6b6d576f231453ea"
@@ -2125,15 +2476,6 @@ inherits@2.0.3:
resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.3.tgz#633c2c83e3da42a502f52466022480f4208261de"
integrity sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=
-internal-slot@^1.0.3:
- version "1.0.3"
- resolved "https://registry.yarnpkg.com/internal-slot/-/internal-slot-1.0.3.tgz#7347e307deeea2faac2ac6205d4bc7d34967f59c"
- integrity sha512-O0DB1JC/sPyZl7cIo78n5dR7eUSwwpYPiXRhTzNxZVAMUuB8vlnRFyLxdrVToks6XPLVnFfbzaVd5WLjhgg+vA==
- dependencies:
- get-intrinsic "^1.1.0"
- has "^1.0.3"
- side-channel "^1.0.4"
-
is-accessor-descriptor@^0.1.6:
version "0.1.6"
resolved "https://registry.yarnpkg.com/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz#a9e12cb3ae8d876727eeef3843f8a0897b5c98d6"
@@ -2161,13 +2503,6 @@ is-arrayish@^0.2.1:
resolved "https://registry.yarnpkg.com/is-arrayish/-/is-arrayish-0.2.1.tgz#77c99840527aa8ecb1a8ba697b80645a7a926a9d"
integrity sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0=
-is-bigint@^1.0.1:
- version "1.0.4"
- resolved "https://registry.yarnpkg.com/is-bigint/-/is-bigint-1.0.4.tgz#08147a1875bc2b32005d41ccd8291dffc6691df3"
- integrity sha512-zB9CruMamjym81i2JZ3UMn54PKGsQzsJeo6xvN3HJJ4CAsQNB6iRutp2To77OfCNuoxspsIhzaPoO1zyCEhFOg==
- dependencies:
- has-bigints "^1.0.1"
-
is-binary-path@^1.0.0:
version "1.0.1"
resolved "https://registry.yarnpkg.com/is-binary-path/-/is-binary-path-1.0.1.tgz#75f16642b480f187a711c814161fd3a4a7655898"
@@ -2182,29 +2517,11 @@ is-binary-path@~2.1.0:
dependencies:
binary-extensions "^2.0.0"
-is-boolean-object@^1.1.0:
- version "1.1.2"
- resolved "https://registry.yarnpkg.com/is-boolean-object/-/is-boolean-object-1.1.2.tgz#5c6dc200246dd9321ae4b885a114bb1f75f63719"
- integrity sha512-gDYaKHJmnj4aWxyj6YHyXVpdQawtVLHU5cb+eztPGczf6cjuTdwve5ZIEfgXqH4e57An1D1AKf8CZ3kYrQRqYA==
- dependencies:
- call-bind "^1.0.2"
- has-tostringtag "^1.0.0"
-
is-buffer@^1.1.5, is-buffer@~1.1.6:
version "1.1.6"
resolved "https://registry.yarnpkg.com/is-buffer/-/is-buffer-1.1.6.tgz#efaa2ea9daa0d7ab2ea13a97b2b8ad51fefbe8be"
integrity sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==
-is-buffer@~2.0.3:
- version "2.0.5"
- resolved "https://registry.yarnpkg.com/is-buffer/-/is-buffer-2.0.5.tgz#ebc252e400d22ff8d77fa09888821a24a658c191"
- integrity sha512-i2R6zNFDwgEHJyQUtJEk0XFi1i0dPFn/oqjK3/vPCcDeJvW5NQ83V8QbicfF1SupOaB0h8ntgBC2YiE7dfyctQ==
-
-is-callable@^1.1.4, is-callable@^1.2.4:
- version "1.2.4"
- resolved "https://registry.yarnpkg.com/is-callable/-/is-callable-1.2.4.tgz#47301d58dd0259407865547853df6d61fe471945"
- integrity sha512-nsuwtxZfMX67Oryl9LCQ+upnC0Z0BgpwntpS89m1H/TLF0zNfzfLMV/9Wa/6MZsj0acpEjAO0KF1xT6ZdLl95w==
-
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"
@@ -2278,6 +2595,11 @@ is-fullwidth-code-point@^2.0.0:
resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz#a3b30a5c4f199183167aaab93beefae3ddfb654f"
integrity sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=
+is-fullwidth-code-point@^3.0.0:
+ version "3.0.0"
+ resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz#f116f8064fe90b3f7844a38997c0b75051269f1d"
+ integrity sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==
+
is-glob@^3.1.0:
version "3.1.0"
resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-3.1.0.tgz#7ba5ae24217804ac70707b96922567486cc3e84a"
@@ -2285,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==
@@ -2299,18 +2621,6 @@ is-lower-case@^1.1.0:
dependencies:
lower-case "^1.1.0"
-is-negative-zero@^2.0.1:
- version "2.0.1"
- resolved "https://registry.yarnpkg.com/is-negative-zero/-/is-negative-zero-2.0.1.tgz#3de746c18dda2319241a53675908d8f766f11c24"
- integrity sha512-2z6JzQvZRa9A2Y7xC6dQQm4FSTSTNWjKIYYTt4246eMTJmIo0Q+ZyOsU66X8lxK1AbB92dFeglPLrhwpeRKO6w==
-
-is-number-object@^1.0.4:
- version "1.0.6"
- resolved "https://registry.yarnpkg.com/is-number-object/-/is-number-object-1.0.6.tgz#6a7aaf838c7f0686a50b4553f7e54a96494e89f0"
- integrity sha512-bEVOqiRcvo3zO1+G2lVMy+gkkEm9Yh7cDMRusKKu5ZJKPUYSJwICTKZrNKHA2EbSP0Tu0+6B/emsYNHZyn6K8g==
- dependencies:
- has-tostringtag "^1.0.0"
-
is-number@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/is-number/-/is-number-3.0.0.tgz#24fd6201a4782cf50561c810276afc7d12d71195"
@@ -2328,6 +2638,11 @@ is-object@~1.0.1:
resolved "https://registry.yarnpkg.com/is-object/-/is-object-1.0.2.tgz#a56552e1c665c9e950b4a025461da87e72f86fcf"
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.yarnpkg.com/is-plain-object/-/is-plain-object-2.0.4.tgz#2c163b3fafb1b606d9d17928f05c2a1c38e07677"
@@ -2335,7 +2650,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.4:
+is-regex@^1.0.4:
version "1.1.4"
resolved "https://registry.yarnpkg.com/is-regex/-/is-regex-1.1.4.tgz#eef5663cd59fa4c0ae339505323df6854bb15958"
integrity sha512-kvRdxDsxZjhzUX07ZnLydzS1TU/TJlTUHHY4YLL87e37oUA49DfkLqgy+VjFocowy29cKvcSiu+kIv728jTTVg==
@@ -2343,30 +2658,11 @@ is-regex@^1.0.4, is-regex@^1.1.4:
call-bind "^1.0.2"
has-tostringtag "^1.0.0"
-is-shared-array-buffer@^1.0.1:
- version "1.0.1"
- resolved "https://registry.yarnpkg.com/is-shared-array-buffer/-/is-shared-array-buffer-1.0.1.tgz#97b0c85fbdacb59c9c446fe653b82cf2b5b7cfe6"
- integrity sha512-IU0NmyknYZN0rChcKhRO1X8LYz5Isj/Fsqh8NJOSf+N/hCOTwy29F32Ik7a+QszE63IdvmwdTPDd6cZ5pg4cwA==
-
is-stream@^1.0.1, is-stream@^1.1.0:
version "1.1.0"
resolved "https://registry.yarnpkg.com/is-stream/-/is-stream-1.1.0.tgz#12d4a3dd4e68e0b79ceb8dbc84173ae80d91ca44"
integrity sha1-EtSj3U5o4Lec6428hBc66A2RykQ=
-is-string@^1.0.5, is-string@^1.0.7:
- version "1.0.7"
- resolved "https://registry.yarnpkg.com/is-string/-/is-string-1.0.7.tgz#0dd12bf2006f255bb58f695110eff7491eebc0fd"
- integrity sha512-tE2UXzivje6ofPW7l23cjDOMa09gb7xlAqG6jG5ej6uPV32TlWP3NKPigtaGeHNu9fohccRYvIiZMfOOnOYUtg==
- dependencies:
- has-tostringtag "^1.0.0"
-
-is-symbol@^1.0.2, is-symbol@^1.0.3:
- version "1.0.4"
- resolved "https://registry.yarnpkg.com/is-symbol/-/is-symbol-1.0.4.tgz#a6dac93b635b063ca6872236de88910a57af139c"
- integrity sha512-C/CPBqKWnvdcxqIARxyOh4v1UUEOCHpgDa0WYgpKDFMszcrPcffg5uhwSgPCLD2WWxmq6isisz87tzT01tuGhg==
- dependencies:
- has-symbols "^1.0.2"
-
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"
@@ -2374,13 +2670,6 @@ is-upper-case@^1.1.0:
dependencies:
upper-case "^1.1.0"
-is-weakref@^1.0.1:
- version "1.0.1"
- resolved "https://registry.yarnpkg.com/is-weakref/-/is-weakref-1.0.1.tgz#842dba4ec17fa9ac9850df2d6efbc1737274f2a2"
- integrity sha512-b2jKc2pQZjaeFYWEf7ScFj+Be1I+PXmlu572Q8coTXZ+LD/QQZ7ShPMst8h16riVgyXTQwUsFEl74mDvc/3MHQ==
- dependencies:
- call-bind "^1.0.0"
-
is-windows@^1.0.2:
version "1.0.2"
resolved "https://registry.yarnpkg.com/is-windows/-/is-windows-1.0.2.tgz#d1850eb9791ecd18e6182ce12a30f396634bb19d"
@@ -2475,14 +2764,6 @@ js-tokens@^4.0.0:
resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-4.0.0.tgz#19203fb59991df98e3a287050d4647cdeaf32499"
integrity sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==
-js-yaml@3.13.1:
- version "3.13.1"
- resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.13.1.tgz#aff151b30bfdfa8e49e05da22e7415e9dfa37847"
- integrity sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw==
- dependencies:
- argparse "^1.0.7"
- esprima "^4.0.0"
-
js-yaml@3.14.1, js-yaml@^3.13.1:
version "3.14.1"
resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.14.1.tgz#dae812fdb3825fa306609a8717383c50c36a0537"
@@ -2491,6 +2772,20 @@ js-yaml@3.14.1, js-yaml@^3.13.1:
argparse "^1.0.7"
esprima "^4.0.0"
+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"
+
+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"
@@ -2498,7 +2793,12 @@ js2xmlparser@^4.0.1:
dependencies:
xmlcreate "^2.0.3"
-jsdoc@^3.6.3:
+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.7:
version "3.6.7"
resolved "https://registry.yarnpkg.com/jsdoc/-/jsdoc-3.6.7.tgz#00431e376bed7f9de4716c6f15caa80e64492b89"
integrity sha512-sxKt7h0vzCd+3Y81Ey2qinupL6DpRSZJclS04ugHDNmRUXGzqicMJ6iwayhSA0S0DwwX30c5ozyUthr1QKF6uw==
@@ -2543,6 +2843,11 @@ 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-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"
+ integrity sha1-nbe1lJatPzz+8wp1FC0tkwrXJlE=
+
json-stringify-safe@^5.0.1:
version "5.0.1"
resolved "https://registry.yarnpkg.com/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz#1296a2d58fd45f19a0f6ce01d65701e2c735b6eb"
@@ -2645,6 +2950,14 @@ klaw@^3.0.0:
dependencies:
graceful-fs "^4.1.9"
+levn@^0.4.1:
+ version "0.4.1"
+ resolved "https://registry.yarnpkg.com/levn/-/levn-0.4.1.tgz#ae4562c007473b932a6200d403268dd2fffc6ade"
+ integrity sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==
+ dependencies:
+ prelude-ls "^1.2.1"
+ type-check "~0.4.0"
+
limiter@^1.1.5:
version "1.1.5"
resolved "https://registry.yarnpkg.com/limiter/-/limiter-1.1.5.tgz#8f92a25b3b16c6131293a0cc834b4a838a2aa7c2"
@@ -2719,6 +3032,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.yarnpkg.com/lodash.clonedeep/-/lodash.clonedeep-4.5.0.tgz#e23f3f9c4f8fbdde872529c1071857a086e5ccef"
@@ -2764,22 +3084,27 @@ lodash.isstring@^4.0.1:
resolved "https://registry.yarnpkg.com/lodash.isstring/-/lodash.isstring-4.0.1.tgz#d527dfb5456eca7cc9bb95d5daeaf88ba54a5451"
integrity sha1-1SfftUVuynzJu5XV2ur4i6VKVFE=
+lodash.merge@^4.6.2:
+ version "4.6.2"
+ resolved "https://registry.yarnpkg.com/lodash.merge/-/lodash.merge-4.6.2.tgz#558aa53b43b661e1925a0afdfa36a9a1085fe57a"
+ integrity sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==
+
lodash.once@^4.0.0:
version "4.1.1"
resolved "https://registry.yarnpkg.com/lodash.once/-/lodash.once-4.1.1.tgz#0dd3971213c7c56df880977d504c88fb471a97ac"
integrity sha1-DdOXEhPHxW34gJd9UEyI+0cal6w=
-lodash@^4.17.14, lodash@^4.17.15, lodash@^4.17.5:
+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"
integrity sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==
-log-symbols@2.2.0:
- version "2.2.0"
- resolved "https://registry.yarnpkg.com/log-symbols/-/log-symbols-2.2.0.tgz#5740e1c5d6f0dfda4ad9323b5332107ef6b4c40a"
- integrity sha512-VeIAFslyIerEJLXHziedo2basKbMKtTw3vfn5IzG0XTjhAVEJyNHnL2p7vc+wBDSdQuUpNw3M2u6xb9QsAY5Eg==
+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 "^2.0.1"
+ chalk "^4.0.0"
lower-case-first@^1.0.0:
version "1.0.2"
@@ -3023,13 +3348,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.yarnpkg.com/mkdirp/-/mkdirp-0.5.4.tgz#fd01504a6797ec5c9be81ff43d204961ed64a512"
- 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.yarnpkg.com/mkdirp/-/mkdirp-0.5.5.tgz#d91cefd62d1436ca0f41620e251288d420099def"
@@ -3042,10 +3360,10 @@ mkdirp@^1.0.4:
resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-1.0.4.tgz#3eb5ed62622756d79a5f0e2a221dfebad75c2f7e"
integrity sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==
-mocha-junit-reporter@^1.23.1:
- version "1.23.3"
- resolved "https://registry.yarnpkg.com/mocha-junit-reporter/-/mocha-junit-reporter-1.23.3.tgz#941e219dd759ed732f8641e165918aa8b167c981"
- 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"
@@ -3053,45 +3371,42 @@ 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.yarnpkg.com/mocha/-/mocha-6.2.3.tgz#e648432181d8b99393410212664450a4c1e31912"
- integrity sha512-0R/3FvjIGH3eEuG17ccFPk117XL2rWxatr81a57D+r/x2uTYZRbdZ4oVidEUMh2W2TJDa7MdAb12Lm2/qrKajg==
+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:
- 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.1"
+ debug "4.3.1"
+ diff "5.0.0"
+ escape-string-regexp "4.0.0"
+ find-up "5.0.0"
+ glob "7.1.6"
growl "1.10.5"
he "1.2.0"
- js-yaml "3.13.1"
- log-symbols "2.2.0"
+ js-yaml "4.0.0"
+ log-symbols "4.0.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"
+ ms "2.1.3"
+ nanoid "3.1.20"
+ serialize-javascript "5.0.1"
+ strip-json-comments "3.1.1"
+ supports-color "8.1.1"
+ which "2.0.2"
wide-align "1.1.3"
- yargs "13.3.2"
- yargs-parser "13.1.2"
- yargs-unparser "1.6.0"
+ workerpool "6.1.0"
+ 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.yarnpkg.com/module-not-found-error/-/module-not-found-error-1.0.1.tgz#cf8b4ff4f29640674d6cdd02b0e3bc523c2bbdc0"
integrity sha1-z4tP9PKWQGdNbN0CsOO8UjwrvcA=
-moment@^2.24.0:
- version "2.29.1"
- resolved "https://registry.yarnpkg.com/moment/-/moment-2.29.1.tgz#b2be769fa31940be9eeea6469c075e35006fa3d3"
- integrity sha512-kHmoybcPV8Sqy59DwNDY3Jefr64lK/by/da0ViFcuA4DH0vQg5Q6Ze5VimxkfQNSC+Mls/Kx53s7TjP1RhFEDQ==
-
move-concurrently@^1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/move-concurrently/-/move-concurrently-1.0.1.tgz#be2c005fda32e0b29af1f05d7c4b33214c701f92"
@@ -3114,17 +3429,12 @@ ms@2.0.0:
resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8"
integrity sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=
-ms@2.1.1:
- version "2.1.1"
- resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.1.tgz#30a5864eb3ebb0a66f2ebe6d727af06a09d86e0a"
- integrity sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==
-
ms@2.1.2:
version "2.1.2"
resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.2.tgz#d09d1f357b443f493382a8eb3ccd183872ae6009"
integrity sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==
-ms@^2.1.1, ms@^2.1.2:
+ms@2.1.3, ms@^2.1.1, ms@^2.1.2:
version "2.1.3"
resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.3.tgz#574c8138ce1d2b5861f0b44579dbadd60c6615b2"
integrity sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==
@@ -3144,6 +3454,11 @@ 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.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"
resolved "https://registry.yarnpkg.com/nanomatch/-/nanomatch-1.2.13.tgz#b87a8aa4fc0de8fe6be88895b38983ff265bd119"
@@ -3161,6 +3476,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.yarnpkg.com/natural-compare/-/natural-compare-1.4.0.tgz#4abebfeed7541f2c27acfb29bdbbd15c8d5ba4f7"
+ integrity sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc=
+
neo-async@^2.5.0, neo-async@^2.6.1:
version "2.6.2"
resolved "https://registry.yarnpkg.com/neo-async/-/neo-async-2.6.2.tgz#b4aafb93e3aeb2d8174ca53cf163ab7d7308305f"
@@ -3176,13 +3496,13 @@ nice-try@^1.0.4:
resolved "https://registry.yarnpkg.com/nice-try/-/nice-try-1.0.5.tgz#a3378a7696ce7d223e88fc9b764bd7ef1089e366"
integrity sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==
-nise@^4.0.4:
- version "4.1.0"
- resolved "https://registry.yarnpkg.com/nise/-/nise-4.1.0.tgz#8fb75a26e90b99202fa1e63f448f58efbcdedaf6"
- integrity sha512-eQMEmGN/8arp0xsvGoQ+B1qvSkR73B1nWSCh7nOt5neMCtwcQVYQGdzQMhcNscktTsWB54xnlSQFzOAPJD8nXA==
+nise@^5.1.0:
+ version "5.1.0"
+ resolved "https://registry.yarnpkg.com/nise/-/nise-5.1.0.tgz#713ef3ed138252daef20ec035ab62b7a28be645c"
+ 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"
@@ -3202,14 +3522,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.yarnpkg.com/node-environment-flags/-/node-environment-flags-1.0.5.tgz#fa930275f5bf5dae188d6192b24b4c8bbac3d76a"
- integrity sha512-VNYPRfGfmZLx0Ye20jWzHUjyTW/c+6Wq+iLhDzUI4XmhrDd9l/FozXV3F2xOaXjvp0co0+v1YSR3CMP6g+VvLQ==
- dependencies:
- object.getownpropertydescriptors "^2.0.3"
- semver "^5.7.0"
-
node-fetch@^2.6.1:
version "2.6.5"
resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-2.6.5.tgz#42735537d7f080a7e5f78b6c549b7146be1742fd"
@@ -3320,7 +3632,7 @@ object-copy@^0.1.0:
define-property "^0.2.5"
kind-of "^3.0.3"
-object-inspect@^1.11.0, object-inspect@^1.9.0:
+object-inspect@^1.9.0:
version "1.11.0"
resolved "https://registry.yarnpkg.com/object-inspect/-/object-inspect-1.11.0.tgz#9dceb146cedd4148a0d9e51ab88d34cf509922b1"
integrity sha512-jp7ikS6Sd3GxQfZJPyH3cjcbJF6GZPClgdV+EFygjFLQ5FmW/dRUnTd9PQ9k0JhoNDabWFbpF1yCdSWCC6gexg==
@@ -3333,7 +3645,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.yarnpkg.com/object-keys/-/object-keys-1.1.1.tgz#1c47f272df277f3b1daf061677d9c82e2322c60e"
integrity sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==
@@ -3345,35 +3657,6 @@ object-visit@^1.0.0:
dependencies:
isobject "^3.0.0"
-object.assign@4.1.0:
- version "4.1.0"
- resolved "https://registry.yarnpkg.com/object.assign/-/object.assign-4.1.0.tgz#968bf1100d7956bb3ca086f006f846b3bc4008da"
- 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.2:
- version "4.1.2"
- resolved "https://registry.yarnpkg.com/object.assign/-/object.assign-4.1.2.tgz#0ed54a342eceb37b38ff76eb831a0e788cb63940"
- 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.3"
- resolved "https://registry.yarnpkg.com/object.getownpropertydescriptors/-/object.getownpropertydescriptors-2.1.3.tgz#b223cf38e17fefb97a63c10c91df72ccb386df9e"
- integrity sha512-VdDoCwvJI4QdC6ndjpqFmoL3/+HxffFBbcJzKi5hwLLqqx3mdbedRpfZDdK0SrOSauj8X4GzBvnDZl4vTN7dOw==
- dependencies:
- call-bind "^1.0.2"
- define-properties "^1.1.3"
- es-abstract "^1.19.1"
-
object.pick@^1.3.0:
version "1.3.0"
resolved "https://registry.yarnpkg.com/object.pick/-/object.pick-1.3.0.tgz#87a10ac4c1694bd2e1cbf53591a66141fb5dd747"
@@ -3393,6 +3676,18 @@ opencollective-postinstall@^2.0.2:
resolved "https://registry.yarnpkg.com/opencollective-postinstall/-/opencollective-postinstall-2.0.3.tgz#7a0fff978f6dbfa4d006238fbac98ed4198c3259"
integrity sha512-8AV/sCtuzUeTo8gQK5qDZzARrulB3egtLzFgteqB2tcT4Mw7B8Kt7JcDHmltjz6FOAHsvTevk70gZEbhM4ZS9Q==
+optionator@^0.9.1:
+ version "0.9.1"
+ resolved "https://registry.yarnpkg.com/optionator/-/optionator-0.9.1.tgz#4f236a6373dae0566a6d43e1326674f50c291499"
+ 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.yarnpkg.com/os-browserify/-/os-browserify-0.3.0.tgz#854373c7f5c2315914fc9bfc6bd8238fdda1ec27"
@@ -3427,6 +3722,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.yarnpkg.com/p-locate/-/p-locate-2.0.0.tgz#20a0103b222a70c8fd39cc2e580680f3dde5ec43"
@@ -3448,6 +3750,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.yarnpkg.com/p-try/-/p-try-1.0.0.tgz#cbc79cdbaf8fd4228e13f621f2b1a237c1b207b3"
@@ -3489,6 +3798,13 @@ param-case@^1.1.0:
dependencies:
sentence-case "^1.1.2"
+parent-module@^1.0.0:
+ version "1.0.1"
+ resolved "https://registry.yarnpkg.com/parent-module/-/parent-module-1.0.1.tgz#691d2709e78c79fae3a156622452d00762caaaa2"
+ 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.yarnpkg.com/parse-asn1/-/parse-asn1-5.1.6.tgz#385080a3ec13cb62a62d39409cb3e88844cdaed4"
@@ -3568,6 +3884,11 @@ path-key@^2.0.0, path-key@^2.0.1:
resolved "https://registry.yarnpkg.com/path-key/-/path-key-2.0.1.tgz#411cadb574c5a140d3a4b1910d40d80cc9f40b40"
integrity sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=
+path-key@^3.1.0:
+ version "3.1.1"
+ resolved "https://registry.yarnpkg.com/path-key/-/path-key-3.1.1.tgz#581f6ade658cbba65a0d3380de7753295054f375"
+ 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"
@@ -3654,10 +3975,22 @@ posix-character-classes@^0.1.0:
resolved "https://registry.yarnpkg.com/posix-character-classes/-/posix-character-classes-0.1.1.tgz#01eac0fe3b5af71a2a6c02feabb8c1fef7e00eab"
integrity sha1-AerA/jta9xoqbAL+q7jB/vfgDqs=
-prettier@^1.18.2:
- version "1.19.1"
- resolved "https://registry.yarnpkg.com/prettier/-/prettier-1.19.1.tgz#f7d7f5ff8a9cd872a7be4ca142095956a60797cb"
- integrity sha512-s7PoyDv/II1ObgQunCbB9PdLmUcBZcnWOcxDh7O0N/UwDEsHyqkW+Qh28jW+mVuCdx7gLB0BotYI1Y6uI9iyew==
+prelude-ls@^1.2.1:
+ version "1.2.1"
+ resolved "https://registry.yarnpkg.com/prelude-ls/-/prelude-ls-1.2.1.tgz#debc6489d7a6e6b0e7611888cec880337d316396"
+ integrity sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==
+
+prettier-linter-helpers@^1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/prettier-linter-helpers/-/prettier-linter-helpers-1.0.0.tgz#d23d41fe1375646de2d0104d3454a3008802cf7b"
+ 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"
@@ -3681,6 +4014,11 @@ process@^0.11.10:
resolved "https://registry.yarnpkg.com/process/-/process-0.11.10.tgz#7332300e840161bda3e69a1d1d91a7d4bc16f182"
integrity sha1-czIwDoQBYb2j5podHZGn1LwW8YI=
+progress@^2.0.0:
+ version "2.0.3"
+ resolved "https://registry.yarnpkg.com/progress/-/progress-2.0.3.tgz#7e8cf8d8f5b8f239c1bc68beb4eb78567d572ef8"
+ integrity sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==
+
promise-inflight@^1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/promise-inflight/-/promise-inflight-1.0.1.tgz#98472870bf228132fcbdd868129bad12c3c029e3"
@@ -3696,7 +4034,7 @@ proxy-from-env@^1.1.0:
resolved "https://registry.yarnpkg.com/proxy-from-env/-/proxy-from-env-1.1.0.tgz#e102f16ca355424865755d2c9e8ea4f24d58c3e2"
integrity sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==
-proxyquire@^2.1.1:
+proxyquire@^2.1.3:
version "2.1.3"
resolved "https://registry.yarnpkg.com/proxyquire/-/proxyquire-2.1.3.tgz#2049a7eefa10a9a953346a18e54aab2b4268df39"
integrity sha512-BQWfCqYM+QINd+yawJz23tbBM40VIGXOdDw3X344KcclI/gtBbdWF6SlQ4nK/bYhF9d27KYug9WzljHC6B9Ysg==
@@ -3857,6 +4195,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"
@@ -3880,6 +4225,16 @@ regexp.prototype.flags@^1.2.0:
call-bind "^1.0.2"
define-properties "^1.1.3"
+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==
+
+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.yarnpkg.com/release-zalgo/-/release-zalgo-1.0.0.tgz#09700b7e5074329739330e535c5a90fb67851730"
@@ -3934,7 +4289,7 @@ resolve-url@^0.2.1:
resolved "https://registry.yarnpkg.com/resolve-url/-/resolve-url-0.2.1.tgz#2c637fe77c893afd2a663fe21aa9080068e2052a"
integrity sha1-LGN/53yJOv0qZj/iGqkIAGjiBSo=
-resolve@^1.10.0, resolve@^1.11.1:
+resolve@^1.10.0, resolve@^1.10.1, resolve@^1.11.1:
version "1.20.0"
resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.20.0.tgz#629a013fb3f70755d6f0b7935cc1c2c5378b1975"
integrity sha512-wENBPt4ySzg4ybFQW2TT1zMQucPK95HSh/nq2CFTZVOGut2+pQvSsgtda4d26YrYcr067wjbmzOG8byDPBX63A==
@@ -3969,6 +4324,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.yarnpkg.com/rimraf/-/rimraf-3.0.2.tgz#f1a5402ba6220ad52cc1282bac1ae3aa49fd061a"
+ 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.yarnpkg.com/ripemd160/-/ripemd160-2.0.2.tgz#a1c1a6f624751577ba5d07914cbc92850585890c"
@@ -4025,17 +4387,17 @@ semver-compare@^1.0.0:
resolved "https://registry.yarnpkg.com/semver-compare/-/semver-compare-1.0.0.tgz#0dee216a1c941ab37e9efb1788f6afc5ff5537fc"
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.yarnpkg.com/semver/-/semver-5.7.1.tgz#a954f931aeba508d307bbf069eff0c01c96116f7"
integrity sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==
-semver@^6.0.0:
+semver@^6.0.0, semver@^6.1.0:
version "6.3.0"
resolved "https://registry.yarnpkg.com/semver/-/semver-6.3.0.tgz#ee0a64c8af5e8ceea67687b133761e1becbd1d3d"
integrity sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==
-semver@^7.3.2:
+semver@^7.2.1, semver@^7.3.2, semver@^7.3.5:
version "7.3.5"
resolved "https://registry.yarnpkg.com/semver/-/semver-7.3.5.tgz#0b621c879348d8998e4b0e4be94b3f12e6018ef7"
integrity sha512-PoeGJYh8HK4BTO/a9Tf6ZG3veo/A7ZVsYrSA6J8ny9nb3B1VrpkuN+z9OE5wfE5p6H4LchYZsegiQgbJD94ZFQ==
@@ -4049,6 +4411,13 @@ sentence-case@^1.1.1, sentence-case@^1.1.2:
dependencies:
lower-case "^1.1.1"
+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"
+
serialize-javascript@^4.0.0:
version "4.0.0"
resolved "https://registry.yarnpkg.com/serialize-javascript/-/serialize-javascript-4.0.0.tgz#b525e1238489a5ecfc42afacc3fe99e666f4b1aa"
@@ -4091,11 +4460,23 @@ shebang-command@^1.2.0:
dependencies:
shebang-regex "^1.0.0"
+shebang-command@^2.0.0:
+ version "2.0.0"
+ resolved "https://registry.yarnpkg.com/shebang-command/-/shebang-command-2.0.0.tgz#ccd0af4f8835fbdc265b82461aaf0c36663f34ea"
+ integrity sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==
+ dependencies:
+ shebang-regex "^3.0.0"
+
shebang-regex@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/shebang-regex/-/shebang-regex-1.0.0.tgz#da42f49740c0b42db2ca9728571cb190c98efea3"
integrity sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=
+shebang-regex@^3.0.0:
+ version "3.0.0"
+ resolved "https://registry.yarnpkg.com/shebang-regex/-/shebang-regex-3.0.0.tgz#ae16f1644d873ecad843b0307b143362d4c42172"
+ integrity sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==
+
side-channel@^1.0.4:
version "1.0.4"
resolved "https://registry.yarnpkg.com/side-channel/-/side-channel-1.0.4.tgz#efce5c8fdc104ee751b25c58d4290011fa5ea2cf"
@@ -4110,17 +4491,17 @@ signal-exit@^3.0.0, signal-exit@^3.0.2:
resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-3.0.5.tgz#9e3e8cc0c75a99472b44321033a7702e7738252f"
integrity sha512-KWcOiKeQj6ZyXx7zq4YxSMgHRlod4czeBQZrPb8OKcohcqAXShm7E20kEMle9WBt26hFcAf0qLOcp5zmY7kOqQ==
-sinon@^9.0.3:
- version "9.2.4"
- resolved "https://registry.yarnpkg.com/sinon/-/sinon-9.2.4.tgz#e55af4d3b174a4443a8762fa8421c2976683752b"
- integrity sha512-zljcULZQsJxVra28qIAL6ow1Z9tpattkCTEJR4RBP3TGc00FcttsP5pK284Nas5WjMZU5Yzy3kAIp3B3KRf5Yg==
+sinon@^11.1.2:
+ version "11.1.2"
+ resolved "https://registry.yarnpkg.com/sinon/-/sinon-11.1.2.tgz#9e78850c747241d5c59d1614d8f9cbe8840e8674"
+ integrity sha512-59237HChms4kg7/sXhiRcUzdSkKuydDeTiamT/jesUVHshBgL8XAmhgFo0GfK6RruMDM/iRSij1EybmMog9cJw==
dependencies:
- "@sinonjs/commons" "^1.8.1"
- "@sinonjs/fake-timers" "^6.0.1"
- "@sinonjs/samsam" "^5.3.1"
- diff "^4.0.2"
- nise "^4.0.4"
- supports-color "^7.1.0"
+ "@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"
@@ -4235,7 +4616,7 @@ spdx-exceptions@^2.1.0:
resolved "https://registry.yarnpkg.com/spdx-exceptions/-/spdx-exceptions-2.3.0.tgz#3f28ce1a77a00372683eade4a433183527a2163d"
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.yarnpkg.com/spdx-expression-parse/-/spdx-expression-parse-3.0.1.tgz#cf70f50482eefdc98e3ce0a6833e4a53ceeba679"
integrity sha512-cbqHunsQWnJNE6KhVSMsMeH5H/L9EpymbzqTQ3uLwNCLZ1Q481oWaofqH7nO6V07xlXwY6PhQdQ2IedWx/ZK4Q==
@@ -4343,21 +4724,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.4:
- version "1.0.4"
- resolved "https://registry.yarnpkg.com/string.prototype.trimend/-/string.prototype.trimend-1.0.4.tgz#e75ae90c2942c63504686c18b287b4a0b1a45f80"
- integrity sha512-y9xCjw1P23Awk8EvTpcyL2NIr1j7wJ39f+k6lvRnSMz+mz9CGz9NYPelDk42kOz6+ql8xjfK8oYzy3jAP5QU5A==
+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==
dependencies:
- call-bind "^1.0.2"
- define-properties "^1.1.3"
-
-string.prototype.trimstart@^1.0.4:
- version "1.0.4"
- resolved "https://registry.yarnpkg.com/string.prototype.trimstart/-/string.prototype.trimstart-1.0.4.tgz#b36399af4ab2999b4c9c648bd7a3fb2bb26feeed"
- integrity sha512-jh6e984OBfvxS50tdY2nRZnoC5/mLFKOREQfw8t5yytkoUsJRNxvI/E39qu1sD0OtWI3OC0XgKSmcWwziwYuZw==
- dependencies:
- call-bind "^1.0.2"
- 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"
@@ -4387,6 +4761,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.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9"
+ integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==
+ dependencies:
+ ansi-regex "^5.0.1"
+
strip-bom@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-3.0.0.tgz#2334c18e9c759f7bdd56fdef7e9ae3d588e68ed3"
@@ -4397,12 +4778,7 @@ strip-eof@^1.0.0:
resolved "https://registry.yarnpkg.com/strip-eof/-/strip-eof-1.0.0.tgz#bb43ff5598a6eb05d89b59fcd129c983313606bf"
integrity sha1-u0P/VZim6wXYm1n80SnJgzE2Br8=
-strip-json-comments@2.0.1:
- version "2.0.1"
- resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-2.0.1.tgz#3c531942e908c2697c0ec344858c286c7ca0a60a"
- 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.yarnpkg.com/strip-json-comments/-/strip-json-comments-3.1.1.tgz#31f1281b3832630434831c310c01cccda8cbe006"
integrity sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==
@@ -4436,12 +4812,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.yarnpkg.com/supports-color/-/supports-color-6.0.0.tgz#76cfe742cf1f41bb9b1c29ad03068c05b4c0e40a"
- 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"
@@ -4457,7 +4833,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.yarnpkg.com/supports-color/-/supports-color-7.2.0.tgz#1b7dcdcb32b8138801b3e478ba6a51caa89648da"
integrity sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==
@@ -4527,6 +4903,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.yarnpkg.com/text-table/-/text-table-0.2.0.tgz#7f5ee823ae805207c00af2df4a84ec3fcfa570b4"
+ integrity sha1-f17oI66AUgfACvLfSoTsP8+lcLQ=
+
through2@^2.0.0:
version "2.0.5"
resolved "https://registry.yarnpkg.com/through2/-/through2-2.0.5.tgz#01c1e39eb31d07cb7d03a96a70823260b23132cd"
@@ -4602,11 +4983,23 @@ tty-browserify@0.0.0:
resolved "https://registry.yarnpkg.com/tty-browserify/-/tty-browserify-0.0.0.tgz#a157ba402da24e9bf957f9aa69d524eed42901a6"
integrity sha1-oVe6QC2iTpv5V/mqadUk7tQpAaY=
+type-check@^0.4.0, type-check@~0.4.0:
+ version "0.4.0"
+ resolved "https://registry.yarnpkg.com/type-check/-/type-check-0.4.0.tgz#07b8203bfa7056c0657050e3ccd2c37730bab8f1"
+ integrity sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==
+ dependencies:
+ prelude-ls "^1.2.1"
+
type-detect@4.0.8, type-detect@^4.0.0, type-detect@^4.0.5, type-detect@^4.0.8:
version "4.0.8"
resolved "https://registry.yarnpkg.com/type-detect/-/type-detect-4.0.8.tgz#7646fb5f18871cfbb7749e69bd39a6388eb7450c"
integrity sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==
+type-fest@^0.20.2:
+ version "0.20.2"
+ resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.20.2.tgz#1bf207f4b28f91583666cb5fbd327887301cd5f4"
+ integrity sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==
+
type-fest@^0.6.0:
version "0.6.0"
resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.6.0.tgz#8d2a2370d3df886eb5c90ada1c5bf6188acf838b"
@@ -4622,16 +5015,6 @@ uc.micro@^1.0.1, uc.micro@^1.0.5:
resolved "https://registry.yarnpkg.com/uc.micro/-/uc.micro-1.0.6.tgz#9c411a802a409a91fc6cf74081baba34b24499ac"
integrity sha512-8Y75pvTYkLJW2hWQHXxoqRgV7qb9B+9vFEtidML+7koHUFapnVJAZ6cKs+Qjz5Aw3aZWHMC6u0wJE3At+nSGwA==
-unbox-primitive@^1.0.1:
- version "1.0.1"
- resolved "https://registry.yarnpkg.com/unbox-primitive/-/unbox-primitive-1.0.1.tgz#085e215625ec3162574dc8859abee78a59b14471"
- integrity sha512-tZU/3NqK3dA5gpE1KtyiJUrEB0lxnGkMFHptJ7q6ewdZ8s12QrODwNbhIJStmJkd1QDXa1NRA8aF2A1zk/Ypyw==
- dependencies:
- function-bind "^1.1.1"
- has-bigints "^1.0.1"
- has-symbols "^1.0.2"
- which-boxed-primitive "^1.0.2"
-
underscore@~1.13.1:
version "1.13.1"
resolved "https://registry.yarnpkg.com/underscore/-/underscore-1.13.1.tgz#0c1c6bd2df54b6b69f2314066d65b6cde6fcf9d1"
@@ -4747,6 +5130,11 @@ uuid@^8.0.0:
resolved "https://registry.yarnpkg.com/uuid/-/uuid-8.3.2.tgz#80d5b5ced271bb9af6c445f21a1a04c606cefbe2"
integrity sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==
+v8-compile-cache@^2.0.3:
+ version "2.3.0"
+ resolved "https://registry.yarnpkg.com/v8-compile-cache/-/v8-compile-cache-2.3.0.tgz#2de19618c66dc247dcfb6f99338035d8245a2cee"
+ integrity sha512-l8lCEmLcLYZh4nbunNZvQCJc5pv7+RCwa8q/LdUx8u7lsWvPDKmpodJAJNwkAhJC//dFY48KuIEmjtd4RViDrA==
+
validate-npm-package-license@^3.0.1:
version "3.0.4"
resolved "https://registry.yarnpkg.com/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz#fc91f6b9c7ba15c857f4cb2c5defeec39d4f410a"
@@ -4828,36 +5216,25 @@ whatwg-url@^5.0.0:
tr46 "~0.0.3"
webidl-conversions "^3.0.0"
-which-boxed-primitive@^1.0.2:
- version "1.0.2"
- resolved "https://registry.yarnpkg.com/which-boxed-primitive/-/which-boxed-primitive-1.0.2.tgz#13757bc89b209b049fe5d86430e21cf40a89a8e6"
- integrity sha512-bwZdv0AKLpplFY2KZRX6TvyuN7ojjr7lwkg6ml0roIy9YeuSr7JS372qlNW18UQYzgYK9ziGcerWqZOmEn9VNg==
- dependencies:
- is-bigint "^1.0.1"
- is-boolean-object "^1.1.0"
- is-number-object "^1.0.4"
- is-string "^1.0.5"
- is-symbol "^1.0.3"
-
which-module@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/which-module/-/which-module-2.0.0.tgz#d9ef07dce77b9902b8a3a8fa4b31c3e3f7e6e87a"
integrity sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho=
-which@1.3.1, which@^1.2.9, which@^1.3.0:
- version "1.3.1"
- resolved "https://registry.yarnpkg.com/which/-/which-1.3.1.tgz#a45043d54f5805316da8d62f9f50918d3da70b0a"
- 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.yarnpkg.com/which/-/which-2.0.2.tgz#7c6a8dd0a636a0327e10b59c9286eee93f3f51b1"
integrity sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==
dependencies:
isexe "^2.0.0"
+which@^1.2.9, which@^1.3.0:
+ version "1.3.1"
+ resolved "https://registry.yarnpkg.com/which/-/which-1.3.1.tgz#a45043d54f5805316da8d62f9f50918d3da70b0a"
+ integrity sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==
+ 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"
@@ -4865,6 +5242,11 @@ wide-align@1.1.3:
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"
+ integrity sha512-Hz/mrNwitNRh/HUAtM/VT/5VH+ygD6DV7mYKZAtHOrbs8U7lvPS6xf7EJKMF0uW1KJCl0H701g3ZGus+muE5vQ==
+
worker-farm@^1.7.0:
version "1.7.0"
resolved "https://registry.yarnpkg.com/worker-farm/-/worker-farm-1.7.0.tgz#26a94c5391bbca926152002f69b84a4bf772e5a8"
@@ -4872,6 +5254,11 @@ worker-farm@^1.7.0:
dependencies:
errno "~0.1.7"
+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"
resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-5.1.0.tgz#1fd1f67235d5b6d0fee781056001bfb694c03b09"
@@ -4881,6 +5268,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.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f"
@@ -4915,6 +5311,11 @@ y18n@^4.0.0:
resolved "https://registry.yarnpkg.com/y18n/-/y18n-4.0.3.tgz#b5f259c82cd6e336921efd7bfd8bf560de9eeedf"
integrity sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==
+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, yallist@^2.1.2:
version "2.1.2"
resolved "https://registry.yarnpkg.com/yallist/-/yallist-2.1.2.tgz#1c11f9218f076089a47dd512f93c6699a6a81d52"
@@ -4930,7 +5331,12 @@ yallist@^4.0.0:
resolved "https://registry.yarnpkg.com/yallist/-/yallist-4.0.0.tgz#9bb92790d9c0effec63be73519e11a35019a3a72"
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.yarnpkg.com/yargs-parser/-/yargs-parser-13.1.2.tgz#130f09702ebaeef2650d54ce6e3e5706f7a4fb38"
integrity sha512-3lbsNRf/j+A4QuSZfDRA7HRSfWrzO0YjqTJd5kjAq37Zep1CEgaYmrH9Q3GwPiB9cHyd1Y1UwggGhJGoxipbzg==
@@ -4938,16 +5344,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.yarnpkg.com/yargs-unparser/-/yargs-unparser-1.6.0.tgz#ef25c2c769ff6bd09e4b0f9d7c605fb27846ea9f"
- 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@13.3.2, yargs@^13.2.2, yargs@^13.3.0:
+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.2.2:
version "13.3.2"
resolved "https://registry.yarnpkg.com/yargs/-/yargs-13.3.2.tgz#ad7ffefec1aa59565ac915f82dccb38a9c31a2dd"
integrity sha512-AX3Zw5iPruN5ie6xGRIDgqkT+ZhnRlZMLMHAs8tg7nRruy2Nb+i5o9bwghAogtM08q1dpr2LVoS8KSTMYpWXUw==
@@ -4962,3 +5387,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==