Passport verification is successful during the login process, however, it encounters issues during registration

I am currently learning about passport.js and session management, and I'm in the process of implementing a local login feature on my website.

Here is what I am attempting to achieve:

  • Secret page: Authenticated users can access the secret page, while unauthorized users will be redirected to the login page.
  • Login page: Users who enter correct username and password details are authenticated and transferred to the secret page; otherwise, they are sent back to the login page.
  • Register page: Users provide a username and password, a new MongoDB document is created and stored in the database. Simultaneously, the user is authenticated for the current session and forwarded to the secret page.

The Issue I'm Facing:

  • Login page authentication works fine: The authentication process on the login page functions correctly. A cookie is sent to the browser upon successful login, and the user is authenticated within the session to access the secret page.
  • Register page data insertion is successful: After registration, the new username and password are saved in the MongoDB database. Users can log in using this newly registered account.
  • Register page authentication failure: Despite utilizing the same passport.authenticate() function, the register page encounters an issue with the authentication process. However, no error messages are displayed in the console.

After researching and attempting various passport authentication methods found on Google, they all worked well for the 'login' POST Request but not for the 'register' POST Request. I have gone through the documentation of passport-local and passport-local-mongoose, as well as tried out this solution. Unfortunately, I still encounter authentication issues on the register page despite following these resources. I am utilizing express-session, passport, and passport-local-mongoose packages.

I'm beginning to question if there is a gap in my understanding of passport authentication? Thank you for your assistance and patience!

My Code:

EJS File - Register Page:

<!-- ... -->
<form action="/register" method="POST">
  <div class="form-group">
    <label for="email">Email</label>
    <input type="email" class="form-control" name="username">
  </div>
  <div class="form-group">
    <label for="password">Password</label>
    <input type="password" class="form-control" name="password">
  </div>
  <button type="submit" class="btn btn-dark">Register</button>
</form>
<!-- ... -->

JS File:

require('dotenv').config();

const express = require('express');
const app = express();
const port = 3000;

const ejs = require('ejs');

const session = require('express-session');
const passport = require('passport');
const passportLocalMongoose = require('passport-local-mongoose')

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

//session and passport set up
app.use(session({
  secret: process.env.SECRET,
  resave: false,
  saveUninitialized: true,
  cookie: {
    sameSite: 'lax'
  },
}))

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

//user database set up ////////
const mongoose = require("mongoose");

main().catch(err => console.log(err));
async function main() {
  await mongoose.connect('mongodb://localhost:27017/userDB');
}

const userSchema = new mongoose.Schema({
  username: {
    type: String,
    unique: true
  },
  password: String
})

userSchema.plugin(passportLocalMongoose)

const User = mongoose.model("User", userSchema)

passport.use(User.createStrategy());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
//user database set up end ///////

//GET Request
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");
})

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

app.get('/logout', function(req, res) {
  req.logout(function(err) {
    if (err) {
      console.log(err);
    }
    res.redirect('/');
  });
});

//POST request
//Register POST Request ////////////////////////////////
app.post("/register", function(req, res) {
  User.register(new User({
      username: req.body.username
    }), req.body.password,
    function(err, user) {
      if (err) {
        console.log(err);
        res.redirect('/register')
      }
      passport.authenticate('local'), function(req, res) {
        res.redirect("/secrets");
      }
    }
  )
})

app.post('/login', passport.authenticate('local', {
  failureRedirect: '/login',
}), function(req, res) {
  res.redirect("/secrets");
});

app.listen(port, function() {
  console.log("start listening to port 3000")
})

Answer №1

Experimenting with my code, I decided to follow this helpful suggestion. By introducing a 'returnCode' parameter to the passport authenticate function callback, I was pleasantly surprised to see that the code worked seamlessly despite logging 'undefined'. It made me realize that maybe my confusion stems from not fully grasping how passport works?

However, it's frustrating to encounter a 404 error page when trying to access the examples section on passport-local's official documentation. Are there any alternate resources or examples available for better understanding passport-local?

Snippet of My Code

app.post("/register", function(req, res) {
  User.register(new User({
      username: req.body.username
    }), req.body.password,
    function(err, user) {
      if (err) {
        console.log(err);
        res.redirect('/register')
      } else {
        passport.authenticate('local', {})(req, res, function(returnCode) {
          console.log(returnCode); //return: undefined
          res.redirect('/secrets');
        })
      }
    }
  )
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Handle file size errors in Node.js using Multer

I have been using the "multer" code to handle file uploads on my server. However, I noticed that despite setting a filesize limit, the code seems to ignore it and still uploads the files. const multer = require("multer"); const path = require("path"); c ...

Storing account information in a .env file can be a more secure option compared to storing it in a client

Working on a basic nodejs application using express for file processing operations. Planning to package the final app with pkg. I need to implement a login system and one time account creation. The app will launch a browser tab running a vuejs UI app. Cons ...

Tips for transferring data to an entry component in Angular 2 using ng-bootstrap modal

I've been grappling with sending data to a custom modal content component in Angular 2. My objective is to have the flexibility of calling this modal from any other component without duplicating code. Despite my efforts, including referencing the "Com ...

Design a div in the shape of a trapezium with clipped overflow

Is there a way to create a trapezium using CSS/Html/Canvas? I have attempted to do so, but my current method is messy and not practical. div { width:0; margin-left:-1000px; height:100px; border-right:1000px solid lightblue; border-top:60px solid tra ...

Limiting Ant Design Date range Picker to display just a single month

insert image description here According to the documentation, the date range picker is supposed to display two months on the calendar, but it's only showing one month. I carefully reviewed the documentation and made a change from storing a single va ...

Simulated database in a Service using TypeScript with Node

Struggling with a unit test, I need to mock the this.orderRepository.findById(id); method to find an object by its ID. Although I've set the return value, the test keeps failing. This is my first time creating a unit test in Node using TypeScript and ...

Can I use my local network/browser to download an html file from a webpage as if I manually downloaded it using javascript or nodejs?

As someone who is relatively new to javascript/nodejs and its packages, I have a question about downloading files. Is it feasible for me to download a file using my own local browser or network? Typically, when researching how to scrape or download html ...

Every time Lodash.uniqueId is called, it consistently generates the value of

Consider using the lodash library, specifically version 4.17.11. _.uniqueId() seems to consistently output 1 instead of a random three-digit number. Similarly, _.uniqueId('prefix') always returns prefix1. Do you see this as a potential issue? ...

The HTML iframe is displaying blank content

I'm trying to embed a webpage within another webpage using an iframe. I attempted to do so with this simple code: <iframe src="http://edition.cnn.com/" id="i_frame"></iframe> JSFIDDLE However, nothing is displaying. Any thoughts on why ...

The close button on the jQuery UI Dialog fails to appear when using a local jQuery file

I may sound silly asking this, but I have a simple webpage where I've added a jQuery modal dialog box. Strangely, when I link directly to the jQuery files online (like http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css), everything works ...

Update nested child object in React without changing the original state

Exploring the realms of react and redux, I stumbled upon an intriguing challenge - an object nested within an array of child objects, complete with their own arrays. const initialState = { sum: 0, denomGroups: [ { coins: [ ...

The characteristics of angular js Service/Factory and how they influence functionality

I'm seeking clarification on the behavior of AngularJS, especially in terms of JavaScript. In my code, I have a controller that has an Angular factory injected into it. Here's a snippet from the controller: $scope.localObjCollection = myObjFac ...

Can one intercept the window.location.replace event?

Suppose I am currently browsing the URL "example.com/somepage#somehash" and then decide to execute window.location.hash = "anotherhash", the URL will be updated to "example.com/somepage#anotherhash". This action triggers the window.hashashchange event. On ...

reveal concealed section and seamlessly glide to specified location inside the secret compartment

I have implemented a feature on my website where hidden divs are revealed one at a time, with the screen scrolling to display each specific div. While this code functions well, I am now looking to enhance it by opening the hidden div and smoothly scrolling ...

Tips on keeping Bootstrap Modals out of your browsing history

Imagine this scenario A visitor lands on Page A, clicks through to Page B, and then engages with a link that triggers a modal (code provided below) <a href="mycontent.html" data-target="#modal_xl" data-toggle="modal" data-backdrop="static">Click me ...

Restarting the express application

I have a node.js application that was created using the express.js framework. const app = express(); require('./config')(app); require('./services')(app); In the ./config/config.js file, we set up the configuration like this: module. ...

Updating a function in jQuery UI after dynamically loading content through AJAX

I've been on a quest for days now, searching high and low for an answer to my dilemma. While I've managed to solve most of the issues that arose after adding AJAX calls to my code, there's one piece that still eludes me. Just to provide som ...

Exploring the concept of front-end deletion through ajax technology

I'm currently tackling a front-end CRUD RESTful API project and encountering challenges specifically related to the DELETE and PUT methods. While I have successfully managed to implement the GET and POST functionalities, utilizing a forms.html file f ...

Trouble executing Vue.js project due to an empty jsconfig.json file?

Currently, I am venturing into a Vue.js project. My workspace is VS Code operating as an administrator. The guide I am following can be found at: https://vuejs.org/guide/quick-start.html#creating-a-vue-application My Node version stands at 6.14.13. Verify ...

Ajax: Failed to send POST request (404)

After adding a POST script in the manage.ejs file and console logging the data to confirm its functionality, I encountered an issue. Below is the code snippet: <script type="text/javascript"> var guildID = "<%= guild.id %>"; let data = {so ...