send-token.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /**
  2. *
  3. * sends auth token to uppy client
  4. */
  5. const tokenService = require('../helpers/jwt')
  6. const parseUrl = require('url').parse // eslint-disable-line node/no-deprecated-api
  7. const { hasMatch, sanitizeHtml } = require('../helpers/utils')
  8. const oAuthState = require('../helpers/oauth-state')
  9. const versionCmp = require('../helpers/version')
  10. /**
  11. *
  12. * @param {object} req
  13. * @param {object} res
  14. * @param {function} next
  15. */
  16. module.exports = function sendToken (req, res, next) {
  17. const uppyAuthToken = req.companion.authToken
  18. // add the token to cookies for thumbnail/image requests
  19. if (req.companion.provider.authProvider !== 'microsoft') {
  20. tokenService.addToCookies(res, uppyAuthToken, req.companion.options, req.companion.provider.authProvider)
  21. }
  22. const state = (req.session.grant || {}).state
  23. if (state) {
  24. const origin = oAuthState.getFromState(state, 'origin', req.companion.options.secret)
  25. const clientVersion = oAuthState.getFromState(
  26. state,
  27. 'clientVersion',
  28. req.companion.options.secret
  29. )
  30. const allowedClients = req.companion.options.clients
  31. // if no preset clients then allow any client
  32. if (!allowedClients || hasMatch(origin, allowedClients) || hasMatch(parseUrl(origin).host, allowedClients)) {
  33. const allowsStringMessage = versionCmp.gte(clientVersion, '1.0.2')
  34. return res.send(allowsStringMessage ? htmlContent(uppyAuthToken, origin) : oldHtmlContent(uppyAuthToken, origin))
  35. }
  36. }
  37. next()
  38. }
  39. /**
  40. *
  41. * @param {string} token uppy auth token
  42. * @param {string} origin url string
  43. */
  44. const htmlContent = (token, origin) => {
  45. return `
  46. <!DOCTYPE html>
  47. <html>
  48. <head>
  49. <meta charset="utf-8" />
  50. <script>
  51. window.opener.postMessage(JSON.stringify({token: "${token}"}), "${sanitizeHtml(origin)}")
  52. window.close()
  53. </script>
  54. </head>
  55. <body></body>
  56. </html>`
  57. }
  58. /**
  59. * @todo remove this function in next major release
  60. * @param {string} token uppy auth token
  61. * @param {string} origin url string
  62. */
  63. const oldHtmlContent = (token, origin) => {
  64. return `
  65. <!DOCTYPE html>
  66. <html>
  67. <head>
  68. <meta charset="utf-8" />
  69. <script>
  70. window.opener.postMessage({token: "${token}"}, "${sanitizeHtml(origin)}")
  71. window.close()
  72. </script>
  73. </head>
  74. <body></body>
  75. </html>`
  76. }