How can I sign out a devise user from the Rails console?

喜你入骨 提交于 2019-12-04 09:53:13

问题


My devise users are "database_authenticatable" and "token_authenticatable". I've tried deleting the "authentication_token" field in the database for that user from the console, but they still seem to be able to use their existing auth token. Deleting the user entirely works, but I don't want to go that far.

Edit: for clarity. I want to use the rails console to sign out a user. i.e. run rails console and then some command.


回答1:


Devise provide helper methods to do these things.

user = User.find(params[:id])
sign_in user
sign_out user

Hope this helps.




回答2:


If you are using Devise you could use the below in your rails console. This works perfect for me as in my app if you are using only 1 session per user account. I am storing my sessions in redisDB.

user = User.first
user.update_attributes(unique_session_id: "")

All I had to do was clear my users unique_session_id for that user and rails kicks the user out of the session.

But for multiple sessions for the same User account this does not work.

If you want to clear all user sessions you can do the below from terminal

rake db:sessions:clear



回答3:


You may be able to use the helpers that others have mentioned after including the necessary module:

include Devise::Controllers::SignInOut

source: Module: Devise::Controllers::SignInOut

There's also another SO question where someone shares a method that doesn't involve using Devise helpers here.




回答4:


I'm not a fan of the sign_out @user pattern because, at least for the devise version I'm using, that signs out the current user, regardless of the argument I pass it. If you're storing sessions in your database then you can do this:

@user.update_attributes(current_sign_in_token: "")

TBH I don't think that's the best way to do it, but it's the best way I've seen in my own research.




回答5:


Seems attribute tokens save sessions:

user.tokens = nil
user.save



回答6:


I believe you can simply update the password_salt and it will invalidate the user session on their next request.

user = User.first
user.update_column(:password_salt, 'reset')    

Reference: http://www.jonathanleighton.com/articles/2013/revocable-sessions-with-devise/




回答7:


You can create a logout link in views->layouts->application.html.erb as:-

<= link_to 'Log Out', destroy_user_session_path, method: :delete %>

It worked for me - hope it does for others as well.



来源:https://stackoverflow.com/questions/28935054/how-can-i-sign-out-a-devise-user-from-the-rails-console

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