How can I find a devise user by it's session id? How can I find a devise user by it's session id? ruby ruby

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


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])


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  endend 

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 answerHow 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