Search code examples
javascriptnode.jsexpresspassport.js

Passport js authenticate by url


I'm using Express JS and Passport JS for my app.

I want to give a new user the opportunity to automatically login, once, by a specific URL. I can get the user from the database with the information from the URL, so I have an User object (with id, email, hashed password etc.) but I don't know how I can use passport to authenticate the user and login.

I tried executing below function with the user object I got from the database:

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

source: http://passportjs.org/guide/login/

But that didn't work. Guess it's just because the user object contains the hashed password... Anyone who ever tried this before and can tell me how it works?


Solution

  • Maybe https://github.com/yarax/passport-url strategy will be useful for you

    Base logic is getting argument from url

    UrlStrategy.prototype.authenticate = function(req, options) {
        var self = this;
    
        function verified(err, user, info) {
            if (err) { return self.redirect(self.failRedirect); } // redirect in fail
            self.success(user, info); // done callback
        }
    
        this._verify(req.query[this.varName], verified);
    };
    

    Full example here https://github.com/yarax/passport-url/blob/master/index.js