V
V
Vitaly2018-01-31 22:47:33
Node.js
Vitaly, 2018-01-31 22:47:33

How to work with sessions in node+express?

All the best!
Decided to try to play a little with authorization, with the help of sessions.
I ran into a problem when the cookie session expires: {maxAge: new Date(Date.now() + (60 * 1000 * 1))} re-visiting something in req.session fails :(
Here is a piece of my code:

let session = require('express-session');

app.use(session({
    secret: 'aaa2C44-4D44-WppQ38Siuyiuy',
    cookie: {maxAge: new Date(Date.now() + (60 * 1000 * 1))},
    resave: true,
    saveUninitialized: true
}));

let checkSignIn = (req, res, next) => {
    if (req.session.user) {   // после истичения сессии req.session.user всегда undefined, 
                                       //несмотря на то что в 
                                       //логине я повторно задаю это
                                     // свойство req.session.user = user['_id']
        next();
    } else {
        res.redirect("/login");
    }
}

app.post("/login",  (req, res) => {
   if(req.body.usr == user && req.body.pwd == password)
           req.session.user = user['_id']
           res.redirect("/manage");
        } else {
            console.log('Could not find user')
            res.render('login')
        }


    })


})


app.get("/manage", checkSignIn, (req, res) => {
        res.render('index')
})

As a result, the first time the login is successful, but after the session expires, it fails to log in again, for some reason, when checking in the custom middelver, checkSignIn req.session.user == undefined , although in "/login" this property is set in the same way as in first time req.session.user = users['_id']
I don't understand why this happens. Please tell me how to fix this

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vitaliy, 2018-02-02
@Scorpiored88

Replaced cookie.maxAge from date to time and everything is fine :)
i.e. from new Date(Date.now() + (60 * 1000 * 1)) to 90000

V
Vitaly, 2018-01-31
@vshvydky

users['_id'] === users._id
judging by the entity, I think that users instanceof Array === true
hence users._id does not exist, is equal to undefined

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question