-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
226 lines (209 loc) · 5.36 KB
/
Copy pathserver.js
File metadata and controls
226 lines (209 loc) · 5.36 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
const bcrypt = require("bcryptjs");
const cors = require("cors");
const express = require("express");
const jwt = require("jsonwebtoken");
const { Poll, User } = require("./database.js");
const path = require("path");
const port = process.env.PORT || 5000;
const saltRounds = parseInt(process.env.SALT_ROUNDS) || 10;
require("dotenv").config();
const app = express();
app.use(cors());
app.use(express.json());
// app.use(express.static("public"));
app.use(express.static(path.join(__dirname, "frontend", "build")));
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "frontend", "build", "index.html"));
});
const generateAccessToken = (data) => {
const token = jwt.sign(data, process.env.JWT_SECRET_KEY, {expiresIn: process.env.TOKEN_LIFE});
return token;
};
// Authentication middleware
const authenticateToken = (req, res, next) => {
const authHeader = req.headers["authorization"];
const token = authHeader && authHeader.split(" ")[1];
if(token == null) {
return res.status(401).send("Unauthorized access");
}
// Veify the token of the user
jwt.verify(token, process.env.JWT_SECRET_KEY, (err, user) => {
if(err) {
console.error(err);
return res.status(403).send("Session expired");
}
req.currentUserName = user.name;
next();
})
};
// Verify authentication in routes
app.get("/api/verify", authenticateToken, (req, res) => {
res.send(req.currentUserName);
});
app.post("/api/register", (req, res) => {
// Check if username already exists
User.findOne({username: req.body.username}, (err, user) => {
if(err) {
console.error(err);
res.status(500).send("Internal server error");
}
else if(user) {
res.status(400).send("Username already exists");
}
else {
// Hash password
bcrypt.hash(req.body.password, saltRounds, (err_hash, hashPassword) => {
if(err_hash) {
console.error(err_hash);
res.status(500).send("Internal server error");
}
else {
const user = new User({
username: req.body.username,
password: hashPassword
});
// Save user to database
user.save((err_save) => {
if(err_save) {
console.error(err_save);
res.status(500).send("Internal server error");
}
else {
res.end();
}
});
}
});
}
});
});
// Login
app.post("/api/login", (req, res) => {
const username = req.body.username;
const password = req.body.password;
// Check if username exists
User.findOne({username: username}, (err, foundUser) => {
if(err) {
console.error(err);
res.status(500).send("Internal server error");
}
else {
if(foundUser) {
// Compare password
bcrypt.compare(password, foundUser.password, (err_cmp, result) => {
if(err_cmp) {
console.error(err_cmp);
res.status(500).send("Internal server error");
}
else if(result) { // Password matched
const accessToken = generateAccessToken({name: username});
res.send({username: username, accessToken: accessToken});
}
else {
res.status(401).send("Please provide a valid username and password.");
}
});
}
else {
res.status(401).send("Please provide a valid username and password.");
}
}
});
});
// Create a poll
app.post("/api/create", authenticateToken, (req, res) => {
const currentUserName = req.currentUserName;
const options = [];
req.body.options.map((element) => {
options.push({name: element, count: 0});
});
const newPoll = new Poll({
question: req.body.question,
options: options,
author: currentUserName,
voters: [],
});
// Save poll data to database
newPoll.save((err) => {
if(err) {
console.error(err);
res.status(500).send("Internal server error");
}
else {
res.end();
}
});
});
// Get all polls
app.get("/api/polls", authenticateToken, (req, res) => {
const currentUserName = req.currentUserName;
// Find all polls
Poll.find({}, (err, foundPolls) => {
if(err) {
console.error(err);
res.status(500).send("Internal server error");
}
else {
res.json({
currentUserName: currentUserName,
polls: foundPolls
});
}
});
});
app.route("/api/poll/:id")
// Get a poll
.get(authenticateToken, (req, res) => {
const currentUserName = req.currentUserName;
const id = req.params.id;
// Find the poll by its id
Poll.findById(id, (err, foundPoll) => {
if(err) {
console.error(err);
res.status(500).send("Internal server error");
}
else {
res.json({
currentUserName: currentUserName,
poll: foundPoll
});
}
});
})
// Delete a poll
.delete(authenticateToken, (req, res) => {
const id = req.params.id;
// Delete a poll by its id
Poll.deleteOne({_id: id}, (err, deletedPoll) => {
if(err) {
console.error(err);
res.status(500).send("Internal server error");
}
else {
res.end();
}
});
});
// Vote a poll
app.post("/api/vote/:id", authenticateToken, (req, res) => {
const currentUserName = req.currentUserName;
const id = req.params.id;
const poll = req.body.poll;
const index = req.body.index;
const newOptions = poll.options;
newOptions[index].count++;
// Update the poll data
Poll.findByIdAndUpdate(id, {options: newOptions, $push: {voters: currentUserName}}, (err, doc) => {
if(err) {
console.error(err);
res.status(500).send("Internal server error");
}
else {
res.end();
}
});
});
// Listen to a specific port
app.listen(port, () => {
console.log("Server running on port " + port);
});