简体   繁体   中英

NodeJS Session Authentication

I'm trying to setup a logged in session so that all pages that should be login-restricted simply redirect to the login screen. Unfortunately, app.get seems to be acting weird and not triggering for some cases.

For example, my authentication function:

function authenticate(req,res) {
    var pass = false; 
    if (req.session.loggedIn) pass = true;
    console.log(pass);
    if (pass) {
        next();
    } else {
        res.redirect("/html/login.html");
    }
}

And my server.js:

app.use(express.static(__dirname));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.cookieParser());
app.use(express.session({secret: 'secretkey'})); //not my real key

//gets
app.get("/onePlayer",authenticate);

app.get("/",authenticate);

app.get("/logout",function(req,res) {
    req.session.destroy();
    res.redirect("/");
});

The / gets authenticated, I can see it in my terminal, but /onePlayer does not trigger at all, and I can get to the page without logging in.

Notes: /onePlayer is a directory. The main page is onePlayer/index.html (tried the full path as well, no trigger). I have also made sure that the session is destroyed by logging out and destroying the session.

Why is the function not being called for /onePlayer ? I can't figure it out.

The problem here is that onePlayer is a directory and that in your code, you give priority first to files that exist, and then to your app.get calls.

Change your code to look something like this:

app.use(express.json());
app.use(express.urlencoded());
app.use(express.cookieParser());
app.use(express.session({secret: 'secretkey'})); //not my real key


app.get("/onePlayer",authenticate);
app.use(express.static(__dirname)); // Moved this after the app.get so that it has a lower priority

app.get("/",authenticate);

app.get("/logout",function(req,res) {
    req.session.destroy();
    res.redirect("/");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM