Issue with Custom Middleware Not Blocking Access to Dashboard

I'm encountering an issue with custom middleware in ui_base.js not properly enforcing session validation before serving the dashboard page. Despite setting up the middleware to check for a valid user session, users are still able to access the dashboard page directly without being redirected to the login page if they don't have a valid session.

const cookieParser = require('cookie-parser');  // Parse the cookie from headers

// Cookie parsing Middleware
uiShared.app.use(cookieParser());

// Middleware to check logged in user session
function checkSession(req, res, next) {
    const sessionId = req.cookies['sessionId'];  // session ID is stored in a cookie
    const userSession = global.get(sessionId);  // Sessions from global context

    // Validate the session
    if (userSession && userSession[sessionId]) {
        // If session is valid, continue to serve the dashboard
        next();
    } else {
        // If no session or invalid session, redirect to login
        res.redirect('http://localhost:1880/login/');
    }
}

// Serve dashboard with session validation
uiShared.app.get(config.path, uiShared.httpMiddleware, checkSession, (req, res) => {
    // Send the dashboard file only if session is valid
    res.sendFile(path.join(__dirname, '../../dist/index.html'));
});

Issue
Even though checkSession middleware is placed before the route handler for the dashboard page, users are able to access the dashboard page directly without being redirected if they don't have a valid session.

Expected Behavior:
Users without a valid session should be redirected to the login page, and the dashboard page should only be accessible if a valid session is present.

Questions:

  • Is there an issue with the way middleware is set up or ordered?
  • How can I ensure that the middleware correctly enforces session validation before serving the dashboard page?

Any insights or suggestions would be greatly appreciated!

Have you added logging to check whether your code is called?

  • Thanks for the response !.
  • I have added logging for the global context, but it does not appear in the server console.
  • Could you please clarify if it is possible to use the global context values within the Express middleware in ui_base.js?

I don't know what you mean by that. Can you not log to the console in middleware?

  • I apologize for the confusion earlier.
  • I had mistakenly been making changes in the /home/node-red directory instead of the correct ./nodered/ location, which is why the log messages weren't appearing. After correcting this, I'm now successfully retrieving logs for the ui base.js file

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.