Listing 26.4 implements the signup
route. The logic in this route first creates a new User
object and then adds the email address and hashed password, using the hashPW()
function defined in the same file. Then the Mongoose save()
method is called on the object to store it in the database. On error, the user is redirected back to the signup page.
If the user saves successfully, the ID created by MongoDB is added as the req.session.user
property, and the username is added as the req.session.username
. The request is then directed to the index page.
08 exports.signup = function(req, res){
09 var user = new User({username:req.body.username});
10 user.set('hashed_password', hashPW(req.body.password));
11 user.set('email', req.body.email);
12 user.save(function(err) {
13 if (err){
14 res.session.error = err;
15 res.redirect('/signup'),
16 } else {
17 req.session.user = user.id;
18 req.session.username = user.username;
19 req.session.msg = 'Authenticated as ' + user.username;
20 res.redirect('/'),
21 }
22 });
23 };