-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
273 lines (235 loc) · 8.27 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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
if (process.env.NODE_ENV !== 'production') {
require('dotenv').config()
}
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const { mongoose, registerUser, loginUser, addFoodToCurrentUser, getCurrentUser, removeFoodFromCurrentUser, changePassword, changePersonalInfo } = require("./backend/backend_funcs")
const fetch = require("node-fetch");
const session = require("express-session")
const { URL, URLSearchParams } = require('url')
const { UserSchema } = require("./backend/backend_funcs");
const cors = require("cors");
const jwt = require('jsonwebtoken');
const path = require('path');
app.set('trust proxy', 1)
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");
app.use(cors());
app.use(session({
secret: process.env.SESSION_SECRET,
resave: true,
saveUninitialized: true,
cookie: { maxAge: 600000 }
}))
app.use(express.static('views'))
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.set('trust proxy', 1)
function isAuthenticated(req) {
return req.session.autho ? true : false;
}
app.get('/is-mongoose-ok', function (req, res) {
if (mongoose) {
res.json({ isMongooseOk: !!mongoose.connection.readyState })
} else {
res.json({ isMongooseOk: false })
}
});
app.get('/test-mongoose', function (req, res) {
createAndSavePerson();
res.json({ isMongooseOk: true })
});
//Remove this later, I'm lazy
app.get("/index.html", (req, res) => {
res.render("index", { loggedin: isAuthenticated(req) })
});
app.get("/login", (req, res) => {
res.render("login");
});
app.post("/user/register", (req, res) => {
registerUser(req.body.name, req.body.email, req.body.password, []);
res.redirect("/login");
});
app.post("/user/login", async function (req, res, next) {
try {
req.session.autho = await loginUser(req.body.email, req.body.password);
const email = req.body.email;
const user = await Person.findOne({ email: email }).exec(); //DO WE NEED THIS LINE?? Nope
const token = jwt.sign({ email }, process.env.ACCESS_TOKEN_SECRET);
req.session.autho = "Bearer " + token;
res.redirect("/");
} catch (err) {
next(err);
}
});
app.get("/suggestions", (req, res) => {
res.render("suggestions", { loggedin: isAuthenticated(req) });
});
app.get("/single-item", (req, res) => {
res.render("single-item", { loggedin: isAuthenticated(req) });
});
app.get("/logout", (req, res) => {
req.session.destroy();
res.redirect("/");
});
app.get("/history", authenticateToken, async (req, res) => {
// const jsonFetch = {
// method: 'POST',
// headers: {
// 'Content-Type': 'application/json',
// 'Accept': 'application/json',
// 'Authorization': `Bearer ${req.session.autho}`
// },
// body: JSON.stringify({
// query: `{
// user {
// name
// foods {
// name
// date
// nutritionixId
// isCommonFood
// imgSrc
// calories
// }
// }
// }
// `,
// })
// };
res.render("history", { user: req.user ? await getCurrentUser(req.user.email) : {}, loggedin: isAuthenticated(req) });
});
app.get("/search", (req, res) => {
let searchURL = new URL("https://trackapi.nutritionix.com/v2/search/instant");
let params = { query: req.query['search-key'] };
searchURL.search = new URLSearchParams(params).toString();
fetch(searchURL, {
method: "GET",
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'x-app-id': 'dc50e0ed',
'x-app-key': 'e4ba8175f2f600d999e22b205a8e402c'
}
}).then(res => res.json())
.then(data => {
res.render("post-search", { searchedFoods: data.common.concat(data.branded), loggedin: isAuthenticated(req) })
})
.catch(err => res.send(err));
});
function findNutrientsValue(full_nutrients) {
return function (attr_id) {
const attr = full_nutrients.find(elem => elem.attr_id === attr_id);
if (attr) return attr.value
return 0;
}
}
app.get("/food/name/:foodname", (req, res) => {
fetch("https://trackapi.nutritionix.com/v2/natural/nutrients", {
method: "POST",
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
"x-app-id": "dc50e0ed",
"x-app-key": "e4ba8175f2f600d999e22b205a8e402c"
},
body: JSON.stringify({
query: req.params.foodname
})
}).then(res => res.json())
.then(data => {
const { full_nutrients, ...food } = data.foods[0]
console.log(food)
res.render("single-item", { food, foodURL: `/food/id/${req.params.foodname}`, nfByCode: findNutrientsValue(full_nutrients), loggedin: isAuthenticated(req) })
}
)
.catch(err => res.send(err));
})
app.get("/food/id/:id", (req, res) => {
fetch(`https://trackapi.nutritionix.com/v2/search/item?nix_item_id=${req.params.id}`, {
method: "GET",
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
"x-app-id": "dc50e0ed",
"x-app-key": "e4ba8175f2f600d999e22b205a8e402c"
}
}).then(res => res.json())
.then(data => {
const { full_nutrients, ...food } = data.foods[0]
console.log(food)
res.render("single-item", { food, foodURL: `/food/id/${req.params.id}`, nfByCode: findNutrientsValue(full_nutrients), loggedin: isAuthenticated(req) })
}
)
.catch(err => res.send(err));
})
var Person = mongoose.model("Person", UserSchema)
app.get('/account-settings', authenticateToken, async (req, res) => {
const user = await Person.findOne({ email: req.user.email }).exec();
res.render("account-settings", user);
})
function authenticateToken(req, res, next) {
const authHeader = req.session.autho;
const token = authHeader && authHeader.split(' ')[1];
// console.log(authHeader)
if (token == null) {
req.errorCode = 401;
return next();
// return res.sendStatus('401');
}
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) => {
// if(err) return res.sendStatus('403');
if (err) {
req.errorCode = 403;
return next();
}
req.user = user;
next();
});
}
app.post("/add-food", authenticateToken, async (req, res) => {
addFoodToCurrentUser(req.user.email, req.body.name, req.body.foodURL, req.body.imgSrc, req.body.calories);
});
app.post("/remove-food", authenticateToken, async (req, res, next) => {
removeFoodFromCurrentUser(req.user.email, req.body._id);
// res.redirect("/");
})
app.get("/", authenticateToken, (req, res) => {
res.render("index", { loggedin: isAuthenticated(req) })
});
app.post("/user/change-password", authenticateToken, async (req, res) => {
changePassword(req.body.email, req.body.oldPw, req.body.newPw, req.body.rptNewPw);
res.redirect("/");
})
app.post("/user/updated-info", authenticateToken, async (req, res) => {
changePersonalInfo(req.user.email, req.body.name, req.body.email);
res.redirect("/");
})
// Not found middleware
app.use((req, res, next) => {
return next({ status: 404, message: "not found" });
});
// Error Handling middleware
app.use((err, req, res, next) => {
let errCode, errMessage;
if (err.errors) {
// mongoose validation error
errCode = 400; // bad request
const keys = Object.keys(err.errors);
// report the first validation error
errMessage = err.errors[keys[0]].message;
} else {
// generic or custom error
errCode = err.status || 500;
errMessage = err.message || "Internal Server Error";
}
res
.status(errCode)
.type("txt")
.send(errMessage);
});
const listener = app.listen(process.env.PORT || 3000, () => {
console.log("Your app is listening on http://localhost:" + listener.address().port);
});
module.exports = app