-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
84 lines (73 loc) · 2.05 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
require('dotenv').config();
const express = require('express');
const {createProxyMiddleware} = require('http-proxy-middleware');
const bodyParser = require('body-parser');
const path = require('path');
const app = express();
const port = process.env.PORT || 3001;
/**
* function to exclude a specific sub-url
*
* @param base base url
* @param paths path to exclude incl. base url
* @param middleware middleware to execute
*/
const except = function (base, paths, middleware)
{
return function (req, res, next)
{
const isCorrectBaseURL = req.path.indexOf(base) === 0;
const isExcludedPath = paths.map(pP => req.path.indexOf(pP) === 0).indexOf(true) > -1;
if (!isCorrectBaseURL || isExcludedPath)
{
// Exclude
return next();
}
else
{
// Apply for all others
return middleware(req, res, next);
}
};
};
// serve build in production
app.use(express.static(path.join(__dirname, 'build')));
// serve index.html in production
app.use(except("/", ["/api", "/auth"], function (req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
}));
// proxy to backend
app.use("/api", createProxyMiddleware({
target: process.env.API_TARGET,
pathRewrite: {
'^/api': '/',
},
changeOrigin: true,
}));
// parse JSON
app.use(bodyParser.json());
// proxy to authentication server
app.use('/auth', createProxyMiddleware({
target: process.env.AUTH_TARGET,
pathRewrite: {
'^/auth': '/',
},
changeOrigin: true,
onProxyReq(proxyReq, req)
{
if (!req.body || !Object.keys(req.body).length)
return;
const bodyData = JSON.stringify({
...req.body,
"grant_type": !!req.body.refresh_token ? "refresh_token" : "password",
"audience": "https://api.homestack.de",
"client_id": process.env.AUTH_APPLICATIONID,
"scope": "openid profile email offline_access",
});
proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
proxyReq.write(bodyData);
},
}));
app.listen(port, () => {
console.log(`Express Backend listening on http://localhost:${port}`)
});