Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting cookie in rails

I have a cookie which can exist on either of these domains - www.xyz.com or .xyz.com. I am having trouble deleting the cookie through code. Since it can exist on either of domains I was assuming doing the following should be sufficient:

...
cookies.delete cookie  #delete cookie if it exists on current domain(www.xyz.com)
cookies.delete cookie, :domain => :all #delete cookie if it exists on root (.xyz.com)
...

But cookies.delete cookie, :domain => :all seems to be rendering the first call useless as if the cookie is set on www.xyz.com then it doesn't get deleted.

Any ideas on how to delete a cookie that might exist on two different domains?

like image 410
shreyj Avatar asked May 15 '14 07:05

shreyj


2 Answers

Well, Rails doesn't allow to delete cookie with the same name twice during one request, although they have been set for different domains.

Assuming you are trying to logout, double redirect is the best what I came up with:

def logout
  cookie.delete(:user_id)
  redirect_to logout_all_path
end

def logout_all
  cookie.delete(:user_id, domain: :all)
end

Don't know whether Rails 6 solved this problem, so PR wouldn't hurt.

When deleting cookie cookie.delete(:user_id) is the same as an explicit form cookie.delete(:user_id, domain: nil).

It is not obligatory to specify domain in your code.

like image 157
Nick Roz Avatar answered Oct 18 '22 00:10

Nick Roz


I believe you need to be explicit on which domain you're deleting cookies

cookies.delete cookie, :domain => "xyz.com"

From Rails docs, looks like you can set with domain: :all but not delete

like image 2
katzmopolitan Avatar answered Oct 17 '22 23:10

katzmopolitan