Question:
How to authenticate user using PassportJS local strategy during registration?

To properly use the passport.Authenticate function with the "local" strategy, by using the latest version of passport-local-mongoose  you have to correctly call the passport.authenticate.


You should pass (req, res, callback) as the arguments.


Code:

import "dotenv/config";

import express from "express";

import bodyParser from "body-parser";

import mongoose from "mongoose";

import session from "express-session";

import passport from "passport";

import passportLocalMongoose from "passport-local-mongoose";


const saltRounds = 10;

const app = express();

const port = 3000;


app.use(express.static("public"));

app.use(bodyParser.urlencoded({ extended: true }));


app.use(

  session({

    secret: "Our little secret.",

    resave: false,

    saveUninitialized: false,

  })

);


app.use(passport.initialize());

app.use(passport.session());


mongoose.connect("mongodb://localhost:27017/userDB", { useNewUrlParser: true });


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("/", (req, res) => {

  res.render("home.ejs");

});


app.get("/login", (req, res) => {

  res.render("login.ejs");

});


app.get("/register", (req, res) => {

  res.render("register.ejs");

});


app.get("/secrets", (req, res) => {

  if (req.isAuthenticated()) {

    console.log("Trying rendering secrets ejs");

    res.render("secrets.ejs");

  } else {

    console.log("Failed rendering secrets ejs");

    res.redirect("/login");

  }

});



app.post("/register", (req, res) => {

  User.register({ username: req.body.username }, req.body.password)

    .then((user) => {

      console.log("Check user Registeration success");

passport.authenticate("local")(req, res, () => {

  console.log("User is now Authenticated");

  res.redirect("/secrets");

});

    })

    .catch((error) => {

      console.log(error);

    });

});


app.post("/login", (req, res) => {});


app.listen(port, () => {

  console.log(`Server started on port ${port}`);

});


Suggested blogs:

>How to test the post-Django function?

>How to filter events by month in Django?

>Implement nested serializers in the Django rest framework

>Solved: TaskList View in Django

>Sending Audio file from Django to Vue

>Creating a form in Django to upload a picture from website

>Fix webapp stops working issue in Django- Python webapp

>How to manage the Text in the container in Django?


Ritu Singh

Ritu Singh

Submit
0 Answers