-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
258 lines (211 loc) · 6.03 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
const express = require('express');
const { pool } = require('./dbConf');
const bcrypt = require('bcrypt');
const passport = require('passport');
const flash = require('express-flash');
const session = require('express-session');
require('dotenv').config();
const app = express();
app.use(express.json());
const PORT = process.env.PORT || 5000;
const initPassport = require('./passportConf');
initPassport(passport);
//Parse details from form
app.use(express.urlencoded({extended: false}));
app.use(express.static(__dirname + '/views'));
app.set('view engine', 'ejs');
app.use(
session({
secret: 'secret',
resave: false,
saveUninitialized: false
})
);
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(express.json());
/* Page Renderers */
app.get('/', (req, res) => {
res.render('login.ejs');
});
app.get('/users/register', checkAuth, (req, res) => {
res.render('register.ejs');
});
app.get('/users/login', checkAuth, (req, res) =>{
console.log(req.session.flash.error);
res.render('login.ejs');
});
app.get('/users/dashboard', checkNotAuthenticated, (req, res) => {
console.log(req.isAuthenticated());
res.render('dashboard', {user: req.user.name});
req.flash('success_msg', 'Logged in successfully');
});
app.get('/users/logout', (req, res) => {
req.logout();
req.flash('success_msg', 'You have logged out');
res.redirect('login');
});
app.post('/users/register', async (req, res) => {
let {name, email, password, password2} =req.body;
let errors = [];
console.log({
name,
email,
password,
password
});
if(!name || !email || !password || !password2) {
errors.push({message: 'All fields should be filled'});
}
if(password.length < 6){
errors.push({message: 'Password must be at least 8 Characters long'});
}
if(password !==password2){
errors.push({message: 'Passwords do not match'});
}
if(errors.length > 0){
res.render('register', {errors, name, email, password, password2});
} else {
hashedPassword = await bcrypt.hash(password, 10);
console.log(hashedPassword);
pool.query(
`SELECT * FROM users
WHERE email = $1
`,
[email],
(err, results) => {
if(err){
console.log(err);
}
console.log(results.rows);
if(results.rows.length > 0){
return res.render('register', {
message: 'Email/User already registered'
});
} else {
pool.query(
`INSERT INTO users (name, email, password)
VALUES ($1, $2, $3)
RETURNING id, password
`,
[name, email, hashedPassword],
(err, results) => {
if(err){
throw err;
}
console.log(results.rows);
req.flash('Success_msg', 'You are a registered user, please login');
res.redirect('/users/login');
}
);
}
}
);
}
});
/* API for HTML webpages */
app.get('/users/students', (req, res) => res.sendFile(`${__dirname}/views/students.html`));
app.get('/users/student_data', async (req, res) => {
const rows = await loadDB();
// console.log(rows);
res.setHeader('content-type', 'application/json');
res.send(JSON.stringify(rows));
});
app.post('/users/student_data', async (req, res) =>{
let result = {};
try{
// const rows = await createRecord();
const reqJSON = req.body;
await createRecord(
reqJSON.fname,
reqJSON.lname,
reqJSON.amount_paid,
reqJSON.amount_owing,
reqJSON.date_joined,
reqJSON.is_owing);
result.success = true;
console.log(reqJSON);
}
catch(e){
result.success = false;
}
finally{
res.setHeader('content-type', 'application/json');
res.send(JSON.stringify(result));
console.log(result);
}
});
app.delete('/users/student_data', async (req, res) =>{
let result = {};
try{
const reqJSON = req.body;
await deleteRecord(reqJSON.id);
result.success = true;
}
catch(e){
result.success = false;
}
finally{
res.setHeader('content-type', 'application/json');
res.send(JSON.stringify(result));
}
});
/* Database Operations */
async function loadDB(){
try{
const results = await pool.query(`SELECT * FROM student_details ORDER BY fname OFFSET 10 ROWS FETCH FIRST 100 ROW ONLY`);
return results.rows;
}
catch(e){
console.log(`Error ${e}`);
return [];
}
}
async function createRecord(name, surname, amount_paid, amount_owing, dob, is_owing){
try{
await pool.query(`INSERT INTO student_details
(fname, lname, amount_paid, amount_owing, date_joined, is_owing)
VALUES ($1, $2, $3, $4, $5, $6)`,
[name, surname, amount_paid, amount_owing, dob, is_owing]);
return true;
}
catch(e){
console.log(`Error ${e}`);
return false;
}
}
async function deleteRecord(id){
try{
await pool.query(`DELETE FROM student_details WHERE id = $1`, [id]);
return true;
}
catch(e){
console.log(`Error ${e}`);
return false;
}
}
/* Authentication Checkers */
app.post(
'/users/login',
passport.authenticate('local', {
successRedirect: '/users/dashboard',
failureRedirect: '/users/login',
failureFlash: true
})
);
function checkAuth(req, res, next){
if(req.isAuthenticated()){
return res.redirect('/users/dashboard');
}
next();
}
function checkNotAuthenticated(req, res, next){
if(req.isAuthenticated()){
return next();
}
res.redirect('/users/login');
}
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});