-
Notifications
You must be signed in to change notification settings - Fork 4
/
authServer.js
113 lines (104 loc) · 3.06 KB
/
authServer.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
const jwt = require('jsonwebtoken');
const cookieParser = require('cookie-parser');
const express = require('express');
const app = express();
app.use(cookieParser());
function authorizeAdmin(req, res, next) {
let token = req.cookies.token;
if(token == null){
res.status = 401;
return res.redirect('/signin');
}
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, decoded) => {
if(err){
res.status = 403;
return res.redirect('/signin');
}
if(decoded.role != 'admin'){
res.status = 403;
return res.redirect('/signin');
}
req.user = decoded;
next();
});
};
function decodeToken(token){
let decodedToken = jwt.decode(token);
return decodedToken;
}
function authorizeCustomer(req, res, next) {
let token = req.cookies.token;
if(token == null){
res.status = 401;
return res.redirect('/signin');
}
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, decoded) => {
if(err){
res.status = 403;
return res.redirect('/signin');
}
if(decoded.role != 'customer'){
res.status = 403;
return res.redirect('/signin');
}
req.user = decoded;
next();
});
};
function authorizeOffice(req, res, next) {
let token = req.cookies.token;
if(token == null){
res.status = 401;
return res.redirect('/signin');
}
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, decoded) => {
if(err){
res.status = 403;
return res.redirect('/signin');
}
if(decoded.role != 'office'){
res.status = 403;
return res.redirect('/signin');
}
req.user = decoded;
next();
});
}
function authroizeAdminOrCustomer(req, res, next) {
let token = req.cookies.token;
if(token == null){
res.status = 401;
return res.redirect('/signin');
}
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, decoded) => {
if(err){
res.status = 403;
return res.redirect('/signin');
}
if(decoded.role != 'admin' && decoded.role != 'customer'){
res.status = 403;
return res.redirect('/signin');
}
req.user = decoded;
next();
});
}
function checkWhereToGo(req,res,next){
if(req.cookies.token === undefined){
next();
return;
}
let decodedToken = decodeToken(req.cookies.token);
if(decodedToken.exp < Date.now() / 1000){
res.clearCookie("token");
next();
return;
}
if(decodedToken && decodedToken.role === "admin")
res.redirect("/admin");
else if(decodedToken && decodedToken.role === "customer")
res.redirect("/customer-home");
else if(decodedToken && decodedToken.role === "office")
res.redirect("/office-home");
}
module.exports = {authorizeAdmin, authorizeCustomer, authorizeOffice, authroizeAdminOrCustomer, decodeToken, checkWhereToGo};