Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does req.login do in passport

I am using multiple passport stratergy across my app.

Now, since I am using multiple passport strategy to connect (and not to just sign-in), I decided to Google things on how to do it.

This is where I stumbled upon this code

 passport.authenticate('meetup', (err, user, info) => {
        if (err) { return next(err); }
        if (!user) { return res.redirect(process.env.CLIENT_ADDRESS); }
        req.logIn(user, function(err) {
            if (err) { return next(err); }
            return res.redirect(process.env.CLIENT_ADDRESS);
          });

Here I am unable to comprehend what is happening, like for first question, what is if (!user), Does it mean req.user

Second, there is req.logIn()

According to passport docs,

Passport exposes a login() function on req (also aliased as logIn()) that can be used to establish a login session.

and

When the login operation completes, user will be assigned to req.user.

Then what is the difference between using serializer/deserializer when compared with req.login?

Also in the callback, we can always do this

  passReqToCallback: true
  }, (req, accessToken, refreshToken, params, profile, cb) => { 

to get req

To summarize can someone please help me comprehend the above code snippet?

like image 574
anny123 Avatar asked Jan 18 '19 20:01

anny123


1 Answers

At a high level Passport.js is a middleware that "serializes" a user identity in a request/response header (usually a session cookie). This serializing step means that it's taking the login information that identifies a user and produces a new object that represents the user. Think of this object as a key 🔑 card that only Passport will know how to interpret.

When a user makes additional API requests they pass that same identification header back. Passport auths the request by "deserializing" it to identify what user is making that request.

req.login() is the magic that is generating a session for a user. This session represents how long a login is good for without having to re-authenticate.

Let's take a look at the beginning of your snippet:

 passport.authenticate('meetup', (err, user, info) => {
   ...
   if (!user) { return...

In this snippet, passport is being set up as middleware. When a request comes through, passport behind the scenes has already interpreted the request header by deserializing the cookie and determines if it represents a user. If there is not a user or the request header does not represent a user, the request is not authorized.

like image 85
AdamSchuld Avatar answered Oct 19 '22 19:10

AdamSchuld