0

I have a problem that on specific view request.user returns AnonymousUser.

This is caused by a javascript library which I use to collect payments. That javascript library makes a cookie which makes django see a logged-in user as AnonymousUser.

If I delete that cookie, django sees the user as logged-in but after a couple of refreshes, I get a new cookie which makes again the logged-in user an AnonymousUser.

And I have this issue only in one specific page where that library is inserted in the page.

Any ideas what is wrong?

Setily
  • 814
  • 1
  • 9
  • 21
django11
  • 801
  • 1
  • 11
  • 23

1 Answers1

2

The javascript in question sets a cookie by the name mistertango[collect][mt_fp].

When cookies was defined (RFC 6265, I guess) it seems they didn't really specify what characters you're allowed to use in a cookie name, other than basically «text».

This causes some problems with parsing cookie names. Django relies on Python's http.cookies for this, and it seems http.cookies doesn't allow brackets in cookie names. http.cookie failes to parse cookie pairs with brackets in it, and doesn't parse pairs after that which means it doesn't see the sessionid cookie it uses for authentication.

I'm not able to tell if Django/http.cookie should or shouldn't support this. PHP does however seem to support it (even if it's broken), while Ruby on Rails does not. The easy solution is to use only alphanumeric characters in cookie names.

For your case, the best solution is to get the javascript author to change their cookie name. If that's not possible, or in the mean time, you could host the javascript yourself and change the cookie name in your copy. (This may not work if the cookie is used for something outside of this javascript snippet, but I don't really understand Javascript and does not see what it is used for.)

Community
  • 1
  • 1
mboehn
  • 186
  • 1
  • 6
  • 1
    It's a bit more complex than that when it comes to cookie __names__. See http://stackoverflow.com/questions/1969232/allowed-characters-in-cookies – Peter Brittain Aug 08 '16 at 17:25
  • Thanks. I should have thought of searching SO instead of trying to read the RFCs. That just made me confused and sleepy. I guess you should stick to alphanumeric characters (newest RFC minus real life implementations) when setting cookies, and be ready for just about everything when parsing cookies. – mboehn Aug 08 '16 at 17:52