Background
Passport is a user authentication library for node. It provides tons of strategies (facebook, google, etc). I’ll be going over the basic passport-local strategy which you sign up with username and passpord. User login with valid name and password.
I’ll also show to how to use session and flash to display error or success message. Also, use express validator to validate user input. Finally encrypt user password with the mighty bcryptjs.
Steps
Install Packages. (bcryptJS, express-validator, passport, psasport-local, etc) You can refer to package.json
Setup User Model with some functions
1234567891011121314151617181920212223242526272829303132333435// routes/users.jsvar mongoose = require('mongoose')var bcrypt = require('bcryptjs')var UserSchema = mongoose.Schema({username: { type: String, index: true},password: { type: String}})var User = module.exports = mongoose.model('User', UserSchema)module.exports.createUser = function(newUser, callback) {bcrypt.genSalt(10, function(err, salt) {bcrypt.hash(newUser.password, salt, function(err, hash){newUser.password = hashnewUser.save(callback)})})}module.exports.getUserByUsername = function(username, callback) {var query = { username: username }User.findOne(query, callback)}module.exports.getUserById = function(id, callback) {User.findById(id, callback)}module.exports.comparePassword = function(candidatePassword, hash,callback) {bcrypt.compare(candidatePassword, hash, function(err, isMatch) {if(err) throw errcallback(null, isMatch)});}Setup mongoDB and passportJS in app.js ( I’m only going over the main imports the basic imports such as express please refer to my github, link below)
12345678910111213141516var passport = require('passport')var LocalStrategy = require('passport-local')var mongoose = require('mongoose')var flash = require('connect-flash');var users = require('./routes/users');...mongoose.connect('mongodb://localhost/loginappv2');var db = mongoose.connection;...app.use(passport.initialize());app.use(passport.session());set up routes in routes/user.js
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152/* GET users listing. */router.get('/signin', function(req, res, next) {console.log(res.locals)res.render('signin');});router.post('/signin',passport.authenticate('local', {successRedirect: '/users/profile',failureRedirect: '/users/signin',failureFlash: true}),function(req, res) {res.redirect('/users/profile')});/* GET users listing. */router.get('/signup', function(req, res, next) {res.render('signup', {errors: ''});});// Post Sign Uprouter.post('/signup', function(req, res, next) {// Parse Infovar username = req.body.usernamevar password = req.body.password//Create Uservar newUser = new User({username: username,password: password})User.createUser(newUser, function(err, user){if(err) throw err;})res.redirect('/users/signin')});router.get('/profile', ensureAuthenticated, function(req, res, next) {console.log(req.user)res.render('profile', {user: req.user.username});});router.get('/logout', function(req, res, next) {req.logout()req.flash('success_msg', 'You are logged out')res.redirect('/users/signin')})module.exports = router;setup passport and local in routes/user.js
|
|
This is part one. I’ll implement flash, session and express validator in next part.