Skip to content

Commit de82978

Browse files
committed
setup middleware
1 parent dc5265a commit de82978

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

services/user-service/index.js

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
const express = require("express");
2+
const cors = require("cors");
3+
const { createProxyMiddleware } = require("http-proxy-middleware");
4+
const { admin } = require("./firebase-admin-config");
5+
6+
const app = express();
7+
app.use(cors());
8+
9+
const MATCHING_SERVICE_URL = process.env.MATCHING_SERVICE_URL || "http://localhost:4001";
10+
const QUESTION_SERVICE_URL = process.env.QUESTION_SERVICE_URL || "http://localhost:4002";
11+
const COLLABORATION_SERVICE_URL = process.env.COLLABORATION_SERVICE_URL || "http://localhost:4003";
12+
13+
const verifyToken = async (req, res, next) => {
14+
const header = req.headers.authorization;
15+
if (!header || !header.startsWith("Bearer ")) {
16+
return res.status(401).json({ message: "Unauthorized" });
17+
}
18+
const token = header.split(" ")[1];
19+
try {
20+
const decodedToken = await admin.auth().verifyIdToken(token);
21+
req.user = decodedToken;
22+
next();
23+
} catch (error) {
24+
return res.status(401).json({ message: "Unauthorized" });
25+
}
26+
};
27+
28+
const onProxyReq = (proxyReq, req, res) => {
29+
if (req.user) {
30+
proxyReq.setHeader("x-user-id", req.user.uid);
31+
proxyReq.setHeader("x-user-email", req.user.email);
32+
}
33+
};
34+
35+
app.use(
36+
"/matching",
37+
verifyToken,
38+
createProxyMiddleware({
39+
target: MATCHING_SERVICE_URL,
40+
changeOrigin: true,
41+
onProxyReq,
42+
})
43+
);
44+
45+
app.use(
46+
"/questions",
47+
verifyToken,
48+
createProxyMiddleware({
49+
target: QUESTION_SERVICE_URL,
50+
changeOrigin: true,
51+
onProxyReq,
52+
})
53+
);
54+
55+
app.use(
56+
"/collaboration",
57+
verifyToken,
58+
createProxyMiddleware({
59+
target: COLLABORATION_SERVICE_URL,
60+
changeOrigin: true,
61+
onProxyReq,
62+
})
63+
);
64+
65+
app.get("/health", (req, res) => {
66+
res.send("User Service is healthy");
67+
});
68+
69+
const PORT = process.env.PORT || 4000;
70+
app.listen(PORT, () => {
71+
console.log(`User Service listening on port ${PORT}`);
72+
});

0 commit comments

Comments
 (0)