Full-Stack Web Development with Vue.js and Node

(singke) #1
Building Authentication with passport.js Chapter 6

// register a user
app.post('/users/register', (req, res) => {
const name = req.body.name;
const email = req.body.email;
const password = req.body.password;
const newUser = new User({
name,
email,
password,
});
User.createUser(newUser, (error, user) => {
if (error) {
res.status(422).json({
message: 'Something went wrong. Please try again after some
time!',
});
}
res.send({ user });
});
});
};

Here, we have added a route for users login as /users/login which then uses


passport.js local authentication mechanism to log in the user to the app.


Also, we configured passport.js to use LocalStrategy when user logs in which takes the


username and password of the user.


Installing express-session


The next thing we need to do is setup a session so that when a user successfully logs in,


the user data can be stored in the session and can be retrieved easily when we make


other requests. For this, we need to add a package called express-session. Let's go ahead


and install the package with the following command:


$ npm install express-session --save

Configuring express-session


Now, that we have the package, let's configure this package to fulfill our needs to save the
user in the session. Add the following lines of code in it.

Free download pdf