问题
I am new to Rails and I am following Michael Hartl's Rails Tutorial, so my code is mostly borrowed from there. Here is the scenario:
I log onto my site using Computer A
. Then I log onto the site using the same user id using Computer B
. When I log out of the site using Computer A
, Computer B
remains logged in and can still perform actions. For security reasons, I would like Computer B
to be forced to login again when Computer A
has logged out. Is there an easy way to invalidate all sessions for a given user upon log out? If you have some sample code that would be very much appreciated.
I also read that it is best practice to use reset_session on log out. However, I had trouble determining whether you should use reset_session
before or after logging out the user?
This is from my Sessions Controller:
def destroy
log_out if logged_in?
# Reset session to prevent session fixation vulnerability
reset_session
flash[:info] = "You are now logged out"
redirect_to root_url
end
This is from my Sessions Helper:
# Forgets a persistent session
def forget(user)
user.forget
cookies.delete(:user_id)
cookies.delete(:remember_token)
end
# Logs out the current user
def log_out
forget(current_user)
session.delete(:user_id)
@current_user = nil
end
回答1:
It's work as they have to.
Session has depends on browser.if logged in one PC then your session retain on same browser that you currently working. And if you logged in with another PC then your browser create another session for you.
You can try this scenario with well known site like google and Facebook.
Please refer below link.
What are sessions? How do they work?
And if you trying to destroy all session in single machine you can try.
rake db:sessions:clear
回答2:
One way you could go about this is to set a flag on your user model, let's call it active
or status
, which would be a boolean column on your database. When the user signs out, you set the active column to false
. Now, in your current_user
method, in your controller, you just have to check if the user is active
, if not clear the session.
Here's a little snippet I could scribble for this:
class User
# you should add an active or status column through a migration
# enum status: {true => :active, false => :inactive} # largely personal preference for enums, you could define other helper methods without needing the enums
end
# x_controller
def log_out
...
user.inactive!
...
end
def current_user
if @current_user ||= User.active.find_by_id(session[:user_id])
# the user is active continue
@current_user
else
# the user is not active clear the session
session.clear
end
end
Not tried the code before, but this is a way I think you could accomplish this.
来源:https://stackoverflow.com/questions/38158904/how-to-invalidate-all-sessions-after-user-log-out-in-rails