azureProxy.ts 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 express from 'express'
  15. import MsRest from 'ms-rest-azure'
  16. import axios from 'axios'
  17. const forwardHeaders = ['authorization']
  18. const buildError = (message: any) => ({
  19. error: { message: `Proxy - ${message}` },
  20. })
  21. export default (router: express.Router) => {
  22. router.post('/azure/login', (req, res) => {
  23. const handleResponse = (err: any, credentials: any) => {
  24. if (err) {
  25. console.log(err)
  26. res.status(401).send(buildError('Azure API authentication error'))
  27. } else {
  28. res.send(credentials)
  29. }
  30. }
  31. const connInfo = req.body
  32. const userCred = connInfo.user_credentials
  33. const servicePrin = connInfo.service_principal_credentials
  34. if (userCred && userCred.username && userCred.password) {
  35. MsRest.loginWithUsernamePassword(userCred.username, userCred.password, handleResponse)
  36. } else if (servicePrin && servicePrin.client_id && servicePrin.client_secret) {
  37. MsRest.loginWithServicePrincipalSecret(servicePrin.client_id, servicePrin.client_secret, connInfo.tenant, handleResponse)
  38. } else {
  39. res.status(401).send(buildError('Azure API authentication error'))
  40. }
  41. })
  42. router.get('/azure/*', (req, res) => {
  43. process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'
  44. const url = Buffer.from(req.url.substr('/proxy/'.length), 'base64').toString()
  45. const headers: any = {}
  46. forwardHeaders.forEach(headerName => {
  47. if (req.headers[headerName] != null) {
  48. headers[headerName] = req.headers[headerName]
  49. }
  50. })
  51. axios({ url, headers }).then(response => {
  52. res.send(response.data)
  53. }).catch(error => {
  54. if (error.response) {
  55. res.status(error.response.status).send(buildError(error.response.data.error.message))
  56. } else if (error.request) {
  57. console.log(error)
  58. res.status(500).send(buildError('No Response!'))
  59. } else {
  60. res.status(500).send(buildError('Error creating request!'))
  61. }
  62. })
  63. })
  64. }