Home > other >  How to find a session record in the database using the cookie value in an Rails app using activereco
How to find a session record in the database using the cookie value in an Rails app using activereco

Time:11-28

I have a Rails app that uses Devise and the activerecord-session_store gem with a minimalistic setup (nothing beyond the defaults).

I'm trying to to use the value stored in the cookie to manually find the corresponding session record in the sessions table that activerecord-session_store uses.

The problem is that the session value that I get from the cookie does not appear to be stored "as is" in the database and ergo I cannot simply do a find_by to find the record it matches to.

Or in other words:

This is what the cookie value looks like: a5a879b4f923d2eea7707cf8ce28cd80

and this is what the session_id in the sessions table looks like: 2::801e4371783f192b4ee95be9def08bf17daaa1ebeed589dbdfeeb8742e2dd9f6

The value in the sessions table appears to be somehow encrypted and I cannot find info on how to match the two.

Worth pointing out at the app works normally so it somehow does the matching internally. I'm trying to match the session_id for a different use case.

I have tried using the find_by_session_id method that ActiveRecord::SessionStore::Session exposes in hopes it will do some transformations and magically find the correct session but it appears to be just the standard find_by from active record which does not work since the string values are different.

My guess is that I need to somehow transform the value that comes from the cookie to the format data is kept in the session_id columns and only then do a find_by but I'm not sure how.

Do you have any ideas how I could find the correct session using the cookie value? Thanks

CodePudding user response:

Although I can't provide details about how and why this works, I figured out a solution:

First, a private_session_id needs to be generated from the value from the cookie value and only then a find_by_session_id can be called.

Something like this:

private_session_id = Rack::Session::SessionId.new(COOKIE_VALUE).private_id ActiveRecord::SessionStore::Session.find_by_session_id(private_session_id)

  • Related