entities/oauth.js

  1. import axios from 'axios';
  2. import debug from 'debug';
  3. import {typeValidation} from '../utils/validator';
  4. const ACCESS_TOKEN_GRANT_TYPE = 'authorization_code';
  5. const REFRESH_TOKEN_GRANT_TYPE = 'refresh_token';
  6. const log = debug('starling:oauth-service');
  7. /**
  8. * Service to interact with a the oauth endpoint
  9. */
  10. class OAuth {
  11. /**
  12. * Create a new oauth service
  13. * @param {Object} options - configuration parameters
  14. */
  15. constructor (options) {
  16. this.options = options;
  17. }
  18. /**
  19. * Exchanges the authorization code for an access token
  20. * @param {string} authorizationCode - the authorization code, acquired from the user agent after the
  21. * user authenticates with starling
  22. * @return {Promise} - the http request promise
  23. */
  24. getAccessToken (authorizationCode) {
  25. typeValidation(arguments, authorizationCodeParameterDefinition);
  26. return this.getOAuthToken({
  27. 'code': authorizationCode,
  28. 'grant_type': ACCESS_TOKEN_GRANT_TYPE,
  29. 'client_id': this.options.clientId,
  30. 'client_secret': this.options.clientSecret,
  31. 'redirect_uri': this.options.redirectUri
  32. });
  33. }
  34. /**
  35. * Exchanges the authorization code for an access token
  36. * @param {string} refreshToken - the oauth refresh token, used when the access token
  37. * expires to claim a new access token.
  38. * @return {Promise} - the http request promise
  39. */
  40. refreshAccessToken (refreshToken) {
  41. typeValidation(arguments, refreshTokenParameterDefinition);
  42. return this.getOAuthToken({
  43. 'refresh_token': refreshToken,
  44. 'grant_type': REFRESH_TOKEN_GRANT_TYPE,
  45. 'client_id': this.options.clientId,
  46. 'client_secret': this.options.clientSecret
  47. });
  48. }
  49. /**
  50. * Gets the access token from the starling oauth endpoint
  51. * @param {object} params - the query params passed to the oauth endpoint as per the oauth spec
  52. * @return {Promise} - the http request promise
  53. */
  54. getOAuthToken (params) {
  55. if (!this.options.clientId) {
  56. throw Error('clientId is not configured');
  57. }
  58. if (!this.options.clientSecret) {
  59. throw Error('clientSecret is not configured');
  60. }
  61. const url = `${this.options.oauthUrl}/oauth/access-token`;
  62. log(`GET ${url} queryParams:${JSON.stringify(params)}`);
  63. return axios({
  64. url,
  65. method: 'GET',
  66. headers: {
  67. 'Content-Type': 'application/x-www-form-urlencoded',
  68. Accept: 'application/json'
  69. },
  70. params: params
  71. });
  72. }
  73. }
  74. const refreshTokenParameterDefinition = [
  75. {name: 'refreshToken', validations: ['required', 'string']}
  76. ];
  77. const authorizationCodeParameterDefinition = [
  78. {name: 'authorizationCode', validations: ['required', 'string']}
  79. ];
  80. module.exports = OAuth;