proxy.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. let handleResponse = (err, credentials) => {
  27. if (err) {
  28. console.log(err)
  29. res.status(401).send(buildError('Azure API authentication error'))
  30. } else {
  31. res.send(credentials)
  32. }
  33. }
  34. let connInfo = req.body
  35. let userCred = connInfo.user_credentials
  36. let servicePrin = connInfo.service_principal_credentials
  37. if (userCred && userCred.username && userCred.password) {
  38. MsRest.loginWithUsernamePassword(userCred.username, userCred.password, handleResponse)
  39. } else if (servicePrin && servicePrin.client_id && servicePrin.client_secret) {
  40. MsRest.loginWithServicePrincipalSecret(servicePrin.client_id, servicePrin.client_secret, connInfo.tenant, handleResponse)
  41. } else {
  42. res.status(401).send(buildError('Azure API authentication error'))
  43. }
  44. })
  45. app.get('/proxy/*', (req, res) => {
  46. process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'
  47. let url = Buffer.from(req.url.substr('/proxy/'.length), 'base64').toString()
  48. let headers = {}
  49. forwardHeaders.forEach(headerName => {
  50. if (req.headers[headerName] != null) {
  51. headers[headerName] = req.headers[headerName]
  52. }
  53. })
  54. axios({ url, headers }).then(response => {
  55. res.send(response.data)
  56. }).catch(error => {
  57. if (error.response) {
  58. res.status(error.response.status).send(buildError(error.response.data.error.message))
  59. } else if (error.request) {
  60. console.log(error)
  61. res.status(500).send(buildError('No Response!'))
  62. } else {
  63. res.status(500).send(buildError('Error creating request!'))
  64. }
  65. })
  66. })
  67. }