This repository has been archived by the owner on Apr 9, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
394 lines (351 loc) · 10.4 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
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
let mysql = require("mysql");
let bcrypt = require("bcrypt");
let express = require("express");
let path = require("path");
let sessions = require("express-session");
let cookieParser = require('cookie-parser');
// config.json holds the credentials for the database and other important
// init settings
const init = require("./config.json");
const app = express();
// root directory
const root = path.join(__dirname, "./root");
const db = mysql.createConnection(init.db);
// const db = mysql.createPool(init.db);
// connect to the database
db.connect((err) =>
{
if (err) throw err;
console.log("Connected to database");
// just to verify that it connected to the DB, print to console
db.query("SHOW TABLES", function (err, result)
{
if (err) throw err;
console.log(result);
});
});
// set the application to use the cookies specified in config.json
app.use(cookieParser());
app.use(express.json());
app.use(sessions(init.cookies));
app.use(express.static(root));
app.use((req, res, next) =>
{
if (req.cookies.tracker && !req.session.uid)
{
res.clearCookie(init.cookies.key);
}
next();
});
// start the server listening on port 8080
app.listen(8080, function (err)
{
if (err) throw err;
console.log("Server started");
});
// Get root file path
app.get('/', function (request, response)
{
console.log("GET / ");
console.log(request.headers);
console.log(request.session);
response.sendFile(path.join(root, 'index.html'));
});
// send html file for login page
app.get("/login", is_logged_in, (req, res) =>
{
console.log("\n\nGET /login");
console.log(req.cookies);
console.log(req.session);
res.sendFile(path.join(root, "login.html"));
});
// user has submitted the login information
app.post('/login', is_logged_in, (request, response) =>
{
console.log(request.session);
console.log("\n\nPOST /login ");
var email = request.headers.email;
var password = request.headers.password;
console.log("\n\nUsername: " + email + " | Password: " + password);
// empty username or password
if (!email || !password)
{
response.status(401).send("Error: Please fill all fields.");
return;
}
// query db for user info
db.query("SELECT * FROM ?? WHERE EMAIL=?", [init.db.user_table, email], (err, res) =>
{
if (err) console.log("Code: ", err.code, "SQL: ", err.sql);
console.log(res);
// if the response is not empty
if (res !== undefined && res.length > 0)
{
// compare the password to the hashed password
if (res[0].PASSHASH === null)
{
response.status(401).send("Error: Invalid username or password.");
return;
}
// compare stored hash
bcrypt.compare(password, res[0].PASSHASH, (err, res)=>
{
if (err) console.log(err);
// password matches
if (res === false)
{
console.log("Password does not match");
response.status(401).send("Error: Invalid username or password.");
}
else
{
console.log("\nredirecting to user dashboard");
request.session.uid = email;
response.status(202).send(`/dashboard/${request.session.uid}`);
}
});
}
else
{
console.log("User doesn't exist");
response.status(401).send("Error: No such user.");
}
});
});
// function to log the user out.
app.get("/signout", not_logged_in, (req, res) =>
{
console.log("signing user out");
req.session.uid = null;
req.session.destroy();
res.redirect("/");
});
app.get("/signup", is_logged_in, (req, res) =>
{
console.log("\nGET /signup\n");
res.sendFile(path.join(root, "signup.html"));
});
// user has submitted the login information
app.post('/signup', is_logged_in, (request, response) =>
{
console.log("\nPOST /signup ");
var email = request.headers.email;
var password = request.headers.password;
var name = request.headers.name;
// if any fields are empty or the email is not valid return an error
const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (email === "" || password === "" || name === "" || !re.test(email))
{
console.log("invalid password, email, or name");
response.status(401).send("Error: Invalid Email, Name, or Password");
return;
}
// hash password and verify user
bcrypt.hash(password, 10, (err, hash) =>
{
const data = [email, name, hash];
check_user_in_users(data)
.then(create_user_table)
.then(insert_to_users_table)
.then((res) =>
{
request.session.uid = email;
const url = `/dashboard/${request.session.uid}`;
console.log("redirecting to dashboard at", request.session.uid);
response.status(202).send(url);
})
.catch(err => response.status(500).send("Error" + err.toString()));
});
});
// redirect the user to their dashboard. totally unnecessary
app.get("/dashboard", not_logged_in, (request, response) =>
{
var uid = request.session.uid;
response.redirect(`/dashboard/${uid}`);
});
// the user's dashboard
app.get('/dashboard/:uid', not_logged_in, (request, response) =>
{
console.log("\nGET /dashboard/:", request.session.uid);
const uid = request.session.uid;
const query_string = "SELECT * FROM " + mysql.escapeId(uid, true);
new Promise((resolve, reject) =>
{
db.query(query_string, uid, (err, res) =>
{
if (err) reject(err);
else resolve(res);
});
}).then((res) =>
{
console.log("redirecting");
response.sendFile(path.join(root, "dashboard.html"));
})
.catch((err) =>
{
console.log("Code: ", err.code, "SQL: ", err.sql);
response.status(501).send("Error: The server encountered an error.");
});
});
// post request sent by the dashboard
app.post("/data", not_logged_in, (request, response) =>
{
console.log("POST /data?", request.query);
let init = request.query.init_load;
let insert = request.query.insert;
const uid = request.session.uid;
var query_string;
var options = [];
console.log("init=", init, "&insert=", insert);
// ?init=true&insert=false
if (init === "true" && insert === 'false' )
{
query_string = "SELECT * FROM " + mysql.escapeId(uid, true);
}
// ?init=false&insert=true
else if (init === 'false' && insert === 'true')
{
const values = request.body;
console.log(request.body);
const table_name = mysql.escapeId(uid, true);
query_string = "INSERT INTO " + table_name +
" SET TRANS_DATE=?, AMOUNT=?, TRANS_TYPE=?, TRANS_DESCRIPTION=?";
options = [values.TRANS_DATE, parseFloat(values.AMOUNT), values.TRANS_TYPE, values.TRANS_DESCRIPTION];
}
else
{
console.log(request.session.uid, "Sent invalid parameters");
response.status(500).send("Error: Invalid parameters.");
return;
}
db.query(query_string, options, (err, res) =>
{
if (err)
{
console.log("Code:", err.code, " | SQL:", err.sql);
response.status(500).send("Error: The server encountered an error.");
}
else response.status(202).json(res);
});
});
// client function to remove an entry from the DB
app.delete("/data", not_logged_in, (request, response) =>
{
console.log("DELETE /data?" + JSON.stringify(request.query));
console.log(request.query);
const trans_id = request.query.trans_id;
const uid = request.session.uid;
// if there was an error with sending the transaction id send an error
if (trans_id === undefined || trans_id === "")
{
response.status(501).send("Error: transaction id:", trans_id);
return;
}
const query_string = "DELETE FROM " + mysql.escapeId(uid, true) + " WHERE" +
" TRANS_ID=?";
db.query(query_string, trans_id, (err, res) =>
{
if (err)
{
console.log("Code:", err.code, " | SQL:", err.sql);
response.status(501).send("Error: The server encountered an error.");
}
else
{
console.log("Deletion of", trans_id, "successful. Result:", res);
response.status(202).send("Deletion successful.");
}
})
});
// query the database during creation to see if the user already exists in the table of users
function check_user_in_users(data)
{
const email = data[0];
return new Promise((resolve, reject) =>
{
console.log("checking if user already exists");
db.query("SELECT * FROM ?? WHERE EMAIL=?", [init.db.user_table, email], (err, res) =>
{
if (err) reject([err.code, err.sql]);
console.log(res);
if (res !== undefined && res.length > 0) reject("User already exists.");
else resolve(data);
});
});
}
// create a new table for the user
function create_user_table(data)
{
const email = data[0];
console.log("creating user table");
return new Promise((resolve, reject) =>
{
var query = "CREATE TABLE " + mysql.escapeId(email, true) + " LIKE template";
db.query(query, (err, res) =>
{
if (err)
{
console.log("Code: ", err.code, "Sql: ", err.sql);
reject("User already exists.");
}
else
{
console.log(email, " table created");
resolve(data);
}
});
});
}
// add the user to the users table
function insert_to_users_table(data)
{
const email = data[0];
const name = data[1];
const hash = data[2];
console.log("inserting user to users table");
return new Promise((resolve, reject) =>
{
var data = {USERNAME: name, PASSHASH: hash, EMAIL: email};
db.query("INSERT INTO ?? SET ?", [init.db.user_table, data], (err, res) =>
{
if (err) reject([err.code, err.sql]);
else
{
console.log(email, " inserted into table of users.", "hash: ", hash);
resolve(data);
}
});
});
}
// check if the user is logged into an account
function is_logged_in(request, response, next)
{
console.log("\nverifying login");
// if the user is not logged in redirect them to the login page
if (request.session.uid && request.cookies.tracker)
{
console.log("redirecting to user dashboard");
response.redirect(`/dashboard/${request.session.uid}`);
}
// do the next function
else
{
console.log("user not logged in");
next();
}
}
function not_logged_in(request, response, next)
{
console.log('\nverifying user is not logged in');
if (!request.session.uid || !request.cookies.tracker)
{
console.log("redirecting to login page");
response.redirect("/login");
}
// do the next function
else
{
console.log("user logged in: ", request.session.uid);
next();
}
}