Search code examples
node.jsmongodbexpresspassport.js

How does passport.authenticate(...) gets the value from the user?


Top code

require('dotenv').config()
const express= require("express")
const ejs=require("ejs")
const bodyParser=require("body-parser")
const mongoose =require("mongoose")
const session=require("express-session")
const passport=require("passport")
const passportLocalMongoose=require("passport-local-mongoose")

const app= express()

const saltRounds = 10;
const PORT=3000||process.env.PORT

app.use(bodyParser.urlencoded({extended:true}))
app.use(express.static("public"))
app.set('view engine',"ejs")

app.use(session({
    secret:"My secret",
    resave:false,
    saveUninitialized:false,
}))
app.use(passport.initialize())
app.use(passport.session())
const uri='mongodb://127.0.0.1:27017/userDB'

const MongoConnect=async()=>{
    try {
        await mongoose.connect(uri);
        console.log("Connected Succesfully")
    }
     catch (error) {
        console.log(error);
    }
    
}
const userSchema= new mongoose.Schema({
    email:String,
    password:String
})
userSchema.plugin(passportLocalMongoose)



 const user= new mongoose.model("user",userSchema)

 passport.use(user.createStrategy());

 passport.serializeUser(function(user, done) {
    done(null, user);
  });
  
  passport.deserializeUser(function(user, done) {
    done(null, user);
  });

app.route("/")

.get((req,res)=>{
res.render("home")
})


app.route("/login")

.get((req,res)=>{
res.render("login")
})
//-----------------------------THE "PROBLEM"--------------------
.post((req,res)=>{

        passport.authenticate("local",{ failureRedirect: '/login', failureMessage: true })(req,res,function () {
            res.redirect("/secrets")
 
    
  })
})
//-------------------------------------------------
app.route("/register")

.get((req,res)=>{
res.render("register")
})

.post((req,res)=>
{
    user.register({username:req.body.username},req.body.password,(err,user) =>{
        if(err)
        {
            console.log(err)
            res.redirect("/register")
        }
        else{
            passport.authenticate("local")(req,res,function () {
                res.redirect("/secrets")
                
            })
            
        }
    })
    
})


app.get("/secrets",function (req,res) {
    console.log(req.isAuthenticated())
    if(req.isAuthenticated()){
        res.render("secrets")
    }
    else{
        res.redirect("/login")
    }
})

app.get('/logout', function(req, res, next){
    req.logout(function(err) {
      if (err) { return next(err); }
      res.redirect('/');
    });
  });
MongoConnect(). then(()=>{
    app.listen(PORT,()=>
    {
        console.log("Server is Running on port 3000")
    })

})
.catch((err)=>{
   console.log(err)

})
Faulty code

So I have this code, and I don't get how passport.authenticate gets the user's inputs. There is no body parser, how does it compare it in the database without bodyparser.

Before i tried the code above, i implemented the one below (req.login) and it gave me some issues, even when i wrote the wrong password,i was still able to get through by going through the route localhost:3000/secrets, so i changed it and just added the passport.authenticate(..) function and it fixed the issue, but I don't understand why it works at all. how does the passport.authenticate(..) get the user's input without body-parser.

.post((req,res)=>{
   const user1 =new user({
    username:req.body.usermame,
    password:req.body.password
   })


   req.login(user1,function (err) {
    if(err)
    console.log(err)
    else{
        passport.authenticate("local",{ failureRedirect: '/login', failureMessage: true })(req,res,function () {
            res.redirect("/secrets")
            
        })
    }
    
  })
})

Solution

    1. You use passport-local-mongoose as a loxal strategy

    2. passport-local-mongoose uses passport-local

    3. passport-local checks req.body.username and req.body.password:

    Souce code:

    var username = lookup(req.body, this._usernameField) || lookup(req.query, this._usernameField);
    var password = lookup(req.body, this._passwordField) || lookup(req.query, this._passwordField);