Skip to content

Instantly share code, notes, and snippets.

@kareemsuhail
Created January 24, 2018 16:17
Show Gist options
  • Save kareemsuhail/8a828901207d6e5cfe4160ba69d4710a to your computer and use it in GitHub Desktop.
Save kareemsuhail/8a828901207d6e5cfe4160ba69d4710a to your computer and use it in GitHub Desktop.
// this gist is for eng.adnan about jwt
// first of all use this packge jsonwebtoken
// you can download it simply by typing this in your cmd :
//npm install jsonwebtoken
// ==========================//
// how to create tokens (login)
var user = await User.findOne({email:data.email}).exec(); //get user from database by email
if(user.validatePassword(data.password)){ // check password
var Token = jwt.sign({_id:user._id}, // generate token for and storing user id and expiration period
config.secret,{ expiresIn: 60*60*24*7 })
return{token:Token,username:user.username,email:user.email,id:user._id}// return token as response
}else{
throw new Error("user not found") // password validation faild
}
//==========================//
//how to check if the token is valid for each request
// this is a simple express middleware
app.use("/",(req,res,next)=>{
if(!req.headers.authorization){ // if there is no token on his request set req.user = undeifind
req.user = undefined;
next()
}else{
// check if the token is valid and not expired
jwt.verify(req.headers.authorization,config.secret,function (err,decoded) {
// go here if the token is not valid
if(err){
req.user = undefined;
next();
// go here if the token is valid
}else{
// get user_id from decoded token
User.findOne({_id:decoded._id}).exec(function (err,user) {
// set req.user to be the authenticated user
req.user = user ;
// use next() to move to the next pipline
next();
})
}
})
}
});
// refresh token is just like creating token but you have to check if the token is valid before generating a new one
//===========//
// syntax to add any thing into local storage
storage.setItem(keyName, value);
//another example for tokens
localStorage.setItem('token', 'token received from server' );
// if you have any question eng.adnan feel free to contact me again ^_^
@amuammer
Copy link

amuammer commented Feb 4, 2019

Thanks.. From 24 January 2018 until now

@amuammer
Copy link

Thanks Again !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment