Listing 26.5 implements the login
route. First, the handler finds the user by username, then it compares the stored hashed password with a hash of the password sent in the request. If the passwords match, the user session is regenerated using the regenerate()
method. Notice that req.session.user
and req.session.username
are set in the regenerated session.
24 exports.login = function(req, res){
25 User.findOne({ username: req.body.username })
26 .exec(function(err, user) {
27 if (!user){
28 err = 'User Not Found.';
29 } else if (user.hashed_password ===
30 hashPW(req.body.password.toString())) {
31 req.session.regenerate(function(){
32 req.session.user = user.id;
33 req.session.username = user.username;
34 req.session.msg = 'Authenticated as ' + user.username;
35 res.redirect('/'),
36 });
37 }else{
38 err = 'Authentication failed.';
39 }
40 if(err){
41 req.session.regenerate(function(){
42 req.session.msg = err;
43 res.redirect('/login'),
44 });
45 }
46 });
47 };