Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create and save an expiring user token in node js?

Hi so I have come across this for creating a random token on crypto for Node js.

require('crypto').randomBytes(48, function(ex, buf) {
  var token = buf.toString('hex');
});

I am trying to figure out how to go about adding it to my route file here? I already set a token field in my mongoose schema to a type string.

    exports.forgotPasswordPost = function(req, res, next) {
    console.log("Forgot Password Post");
    if(req.body.email === '') {
        console.log('err');
    } else {
    crypto.randomBytes(48, function(ex, buf) {
        var userToken = buf.toString('hex');
        console.log(userToken);
        User.findOne({email: (req.body.email)}, function(err, usr) {
            if(err || !usr) {
                console.log('err');             
            } 
            console.log(usr);
            usr.token = new User({token: userToken});
            usr.save(function(err, usr){
                res.redirect('login', {title: 'Weblio', message: 'Your token was sent by email. Please enter it on the form below.'});
            });
        });
    });
    }
};

Mongoose file:

var mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    ObjectId = mongoose.Schema.Types.ObjectId,
    bcrypt = require('bcrypt-nodejs'),
    SALT_WORK_FACTOR = 10;



var UserSchema = new Schema({ 
    email: { type: String, required: true, lowercase:true, index: { unique: true } },
    password: { type: String, required: true },
    firstName: {type: String, required: true},
    lastName: {type: String, required: true},
    phone: {type: Number, required: true},
    birthday: {type: Date, required: true},
    friendRequest: {type: Object},
    notifications: {type: Object},
    friend: {type: Object},
    date_created: {type: Date},
    token: {type: String},
    tokenCreated: {type: Date, default: Date.now}
}, {collection: "users"});


UserSchema.methods.hasExpired = function() {
    var now = new Date();
    return (now - createDate) > 2;
};

module.exports = mongoose.model('User', UserSchema);

This is the query result:

        "token" : "{ token: 'fa9e573e5ec8ed6d7bf53c9296f703b4ea6895c0a5438a0e0c4
b9a43f4db9bce7dd55e82c3188056efdc9ab53b9b5185',\n  _id: 51fe1bcaa32f6b300c000001
 }"

I just updated the code with my new usage of it, and included my mongoose schema too...

like image 787
Lion789 Avatar asked Aug 04 '13 00:08

Lion789


1 Answers

First, the user token should be a Model:

var mongoose = require( 'mongoose' );
var Schema = mongoose.Schema;

var Token = new Schema({
    token: {type: String},
    createDate: {type: Date, default: Date.now()}
});

Token.methods.hasExpired= function(){
    var now = Date.now();
    return (now - Date.parse(createDate)) > 604800000; // Date is converted to milliseconds to calculate 7 days it > one day = 24 hours * 60 minutes * 60 seconds *1000 milliseconds * 7 days = 604800000
};

//don't forget to add the token as a field in your user

mongoose.model( 'Token', Token);

Next, in the router, inside the else clause, I would change your findOneAndUpdate to findOne, because you are not updating the whole User object, but simply a property on it.

require('crypto').randomBytes(48, function(ex, buf) {
  var userToken = buf.toString('hex');
  User.findOne({email: (req.body.email)}, function(err, usr) { 
            if(err || !usr) {
                console.log('err');             
            }
            usr.token = new Token(token:userToken);
            usr.save(function(err, usr){
                res.redirect('recoverPassword', {title: 'Weblio', message:'Your token was sent by email. Please enter it on the form below.'});
           };
        });
});

In a different route, where your user is POSTing his token, you will do the following:

exports.postToken = function(req, res, next) {
    if(req.body.token === '') {
        console.log('err');
    } else {
        User.findOne({email: (req.body.email)}, function(err, usr) {
            if(err || !usr) {
                console.log('err');             
            }
            if(usr.token == req.body.token && !usr.tokenHasExpired()) {
                usr.token = undefined;
                usr.tokenCreated = undefined;
                usr.save(function(err, usr){
                    res.redirect('index', {title: 'Weblio', message: 'Here is your password. Please dont lose it again', password: usr.password});
            });
            } else {
                res.redirect('recoverPassword', {title: 'Weblio', message:'The token is not set, or has expired. Though luck!'});
            }
        });
    });
};
like image 72
verybadalloc Avatar answered Oct 31 '22 19:10

verybadalloc