JavaScript Role Based Access Failed

Very New to backend development and decided to use Node.JS as my backend due to already having experience with front end JS, i am at a loss on how i can accomplish Role based access.

I want the code to block any users that are not logged in from accessing anything other than the log in and signup page as well as preventing the user without the proper role to access certain things.

here is my front end login JS:

    // Wait for the DOM to load
if (document.readyState == 'loading') {
    document.addEventListener('DOMContentLoaded', ready);
} else {
    ready();
}

function ready() {
    const loginpassword = document.getElementById('loginpassword');
    const togglePasswordButton = document.getElementById('ShowPass');

    togglePasswordButton.addEventListener('click', function () {
        if (loginpassword.type === 'password') {
            loginpassword.type = 'text';
        } else {
            loginpassword.type = 'password';
            togglePasswordButton.textContent = 'Show Password';
        }
    });

    // Add event listener to the Login button
    const loginButton = document.getElementById('Login');

    loginButton.addEventListener('click', () => {
        const username = document.getElementById('loginuser').value;
        const password = document.getElementById('loginpassword').value;

        // Validate user input
        if (!username || !password) {
            alert('Please enter your username and password.');
            return;
        }

        // Create an object with login data
        const loginData = {
            username,
            password,
        };

        // Send a POST request to the backend login route
        fetch('/api/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(loginData),
        })
            .then((response) => response.json())
            .then((data) => {
                if (data.error) {
                    // Display an error alert if login fails
                    alert('Login failed. Please check your username and password.');
                } else {
                    // Store the token securely in localStorage
                    localStorage.setItem('authToken', data.token);
                    
                    // Determine where to redirect based on user's access
                    if (data.access === 'teacher') {
                        window.location.href = '../Teacher-Pages/T-Home.html'; // Teacher dashboard URL
                    } else if (data.access === 'student') {
                        window.location.href = '../Student-Pages/S-Home.html'; // Student dashboard URL
                    } else {
                        alert('Invalid user access.'); // Handle other access types as needed
                    }
                }
            })
            .catch((error) => {
                console.error(error); // Log the error for debugging
                alert('An error occurred during the login process.');
            });
    });
}

Here a token i set when the user logs in

// NPM Packages used
const express = require('express'); // Node Framework For Web Apps
const router = express.Router(); // Express to export this route as a router fetchables by front end
const mysql = require('mysql'); // NPM Package For Using MySQL
const bodyParser = require('body-parser'); // NPM Package that enables backend to parse user inputs as json
const bcrypt = require('bcrypt'); // NPM Package used to encrypt passwords
const jwt = require('jsonwebtoken'); // NPM Package for creating session tokens

const connection = require('../database/connector');
const config = require('../Misc/Config');

router.use(bodyParser.json());

// Define the login route
router.post('/login', (req, res) => {
    const { username, password } = req.body;

    // Check if the username and password are provided
    if (!username || !password) {
        res.status(400).json({ error: 'Username and password are required.' });
        return;
    }

    // Query the database to find the user by username
    const sql = 'SELECT * FROM accounts.loginfo WHERE username = ?';
    connection.query(sql, [username], async (error, results) => {
        if (error) {
            console.error(error);
            res.status(500).json({ error: 'An error occurred during login.' });
        } else {
            // Check if the user exists
            if (results.length === 0) {
                res.status(401).json({ error: 'Invalid username or password.' });
            } else {
                // Verify the password
                const user = results[0];
                const passwordMatch = await bcrypt.compare(password, user.password);

                if (!passwordMatch) {
                    res.status(401).json({ error: 'Invalid username or password.' });
                } else {
                    // User is authenticated; create a JWT token with the user's role
                    const token = generateAuthToken(user);

                    // Include the user's role in the response
                    res.status(200).json({ token, access: user.access });
                }
            }
        }
    });
});

// Function to generate a JWT token with user role
function generateAuthToken(user) {
    // Include user data and role in the JWT token payload
    const token = jwt.sign({ userId: user.id, username: user.username, role: user.access }, config.secretKey, { expiresIn: '2h' });
    return token;
}

module.exports = router;

(ignore some of the comments, its for documentation)
Here on the backend route i add some info to the token regarding who logged in

// authentication.js

const jwt = require('jsonwebtoken');
const config = require('../Misc/Config');

function authenticateToken(requiredRole) {
    return (req, res, next) => {
        const token = req.headers.authorization;

        if (!token) {
            return res.status(401).json({ error: 'Authentication token is missing.' });
        }

        jwt.verify(token, config.secretKey, (err, user) => {
            if (err) {
                return res.status(403).json({ error: 'Invalid token.' });
            }

            if (user.access !== requiredRole) {
                return res.status(403).json({ error: 'Access denied. Insufficient privileges.' });
            }

            req.user = user;
            next();
        });
    };
}

module.exports = authenticateToken;

Here i tried to add a authentication function by the using tokens. (but in my case they don’t work because despite not being logged in and just tampering with the url i am able to access the pages only those logged in should have access to)

// student-homepage.js

// Wait for the DOM to load
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', setup);
} else {
    setup();
}

function setup() {
    const logoutButton = document.getElementById('Logout');

    logoutButton.addEventListener('click', () => {
        const authToken = localStorage.getItem('authToken');

        if (!authToken) {
            window.location.href = '../Universal-Pages/LogIn.html';
        } else {
            fetch('/api/logout', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
            })
                .then((response) => {
                    if (response.ok) {
                        localStorage.removeItem('authToken');
                        window.location.href = '../Universal-Pages/LogIn.html';
                        alert('Successfully Logged Out');
                    } else {
                        alert('Logout failed. Please try again.');
                    }
                })
                .catch((error) => {
                    console.error(error);
                    alert('An error occurred during the logout process.');
                });
        }

        // Decode the token to get user's role
        const decodedToken = jwt_decode(authToken);
        const userRole = decodedToken.access;

        if (userRole !== 'student') {
            window.location.href = '../Universal-Pages/AccessDenied.html';
        }
    });
}

Here for example for the front end script of the student homepage i have some code that should verify if the user is a student based on their token but in my case they dont work, this code is also supposed to work in conjuction with the following:

const express = require('express');
const router = express.Router();
const authenticateToken = require('./authentication');

// Protected teacher homepage route
router.get('/student-home', authenticateToken('student'), (req, res) => {
    res.sendFile('../public/Student-Pages/S-Home.html');
});

module.exports = router;

i have an inkling that i may have done something wrong here thats why i am asking for your help to solve my predicament.

Here is My main app.js if its necessary:

// NPM packages used
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const config = require('./Misc/Config');

// Import the necessary routes
const signupRoute = require('./routes/signup');
const loginRoute = require('./routes/login');
const logoutRoute = require('./routes/logout');
const authFunction = require('./routes/authentication');
const studentRoute = require('./routes/student');
const teacherRoute = require('./routes/teacher');

// Serve static files from the 'public' directory
app.use(express.static('public'));

// Middleware to parse incoming JSON data
app.use(bodyParser.json());

// api prefixes
app.use('/api', signupRoute);
app.use('/api', loginRoute);
app.use('/api', logoutRoute);
app.use('/api', studentRoute);
app.use('/api', teacherRoute);
app.use('/func', authFunction);


// Start the server
const port = process.env.PORT || 3002;
app.listen(port, () => {
    console.log(`Server is running on port ${port}`);
});

Here is also my File Structure:

File Structure

Again im am very new to full stack web development and is in need of how i can implement the role based access system and preventing people who arent logged in the first place to access the pages via tampering with the url, i know the question is quite cumbersome but i thank anyone who could help. i can provide more information or code if needed.

and if you know a better way to implement the feature i need instead of my janky code please do let me know.