New Session/Cookie for Each User in Express

684 Views Asked by At

I'm using express to make API calls to a e-commerce platform. The API uses sessions to handle the persistent data needed for user tasks, like account and cart records. Cart and account details are attached to sessions (and the cookies that the sessionID is stored in), so when I log in with User1 and create a cart with items, and then log out, the cart persists. However, when logging in with User2, they inherit the cart of User1 because it's attached to the session.

EDIT/UPDATE

Main app.js:

    var nodemailer      = require("nodemailer"),
    request         = require("superagent"),
    flash           = require("connect-flash"),
    bodyParser      = require("body-parser"),
    session         = require("express-session"),
    cookieParser    = require("cookie-parser"),
    methodOverride  = require("method-override"),
    Schema          = require("schema-client"),
    express         = require("express"),
    nodeuuid        = require("uuid"),
    cors            = require("cors"),
    app             = express();


app.use(session({
    name: "X-Session",
    secret: "randomstring",
    resave: false,
    saveUninitialized: false, 
    cookie: {
        maxAge: 60*60*1000,
        secure: false
    }

}));

app.use(bodyParser.urlencoded({extended:false}))
.use(cookieParser())
.set("view engine", "ejs")
.use(express.static(__dirname + "/public"))
.use(methodOverride("_method"))
.use(flash())

var client = new Schema.Client("clientname", 'privateKeyhere');

var SchemaAPI = "https://clientname:[email protected]";


app.use(function(req, res, next){
    res.locals.success = req.flash("success");
    res.locals.errors = req.flash("error");
    res.locals.account = req.session.account;
    res.locals.session = req.session;
    res.locals.cart = req.session.cart;
    if(req.session.account_id){
        client.get("/accounts/{id}", {
            id: req.session.account_id
        }, function(err, account){
            if(account){
                req.account = account;
                res.locals.account = account;
            };
            next();
        });
    } else {
        next();
    }
});

Login Route:

app.post("/login", function(req, res, next) {
request
    .post('http://localhost:3001/v1/account/login')
    .set('X-Session', req.session.id)
    .set('Accept', 'application/json')
    .send({
            email: req.body.email,
            password: req.body.password
        })
    .end(function (error, account){
        if(account){
            account = account.body;
            req.session.account = account;
            console.log(account.name + " - " + account.id);
            console.log(req.sessionID);
            req.flash("success", "Logged in, " + account.email + ".");
            res.redirect("/index");
        } else if(account == null){
            req.flash("error", "Your username or password is incorrect. Try again or <a href='/register'> sign up here</a>");
            res.redirect("login");
        } else {
            console.log(error);
            res.redirect('login');
        }
    });

});

All my other app routes have that "X-Session" header being passed with each request.

How can I create one session for each user such that when they log in, their session is retrieved, along with any cart information associated with their session? I'm using express-session to generate a sessionID, and then passing that ID to the API. Thanks in advance for your help.

0

There are 0 best solutions below