forked from cs4241-20a/final-project
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
331 lines (287 loc) · 8.6 KB
/
server.js
File metadata and controls
331 lines (287 loc) · 8.6 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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
// server.js
// where your node app starts'
// we've started you off with Express (https://expressjs.com/)
// but feel free to use whatever libraries or frameworks you'd like through `package.json`.
const express = require("express");
const fetch = require("node-fetch");
const compression = require("compression");
const cookieSession = require("cookie-session");
const app = express();
const bodyparse = require("body-parser");
// specific to chat server
const ws = require("ws");
const http = require("http");
require("dotenv").config();
// middleware #1 - // make all the files in 'public' available
app.use(express.static("public"));
// middleware #2 - cookie session
app.use(
cookieSession({
httpOnly: false,
keys: ["secret"]
})
);
const mongodb = require("mongodb");
const MongoClient = mongodb.MongoClient;
const uri = `mongodb+srv://admin:a3-admin-password@a3-matt-tolbert.gv63o.mongodb.net/final_project?retryWrites=true&w=majority`;
const client = new MongoClient(uri, { useNewUrlParser: true });
let collection = null;
client.connect(err => {
collection = client.db("final_project").collection("database");
});
// user db
const users_uri = `mongodb+srv://admin:a3-admin-password@a3-matt-tolbert.gv63o.mongodb.net/final_project?retryWrites=true&w=majority`;
const users_client = new MongoClient(users_uri, { useNewUrlParser: true });
let users_collection = null;
users_client.connect(err => {
users_collection = users_client.db("final_project").collection("users");
});
// middleware #3 - verify mongodb connection
app.use((req, res, next) => {
if (collection !== null) {
next();
} else {
res.status(503).send();
}
});
// middleware #4 - convert body to json using bodyparser (consolidates parsing of body for add/modify/delete)
app.use(bodyparse.json());
// middleware #5 - use compression
app.use(compression({ filter: shouldCompress }));
function shouldCompress(req, res) {
if (req.headers["x-no-compression"]) {
// don't compress responses with this request header
return false;
}
// fallback to standard filter function
return compression.filter(req, res);
}
/*
Main Routing Handler
*/
app.get("/", (request, response) => {
// check if user logged in
if (request.session.userID) {
//console.log("Authenticated user found")
response.sendFile(__dirname + "/views/home.html");
} else {
//console.log("No authenticated user found")
response.sendFile(__dirname + "/views/login.html");
}
});
/*
Menu Button Handlers
*/
app.get("/goToChat", (request, response) => {
response.redirect("/chat");
});
app.get("/chat", (request, response) => {
// check if user logged in
if (request.session.userID) {
response.sendFile(__dirname + "/views/chat.html");
} else {
response.sendFile(__dirname + "/views/login.html");
}
});
app.get("/goToUsers", (request, response) => {
response.redirect("/users");
});
app.get("/users", (request, response) => {
// check if user logged in
if (request.session.userID) {
response.sendFile(__dirname + "/views/users.html");
} else {
response.sendFile(__dirname + "/views/login.html");
}
});
app.get("/goToAbout", (request, response) => {
response.redirect("/about");
});
app.get("/about", (request, response) => {
// check if user logged in
if (request.session.userID) {
response.sendFile(__dirname + "/views/about.html");
} else {
response.sendFile(__dirname + "/views/aboutOpen.html");
}
});
app.get("/goHome", (request, response) => {
response.redirect("/");
});
/*
Handle OAuth with GitHub - Tutorial from Kevin Simper @
https://www.kevinsimper.dk/posts/how-to-make-authentication-with-github-apps-for-side-projects
*/
const clientID = "fefd7ab3c9ce0018180d";
const clientSecret = "dd1fff679466ddc8176faa7536be6bf8f84eb78f";
app.get("/login", (req, res) => {
const path = req.protocol + "://" + req.get("host");
const url = `https://github.com/login/oauth/authorize?client_id=${clientID}&redirect_uri=${path}/login/github/callback`;
res.json(url);
});
// get access token from github oauth
async function getAccessToken(code, client_id, client_secret) {
const request = await fetch("https://github.com/login/oauth/access_token", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
client_id,
client_secret,
code
})
});
const text = await request.text();
const params = new URLSearchParams(text);
return params.get("access_token");
}
// get users profile from GitHub API
async function fetchGitHubUser(token) {
const request = await fetch("https://api.github.com/user", {
headers: {
Authorization: "token " + token
}
});
return await request.json();
}
app.get("/login/github/callback", async (req, res) => {
const code = req.query.code;
const access_token = await getAccessToken(code, clientID, clientSecret);
const user = await fetchGitHubUser(access_token);
if (user) {
console.log("user logged in as " + user.id);
req.session.userID = user.id;
req.session.username = user.login;
// see if user already exists
var userFound = false;
users_collection
.find({})
.toArray()
.then(result => {
result.forEach(element => {
if (element.userID === user.id) {
userFound = true;
}
});
if (!userFound) {
console.log("user not in system, adding them to db");
// add user to db list of users
const contents = {
userID: user.id,
username: user.login
};
users_collection.insertOne(contents);
} else {
console.log("User is in system, not adding them again...");
}
});
res.redirect("/");
} else {
// reload the page
console.log("Could not login user");
res.redirect("/login.html");
}
});
// logout user
app.get("/logout", (req, res) => {
if (req.session) req.session = null;
res.redirect("/");
});
/*
Data Management endpoints
*/
//TODO get users other than requesting users
app.get("/getUsers", (req, res) => {
users_collection
.find({})
.toArray()
.then(result => {
// only return other users
result = result.filter(function(value, index, arr) {
return value.userID != req.session.userID;
});
res.json(result);
});
});
app.post("/otherData", (req, res) => {
var userData = [];
collection
.find({ userID: req.body.requestID })
.toArray()
.then(result => res.json(result));
});
app.get("/data", (req, res) => {
var userData = [];
collection
.find({ userID: req.session.userID })
.toArray()
.then(result => res.json(result));
});
app.post("/add", (req, res) => {
// pull contents from req and insert to DB
const contents = {
userID: req.session.userID,
date: req.body.date,
musclegroup: req.body.musclegroup,
exercise: req.body.exercise,
repcount: req.body.repcount,
weight: req.body.weight
};
console.log(contents);
collection.insertOne(contents).then(result => {
// return entry from DB so that client can keep track of _id
res.json(result.ops[0]);
});
});
app.post("/delete", (req, res) => {
collection
.deleteOne({ _id: mongodb.ObjectID(req.body._id) })
.then(result => res.json(result));
});
app.post("/update", (req, res) => {
const json = {
userID: req.session.userID,
date: req.body.date,
musclegroup: req.body.musclegroup,
exercise: req.body.exercise,
repcount: req.body.repcount,
weight: req.body.weight
};
collection
.updateOne({ _id: mongodb.ObjectID(req.body._id) }, { $set: json })
.then(result => res.json(result));
});
// ------------------- Chat server ------------
const server = http.createServer(app);
const socketServer = new ws.Server({ server });
const clients = [];
let count = 0;
socketServer.on("connection", client => {
// when the server receives a message from this client...
client.on("message", msg => {
console.log(msg);
// send msg to every client EXCEPT
// the one who originally sent it. in this demo this is
// used to send p2p offer/answer signals between clients
if (msg.includes("commence connection")) {
}
clients.forEach(c => {
if (c !== client) c.send(msg);
});
});
// add client to client list
clients.push(client);
client.send(
JSON.stringify({
address: "connect",
// we only initiate p2p if this is the second client connected
initiator: ++count % 2 === 0
})
);
});
// --------------------------------------------
// listen for requests :)
const listener = server.listen(3000, () => {
console.log("Your app is listening on port " + listener.address().port);
});