gpt4 book ai didi

javascript - 如何自动登录用户node.js Passport.js

转载 作者:太空宇宙 更新时间:2023-11-04 00:19:41 24 4
gpt4 key购买 nike

我使用了node.js和passport.js来创建登录应用程序。我正在使用 express-session 和 connect-mongo 来维护 session 。我希望用户每次访问该网址时都直接移至主页。仅当用户尚未登录一次时,才应将他定向到登录页面。我怎样才能做到这一点。

登录.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;
}

最佳答案

session 数据通常以cookie的形式存储在客户端,或者存储在本地存储中。您的 UI 应用程序应检查此数据是否存在,并将经过身份验证的用户重定向到特定 URL(一切都在客户端,不与服务器交互)。

在 UI 发出的第一个请求(使用来自 cookie 或本地存储的数据)时,您可以重新验证从 UI 传递的数据(在服务器上),如果它无效,您可以刷新 session 数据并将其返回给用户或注销该用户(取决于工作流程)。

关于javascript - 如何自动登录用户node.js Passport.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44884048/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com