DEV Community

Code_Regina
Code_Regina

Posted on

|YelpCamp| Adding in Authentication

               -Introduction to passport 
               -Creating Our User Model 
               -Configuring Passport 
               -Register Form 
               -Register Route Logic
               -Login Routes
               -isLoggedIn Middleware
               -Adding Logout 
Enter fullscreen mode Exit fullscreen mode

Introduction to passport

http://www.passportjs.org/

Passport is a library that helps add authentication into node apps.

Creating Our User Model

Create a new user.js file

Alt Text

Configuring Passport

Implementing serialization in the app.js file
Alt Text


passport.serializeUser(User.serializeUser())

Enter fullscreen mode Exit fullscreen mode

Tells passport how to serialize a user. Serialization is how session is stored.


passport.deserializeUser(User.deserializeUser();

Enter fullscreen mode Exit fullscreen mode

Is how to get out of sterilization.

Register Form

Creating the register form in users.js


const router = express.Router(); 
const User = require('../models/user'); 
const { remove } = require('../models/user'); 

router.get('/register', (req, res) => {
  res.render('users/register');
 });
 router.post('/register', async(req, res) => {
    res.send(req.body);
 })

module.exports = router; 

Enter fullscreen mode Exit fullscreen mode

Alt Text

Alt Text

Register Route Logic


router.post('/register', catchAsync (req, res) => {
try {
  const { email, username, password } = req.body; 
  const user = new User({ email, username}); 
  const registeredUser = await User.register(user, password);
  req.flash('success', 'Welcome to Yelp Camp!'); 
 } catch(e) {
   req.flash('error', e.message);
   res.redirect('register');

  }));

module.exports = router; 

Enter fullscreen mode Exit fullscreen mode

Alt Text

Login Routes


router.get('/login', (req, res) => {
   res.render('users/login');
})

router.post('/login', passport.authenticate('local' { failureFlash: true, failureRedirect: '/login' }), (req, res) => {
   req.flash('success', 'welcome back!'); 
   res.redirect('/campgrounds');
})

Enter fullscreen mode Exit fullscreen mode

isLoggedIn Middleware


module.exports.isLoggedIn = (req, res, next) => {
  if (!req.isAuthenticated()) {
     req.flash('error', 'You must be signed in first!'); 
     return res.redirect('/login');
  }
 next(); 
}

Enter fullscreen mode Exit fullscreen mode

Adding Logout


router.get('/logout', (req, res) => {
  req.logout(); 
  req.flash('success', 'Goodbye!');
  res.redirect('/campgrounds'); 
 })
Enter fullscreen mode Exit fullscreen mode

Top comments (0)