I have saved my id and password on an mongo atlas db and now i want to login in my web app using that mongo atlas db saved credentials using passport js , how i can do that ?i have ried looking up the tutorials on the internet but unable to find any ?
Peter Scheler
JS enthusiast
It is all written in passports documentation.
Fist you need a strategy against your model (
User):const passport = require('passport') const LocalStrategy = require('passport-local').Strategy; passport.use(new LocalStrategy({ usernameField: 'username', passwordField: 'password' }, function(username, password, done) { User.findById(username, function (err, user) { if (err) return done(err) if (!user) { return done(null, false, { message: 'Incorrect username.' }) } if (!checkPwd(user.password, password)) { return done(null, false, { message: 'Incorrect password.' }) } return done(null, user) }) } )) passport.serializeUser(function(user, done) { done(null, user.id) }) passport.deserializeUser(function(id, done) { User.findById(id, function(err, user) { done(err, user) }) })Add passport to your app:
app.use(bodyParser.urlencoded({ extended: true })) app.use(session({ secret: 'secret key' })) app.use(passport.initialize()) app.use(passport.session())and create a login endpoint:
app.post('/login', passport.authenticate('local', { successRedirect: '/', failureRedirect: '/login' }) )Your login form could look like:
<form action="/login" method="post"> <div> <label>Username:</label> <input type="text" name="username"/> </div> <div> <label>Password:</label> <input type="password" name="password"/> </div> <div> <input type="submit" value="Log In"/> </div> </form>Look here how to use the authentication middleware.