roflmyeggo February 2016

Node.js Passport Login Race Condition

I believe I am dealing with a race condition on Node.js authentication using PassportJS (specifically passport-local).

Here is my Router for registration:

router.post('/', upload.single('avatar'), function(req, res, next) {
    var userType = req.body.userType;
    var username = req.body.username;
    var password = req.body.password;
    var email = req.body.email;
    // Convert Buffer data to base64 encoded string
    var base64Avatar = new Buffer(req.file.buffer).toString('base64');
    var avatar = 'data:' + req.file.mimetype + ';base64,' + base64Avatar;

    var createdUser;
    if (userType == 'viewer') {
        createdUser = new user.User(username, password, email, [], [], avatar).getInstance();
    } else if (userType == 'contributor') {
        createdUser = new contributor.Contributor(username, password, email, [], [], avatar, []).getInstance();
    }

    req.login(createdUser, function(err) {
        if (err) { return next(err); }
        req.session.save(function() {
           res.redirect('/user/' + req.user.username);
        });
    });
});

In the constructor of the User model using TypeScript:

constructor(private _username: String, private _password: String, private\
 _email: String, private _favorites: Array<any>, private _inbox: Array<any>, \
private _avatar: String) {
        this._modelInstance = new userModel({username: _username, password: _\
password, email: _email, favorites: _favorites, inbox: _inbox, avatar: _avata\
r});
        this._modelInstance.save();
};

I've tried applying async.series to:

a) The model instance creation and save in the User class constructor.

b) The createdUser creation in the route and the req.login request.

I've also tried (as you can se

Answers


roflmyeggo February 2016

I fixed it by moving the save() logic to the registration Router.

Then I could simply add the req.login call to the save() callback:

createdUser.save(function(err, data) {
    if (err) {
            console.log(err);
    } else {
        req.login(createdUser, function(err) {
            if (err) { return next(err); }
            req.session.save(function() {
                res.redirect('/user/' + req.user.username);
            });
        });
    }
 });

Post Status

Asked in February 2016
Viewed 2,071 times
Voted 7
Answered 1 times

Search




Leave an answer