How to use Passport.js correctly?

I use:

  • Node.js
  • Express 4.0
  • Passport.js
  • Google OAuth 2 for authentication

For each user, I store in the MySQL database (I have no choice regarding this technology) some information from his Google profile (email, etc.), access and updating of tokens, as well as additional information about what the user provides when it is registered in my application.

I have seen various uses of passport.js, in particular about how this information is stored in a session.

  • On the passport.js configure page , I really don’t understand the point of the following block of code:

    passport.deserializeUser(function(id, done) {
      User.findById(id, function(err, user) {
        done(err, user);
      });
    });
    

    , , , . ? . serializeUser (.. )?

  • , session . " "? ? - , - ? (, , , , ..). session, passport.authenticate ( ), ?

  • , : Google, - , , . , , Google , . , session, . , , , passport.authenticate:

    return done(null,false,userInfo);
    

    , , 2 : userInfo -, , , req.login() .

    , Google? , ?

  • , Reddis. ?

!

+4
2

1) serializeUser cookie . , cookie, . db , , , deserializeUser.

, cookie, , cookie , cookie db. , , , , cookie, db, cookie.

, , , , ( , ).

, cookie, , , , - cookie .

2) , , . , , .

, cookie ; , , , () , , , cookie .

, . . , .

3) , . ( , ), . , .

, .

4) Redis , node - (, ). , node, , node , , . http://www.ourdailycodes.com/2013/09/redis-when-should-i-use-it.html

EDIT: , cookie, , , , . , , , ... (- , ).

+7

node.js :

passport.serializeUser(function(user, done) {
   done(null, user.id);
});

passport.deserializeUser(function(id, done) {
   User.findById(id, function (err, user) {
        done(err, user);
   });
});

, , :

var passport = require ('passport')
passport.serializeUser (function(user, done) {
   done(null, user.id);
});

passport.deserializeUser(function(id, done) {
   var user = _.find(fixtures.users, 'id', id)
       if (user) {
          done (null, user);
       }
       else
          { done (null, false) }
});


module.exports = passport;

serializeUser cookie . '(user)' serializeUser - , "id" . , user.id .

deserializedUser "id" serializedUser . lodash .

var _ = require ('lodash')
var user = _.find(fixtures.users, 'id', id)

find . lodash : lodash. , , , false.

, .

module.exports = passport;
+1

Source: https://habr.com/ru/post/1546328/


All Articles