-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.js
86 lines (78 loc) · 1.85 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
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const saltRound = 10;
const secretKey = "PoINjnLK89$#!Nnjsdk!@%";
const JWTD = require("jwt-decode");
let hashPassowrd = async (password) => {
let salt = await bcrypt.genSalt(saltRound);
let hashedPassword = await bcrypt.hash(password, salt);
return hashedPassword;
};
let hashCompare = async (password, hashedPassword) => {
return bcrypt.compare(password, hashedPassword);
};
let createToken = async (email, role) => {
let token = await jwt.sign({ email, role }, secretKey, { expiresIn: "1h" });
return token;
};
let jwtDecode = async (token) => {
let data = await jwt.decode(token);
return data;
};
let validate = async (req, res, next) => {
if(req.headers && req.headers.authorization)
{
let token = req.headers.authorization.split(" ")[1];
let data = await jwtDecode(token);
let currentTime = Math.round(new Date() / 1000);
if (currentTime <= data.exp) next();
else
res.send({
stausCode: 401,
message: "Token Expired",
});
}
else{
res.send({
statusCode:401,
message:"Invalid Token or no token"
})
}
};
let roleAdmin = async (req, res) => {
if(req.headers && req.headers.authorization)
{
let token = req.headers.authorization.split(" ")[1];
let data = await jwtDecode(token);
if (data.role == "Admin" ) next();
else
res.send({
stausCode: 401,
message: "Unauthorized! Only Admin can access!",
});
}
else{
res.send({
statusCode:401,
message:"Invalid Token or no token"
})
}
};
const authenticate = async(token)=>{
const decode = JWTD(token);
if(Math.round(new Date() / 1000) <= decode.exp){
return decode.email;
}
else{
return "";
}
}
module.exports = {
hashPassowrd,
hashCompare,
createToken,
jwtDecode,
validate,
roleAdmin,
authenticate
};