-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.js
More file actions
65 lines (59 loc) · 1.6 KB
/
Copy pathmiddleware.js
File metadata and controls
65 lines (59 loc) · 1.6 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
let jwt = require('jsonwebtoken');
const config = require('./config.json');
const translations = require('./lang');
const locale = require("locale");
const supported_lang = ["de"];
const default_lang = "de";
let setUpMiddleware = (app, settings_helper) => {
app.use(locale(supported_lang, default_lang));
app.use(addLocals);
app.use(checkToken);
app.use(settings_helper.getMiddleware());
app.use(addIsAuthenticated);
}
let checkToken = (req, res, next) => {
let token = req.headers['x-access-token'] || req.headers['authorization'] || req.cookies.auth; // Express headers are auto converted to lowercase
if (token) {
if (token.startsWith('Bearer ')) {
// Remove Bearer from string
token = token.slice(7, token.length);
}
new Promise((resolve, reject)=>{
jwt.verify(token, config.secret, (err, decoded) => {
if (err) {
reject(err)
} else {
resolve(decoded);
}
});
}).then(decoded =>{
res.locals.token = decoded;
res.locals.authenticated = true;
}).catch(err =>{
console.error(err);
res.locals.authenticated = false;
}).finally(()=>{
next();
})
} else {
res.locals.authenticated = false;
next();
}
};
let addLocals = (req, res, next)=>{
res.locals = translations[req.locale];
next();
}
let addIsAuthenticated = (req, res, next)=>{
req.isAuthenticated = (role)=>{
if(role){
return res.locals.authenticated && res.locals.token.role == role;
}else{
return res.locals.authenticated;
}
}
next();
}
module.exports = {
setUpMiddleware: setUpMiddleware
}