From d7e364d83153425e412032dd997e9c58cbc235eb Mon Sep 17 00:00:00 2001 From: Mateja Date: Fri, 7 May 2021 00:17:56 +0200 Subject: Using `passport.js` for login system. --- config/passport.js | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 config/passport.js (limited to 'config/passport.js') diff --git a/config/passport.js b/config/passport.js new file mode 100644 index 0000000..c4368cb --- /dev/null +++ b/config/passport.js @@ -0,0 +1,33 @@ +const passport = require('passport'); +const LocalStrategy = require('passport-local').Strategy; +const bcrypt = require('bcryptjs'); + +const User = require('../models/user'); + +const strategyCallback = (email, password, done) => { + // Try to find user + User.findOne({email}, (err, user) => { + // Database error + if (err) + return done(err); + + // No user found + if (!user) + return done(null, false); + + // Wrong password + if (!bcrypt.compareSync(password, user.password)) + return done(null, false); + + // Successful login + return done(null, user); + }) +}; + +passport.use(new LocalStrategy({usernameField: 'email'}, strategyCallback)); + +passport.serializeUser((user, done) => done(null, user._id)); + +passport.deserializeUser((id, done) => { + User.findById(id, (err, user) => done(err, user)); +}); -- cgit v1.2.3