Provider.js 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. 'use strict'
  2. const RequestClient = require('./RequestClient')
  3. const tokenStorage = require('./tokenStorage')
  4. const getName = (id) => {
  5. return id.split('-').map((s) => s.charAt(0).toUpperCase() + s.slice(1)).join(' ')
  6. }
  7. module.exports = 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()])
  20. .then(([headers, token]) => {
  21. const authHeaders = {}
  22. if (token) {
  23. authHeaders['uppy-auth-token'] = token
  24. }
  25. if (this.companionKeysParams) {
  26. authHeaders['uppy-credentials-params'] = btoa(
  27. JSON.stringify({ params: this.companionKeysParams })
  28. )
  29. }
  30. return { ...headers, ...authHeaders }
  31. })
  32. }
  33. onReceiveResponse (response) {
  34. response = super.onReceiveResponse(response)
  35. const plugin = this.uppy.getPlugin(this.pluginId)
  36. const oldAuthenticated = plugin.getPluginState().authenticated
  37. const authenticated = oldAuthenticated ? response.status !== 401 : response.status < 400
  38. plugin.setPluginState({ authenticated })
  39. return response
  40. }
  41. setAuthToken (token) {
  42. return this.uppy.getPlugin(this.pluginId).storage.setItem(this.tokenKey, token)
  43. }
  44. getAuthToken () {
  45. return this.uppy.getPlugin(this.pluginId).storage.getItem(this.tokenKey)
  46. }
  47. authUrl (queries = {}) {
  48. if (this.preAuthToken) {
  49. queries.uppyPreAuthToken = this.preAuthToken
  50. }
  51. return `${this.hostname}/${this.id}/connect?${new URLSearchParams(queries)}`
  52. }
  53. fileUrl (id) {
  54. return `${this.hostname}/${this.id}/get/${id}`
  55. }
  56. fetchPreAuthToken () {
  57. if (!this.companionKeysParams) {
  58. return Promise.resolve()
  59. }
  60. return this.post(`${this.id}/preauth/`, { params: this.companionKeysParams })
  61. .then((res) => {
  62. this.preAuthToken = res.token
  63. }).catch((err) => {
  64. this.uppy.log(`[CompanionClient] unable to fetch preAuthToken ${err}`, 'warning')
  65. })
  66. }
  67. list (directory) {
  68. return this.get(`${this.id}/list/${directory || ''}`)
  69. }
  70. logout () {
  71. return this.get(`${this.id}/logout`)
  72. .then((response) => Promise.all([
  73. response,
  74. this.uppy.getPlugin(this.pluginId).storage.removeItem(this.tokenKey),
  75. ])).then(([response]) => response)
  76. }
  77. static initPlugin (plugin, opts, defaultOpts) {
  78. plugin.type = 'acquirer'
  79. plugin.files = []
  80. if (defaultOpts) {
  81. plugin.opts = { ...defaultOpts, ...opts }
  82. }
  83. if (opts.serverUrl || opts.serverPattern) {
  84. 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.`')
  85. }
  86. if (opts.companionAllowedHosts) {
  87. const pattern = opts.companionAllowedHosts
  88. // validate companionAllowedHosts param
  89. if (typeof pattern !== 'string' && !Array.isArray(pattern) && !(pattern instanceof RegExp)) {
  90. throw new TypeError(`${plugin.id}: the option "companionAllowedHosts" must be one of string, Array, RegExp`)
  91. }
  92. plugin.opts.companionAllowedHosts = pattern
  93. } else if (/^(?!https?:\/\/).*$/i.test(opts.companionUrl)) {
  94. // does not start with https://
  95. plugin.opts.companionAllowedHosts = `https://${opts.companionUrl.replace(/^\/\//, '')}`
  96. } else {
  97. plugin.opts.companionAllowedHosts = new URL(opts.companionUrl).origin
  98. }
  99. plugin.storage = plugin.opts.storage || tokenStorage
  100. }
  101. }