send-token.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /**
  2. *
  3. * sends auth token to uppy client
  4. */
  5. const tokenService = require('../helpers/jwt')
  6. const parseUrl = require('url').parse
  7. const { hasMatch, sanitizeHtml } = require('../helpers/utils')
  8. const oAuthState = require('../helpers/oauth-state')
  9. /**
  10. *
  11. * @param {object} req
  12. * @param {object} res
  13. * @param {function} next
  14. */
  15. module.exports = function sendToken (req, res, next) {
  16. const uppyAuthToken = req.uppy.authToken
  17. // add the token to cookies for thumbnail/image requests
  18. tokenService.addToCookies(res, uppyAuthToken, req.uppy.options)
  19. const state = (req.session.grant || {}).state
  20. if (state) {
  21. const origin = oAuthState.getFromState(state, 'origin', req.uppy.options.secret)
  22. const allowedClients = req.uppy.options.clients
  23. // if no preset clients then allow any client
  24. if (!allowedClients || hasMatch(origin, allowedClients) || hasMatch(parseUrl(origin).host, allowedClients)) {
  25. return res.send(htmlContent(uppyAuthToken, origin))
  26. }
  27. }
  28. next()
  29. }
  30. /**
  31. *
  32. * @param {string} token uppy auth token
  33. * @param {string} origin url string
  34. */
  35. const htmlContent = (token, origin) => {
  36. return `
  37. <!DOCTYPE html>
  38. <html>
  39. <head>
  40. <meta charset="utf-8" />
  41. <script>
  42. window.opener.postMessage({token: "${token}"}, "${sanitizeHtml(origin)}")
  43. window.close()
  44. </script>
  45. </head>
  46. <body></body>
  47. </html>`
  48. }