1

I've been trying to make an authentification system with Node.js for a small web app.

So far I've made a login route :

app.post('/login', async function(req, res) {
    let login = req.body.login;
    let password = req.body.password;

    let userId = await databaseUsers.verifyUser(login, password);

    if(userId != null) {
        req.session.userId = userId;
    }

    res.send(userId != null);
});

Then I created a protected route :

app.get('/homepage', requiresLogin, function(req, res) {
    res.sendFile(__dirname + '/client/homepage.html');
});

And a function that checks if the user is logged :

function requiresLogin(req, res, next) {
    if (req.session.userId) {
        next();
    } 
    else {
        res.send('You must be logged in to view this page.');
    }
}

Client-side, i'm using only JS, with the fetch API :

let url = "/login";
let headers = new Headers({
    "Content-Type": "application/json"
});
let init = {    
    method: 'POST',
    headers: headers,
    cache: 'default',
    body: JSON.stringify({'login': user.login, 'password': user.password})
};

let verif = await fetch(url, init);

Now when I log myself in, the server stores in the session the user's ID.

But when trying to reach /homepage, i get the 'not connected' error.

I could use a global variable to store the session but therefor multi-user would no longer be an option.

I also thought using cookies, like when the user successfully logs in, the server sends him a cookie.

But then how to handle the user's accesses to the pages ?

0 Answers0