-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
199 lines (176 loc) · 4.64 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
"use strict";
require('dotenv').config();
const PORT = process.env.PORT || 8080;
const ENV = process.env.ENV || "development";
const express = require("express");
const bodyParser = require("body-parser");
const cookieSession = require('cookie-session');
const sass = require("node-sass-middleware");
const app = express();
const knexConfig = require("./knexfile");
const knex = require("knex")(knexConfig[ENV]);
const morgan = require('morgan');
const knexLogger = require('knex-logger');
const bcrypt = require('bcrypt');
// Seperated Routes for each Resource
const mapsRoutes = require("./routes/maps");
const usersRoutes = require("./routes/users");
// Load the logger first so all (static) HTTP requests are logged to STDOUT
// 'dev' = Concise output colored by response status for development use.
// The :status token will be colored red for server error codes, yellow for client error codes, cyan for redirection codes, and uncolored for all other codes.
app.use(morgan('dev'));
// Log knex SQL queries to STDOUT as well
app.use(knexLogger(knex));
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieSession({
name: 'session',
keys: ["Slowly at first", "as if it hardly meant it", "the snow began to fall."],
// Cookie Options
maxAge: 24 * 60 * 60 * 1000
}));
// checks session and if valid sets req.userLoggedIn = true (or false if not logged in)
app.use((req, res, next) => {
// console.log(`req.session.userId is ${req.session.userId}`);
if(req.session.userId){
req.loggedIn = true;
} else {
req.loggedIn = false;
}
next();
});
app.use("/styles", sass({
src: __dirname + "/styles",
dest: __dirname + "/public/styles",
debug: true,
outputStyle: 'expanded'
}));
app.use(express.static("public"));
// Mount all resource routes
app.use("/maps", mapsRoutes(knex));
app.use("/users", usersRoutes(knex));
app.get("/", (req, res) => {
res.redirect("/maps");
});
app.get("/login", (req, res) => {
if(req.loggedIn){
res.redirect("/");
} else {
res.render("login", {loggedIn: req.loggedIn, userId: req.session.userId});
}
});
app.get("/register", (req, res) => {
if(req.loggedIn){
res.redirect("/");
} else {
res.render("register", {loggedIn: req.loggedIn, userId: req.session.userId});
}
});
function checkEmptyFields(req, res) {
return (!req.body.username ||
!req.body.email ||
!req.body.first_name ||
!req.body.last_name ||
!req.body.password);
}
// Calls callback if username does not already exist.
function checkUsernameReg(req, res, callback) {
knex
.select()
.from('users')
.where('username', req.body.username)
.then(user => {
if (!user.length) {
callback();
} else {
res.status(200).send("1");
}
})
.catch(err => {
console.error(err);
});
}
function checkEmailReg(req, res, cb) {
knex
.select()
.from('users')
.where('email', req.body.email)
.then(user => {
if (!user.length) {
cb();
} else {
res.status(200).send("2");
}
})
.catch(err => {
console.error(err);
});
}
function insertUserInfoDb(req, cb) {
bcrypt.hash(req.body.password, 12)
.then(hash => {
knex("users").insert({
username: req.body.username,
email: req.body.email,
first_name: req.body.first_name,
last_name: req.body.last_name,
password_hash: hash
})
.then(cb);
})
.catch(err => {
console.error(err);
});
}
function getUserIdFromEmail(req, res) {
knex
.select()
.from('users')
.where('email', req.body.email)
.then(rows => {
req.session.userId = rows[0].id;
res.status(200).send();
})
.catch(err => {
console.error(err);
});
}
app.post("/register", (req, res) => {
if (checkEmptyFields(req)) {
res.status(200).send("3");
} else {
checkUsernameReg(req, res, function() {
checkEmailReg(req, res, function() {
insertUserInfoDb(req, function() {
getUserIdFromEmail(req, res);
});
});
});
}
});
// logs in user with email
app.post("/login", (req, res) => {
if(req.body.email) {
knex
.select()
.from('users')
.where('email', req.body.email)
.then(rows => {
req.session.userId = rows[0].id;
res.redirect("/");
})
.catch(err => {
console.error(err);
});
} else {
res.redirect("/");
}
});
// remove session cookie and redirect to main page
app.post("/logout", (req, res) => {
req.session = null;
res.redirect("/");
});
app.listen(PORT, () => {
console.log("Example app listening on port " + PORT);
});