-Introduction to passport
-Creating Our User Model
-Configuring Passport
-Register Form
-Register Route Logic
-Login Routes
-isLoggedIn Middleware
-Adding Logout
Introduction to passport
Passport is a library that helps add authentication into node apps.
Creating Our User Model
Create a new user.js file
Configuring Passport
Implementing serialization in the app.js file
passport.serializeUser(User.serializeUser())
Tells passport how to serialize a user. Serialization is how session is stored.
passport.deserializeUser(User.deserializeUser();
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;
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;
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');
})
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();
}
Adding Logout
router.get('/logout', (req, res) => {
req.logout();
req.flash('success', 'Goodbye!');
res.redirect('/campgrounds');
})
Top comments (0)