-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathguards.js
More file actions
102 lines (89 loc) · 3.52 KB
/
guards.js
File metadata and controls
102 lines (89 loc) · 3.52 KB
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
const jwt = require('jsonwebtoken');
const guards = {
protectRouteByACL: function (model, defRoles, options = {}) {
const JWT_SECRET_KEY = options.authSecrets.JWT_SECRET_KEY;
return async function (req, res, next) {
if (
req.headers.authorization &&
req.headers.authorization.startsWith('Bearer')
) {
token = req.headers.authorization.split(' ')[1];
}
try {
const {
token
} = req.cookies;
} catch (error) {
return res.status(401).end(`User may not be logged in: token not set ${error.message}`)
}
try {
jwt.verify(token, JWT_SECRET_KEY, function (err, decoded) {
if (err) {
return res.status(401).end(`${err.message}: User may not be logged in.`);
}
if (!decoded) {
return res.status(401).end(`Aww Snap, there was something wrong: ${err.message}`)
}
model.findById(decoded._id, function (err, user) {
if (err) {
res.status(404).json({
message: `${err}`
})
}
const {
role
} = user;
if ((defRoles.includes(role))) {
req.user = user;
next()
} else {
return res.status(401).end("You don't have the required permisions")
}
});
// next();
});
} catch (error) {
return res.status(401).end(error.message)
}
}
},
protectRoute: function (model, options = {}) {
const JWT_SECRET_KEY = options.authSecrets.JWT_SECRET_KEY;
return async function (req, res, next) {
let token = null;
if (
req.headers.authorization &&
req.headers.authorization.startsWith('Bearer')
) {
token = req.headers.authorization.split(' ')[1];
}
try {
token = req.cookies.token;
} catch (error) {
return res.end(`User may not be logged in: token not set ${error.message, error.stack}`)
}
try {
await jwt.verify(token, JWT_SECRET_KEY, function (err, decoded) {
if (err) {
return res.status(401).end(`User may not be logged in--> Error message: ${err.message}:(`);
}
if (!decoded) {
return res.status(401).end(`Aww Snap, there was something wrong: ${err.message}`)
}
model.findById(decoded._id, function (err, user) {
if (err) {
return res.status(404).json({
message: `${err}`
})
}
req.user = user;
next();
})
})
} catch (error) {
return res.status(401).end(`Not authoried: ${error.message, error.stack}`)
}
};
}
}
module.exports = guards;