Full-Stack Web Development with Vue.js and Node

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

The important part here is that since we are interacting on the client side, we will need the
previously generated JWT token to be saved somewhere. The best way to access the token


is by saving it to the browser's session. So, we have set a key called auth, which saves the


JWT token in the local storage. Whenever any other requests are made, the request will first


check whether it is a valid token or not and perform the action accordingly.


The following is what we have done so far:


Added getUserByEmail() and comparePassword() to the Users model
Created a login view page
Added methods to be able to submit and clear the form
Generated a JWT signed token and saved it to the session for reuse later
Displayed success and error messages

Authenticating our user in Home.vue


The last thing we need to do is check whether the current logged in user is authorized to


view the movie listing page or not. Although it makes sense to make the home page (movie


listing page) accessible to all users, for learning purpose, let's add JWT authorization when
a user goes to the home page. Let's make the home page not accessible to the outside users


who are not in our app.


In movies.js, add the following piece of code:


const MovieSchema = require('../models/Movie.js');
const Rating = require('../models/Rating.js');
const passport = require('passport');

module.exports.controller = (app) => {
// fetch all movies
app.get('/movies', passport.authenticate('jwt', { session: false }),
(req, res) => {
MovieSchema.find({}, 'name description release_year genre', (error,
movies) => {
if (error) { console.log(error); }
res.send({
movies,
});
});
});
...
Free download pdf