forked from hannahpatellis/gthousedash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
255 lines (227 loc) · 7.49 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
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
const express = require("express");
const path = require("path");
const bodyParser = require("body-parser");
const mongojs = require("mongojs");
const ObjectId = require("mongodb").ObjectID;
require('dotenv').config();
const PORT = process.env.PORT || 3001;
const bcrypt = require('bcrypt');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
if (process.env.NODE_ENV === "production") {
app.use(express.static("client/build"));
}
// Mongo connection
const db = mongojs(process.env.MONGODB_URI, ["houses", "users", "log", "challenge"]);
db.on("error", error => {
console.log("Database Error: ", error);
});
// Mongo log point change
const dbLog = (user, points, house) => {
const logEntry = {
user: user,
points: points,
house: house,
ts: new Date().toString()
};
db.log.save(logEntry, (err, results) => {
if (err) throw err;
return true;
});
};
// Mongo log new challenge
const dbChallengeLog = (user, challenge) => {
const logEntry = {
user: user,
challenge: challenge,
ts: new Date().toString()
};
db.log.save(logEntry, (err, results) => {
if (err) throw err;
return true;
});
};
// Make and store a new token and expiration
const makeToken = user => {
const tokenPart = Math.random().toString(36).substr(2);
const token = tokenPart + tokenPart;
const expires = Date.now() + 604800000;
db.users.update({ user: user }, { $push: { tokens: { token: token, expires: expires } } }, (err, results) => {
if (err) throw err;
});
return token;
};
// Validate API calls using token
/* This function currently returns undefined before finishing the if statement. */
const validateToken = (user, token) => {
console.log("validateToken: Token: ", token);
console.log("validateToken: User: ", user);
let userExpire;
let tokenFound = false;
if (!token || !user) {
console.log("validateToken: No token or no user. FAIL");
return false;
} else {
db.users.find({ user: user }, (err, results) => {
if (err) throw err;
results[0].tokens.forEach(e => {
if (e.token === token) {
tokenFound = true;
userExpire = e.expires;
}
});
if (tokenFound) {
const currentTS = Date.now();
if (currentTS > userExpire) {
console.log("validateToken: Today's timestamp is greater than the expiration timestamp. FAIL");
return false;
} else if (currentTS < userExpire) {
console.log("validateToken: Today's timestamp is less than the expiration timestamp. PASS");
return true;
}
} else if (tokenFound === false) {
console.log("validateToken: No token found. FAIL");
return false;
} else {
console.log("validateToken: None of the conditionals passed. FAIL");
return false;
}
});
}
};
// Routes
app.post("/api/add", (req, res) => {
db.houses.find({ house: req.body.house }, (err, results) => {
if (err) throw err;
let currentPoints = parseInt(results[0].points);
let currentWeekPoints = parseInt(results[0].weekpoints);
let revisedPoints = currentPoints + parseInt(req.body.points);
let revisedWeekPoints = currentWeekPoints + parseInt(req.body.points);
console.log(validateToken(req.body.user, req.body.token));
dbLog(req.body.user, parseInt(req.body.points), req.body.house);
db.houses.update({ house: req.body.house }, { $set: { points: revisedPoints, weekpoints: revisedWeekPoints } }, () => {
res.status(200).end();
});
});
});
app.post("/api/subtract", (req, res) => {
db.houses.find({ house: req.body.house }, (err, results) => {
if (err) throw err;
let currentPoints = parseInt(results[0].points);
let currentWeekPoints = parseInt(results[0].weekpoints);
let revisedPoints = currentPoints - 1;
let revisedWeekPoints = currentWeekPoints - 1;
console.log(validateToken(req.body.user, req.body.token));
dbLog(req.body.user, -1, req.body.house);
db.houses.update({ house: req.body.house }, { $set: { points: revisedPoints, weekpoints: revisedWeekPoints } }, () => {
res.status(200).end();
});
});
});
app.post("/api/reset", (req, res) => {
db.houses.update({ house: req.body.house }, { $set: { weekpoints: 0 } }, (err) => {
if(err) throw err;
res.status(200).end();
});
});
app.post("/api/owl", (req, res) => {
db.houses.update({}, { $set: { owl: false } }, { multi: true }, (err) => {
if(err) throw err;
db.houses.update({ house: req.body.house }, { $set: { owl: true } }, (err) => {
if(err) throw err;
res.status(200).end();
});
});
});
app.get("/api/get", (req, res) => {
db.houses.find({}, (err, results) => {
if (err) throw err;
res.send(results).end();
});
});
app.post("/api/challenge", (req, res) => {
dbChallengeLog(req.body.user, req.body.challenge);
db.challenge.update({ "_id": ObjectId("5b7cf1d6b48b0921af336561") }, { $set: { challenge: req.body.challenge } }, () => {
res.status(200).end();
});
});
app.get("/api/getchallenges", (req, res) => {
db.challenge.find({ "_id": ObjectId("5b7cf1d6b48b0921af336561") }, (err, results) => {
if (err) throw err;
res.json({ challenge: results[0].challenge });
});
});
app.post("/api/auth", (req, res) => {
if (!req.body.user || !req.body.password) {
res.json({ success: false });
} else {
db.users.find({ user: req.body.user }, (err, results) => {
if (err) throw err;
if (!results[0]) {
res.json({ success: false });
} else {
bcrypt.compare(req.body.password, results[0].password, function (err, result) {
if (err) throw err;
if (result === true) {
const token = makeToken(req.body.user);
res.json({ success: true, token: token, user: req.body.user });
} else if (result === false) {
res.json({ success: false });
} else {
res.json({ success: false });
}
});
// Fallback to using password in env because bcrypt won't work on Heroku right now
if(process.env.PASS === req.body.password) {
const token = makeToken(req.body.user);
res.json({ success: true, token: token, user: req.body.user });
} else {
res.json({ success: false });
}
}
});
}
});
app.post("/api/validate", (req, res) => {
let userExpire;
let tokenFound = false;
if (!req.body.token || !req.body.user) {
res.json({ success: false });
} else {
db.users.find({ user: req.body.user }, (err, results) => {
if (err) throw err;
results[0].tokens.forEach(e => {
if (e.token === req.body.token) {
tokenFound = true;
userExpire = e.expires;
}
});
if (tokenFound === true) {
const currentTS = Date.now();
if (currentTS > userExpire) {
res.json({ success: false });
} else if (currentTS < userExpire) {
res.json({ success: true });
}
} else if (tokenFound === false) {
res.json({ success: false });
} else {
res.json({ success: false });
}
});
}
});
// HASHING ROUTE
// Uncomment this to make the hash function available for making new users
app.post("/api/hash", (req, res) => {
bcrypt.hash(req.body.password, 10, function(err, hash) {
res.json({ hash: hash });
});
});
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "./client/build/index.html"));
});
app.listen(PORT, () => {
console.log(`🌎 ==> Server now on port ${PORT}!`);
});