1

So, I have some current_user method, which takes ID from cookie's auth_token, and I want cookie be to deleted when window with site has been closed.

 cookies[:auth_token] = @user.auth_token

What I have to add?

Joe Half Face
  • 2,303
  • 1
  • 17
  • 45
  • Look for [event that fires when browser window is closed or user navigates away](http://stackoverflow.com/questions/1025935/capture-event-onclose-browser) and [update expiration date of your cookie](http://stackoverflow.com/questions/2144386/javascript-delete-cookie) in that event handler. – Anton Strogonoff May 13 '13 at 20:47
  • So it is done through JS? No build-in Rails feature? Than what difference between `cookies` and `cookies.permanent`? – Joe Half Face May 13 '13 at 20:51
  • 1
    Didn't notice the ruby-on-rails tag at first. I'm not very proficient with Rails (more of a Django guy). Since cookies are saved in user's browser, you certainly can deal with them on client side from JS. It might be more convenient to do from Rails, but then you'd have to make an AJAX request from ``beforeunload`` handler in JS to get new response from Rails with updated cookies. – Anton Strogonoff May 13 '13 at 21:15

2 Answers2

0

Actually, if you set a cookie without giving an expiration date, it is only retained until the browser is closed. (Which can mean the program itself, not just a window or a tab.)

An expiration in the past will delete the cookie immediately.

From Thread: http://www.ruby-forum.com/topic/94682

@Joe Half Face, If it helps you, please mark it useful.

Vieenay Siingh
  • 867
  • 2
  • 17
  • 44
  • it works, but I don't know if idea of setting cookie expired from beginning is good? P.S. I don't want to follow user activity when they logged off – Joe Half Face May 13 '13 at 21:51
  • No, it deletes cookie immediantly, I found out... Guy gave wrong answer. Even hitting reload kicks your out to login page – Joe Half Face May 13 '13 at 21:53
0

I once implemented a similar thing. For security purposes we had to automatically log the user out when they navigate away from the page. The solution looked like this:

  • On client side, write a beforeunload event handler.
  • From that handler make an AJAX request to logout URL, in your case it might be a special view that deletes the cookie (see Rails docs on cookies).
  • The AJAX request has to be synchronous to make sure beforeunload event handler waits for its completion.
Anton Strogonoff
  • 32,294
  • 8
  • 53
  • 61