Reputation: 41999
I'm working with an admin user in Chrome and a regular user in another browser. After I as admin destroy one of the regular users, I tried to reopen the application in the browser the destroyed user was using. However, I got this error message
Couldn't find Twitteruser with id=2
So the session's living on in the browser after the user's destroyed
The session's created like this
def create
twitteruser = Twitteruser.from_omniauth(env["omniauth.auth"])
session[:twitteruser_id] = twitteruser.id
redirect_to twitterquestions_url, notice: "Signed in!"
end
In the application_controller, it current user's created like this
def current_user
@current_user ||= Twitteruser.find(session[:twitteruser_id]) if session[:twitteruser_id]
end
This is the destroy action
def destroy
Twitteruser.find(params[:id]).destroy
flash[:success] = "User destroyed."
redirect_to users_url
end
Based on other SO answers I found, I tried to reset the session two different ways, but they both reset the session of the admin user, not the user who was destroyed
def destroy
Twitteruser.find(params[:id]).destroy
#1. session[:twitteruser_id] = nil destroys my own session, not deleted users
#2. reset_session #reset admin's session
flash[:success] = "User destroyed."
redirect_to twitterusers_url
end
I also tried to pass an argument to reset_session but it doesn't accept them.
Can anyone tell me how to clear the destroyed user's session? Thanks
Upvotes: 2
Views: 1548
Reputation: 5626
It depends on what your using for backing your sessions. If the session is in the Cookie then there's nothing your Admin can do with it as there's nothing server side to work with. Irregardless, messing with someone else's session may not be possible as you won't know the session ID.
What you want to do is either catch the ActiveRecord::RecordNotFound
that is thrown by find or use find_by_id which will return nil. When the user tries to access the site with the session referencing a deleted user, you can then kill the session.
def current_user
@current_user ||= Twitteruser.find(session[:twitteruser_id]) if session[:twitteruser_id]
rescue ActiveRecord::RecordNotFound
session[:twitteruser_id] = nil # or reset_session
end
or
def current_user
@current_user ||= fetch_user(session[:twitteruser_id])
end
def fetch_user(id)
Twitteruser.find_by_id(id) || reset_session unless id.nil?
end
This will work regardless of how a Twitteruser gets deleted. For example, imagine if you deleted the user from the rails console where there is no session.
Upvotes: 4