-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.js
More file actions
85 lines (78 loc) · 2.86 KB
/
auth.js
File metadata and controls
85 lines (78 loc) · 2.86 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
const User = require("./models/user.js");
const checkStripeAccount = require("./controllers/checkStripeAccount.js");
const sendEmail = require("./controllers/sendEmail.js");
const confirmationEmail = require("./email/confirmationEmail.js");
const jwt = require("jsonwebtoken");
module.exports = {
auth: function(req, res, next){
let userData = {};
try{
let token = req.headers.authorization.split(" ")[1];
userData = jwt.verify(token, process.env.JWT_SECRET);
}catch(e){
return res.json({
error: true,
message: "Authorization"
});
}
User.findOne({_id: userData._id})
.then((user)=>{
res.locals.user = user;
if(user.status.includes("email")){
let code = user.status.split("-")[1];
let html = confirmationEmail(user.firstName, `${req.protocol}://${req.get("host")}/email/code/${user.email}/${code}`);
sendEmail(user.email, "CoSphere email confirmation", html);
throw "email";
}
if(userData.session !== user.session) throw "token";
if(user.status === "payment" && !req.body.payment) throw "payment";
if(user.expiration <= new Date()) return checkStripeAccount(user);
next();
throw "done";
})
.then((response)=>{
if(response){
next();
}else{
throw "payment";
}
})
.catch((err)=>{
switch(err){
case "token":
return res.json({
error: true,
message: "bad token"
});
case "email":
return res.json({
error: true,
message: "email"
});
case "payment":
return res.json({
error: true,
message: "payment"
});
case "done": break;
default:
console.error(err);
return res.json({
error: true,
message: "Invalid user token"
});
}
});
},
wsAuth: async function(token){
let userData = {};
try{
userData = jwt.verify(token, process.env.JWT_SECRET);
}catch(e){
console.error(e);
}
let user = await User.findOne({_id: userData._id});
if(user.status !== "active") return false;
return user;
}
}