aboutsummaryrefslogtreecommitdiff
path: root/config/passport.js
diff options
context:
space:
mode:
authorMateja <mail@matejamaric.com>2021-05-07 00:17:56 +0200
committerMateja <mail@matejamaric.com>2021-05-07 00:17:56 +0200
commitd7e364d83153425e412032dd997e9c58cbc235eb (patch)
treea2095100f5c5e65633c0015a0cc378deb040ac62 /config/passport.js
parent3237737dc88ebff88c258972ac902f9221a003b5 (diff)
downloadnode-playground-d7e364d83153425e412032dd997e9c58cbc235eb.tar.gz
node-playground-d7e364d83153425e412032dd997e9c58cbc235eb.zip
Using `passport.js` for login system.
Diffstat (limited to 'config/passport.js')
-rw-r--r--config/passport.js33
1 files changed, 33 insertions, 0 deletions
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));
+});