如何自动login用户node.js + passport.js

我已经使用node.js和passport.js来创buildlogin应用程序。 我正在使用express-session和connect-mongo来维护会话。 我希望用户每次访问url时都直接移到主页。 只有当用户还没有login时,他才应该被引导到login页面。 我怎样才能做到这一点。

Login.js

module.exports = function(passport){ passport.use('login', new LocalStrategy({ passReqToCallback : true }, function(req, username, password, done) { // check in mongo if a user with username exists or not User.findOne({ 'username' : username }, function(err, user) { // In case of any error, return using the done method if (err) return done(err); // Username does not exist, log the error and redirect back if (!user){ console.log('User Not Found with username '+username); return done(null, false, req.flash('message', 'User Not found.')); } // User exists but wrong password, log the error if (!isValidPassword(user, password)){ console.log('Invalid Password'); return done(null, false, req.flash('message', 'Invalid Password')); // redirect back to login page } // User and password both match, return user from done method // which will be treated like success return done(null, user); } ); }) ); var isValidPassword = function(user, password){ return bCrypt.compareSync(password, user.password); } } 

Signup.js

 module.exports = function(passport){ passport.use('signup', new LocalStrategy({ passReqToCallback : true // allows us to pass back the entire request to the callback }, function(req, username, password, done) { findOrCreateUser = function(){ // find a user in Mongo with provided username User.findOne({ 'username' : username }, function(err, user) { // In case of any error, return using the done method if (err){ console.log('Error in SignUp: '+err); return done(err); } // already exists if (user) { console.log('User already exists with username: '+username); return done(null, false, req.flash('message','User Already Exists')); } else { // if there is no user with that email // create the user var newUser = new User(); // set the user's local credentials newUser.username = username; newUser.password = createHash(password); newUser.email = req.param('email'); newUser.firstName = req.param('firstName'); newUser.lastName = req.param('lastName'); // save the user newUser.save(function(err) { if (err){ console.log('Error in Saving user: '+err); throw err; } console.log('User Registration succesful'); return done(null, newUser); }); } }); }; // Delay the execution of findOrCreateUser and execute the method // in the next tick of the event loop process.nextTick(findOrCreateUser); }) ); // Generates hash using bCrypt var createHash = function(password){ return bCrypt.hashSync(password, bCrypt.genSaltSync(10), null); } } 

index.js

 var isAuthenticated = function (req, res, next) { // if user is authenticated in the session, call the next() to call the next request handler // Passport adds this method to request object. A middleware is allowed to add properties to // request and response objects if (req.isAuthenticated()) return next(); // if the user is not authenticated then redirect him to the login page res.redirect('/'); } module.exports = function(passport){ /* GET login page. */ router.get('/', function(req, res) { // Display the Login page with any flash message, if any res.render('index', { message: req.flash('message') }); }); /* Handle Login POST */ router.post('/login', passport.authenticate('login', { successRedirect: '/home', failureRedirect: '/', failureFlash : true })); /* GET Registration Page */ router.get('/signup', function(req, res){ res.render('register',{message: req.flash('message')}); }); /* Handle Registration POST */ router.post('/signup', passport.authenticate('signup', { successRedirect: '/home', failureRedirect: '/signup', failureFlash : true })); /* GET Home Page */ router.get('/home', isAuthenticated, function(req, res){ res.render('home', { user: req.user }); }); /* Handle Logout */ router.get('/signout', function(req, res) { req.logout(); res.redirect('/'); }); return router; } 

会话数据通常以cookieforms存储在客户端,或存储在本地存储中。 您的UI应用程序应检查此数据是否存在,并将经过身份validation的用户redirect到特定的URL(客户端的所有内容,不与服务器交互)。

在UI(通过cookie或本地存储的数据)发出的第一个请求中,可以重新validation从UI传递的此数据(在服务器上),如果无效,则可以刷新会话数据并将其返回给用户或注销此用户(取决于工作stream程)。