Search code examples
node.jsexpresssessionpassport.jspassport-local

Session not created in Express


Here is the project [dev branch]: https://github.com/asid-team/library_system

I'm working on a Library App. It's server-side rendered, I'm using Express and Passport for auth and MongoDB.

The thing is, I wanted two User roles (1 for regular users, and the 1 for Librarians, the people who work in the Library). So, I came up with something shown on the links https://github.com/asid-team/library_system/tree/dev/config/routes

It works perfectly for users. Passport does all the job, and makes req.user after the successful login. But, the Librarian part doesn't seem to work properly: it doesn't save the Librarian session.

Can you maybe spot a mistake in my approach / code?

EDIT: When I console.log the req for sessions I get:

sessions:
  { UaRq2ZBvDAkeckjWJU38wfdlalPmKKwb: '{"cookie":{"originalMaxAge":null,"expires":null,"httpOnly":true,"path":"/"},"flash":{},"passport":{}}',
    zl24_yTpebRC6rP4I9pcNwCVKNwXa2zH: '{"cookie":{"originalMaxAge":null,"expires":null,"httpOnly":true,"path":"/"},"flash":{},"passport":{"user":"5a620ae6091a07cf8dc82fc9"}}',
    '359N-18VDvgNIDzVj-BQ_t_vdQ8Iav7H': '{"cookie":{"originalMaxAge":null,"expires":null,"httpOnly":true,"path":"/"},"flash":{},"passport":{"user":"5a61f14bb4bd20c692aa87e8"}}' },

These two users, 5a620ae6091a07cf8dc82fc9 and 5a61f14bb4bd20c692aa87e8are Users.


Solution

  • The problem is that you define passport.serializeUser and passport.deserializeUser twice. The passport object is the same in both your User and Librarian route, so one is effectively ignored.

    There are likely many different ways to address this problem, some more hacky than others, but this Passportjs Github issue has some discussion.

    Ultimately, you'll need one set of serialize and deserialize functions to handle both User and Librarians.