express vhost dynamic subdomains

271 Views Asked by At

I'm trying to create dynamic subdomains with an authentication check. The subdomains work as expected, but since i added the authentication it just gets ignored, at least most of the time. isAuthenticated always returns false, so in theory it should always redirect to login. But it doesn't. Also the logs are printed (what seems to me) very randomly.

Can someone help me with this?

subdomains.forEach(subdomain => {
    const subDir = `${subdomainDir}/${subdomain}/`;

    let subExpress = express();

    subExpress.use(express.static(__dirname + subDir));

    subExpress.get('*', async (req, res) => {
        let isAuthenticated = false;

        try {
            isAuthenticated = await login.isAuthenticated(req.get('authorization'))
        } catch (error) {
            console.log(error);
        }

        console.log("subdomain", subdomain)
        console.log("isAuthenticated", isAuthenticated, "subdomain === login", subdomain === "login");

        if (isAuthenticated || subdomain === "login") {
            res.sendFile(`/${subDir}index.html`, {
                root: '.'
            });
        } else {
            res.redirect(301, `https://login.${domain}/`);
        }
    });

    app.use(vhost(`${subdomain}.${domain}`, subExpress));
});

let unusedSub = express();

unusedSub.get('*', (req, res) => {
    console.log("unusedSub");
    res.redirect(`https://dashboard.${domain}/`);
});

app.use(vhost(`*.${domain}`, unusedSub));

app.listen(port, () => console.log(`Listening on port ${port}.`));
1

There are 1 best solutions below

0
On BEST ANSWER

I've figured it out. Basically the order of "use" was wrong. The static part has to be after the authentication check and you have to call "next". Maybe this will help someone.

subdomains.forEach(subdomain => {
    const subDir = `${subdomainDir}/${subdomain}/`;

    let subExpress = express();

    subExpress.use(async (req, res, next) => {
        let isAuthenticated = false;

        try {
            isAuthenticated = await login.isAuthenticated(req.get('authorization'))
        } catch (error) {
            console.log(error);
        }

        if (isAuthenticated || subdomain === "login") {
            next();
        } else {
            res.redirect(301, `https://login.${domain}/`);
        }
    });

    subExpress.use(express.static(__dirname + subDir));

    app.use(vhost(`${subdomain}.${domain}`, subExpress));
});