0

I have a login form on every page. If login fails because cookies are disabled, I want to show the user a message asking them to enable cookies. I have created this middleware:

class CheckCookiesEnabled(object):
    def process_request(self, request):
        if request.user.is_anonymous():
            request.session.set_test_cookie()
        return

In my login view, I check for request.session.test_cookie_worked() and log in only if it did, otherwise I want to display the message.

if request.session.test_cookie_worked():
    request.session.delete_test_cookie()
    # Log in 
else:
    return HttpResponse(json.dumps({'errors': "Login failed (enable cookies to login)"}), mimetype = 'application/json')

The thing is, request.session.test_cookie_worked() seems to be always true; Django seems to be able to set the test cookie even though cookies are disabled in the browser. Any ideas why and how to fix this? Or is there a better way to check if the browser has cookies enabled?

By the way: If I set_test_cookie() on every request, does Django always set a new cookie or only if there isn't already one?

1
  • I know about that, @cathy, and that's what I did. But my question remains: Why is test_cookie_worked() true even though cookies are disabled?
    – joschaf
    Feb 16, 2013 at 15:19

2 Answers 2

3

You should use set_test_cookie in process_response of your middleware, not the process_request. test_cookie_worked is always true because you're always add it yourself by populating the request.session with the "cookie" at the process_request - it is executed before the control goes to the view.

1
  • Ah, that might work. Anyway, I ended up using JavaScript, which seems somewhat simpler. But thanks!
    – joschaf
    Feb 16, 2013 at 16:44
0

Ended up using JavaScript:

function cookies_enabled() {
    if (navigator.cookieEnabled) {
        return true;
    } else if (navigator.cookieEnabled === undefined) {
        document.cookie = "testcookie";
        if (cookie_present("testcookie"))
            return true;
    }
    return false;
}

Works just fine. Thanks anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.