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

后端 未结 2 1814
-上瘾入骨i
-上瘾入骨i 2021-01-01 17:40

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

相关标签:
2条回答
  • 2021-01-01 18:25

    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

    0 讨论(0)
  • 2021-01-01 18:27

    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])
    
    0 讨论(0)
提交回复
热议问题