proxy.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. Copyright (C) 2017 Cloudbase Solutions SRL
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Affero General Public License as
  5. published by the Free Software Foundation, either version 3 of the
  6. License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Affero General Public License for more details.
  11. You should have received a copy of the GNU Affero General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. import MsRest from 'ms-rest-azure'
  15. import bodyParser from 'body-parser'
  16. import axios from 'axios'
  17. const forwardHeaders = ['authorization']
  18. let buildError = message => {
  19. return {
  20. error: { message: `Proxy - ${message}` },
  21. }
  22. }
  23. module.exports = app => {
  24. const jsonParser = bodyParser.json()
  25. app.post('/azure-login', jsonParser, (req, res) => {
  26. MsRest.loginWithUsernamePassword(req.body.username, req.body.password, (err, credentials) => {
  27. if (err) {
  28. res.status(401).send(buildError(`Couldn't authenticate user: ${req.body.username}`))
  29. } else {
  30. res.send(credentials)
  31. }
  32. })
  33. })
  34. app.get('/proxy/*', (req, res) => {
  35. let url = req.url.substr('/proxy/'.length)
  36. let headers = {}
  37. forwardHeaders.forEach(headerName => {
  38. if (req.headers[headerName] != null) {
  39. headers[headerName] = req.headers[headerName]
  40. }
  41. })
  42. axios({ url, headers }).then(response => {
  43. res.send(response.data)
  44. }).catch(error => {
  45. if (error.response) {
  46. res.status(error.response.status).send(buildError(error.response.data.error.message))
  47. } else if (error.request) {
  48. res.status(500).send(buildError('No Response!'))
  49. } else {
  50. res.status(500).send(buildError('Error creating request!'))
  51. }
  52. })
  53. })
  54. }