-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
98 lines (76 loc) · 2.71 KB
/
app.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
'use strict';
require('dotenv').config();
const express = require('express');
const app = express();
const dao = require('./dao/access.js');
const session = require('express-session');
const md5 = require('md5');
const sanitizer = require('sanitizer');
const bodyParser = require('body-parser');
const profRoutes = require('./routes/profile.js');
const DEFAULT_PORT = process.env.DEFAULT_PORT;
app.use('/public', express.static('./public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(session({ secret: 'keyboard cat', cookie: { maxAge: 600000 }}));
app.set('view engine', 'pug');
// Apparently important to do this AFTER view engine is set...
app.use('/app', profRoutes);
// APPLICATION ROUTES
app.get(["/", "/login"], (req, res) => {
if (req.session.username) {
res.redirect('/app/home');
}
res.render('begin');
});
app.get('/test', (req, res) => {
dao.findTest(results => {
res.send( '' + results);
})
});
app.post('/login', (req, res) => {
const usrname = sanitizer.sanitize(req.body.username),
passwd = sanitizer.sanitize(req.body.password);
const str = usrname + ", " + passwd;
dao.findUser(usrname, function(errors, results) {
if (errors) {
res.send('An error occurred: ' + error);
} else {
const u = results[0];
if (u && u._data.password === md5(passwd)) {
req.session.username = u._data.username;
req.session.userId = u._data.id;
res.redirect('/app/home');
} else {
res.send('Incorrect username or password.');
}
}
});
});
app.get("/register", (req, res) => {
res.render('register');
});
app.post("/register", (req, res) => {
dao.findUser(req.body.username, function(errors, results) {
if (errors) {
res.send("An error occurred: " + errors);
} else {
const u = results[0];
if (u) {
res.send("A user with the name '" + u._data.username + "' already exists!");
} else {
dao.createUser(req.body.username, req.body.email, md5(req.body.password), function (errors, results) {
if (errors) {
res.send("An error occurred: " + errors);
} else {
req.session.username = req.body.username;
req.session.userId = results._data.id;
res.redirect('/app/home');
}
})
}
}
})
});
// FIRE UP APPLICATION
app.listen(DEFAULT_PORT, () => console.log('Listening on port 3000!'));