SC4RECROW
SC4RECROW

Reputation: 151

Verify jwt token with Mongoose .findOne()

I am following a tutorial that is using node, mongoose and jwt. I am just curious about a single command below.

Why does the tutorial use the command user.findOne(). ?

userSchema.statics.findByToken = function(token,cb){
var user = this;

jwt.verify(token,process.env.SECRET,function(err,decode){
    user.findOne({"_id":decode,"token":token},function(err,user){
        if(err) return cb(err);
        cb(null,user);
    })
})
}

Isn't the token already verified with jwt.verify()?

Why is the findOne() needed? This findOne() command makes it seem like there are more than one user. Since there is only one token that is used at the input.

Why dont they just return the "_id"?

Btw, this is how the token is made:

userSchema.methods.generateToken = function(cb){
var user = this;
var token = jwt.sign(user._id.toHexString(),process.env.SECRET)

user.token = token;
user.save(function(err,user){
    if(err) return cb(err);
    cb(null,user);
})
}

and this is how .findToken() is used in the route authentication:

const { User } = require('./../models/user');

let auth = (req,res,next) => {
    let token = req.cookies.w_auth;

User.findByToken(token,(err,user)=>{
    if(err) throw err;
    if(!user) return res.json({
        isAuth: false,
        error: true
    });

    req.token = token;
    req.user = user;
    next();
})

}


module.exports = { auth }

Upvotes: 2

Views: 921

Answers (1)

SuleymanSah
SuleymanSah

Reputation: 17868

It is an additional security step. Let's say for some reason, administrator deleted the user so that user can't access the application. But if the user still has a valid token, he/she can continue to access the application. This is not acceptable.

So in critical applications, it is good to check if the user really exists in the db.

And to make it more secure, we also need to check if the token was issued before we changed password. This may be helpful if a user suspected or noticed that someone stole his/her password, so after the user changes password, the tokens issued before password change must be invalidated.

Upvotes: 2

Related Questions