Repository: auth0/node-auth0
Pull request #373 (2019-07-07 07:11:35)

Add "getAccessToken" method to "ManagementClient"
It can be useful to manage machine to machine access tokens via the ManagementClient however there is currently no method exposed to get the current valid access token. This PR adds the given method.


Patch:
diff --git a/src/management/index.js b/src/management/index.js
index 6303f0217..9ea1dc562 100644
--- a/src/management/index.js
+++ b/src/management/index.js
@@ -125,6 +125,11 @@ var ManagementClient = function(options) {
   } 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.headers['Authorization'] = 'Bearer ' + options.token;
   }
 
@@ -1578,7 +1583,11 @@ utils.wrapPropertyMethod(ManagementClient, 'unblockUser', 'userBlocks.delete');
  *
  * @return  {Promise|undefined}
  */
-utils.wrapPropertyMethod(ManagementClient, 'getUserBlocksByIdentifier', 'userBlocks.getByIdentifier');
+utils.wrapPropertyMethod(
+  ManagementClient,
+  'getUserBlocksByIdentifier',
+  'userBlocks.getByIdentifier'
+);
 
 /**
  * Unblock an user by its id.
@@ -1601,7 +1610,11 @@ utils.wrapPropertyMethod(ManagementClient, 'getUserBlocksByIdentifier', 'userBlo
  *
  * @return  {Promise|undefined}
  */
-utils.wrapPropertyMethod(ManagementClient, 'unblockUserByIdentifier', 'userBlocks.deleteByIdentifier');
+utils.wrapPropertyMethod(
+  ManagementClient,
+  'unblockUserByIdentifier',
+  'userBlocks.deleteByIdentifier'
+);
 
 /**
  * Get a single Guardian enrollment.
@@ -2016,14 +2029,14 @@ utils.wrapPropertyMethod(ManagementClient, 'sendEmailVerification', 'jobs.verify
  * @memberOf  module:management.ManagementClient.prototype
  *
  * @example
- * 
+ *
  * var params = {
-  *   result_url: '{REDIRECT_URL}',  // Redirect after using the ticket.
-  *   user_id: '{USER_ID}'
-  * };
-  * 
-  * // or
-  * 
+ *   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}',
@@ -2803,4 +2816,14 @@ utils.wrapPropertyMethod(ManagementClient, 'removePermissionsFromRole', 'roles.r
  */
 utils.wrapPropertyMethod(ManagementClient, 'getUsersInRole', 'roles.getUsers');
 
+/**
+ * Returns the access_token.
+ *
+ * @method    getAccessToken
+ * @memberOf  module:management.ManagementClient.prototype
+ *
+ * @return {Promise}   Promise returning an access_token.
+ */
+utils.wrapPropertyMethod(ManagementClient, 'getAccessToken', 'tokenProvider.getAccessToken');
+
 module.exports = ManagementClient;


Test patch:
diff --git a/test/management/management-client.tests.js b/test/management/management-client.tests.js
index 64928b492..c70bdde50 100644
--- a/test/management/management-client.tests.js
+++ b/test/management/management-client.tests.js
@@ -1,4 +1,5 @@
 var expect = require('chai').expect;
+var nock = require('nock');
 var sinon = require('sinon');
 var assign = Object.assign || require('object.assign');
 var proxyquire = require('proxyquire');
@@ -25,7 +26,10 @@ describe('ManagementClient', function() {
   var withTokenProviderConfig = {
     clientId: 'clientId',
     clientSecret: 'clientSecret',
-    domain: 'auth0-node-sdk.auth0.com'
+    domain: 'auth0-node-sdk.auth0.com',
+    tokenProvider: {
+      enableCache: false
+    }
   };
 
   var withTokenConfig = {
@@ -95,6 +99,39 @@ describe('ManagementClient', function() {
     expect(client).to.throw(ArgumentError, 'Must provide a clientSecret');
   });
 
+  describe('getAccessToken', function() {
+    it('should return token provided in config', function(done) {
+      var config = assign({}, withTokenConfig);
+      var client = new ManagementClient(config);
+
+      client.getAccessToken().then(function(accessToken) {
+        expect(accessToken).to.equal(withTokenConfig.token);
+        done();
+      });
+    });
+    it('should return token from provider', function(done) {
+      var config = assign({}, withTokenProviderConfig);
+      var client = new ManagementClient(config);
+
+      nock('https://' + config.domain)
+        .post('/oauth/token', function(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 }]);
+        });
+
+      client.getAccessToken().then(function(data) {
+        expect(data).to.equal('token');
+        done();
+        nock.cleanAll();
+      });
+    });
+  });
+
   describe('instance properties', function() {
     var manager;
     var managers = {
@@ -769,7 +806,8 @@ describe('ManagementClient', function() {
       'getUserBlocks',
       'unblockUser',
       'getUserBlocksByIdentifier',
-      'unblockUserByIdentifier'
+      'unblockUserByIdentifier',
+      'getAccessToken'
     ];
 
     before(function() {
diff --git a/test/management/management-token-provider.tests.js b/test/management/management-token-provider.tests.js
index d7a18cd88..e75a5fd89 100644
--- a/test/management/management-token-provider.tests.js
+++ b/test/management/management-token-provider.tests.js
@@ -151,6 +151,7 @@ describe('ManagementTokenProvider', function() {
     client.getAccessToken().catch(function(err) {
       expect(err).to.exist;
       done();
+      nock.cleanAll();
     });
   });