0

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:privatekey@api.schema.io";


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.

Khari Kisile
  • 79
  • 3
  • 11
  • It depends a bit upon exactly how your making the requests to the API, but the general concept is that you need to create cookiejars that keep track of the cookies separtely for each user like each browser would keep track of separate cookies for each browser. See http://stackoverflow.com/questions/19936705/how-to-maintain-a-request-session-in-nodejs for a start. And search for "jar" in this doc page: https://github.com/request/request – jfriend00 Dec 24 '16 at 18:10
  • Show us your actual code (insert it into your question and format it properly) and we could help a lot better. – jfriend00 Dec 24 '16 at 20:32
  • Updated my question with the code @jfriend00 – Khari Kisile Dec 24 '16 at 20:40
  • Well, SuperAgent seems to have no doc about cookie handling from node.js. You can see some references to a cookieJar in [this source file](https://github.com/visionmedia/superagent/blob/8f1a90cbcc9aac066bfe58b4ad38ff2b3092bb46/lib/node/agent.js#L6), but I don't know if that's something you can control for a different set of requests or not. The `request()` library (something you could replace superAgent with) has very specific doc about using cookieJars. – jfriend00 Dec 24 '16 at 20:53
  • @jfriend00 yes, I read through it. The request.jar() function wouldn't work for superagent tho, would it? I'll have to see if most of these cookie jars on npm work in the same way. – Khari Kisile Dec 24 '16 at 20:55

0 Answers0