Search code examples
javascriptnode.jsexpress

why does it open with any pass after i use the correct password once?


I have 2 HTML files, one with just a form(which takes in a password) and one with secrets. I wrote this js code but when I run it, it refuses every wrong password until I put the correct password once and then when I go back it takes all the incorrect passwords as well.

Where am I going wrong?

import express from "express";
import { dirname } from "path";
import { fileURLToPath } from "url";
const __dirname = dirname(fileURLToPath(import.meta.url));
import bodyParser from "body-parser";


const app = express();
var userAuthorised = false;

app.use(bodyParser.urlencoded({extended: true}));

function passCheck(req, res, next) {
    
    if (req.body["password"] === "ILoveProgramming"){
        userAuthorised = true;
    }
    next();
}

app.use(passCheck);

app.get("/", (req, res) => {
    res.sendFile(__dirname + "/public/index.html");
});

app.post("/check", (req, res) => {
    console.log(req.body);
    if(userAuthorised){
        res.sendFile(__dirname + "/public/secret.html");
    }
    else {
        res.redirect("/");
    }
});

app.listen(3000, () => {
    console.log("Server Running on port 3000");
});

Solution

  • When you start the server, you initialize

    var userAuthorised = false;
    

    Once, it's set to

    userAuthorised = true;
    

    it's never set back to false, because it's a global variable and the initialization happens only once at the start.

    The condition

    if(userAuthorised){
    

    will always be true after the first correct login.

    The solution is to not use a global variable for this. A common pattern in Express is to store additional values in the request, e.g.

    req.userAuthorised = true;
    

    and check them with

    if(req.userAuthorised){