Scylla Scylla - 3 months ago 9
Node.js Question

trying to check if another session with same session.username exists

I am currently practicing nodeJS and I would like to achieve something like this :

I am trying to check if another session with the same session.username exists. and if it does, display a warning. I am doing it this way :

app.post('/login', (req, res) => {
let options = {"username": req.body.username, "error": null};
if(!req.body.username) {
options.error = "username required nobi";
res.render('login', options);
} else if (req.body.username == req.session.username) {
res.redirect('/');
} else {
req.sessionStore.all( (err, sessions) => {
if(!err) {
let isUsed = false;
let i=0;
for(i; i < sessions.length; i++) {
let session = JSON.parse(sessions[i]);
if (session.username == req.body.username) {
err = "name already taken";
isUsed = true;
break;
}
}
}
if (err) {
options.error = err;
res.render('login', options);
} else {
req.session.username = req.body.username;
res.redirect("/");
}
});
}
});


It is not working : I am connecting on chrome and IE with the same username. I do not want that to be possible

as an illustration (if needed) :

{ If9a9SgOoq7roW8Za84CouSEzgqDs1Q3:
{ cookie: { originalMaxAge: null, expires: null, httpOnly: true, path: '/' },
username: 'pseudo' },
MBs41iJmoQpLLCDhP8aFAk5PWAZ_ZQSV:
{ cookie: { originalMaxAge: null, expires: null, httpOnly: true, path: '/' },
username: 'pseudo' } }

Answer
app.post('/login', (req, res) => {
    // You can store username in res.locals.username after auth
    // It's not necessary to pass it into render.

    let username = req.body.username;
    if(!username) 
        return res.render('login', {error: 'username required nobi'});

    if (username == req.session.username) 
        return res.redirect('/');

    if (username && username != req.session.username)   
        return ... // maybe destroy current session?

    req.sessionStore.all( (err, sessions) => {
        if (err) 
            return res.render('login', {error: err.message});

        let isUsed = Object.keys(sessions).some((s) => s.username == username);
        if (isUsed)
            return res.render('login', {error: 'Already used'});

        req.session.username = username;
        res.locals.username = username;
        res.redirect('/');
    });
});