Implementing Routes to Use Authentication

Passport is fully configured now, and you are ready to implement the middleware in your application’s routes. The next step is to add the passport.authenticate() method to your authentication route. The authentication method accepts the authentication source as the first parameter and then an object that contains successRedirect and failureRedirect sources. In the case of Google, a double authentication must take place, as shown in the routes below:

app.get('/auth/google',
  passport.authenticate('google'));
app.get('/auth/google/return',
  passport.authenticate('google', {
    successRedirect: '/info',
    failureRedirect: '/login' }));

You can also use the req.login() method to later log in using the user object. For example:

req.login(user, function(err) {
  if (err) { return next(err); }
  return res.redirect('/users/' + req.user.username);

});

You can also use the req.logout() method to log out, which destroys the session. The actual authentication in the browser to the authentication source—Google, for example—is not terminated. You can still go to gmail.com and access your email, for instance. The following shows using logout() in a route:

app.get('/logout', function(req, res){
  req.logout();
  res.redirect('/login'),

});

Another very helpful method is the req.isAuthenticated() method, which returns true if the current session is in an authenticated state. You can use this method to redirect to login. For example:

app.get('/login', function(req, res){
  if(req.isAuthenticated()){
    res.redirect('/info'),
  } else{
    res.render('login', { user: req.user });
  }
});

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset