3

I am using rails and devise. I want the user to be automatically and instantly logged out on browser close. The way I understand it, in rails, the cookie generated by the session method should expire immediately on browser close. I can't find where devise is making the session if it is at all. I see there is a timeoutable option but I don't want that. If remember me is unchecked I want the user to have to log in again if the browser is closed.

How can I get this functionality?

user4584963
  • 2,403
  • 7
  • 30
  • 62

1 Answers1

1

Do something like this and delete the cookie before the browser closes:

<% if current_user.present? && !current_user.remember_me %>
<script>
window.onbeforeunload = closingCode;
function closingCode(){
   document.cookie = '_' + rails_app_name_here + '_session' +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
   return null;
}
</script>
<% end %>

You could put this in your application layout before the closing body if you wanted.

If you can't make this work, you might be SOL.

Community
  • 1
  • 1
penner
  • 2,707
  • 1
  • 37
  • 48
  • I'm wondering if I should disable devise :rememberable and handle sessions and cookies myself. What do you think? – user4584963 Sep 09 '15 at 21:31
  • Hmm I'm not sure what you gain by doing that yourself. I think devise generates a consistently named cookie, all you need to do is delete it. – penner Sep 09 '15 at 21:44
  • Where would I put the code you pasted above? I'm also having trouble finding the name of the cookie. Thanks for your help. – user4584963 Sep 09 '15 at 21:50
  • The above didn't work. Any other ideas? Maybe the name of the cookie isn't correct. How can I find the name of the cookie that I need to set the expiration date for? – user4584963 Sep 09 '15 at 23:23
  • Use chrome inspector to see what cookies are being created when you login. – penner Sep 09 '15 at 23:24
  • Looks like it's named correctly. The cookie shows expiration set to when "when the browsing session ends" which isn't true because when I close out the browser, the cookie persists. Not quite sure how this is working under the hood in devise and what to try next. – user4584963 Sep 10 '15 at 01:22
  • It actually seems to work normally with firefox. This might be a chrome bug that doesn't delete temporary cookies on browser close. http://stackoverflow.com/a/22776628/4584963 – user4584963 Sep 10 '15 at 01:30
  • The http only cookie could be an issue as well https://alainahardie.com/logging-out-of-a-rails-app-that-uses-session_store-cookie_store/ also maybe just editing the cookie to a bad value could work if chrome refuses to delete cookies and considers it a feature – penner Sep 10 '15 at 06:03