Provider.js 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. 'use strict';
  2. var tokenStorage = require("./tokenStorage.js");
  3. const RequestClient = require("./RequestClient.js");
  4. const getName = id => {
  5. return id.split('-').map(s => s.charAt(0).toUpperCase() + s.slice(1)).join(' ');
  6. };
  7. class Provider extends RequestClient {
  8. constructor(uppy, opts) {
  9. super(uppy, opts);
  10. this.provider = opts.provider;
  11. this.id = this.provider;
  12. this.name = this.opts.name || getName(this.id);
  13. this.pluginId = this.opts.pluginId;
  14. this.tokenKey = `companion-${this.pluginId}-auth-token`;
  15. this.companionKeysParams = this.opts.companionKeysParams;
  16. this.preAuthToken = null;
  17. }
  18. headers() {
  19. return Promise.all([super.headers(), this.getAuthToken()]).then(_ref => {
  20. let [headers, token] = _ref;
  21. const authHeaders = {};
  22. if (token) {
  23. authHeaders['uppy-auth-token'] = token;
  24. }
  25. if (this.companionKeysParams) {
  26. authHeaders['uppy-credentials-params'] = btoa(JSON.stringify({
  27. params: this.companionKeysParams
  28. }));
  29. }
  30. return { ...headers,
  31. ...authHeaders
  32. };
  33. });
  34. }
  35. onReceiveResponse(response) {
  36. response = super.onReceiveResponse(response); // eslint-disable-line no-param-reassign
  37. const plugin = this.uppy.getPlugin(this.pluginId);
  38. const oldAuthenticated = plugin.getPluginState().authenticated;
  39. const authenticated = oldAuthenticated ? response.status !== 401 : response.status < 400;
  40. plugin.setPluginState({
  41. authenticated
  42. });
  43. return response;
  44. }
  45. setAuthToken(token) {
  46. return this.uppy.getPlugin(this.pluginId).storage.setItem(this.tokenKey, token);
  47. }
  48. getAuthToken() {
  49. return this.uppy.getPlugin(this.pluginId).storage.getItem(this.tokenKey);
  50. }
  51. /**
  52. * Ensure we have a preauth token if necessary. Attempts to fetch one if we don't,
  53. * or rejects if loading one fails.
  54. */
  55. async ensurePreAuth() {
  56. if (this.companionKeysParams && !this.preAuthToken) {
  57. await this.fetchPreAuthToken();
  58. if (!this.preAuthToken) {
  59. throw new Error('Could not load authentication data required for third-party login. Please try again later.');
  60. }
  61. }
  62. }
  63. authUrl(queries) {
  64. if (queries === void 0) {
  65. queries = {};
  66. }
  67. const params = new URLSearchParams(queries);
  68. if (this.preAuthToken) {
  69. params.set('uppyPreAuthToken', this.preAuthToken);
  70. }
  71. return `${this.hostname}/${this.id}/connect?${params}`;
  72. }
  73. fileUrl(id) {
  74. return `${this.hostname}/${this.id}/get/${id}`;
  75. }
  76. async fetchPreAuthToken() {
  77. if (!this.companionKeysParams) {
  78. return;
  79. }
  80. try {
  81. const res = await this.post(`${this.id}/preauth/`, {
  82. params: this.companionKeysParams
  83. });
  84. this.preAuthToken = res.token;
  85. } catch (err) {
  86. this.uppy.log(`[CompanionClient] unable to fetch preAuthToken ${err}`, 'warning');
  87. }
  88. }
  89. list(directory) {
  90. return this.get(`${this.id}/list/${directory || ''}`);
  91. }
  92. logout() {
  93. return this.get(`${this.id}/logout`).then(response => Promise.all([response, this.uppy.getPlugin(this.pluginId).storage.removeItem(this.tokenKey)])).then(_ref2 => {
  94. let [response] = _ref2;
  95. return response;
  96. });
  97. }
  98. static initPlugin(plugin, opts, defaultOpts) {
  99. /* eslint-disable no-param-reassign */
  100. plugin.type = 'acquirer';
  101. plugin.files = [];
  102. if (defaultOpts) {
  103. plugin.opts = { ...defaultOpts,
  104. ...opts
  105. };
  106. }
  107. if (opts.serverUrl || opts.serverPattern) {
  108. throw new Error('`serverUrl` and `serverPattern` have been renamed to `companionUrl` and `companionAllowedHosts` respectively in the 0.30.5 release. Please consult the docs (for example, https://uppy.io/docs/instagram/ for the Instagram plugin) and use the updated options.`');
  109. }
  110. if (opts.companionAllowedHosts) {
  111. const pattern = opts.companionAllowedHosts; // validate companionAllowedHosts param
  112. if (typeof pattern !== 'string' && !Array.isArray(pattern) && !(pattern instanceof RegExp)) {
  113. throw new TypeError(`${plugin.id}: the option "companionAllowedHosts" must be one of string, Array, RegExp`);
  114. }
  115. plugin.opts.companionAllowedHosts = pattern;
  116. } else if (/^(?!https?:\/\/).*$/i.test(opts.companionUrl)) {
  117. // does not start with https://
  118. plugin.opts.companionAllowedHosts = `https://${opts.companionUrl.replace(/^\/\//, '')}`;
  119. } else {
  120. plugin.opts.companionAllowedHosts = new URL(opts.companionUrl).origin;
  121. }
  122. plugin.storage = plugin.opts.storage || tokenStorage;
  123. /* eslint-enable no-param-reassign */
  124. }
  125. }
  126. module.exports = Provider;