Rails 3 - How can you get access to Devise's current_user in the IRB console?

与世无争的帅哥 提交于 2019-12-18 10:21:44

问题


I'm doing some design/debugging in IRB and need to login a user and then be able to use current_user in my efforts.

From Brian Deterling's answer to another question, I have been able to successfully login and access a page response with this sequence:

>> ApplicationController.allow_forgery_protection = false
>> app.post('/sign_in', {"user"=>{"login"=>"some-login-id", "password"=>"some-password"}})
>> app.get '/some_other_path_that_only_works_if_logged_in'
>> pp app.response.body

NOTE: If you get a 200 response you are not logged in. You need a 302 redirect to indicate a successful login. See Tim Santeford's answer.

I've been able to get session info:

1.9.3-p125 :009 > app.session
 => {"_csrf_token"=>"1yAn0jI4VWzUH84PNTH0lVhjpY98e9echQGS4=", "session_id"=>"89984667d30d0fec71f2a5cbb9017e24"} 

I've tried everything I can think of to try to get to current_user via app and app.session, but no luck. How can I get current_user?


回答1:


current_user is a property of the controller so after app.post('/sign_in', ... you can call app.controller.current_user in your rails console to get the User object




回答2:


It might be possible that you are not really logging in. One thing to keep in mind is that Devise I build on top of Warden which is rack middleware.

I tried your app.post method of logging in on an app I'm working on that uses Devise. After posting to the login page and getting a 302 redirect the app.session showed the warden user id.

>> app.session
{
 "_csrf_token"=>"dT0/BqgLb84bnE+f1g...",
 "warden.user.user.key"=>["User", [42843], "$2a$10$1OU.1BixIba..."],
 "session_id"=>"0dd49c05ff4e6362c207c6eb877f86cd"
}

I was able to fetch the user like this:

>> current_user = User.find(app.session["warden.user.user.key"][1][0])

When I logged out and then tried logging in with a bad password I get a 200 and then the app.session is missing the warden user info and only contained the csrf token and session id like your example.

BTW: Once logged in app.controller.current_user was nil even when the warden user id was in the session.



来源:https://stackoverflow.com/questions/9544338/rails-3-how-can-you-get-access-to-devises-current-user-in-the-irb-console

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!