PRAKS
PRAKS

Reputation: 11

passport.authenticate not authenticating the user

I am trying to register and authenticate a user using passport-local and passport-local-mongoose but the user is not getting authenticated. I do not want to downgrade my mongoose version.

This is the code for registering and authenticating a user to redirect to '/secrets' route. The user is getting registered successfully in the MongoDB database but is not getting authenticated.

app.post('/register',function(req,res,next){

    User.register({username:req.body.username},req.body.password)
    .then((user) =>{

        passport.authenticate("local",function(err,user,info){
            if(!err)
            {
                res.redirect("/secrets");
            }
            else{
                console.log(err);
            }
        })(req,res,next);
        
    })
    .catch(err =>{
        console.log(err);
        res.redirect("/register");
    });

});

This below is executing without any errors but the user is not getting authenticated and is being redirected to the '/login' route insted of showing the 'secrets' page.

passport.authenticate("local",function(err,user,info){
            if(!err)
            {
                res.redirect("/secrets");
            }
            else{
                console.log(err);
            }
        })(req,res,next);

This is the '/secrets' route :

app.get('/secrets',function(req,res){

    if(req.isAuthenticated())
    {
        res.render("secrets");
    }
    else
    {
        res.redirect("/login");
    }

});

Here is the whole code :

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

const app = express();

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

app.use(session({
    secret: 'Our Little Secret',
    resave: false,
    saveUninitialized: false
}));

app.use(passport.initialize());
app.use(passport.session());

mongoose.connect("mongodb://127.0.0.1:27017/userDB");

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(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

app.get('/',function(req,res){
    res.render('home');
});


app.get('/login',function(req,res){
    res.render('login');
});


app.get('/register',function(req,res){
    res.render('register');
});

app.get('/secrets',function(req,res){

    if(req.isAuthenticated())
    {
        res.render("secrets");
    }
    else
    {
        res.redirect("/login");
    }

});


app.post('/register',function(req,res,next){

    User.register({username:req.body.username},req.body.password)
    .then((user) =>{

        passport.authenticate("local",function(err,user,info){
            if(!err)
            {
                res.redirect("/secrets");
            }
            else{
                console.log(err);
            }
        })(req,res,next);
        
    })
    .catch(err =>{
        console.log(err);
        res.redirect("/register");
    });

});


app.post('/login',function(req,res){

   
});
 
app.listen(3000,function(){
    console.log('server running on port 3000... ');
});

Please help, i am new to Node.js and Mongoose.

Upvotes: 1

Views: 232

Answers (1)

Pooriya A
Pooriya A

Reputation: 1

instead of using ‍‍‍‍‍‍‍‍‍‍‍‍‍passport.use(User.createStrategy());‍‍‍, first require the passport-local to create your strategy (const LocalStrategy = require('passport-local').Strategy), then replace passport.use(User.createStrategy()); with passport.use(new LocalStrategy(User.authenticate()));

Upvotes: 0

Related Questions