-
Notifications
You must be signed in to change notification settings - Fork 1
/
auth.js
34 lines (30 loc) · 996 Bytes
/
auth.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
module.exports.db = null;
module.exports.NotLoggedInError = function NotLoggedInError() {
this.message = 'Not logged in!';
}
module.exports.checkAuthorization = function checkAuthorization(req, res) {
let auth = module.exports.db.isTokenValid(module.exports.getToken(req));
return auth.then((valid) => {
if (!valid) {
throw new module.exports.NotLoggedInError();
} else {
return valid;
}
}).catch((e) => {
if (e instanceof module.exports.NotLoggedInError) {
res.status(401).json({"error": e.message})
}
throw e;
});
}
module.exports.isAuthorized = function isAuthorized(req) {
return module.exports.db.isTokenValid(module.exports.getToken(req));
}
module.exports.getToken = function getToken(req) {
if ('query' in req && 'token' in req.query) {
return req.query.token;
}
if ('cookies' in req && 'token' in req.cookies) {
return req.cookies.token;
}
}