forked from saransh79/LearnGit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.js
40 lines (31 loc) · 1.07 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
const jwt=require("jsonwebtoken")
const User=require("../Models/userModel")
const isAuthenticatedUser= async (req,res,next)=>{
try{
const token=req.cookies.token //OR WE CAN USE DESTRUCTERING const {token}=req.cookies
if(!token){
res.status(401).json({message:"Please Login"})
return
}
const decodedToken=jwt.verify(token,process.env.JWT_SECRET_KEY) // this will give id and iat
req.user= await User.findById(decodedToken.id) // we only want to find by id so .id is used
//req.user is used to make it accesssible to function written after isAuthenticatedUser
console.log(decodedToken)
next()
}
catch(e){
res.json({message:"error"})
}
}
const isAdmin= async (req,res,next)=>{
try{
if(req.user.Role!="Admin")
{
res.status(401).json({message:"Unathorised Access"})
}
next()
}
catch(e){
}
}
module.exports={isAuthenticatedUser,isAdmin}