-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauthorizeToProceed.js
50 lines (47 loc) · 1.18 KB
/
authorizeToProceed.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
let crypto = require("crypto-js");
module.exports = (User, Token) => {
return (req, res, next) => {
// console.log(req.headers.authorization);
if( req.user !== undefined ){
let token = req.headers.authorization.split(" ")[1];
let tokenHash = crypto.MD5(token).toString();
Token.find({
where:{
token_hash:{
$eq: tokenHash
}
}
}).then( tokenRow => {
if(tokenRow == null)
throw new Error('please login');
else
User.findById(tokenRow.get('userId')).then( user => {
if(user !== null){
req.user = user.toPublicJSON();
next();
}
else
throw new Error('User doesn\'t exist');
}).catch(() => res.status(401).send());
}).catch(() => res.status(401).end());
}
else
res.status(401).send('please login');
};
};
// module.exports = User => {
// return (req,res,next) => {
// if( req.user !== undefined ){
// User.getByToken(req.user).then( user => {
// if(user !== null){
// req.user = user.toPublicJSON();
// next();
// }
// else
// throw new Error("User doesn't exist");
// }, (err) => res.send(err));
// }
// else
// res.status(401).send("login first!");
// };
// };