-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmiddleware.js
52 lines (43 loc) · 1.27 KB
/
middleware.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
function logRequests(req, res, next) {
const userStatus = req.session && req.session.user ? 'Authenticated User' : 'Non-Authenticated User';
console.log(`[${new Date().toUTCString()}]: ${req.method} ${req.originalUrl} (${userStatus})`);
next();
}
function redirectBasedOnRole(req, res, next) {
if(req.session.user){
return res.redirect('/auth/user')
}else{
res.redirect('/auth/login');
}
}
function ensureLoggedIn(req, res, next) {
if (!req.session.user) {
res.redirect('/auth/login');
} else {
next();
}
}
function ensureAdmin(req, res, next) {
if(!req.session.user){
res.redirect('/auth/login')
} else if(req.session.user.role !== 'admin') {
return res.status(403).render('error', {
title: "Error",
message: "Only admin have permission to view this page"
})
}
}
function ensureNotLoggedIn(req, res, next) {
if (req.session.user) {
res.redirect('/auth/user');
} else {
next();
}
}
function captureUrl(req, res, next) {
if (req.headers.referer && !req.session.user) {
req.session.previousUrl = req.headers.referer;
}
next();
}
export { logRequests, redirectBasedOnRole, ensureLoggedIn, ensureNotLoggedIn, ensureAdmin, captureUrl};