Cameron
Cameron

Reputation: 28783

List sessions for current user only in Rails

I'm using the activerecord-session_store gem to store sessions in the database.

I list sessions with this method in my SessionsController:

def index
  @sessions = Session.all
end

However this lists ALL sessions in the app and not just ones for the currently logged in user. The database table for sessions has the following columns: id, session_id, data, created_at, updated_at so there is no user_id column to filter on.

I can access the user_id in the session data with Marshal.load(Base64.decode64(session.data))['user_id']

How can I use this data to filter the list? So far all I can think of is to do a conditional in the View that compares it against the current_user.id

e.g.

<% @sessions.each do |session| %>
  <% if Marshal.load(Base64.decode64(session.data))['user_id'] == current_user.id %>
    <!-- LIST SESSION -->
  <% end %>
<% end %>

Upvotes: 1

Views: 1975

Answers (2)

virtuexru
virtuexru

Reputation: 888

If I'm not mistaken you can use the same call current_user in the controller; so if you setup a before_filter on that controller/route you can use the same code to filter against current_user.id

Something like:

before_filter :get_user_session

def get_user_session
  Session.all.each do |session|
    if Marshal.load(Base64.decode64(session.data))['user_id'] == current_user.id
      # do things
    end
  end
end

Upvotes: 1

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

If you use PostgreSQL as a backend, you might simply set a serialization to be :json:

ActiveRecord::SessionStore::Session.serializer = :json

and query the json field against postgres.


If you use MySQL, you could implement your own session class:

ActionDispatch::Session::ActiveRecordStore.session_class = MySessionClass

and implement a pre_commit hook, saving the user_id in the respective column in your table explicitly. Afterwards just query against this column.

Upvotes: 3

Related Questions