-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.js
97 lines (87 loc) · 2.17 KB
/
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
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
const jwt = require('jsonwebtoken');
const { token } = require('morgan');
const { promisify } = require("util");
const AppError = require('../utils/appErrors')
const db = require('../models');
const User = db.users;
exports.authenticate = async (req, res, next) => {
try {
// 1) check if the token is there
let token;
if (
req.headers.authorization &&
req.headers.authorization.startsWith("bearer")
) {
token = req.headers.authorization.split(" ")[1];
}
if (!token) {
return next(
new AppError(
401,
"fail",
"You are not logged in! Please login in to continue",
),
req,
res,
next,
);
}
// 2) Verify token
const decode = await promisify(jwt.verify)(token, process.env.SECRET_KEY);
// 3) check if the user is exist (not deleted)
const user = await User.findOne({
where: { wallet_address: decode.account}
});
if (!user) {
return next(
new AppError(401, "fail", "This user is no longer exist"),
req,
res,
next,
);
}
req.user = user;
next();
} catch (err) {
next(err);
}
};
exports.socketAuth = async(header, next) => {
try {
// 1) check if the token is there
let token;
if (
header &&
header.startsWith("bearer")
) {
token = header.split(" ")[1];
}
if (!token) {
return {
status: false,
message: "You are not logged in! Please login in to continue"
}
}
// 2) Verify token
const decode = await promisify(jwt.verify)(token, process.env.SECRET_KEY);
// 3) check if the user is exist (not deleted)
const user = await User.findOne({
where: { wallet_address: decode.account}
});
if (!user) {
return {
status: false,
message: "This user is no longer exist"
}
}
return {
status: true,
message: "success"
}
} catch (err) {
return {
status: false,
message: err
}
}
}