Uname: Linux business55.web-hosting.com 4.18.0-553.lve.el8.x86_64 #1 SMP Mon May 27 15:27:34 UTC 2024 x86_64
Software: LiteSpeed
PHP version: 8.1.32 [ PHP INFO ] PHP os: Linux
Server Ip: 162.213.251.212
Your Ip: 3.145.201.156
User: allssztx (535) | Group: allssztx (533)
Safe Mode: OFF
Disable Function:
NONE

name : authValidator.js
const jwt = require('jsonwebtoken');
const JWT_SECRET = "l!TtLeGr()O//En";
const Admin = require("../Schema/Admin");

const cookieAuth = () => {
    return async (req, res, next) => {
        try {
            const cookieAuthtoken = req.cookies['authtoken'];
            if (cookieAuthtoken) {
                // Verify the token and fetch admin details
                const tokenAdmin = jwt.verify(cookieAuthtoken, JWT_SECRET);
                const dbAdmin = await Admin.findById(tokenAdmin.id);
                const { _id, name, email } = dbAdmin;

                // Create a new admin object and generate a new token
                const admin = { id: _id, name, email };
                const authtoken = jwt.sign({ id: _id, email }, JWT_SECRET);

                // Set the new token in the cookie
                res.cookie('authtoken', authtoken);
                req.admin = admin;

                // Redirect to admin dashboard if already logged in and trying to access login/register
                if (admin && (req.path.includes('login') || req.path.includes('register'))) {
                    return res.redirect('/sites/pioneer-reality/admin/');
                }

                // Proceed to the next middleware
                next();
            } else {
                // Redirect to login or register based on the route
                if (req.path.includes('register')) {
                    next(); // Allow access to the register page
                } else if (!req.path.includes('login')) {
                    res.redirect('/sites/pioneer-reality/admin/login'); // Redirect to login for other pages
                } else {
                    next(); // Allow access to the login page
                }
            }
        } catch (err) {
            console.log('Error in cookieAuth:', err.message);

            // Redirect to login or register based on the route
            if (req.path.includes('register')) {
                next(); // Allow access to the register page
            } else if (!req.path.includes('login')) {
                res.redirect('/sites/pioneer-reality/admin/login'); // Redirect to login for other pages
            } else {
                next(); // Allow access to the login page
            }
        }
    };
};

module.exports = cookieAuth;
© 2025 GrazzMean-Shell