Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Configuration:
- config/passport.js
- // Set up passport strategy
- // Local Strategy in this case
- // Import modules
- const LocalStrategy = require('passport-local').Strategy;
- const bcrypt = require('bcryptjs');
- const User = require('../models/User');
- module.exports = (passport) => {
- // Local strategy
- passport.use(new LocalStrategy(
- // Use form fields different from the default of "username" and "password"
- {
- usernameField: 'email',
- // passwordField: myPasswordField
- },
- function(email, password, done) {
- // Find the user if they exist
- User.findOne({ email: email }, (err, user) => {
- if (err) {
- return done(err);
- }
- if (!user) {
- return done(null, false, { message: 'Incorrect email and/or password.' });
- }
- // Check user password
- bcrypt.compare(password, user.password, (err, res) => {
- if (err) {
- return done(err);
- }
- if (!res) {
- return done(null, false, { message: 'Incorrect email and/or password.' });
- }
- return done(null, user);
- });
- });
- }
- ));
- // Session configuration
- passport.serializeUser((user, done) => {
- done(null, user.id);
- });
- passport.deserializeUser((id, done) => {
- User.findById(id, done);
- });
- };
- config/general.js
- // General configuration file for the project
- // Takes app as a parameter where app=express();
- // import passport
- const passport = require('passport');
- // Passport middleware
- app.use(passport.initialize());
- app.use(passport.session());
- app.js
- const passport = require('passport');
- require('./config/general')(app);
- // The general configuration file
- require('./config/passport')(passport);
- // Configuration for passport strategy and sessions
- // ----------------------------
- Routes:
- User registration:
- Example form validation and sanitization with express-validator:
- body('name', 'Name is required').trim().isLength({min: 1}),
- body('email').trim()
- .isLength({min: 1}).withMessage('Email is required')
- .isEmail().withMessage('Incorrect format for email'),
- body('password')
- .isLength({min: 1}).withMessage('Password is required')
- .matches(/[^\s]/).withMessage('Must not contain any whitespace characters')
- .matches(/[a-zA-Z]/).withMessage('Must contain at least one letter'),
- body('password2')
- .exists()
- .custom((val, {req}) => val === req.body.password).withMessage('Passwords do not match'),
- sanitizeBody('name').trim().escape(),
- sanitizeBody('email').trim().normalizeEmail(),
- sanitizeBody('password').escape()
- Example errors and flash / page messages:
- // Get matched data from express-validator in variable user
- const user = matchedData(req);
- const errors = validationResult(req);
- // Some view stuff with displaying errors and re-rendering the registration form
- if (!errors.isEmpty()) {
- return res.render('users/register', {errors: errors.array({onlyFirstError: true}), name: user.name, email: user.email})
- }
- User registration POST route:
- // Check if email already exists
- User.findOne({email: user.email}, (err, registeredUser) => {
- if (err) {
- return next(err);
- }
- if (registeredUser) {
- req.flash('error_msg', 'This email has already been registered');
- return res.redirect('back');
- }
- let newUser = new User({
- name: user.name,
- email: user.email,
- });
- bcrypt.hash(user.password, 10, (err, hash) => {
- newUser.password = hash;
- newUser.save((err) => {
- if (err) {
- return next(err);
- }
- req.flash('success_msg', 'You are now registered');
- res.redirect('/users/login');
- // or login immediately
- /*
- req.login(newUser, (err) => {
- if (err) {
- return next(err);
- }
- return res.redirect('/ideas');
- });
- */
- });
- });
- });
- User login POST route:
- // Feel free to add form validation as in the register route
- app.post('/login', passport.authenticate('local', {
- successRedirect: '/ideas',
- failureRedirect: '/users/login',
- failureFlash: true
- });
- User logout:
- app.get('/logout', (req, res) => {
- req.logout();
- res.redirect('/ideas');
- };
- User login / register GET routes:
- Just render a form for login and registration.
Add Comment
Please, Sign In to add comment