Keystonejs session

2k views Asked by At

I need some help with keystonejs sessions. I'm working on a shopping cart, thus after a customer adds a product to the cart they move onto a check-out page that forces them to sign in as a user. However, when they sign in the session restarts and clears the contents of the cart.

My question: Is there a way to sign in and keep the existing session and then add the user id to the session.

I'm persisting the session to mongodb using connect-mongo.

I have written req.session.cart to add the products to the session and use

view.on('post', { action: 'login' }, function (next) {

    if (!req.body.email || !req.body.password) {
        req.flash('error', { detail: 'Please enter your email and password.' });
        return next();
    }

    var onSuccess = function() {
        req.flash('success', { detail: 'Great you are now logged in!' });
        res.redirect('/checkout');//redirect on success
    }

    var onFail = function() {
        req.flash('error', { detail: 'Input credentials were incorrect, please try again.' });
        return next();
    }

    keystone.session.signin({ email: req.body.email, password: req.body.password }, req, res, onSuccess, onFail);//

to authorize the user.

Regards

3

There are 3 answers

1
Shea Hunter Belsky On

As far as I can tell, user signin with Keystone only appends the user property to the request object, and it adds the user's MongoDB id to req.session.userId. It doesn't clear the existing session. How are you currently adding to the Keystone session?

0
Max Ma On

I am wondering that is there any update for this question?

I've digged a little deeper and found that at req.session.reganete() in keystone.session clean the previous session, and the code in keystone looks all good.

I ended up put anonymous user Cart into as an object and at keystone.signin success callback reassign the object back to req.session.cart


[Update after the post]

The session library will clear the session when new session ID issues.

See the discussion here: Request: Option for refreshing the session ID

const currentSession = {}
// 1. have a copy of current session
Object.assign(currentSession, req.session) 
// 2. merge the copied session to new session after keystone signin method.
// ...
0
Ralexrdz On

I don't think you could set that in the session. It is just for users.

Instead I would have a isDraft field on the the Cart List and save the Cart every change of products.