NodeJS login and authorization (Express)

18 views Asked by At

I have a NodeJS backend and an HTML, JS and CSS frontend (separate servers). My login.html works and the session works as well (console.log to the server which displays session id and session email). After a user logs in its supposed to take them to dashboard.html IF LOGGED IN, if not, redirects them to login.html

After I login successfully (session is set), I get directed to dashboard.html and then back to login.html right away - even though my session has started.

Here is my frontends js/auth.js

document.addEventListener("DOMContentLoaded", function () {
  // Check backend for user session
  fetch("http://localhost:3000/api/user-auth")
    .then((response) => {
      if (!response.ok) {
        throw new Error("Network response was not ok");
      }
      return response.json();
    })
    .then((data) => {
      if (!data.authenticated) {
        window.location.href = "login.html"; // Redirect if not authenticated
      }
    })
    .catch((error) => {
      console.error("Error:", error);
    });
});

Here is my servers user-auth

const express = require("express");
const router = express.Router();

router.get("/", (req, res) => {
  // Check if user is authenticated based on session data
  if (req.session.userId) {
    // User is authenticated
    res.json({ authenticated: true });
  } else {
    // User is not authenticated
    res.json({ authenticated: false });
  }
});

module.exports = router;

Here is the relevant part of my backend login.js

const user = result[0];
      // Compare passwords
      bcrypt.compare(userPassword, user.password, (compareErr, match) => {
        if (compareErr) {
          return res.status(500).json({ message: compareErr.message });
        }
        if (!match) {
          return res.status(401).json({ message: "Incorrect password" });
        }

        // Set session variables to indicate user is logged in
        req.session.userId = user.id;
        req.session.userEmail = user.email;
        console.log(req.session.userId);
        console.log(req.session.userEmail);

        // Send JSON response with redirect URL
        res.json({ redirect: "dashboard.html" });
      });

And my session middleware:

app.use(
  session({
    secret:
      "", // Removed from the post but is set.
    resave: false,
    saveUninitialized: true,
  })
);

Nothing much else, as I am fairly new to NodeJS.

0

There are 0 answers