-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
89 lines (79 loc) · 2.39 KB
/
Copy pathserver.js
File metadata and controls
89 lines (79 loc) · 2.39 KB
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
85
86
87
88
89
require("dotenv").config({ path: "./api/.env" });
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const jwt = require("jsonwebtoken");
app.use(bodyParser.json());
const rsaPublicKey =
process.env.NODE_ENV === "production"
? Buffer.from(process.env.RSA_PUBLIC_KEY, "base64").toString()
: process.env.RSA_PUBLIC_KEY.replace("\\n", "\n");
// Set up sequelize
const { sequelize } = require("./api/database/instance.js");
app.all("*", function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Content-Type, Authorization");
next();
});
app.get("/survey-responses", async (req, res) => {
try {
const token = req.headers.authorization.replace("Bearer ", "");
const verified = jwt.verify(token, rsaPublicKey, {
algorithm: "RS256",
});
const surveyResponses = await sequelize.models.SurveyResponse.findAll({
where: {
userId: verified.userId,
},
});
return res.send({ surveyResponses });
} catch (error) {
return res.status(401).send("Unauthorized");
}
});
app.post("/survey-responses", async (req, res) => {
try {
const token = req.headers.authorization.replace("Bearer ", "");
const verified = jwt.verify(token, rsaPublicKey, {
algorithm: "RS256",
});
const surveyResponse = await sequelize.models.SurveyResponse.create({
userId: verified.userId,
data: req.body.data,
});
return res.send(surveyResponse);
} catch (error) {
console.log("error", error);
return res.status(401).send("Unauthorized");
}
});
app.get("/results", async (req, res) => {
try {
const token = req.headers.authorization.replace("Bearer ", "");
const verified = jwt.verify(token, rsaPublicKey, {
algorithm: "RS256",
});
if (
!verified.authorization ||
!verified.authorization["5xbpy4nz"] ||
verified.authorization["5xbpy4nz"].roles.indexOf("admin") < 0
) {
throw new Error("Unauthorized");
}
return res.send({
results: {
data: [],
},
});
} catch (error) {
return res.status(401).send("Unauthorized");
}
});
app.get("/status", async (req, res) => {
return res.send("ok");
});
const port = process.env.PORT || 5000;
const server = app.listen(port, () =>
console.log(`✅ Backend listening on port ${port}`)
);
module.exports = server;