In my app, I have a User
model and it has a rememberable_token
column. When creating a user, a random secure string is saved in a before_create
filter to act as a secure token for the user:
user.rememberable_token = SecureRandom.urlsafe_base64
In the session controller, it creates a permanent cookie with the value of that token so that the user doesn't get logged out when closing the browser and only gets logged out when they log out via the logout
action:
Session controller:
def create
.
.
cookies.permanent.signed[:permanent_user_session] = user.rememberable_token
end
def logout
cookies.delete :permanent_user_session
redirect_to root_url
end
The cookie is used in the application controller to determine if there is a current user as well as in a before_filter that is used in a few controllers to determine if a user is logged in and authorized.
Application controller:
def current_user
@current_user ||= User.find_by_rememberable_token(cookies.signed[:permanent_user_session]) if cookies.signed[:permanent_user_session]
end
def authorize
unless User.find_by_rememberable_token(cookies.signed[:permanent_user_session])
render :action => 'login'
end
end
The question is if this is safe or if it is prone to session hijacking? If it is prone to hijacking, would it be alright if in the session#logout
method it created a new rememberable_token for the user just before deleting the existing cookie (but not creating a new cookie with that value)?
Thank you.