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
|
/* controllers.js */
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const models = require('../models/dbHandlers');
module.exports = {
getQuotes: async function(req, res, next) {
try {
await models.selectQuotes(req, res);
next();
} catch(err) {
res.status(500).json({message: err.message});
}
},
isAdmin: async function(req, res, next) {
try {
if (res.locals.authorized && res.locals.profile == SU)
next();
else
throw new Error('You must be a logged in admin');
} catch(err) {
res.status(500).json({message: err.message});
}
},
isAuth: async function(req, res, next) {
try {
if (!req.body.jwttoken)
throw new Error('Missing token in hidden field')
let token = req.body.jwttoken.split(' ')[1];
if (!token)
throw new Error('Malformed token!');
let rc = await jwt.verify(token, process.env.SECRET);
if (!rc)
throw new Error('Token does not verify');
// check expiration
next();
} catch(err) {
res.status(500).json({message: err.message});
}
},
postQuote: async function(req, res, next) {
try {
next();
} catch(err) {
res.status(500).json({message: err.message});
}
},
postRegistration: async function(req, res, next) {
try {
if (
req.body.email === '' ||
req.body.password === '' ||
req.body.passwordrep === '' ||
req.body.bio === ''
) {
throw new Error('All fields must have content');
}
if (req.body.password != req.body.passwordrep)
throw new Error('Non matching passwords');
let hash = await bcrypt.hash(req.body.password, parseInt(process.env.ROUNDS));
res.locals.hash = hash;
await models.insertUser(req, res);
next();
} catch(err) {
res.status(500).json({message: err.message});
}
},
verifyLogin: async function(req, res, next) {
try {
await models.getUser(req, res, next);
let rc = await bcrypt.compare(req.body.password, '' + res.locals.user.password);
if (!rc)
throw new Error('Error in Credentials');
const payload = { email: res.locals.user.email, profile: res.locals.user.profile };
const lifetime = { expiresIn: '1h' };
let token = await jwt.sign(payload, process.env.SECRET, lifetime);
if (!token)
throw new Error('Error in credentials, token');
res.locals.token = token;
next();
} catch (err) {
return res.status(500).json({message: err.message});
}
}
}
|