How can I find a devise user by it's session id?
Asked Answered
C

3

21

Given session["session_id"] is it possible to find the logged in User to which that session belongs to?

Corrasion answered 26/4, 2012 at 17:48 Comment(1)
You can use User.current_user instead... did you tried?Aintab
P
28

At least on my system (rails 3.2, devise 2.0.4), you can do it like this:

session is:

{"session_id"=>"be02f27d504672bab3408a0ccf5c1db5", "_csrf_token"=>"DKaCNX3/DMloaCHbVSNq33NJjYIg51X0z/p2T1VRzfY=", "warden.user.user.key"=>["User", [3], "$2a$10$5HFWNuz5p6fT3Z4ZvJfQq."]}

session["warden.user.user.key"][1][0], then is 3.

So, I'd find it as:

User.find(session["warden.user.user.key"][1][0])
Polivy answered 26/4, 2012 at 18:1 Comment(2)
On Rails 4.2.1, Devise 3.4.1 you'll want to use User.find(session["warden.user.user.key"][0][0])Amigo
Thanks. This example is ugly, but it work. Thanks again. This example for cookies: https://mcmap.net/q/660113/-user-session-authentication-in-rails-5Ramiah
M
3

I'm not sure what you are trying to accomplish but will try to answer

If you want only the User from the current session, a simple way would be to store his id on session, for example:

def login(username, pass)
  # do the usual authentication stuff and get user
  if logedin
    session[:user_id] = user.id
  end
end 

Then get the current user would be something like

current_user =User.find(session[:user_id])

If what you want is finding all the users that are currently logged in, I think you need to config your app to save session at DB, because predefined is that session data is store in cookies in the browser. For more information on this check this answer How to track online users in Rails?


EDIT: Just noticed you are using devise so the first way is actually there for you. You just need to call current_user method at any controller. For the second way check this answer "Who's Online" using Devise in Rails

Matias answered 26/4, 2012 at 18:39 Comment(0)
A
2

And i might add this, as i was trying to do it the other way, if you are using ActiveRecord session_store you can find all stored sessions of a user like so:

ActiveRecord::SessionStore::Session.select{ |s| s.data["warden.user.user.key"] && s.data["warden.user.user.key"][0][0] == user_id }
Acidimetry answered 24/3, 2022 at 1:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.