Alireza Valizade Alireza Valizade - 1 month ago 11
Node.js Question

token generator in node and express

I trying create a function that generates a random token that doesn't exist in my database (Mongodb) and I use a unique property in my user schema. This is my function:

var UniqueTokenGenerator = function () {

var token = uuid.v4();
UserModel.findOne({token : token} , (err , user)=> {

if(err)
res.status(500).send(err);
else if(user){
//1
}else if(!user){
return token; //2
}

});

};


My problems:


  1. I want if token exist call UniqueTokenGenerator or whatever... like loop.

  2. Token cannot be returned.

  3. Anybody has a better idea?



I don't want to use any library like
jwt
.

Answer

Two answers:

First, you don't need to check the database to make sure your UUID is unique. UUIDs are so big that mathematically you won't run into a collision. See Are GUID collisions possible?

Second, to do what you're trying to do, you need to make your function asynchronous and deliver the result with a callback. E.g.

var generateUniqueToken = (callback) => {
    var token = uuid.v4();
    UserModel.findOne({ token: token }, (err, user) => {
        if(err) {
            // First parameter of the callback is an error.
            callback(err);
        } else if (user) {
            // Try again.
            generateUniqueToken(callback);
        } else if (!user) {
            // First parameter of the callback is an error. The second
            // parameter is the successful result.
            callback(null, token);
        }
    });
};

// Example usage:
generateUniqueToken((err, token) => {
    if (err) {
        res.status(500).send(err);
    } else {
        // Use the token here.
    }
});
Comments