Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>While I would definitely like to see these features in passport.js, they are not there yet.</p> <p>I have created a simple random token generator to use with passport.js serilizeUser() function, and modified Justen's answer just a bit to suit my needs. Basically, the only difference is that if the "remember" option is not set, the session will last as long as the browser is open.</p> <p>This is my serializer with the random access token generator. I am using Mongodb and Mongoose, but the implementation should translate to other systems quite well.</p> <p>Basically, I am getting the time and appending a random 16-character string to it. Then, in the serializeUser() function I check that no other user has the same token (the token should be unique!).</p> <pre><code>User.methods.generateRandomToken = function () { var user = this, chars = "_!abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890", token = new Date().getTime() + '_'; for ( var x = 0; x &lt; 16; x++ ) { var i = Math.floor( Math.random() * 62 ); token += chars.charAt( i ); } return token; }; </code></pre> <p>Here's the serializer:</p> <pre><code>passport.serializeUser( function ( user, done ) { var createAccessToken = function () { var token = user.generateRandomToken(); app.User.findOne( { accessToken: token }, function (err, existingUser) { if (err) return done( err ); if (existingUser) createAccessToken(); // Run the function again - the token has to be unique! else { user.set( 'accessToken', token ); user.save( function ( err ) { if (err) return done( err ); return done( null, user.get('accessToken') ); }) } }); }; if ( user._id ) { createAccessToken(); } }); </code></pre> <p>...and here is my version of the middleware that handles the "remember me" functionality. I would much rather this somehow be part of the serializeUser function or passport.js core, though.</p> <pre><code>app.use( express.session( { secret: 'secret_key' } ) ); app.use( function (req, res, next) { if ( req.method == 'POST' &amp;&amp; req.url == '/login' ) { if ( req.body.remember ) { req.session.cookie.maxAge = 30*24*60*60*1000; // Rememeber 'me' for 30 days } else { req.session.cookie.expires = false; } } next(); }); app.use( passport.initialize() ); app.use( passport.session() ); </code></pre> <p>I hope that helps somehow. It took me couple of hours to figure it out and I am not quite sure this is the <em>best</em> way to do it but it works for me, for now.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload