首页 > 解决方案 > Make parts of website unavailable without login

问题描述

I am creating a game where you have two options: Play the game, and view global and local highscores. I have created a signup and login system. When you successfully log in, you can either 1. play game, 2. check highscores, and 3. log out.

I am hosting a server with nodejs. The problem is, one could easily put localhost:3000/menu to access the menu without logging in. How do I make the rest of the site unavailable if you are not logged in? This is the code I use to display the pages:

app.get('/', function(req, res) {
    res.sendFile(path.join(__dirname + '/public/index.html'));
});

app.get('/signup', function(req, res) {
    res.sendFile(path.join(__dirname + '/public/signup.html'));
});

app.get('/menu', function(req, res) {
    res.sendFile(path.join(__dirname + '/public/menu.html'));
});

app.get('/highscores', function(req, res) {
    res.sendFile(path.join(__dirname + '/public/highscores.html'));
});

app.get('/main', function(req, res) {
    res.sendFile(path.join(__dirname + '/public/main.html'));
});

My friend told me I could do something like this:

app.get('<username>/menu',

Is there a good way to implement this or are there better solutions?

标签: javascripthtmlnode.jsexpressserver

解决方案


I don’t know how your login system works, but if a user successfully log in, you should store a token that identify the user, and is unique. I recommend you this video if this isn’t what you have done.

Then, when a user request the /menu route, you should check that there is a token in the local storage, or wherever you want to store it, and most inportantly, check that the token is valid, that it is not a fake one.


推荐阅读