1

I'm trying to detect with javascript if a user is logged in. For some reason the drupal session cookie is not showing up when I use

alert(document.cookie);

It does show "Drupal.tableDrag.showWeight=0" and "has_js=1" cookie.

When I use a cookie tool I see that the SESS... cookie is set.

Update:

I'm trying to fix a browser caching issue: Varnish sets a "cache-control max-age" header of 30 minutes which causes the browser to cache the page. When a user logs in and then clicks on a link that's already been cached in the browser it will appear to the user that they have been logged out again.

If I could read the Drupal session cookie from Javascript to see if a user is logged in I could then reload that page.

  • 1
    The cookie won't help you, it just contains a session id which anonymous users can have as well. – Berdir Apr 27 '12 at 16:55
  • Are you using secure pages, by chance? I have this problem when a link points to mydrupal/node/123, it shows them the cached page. Maybe it's a related issue... – Johnathan Elmore Apr 27 '12 at 17:13
  • Thanks, Berdir, didn't know that. Jonathan, no, I'm using http:// – uwe Apr 27 '12 at 20:30
2

If your theme is somewhat standard, you should be able to look to see if the body has a class of "logged-in" or "not-logged-in" and key off of that. Eg,

if ($('body').hasClass('not-logged-in')) {
  // do whatever you want for anon users
} else {
  // do whatever you want for logged in users
}

or if all in jQuery:

$('body').hasClass('not-logged-in').doWhatEverHere();

EDIT ADDITION DUE TO COMMENTS :)

It appears that drupal uses httpOnly with its cookie:

https://www.owasp.org/index.php/HTTPOnly

so you won't be able to access it from the client. So..... given that, you might want to investigate setting your own cookie upon login and deleting it on logout and looking for that, but suggesting that makes me make Bill the Cat noises :)

| improve this answer | |
  • that won't work. I'll update my question to explain. – uwe Apr 27 '12 at 5:22
  • 1
    yeah, setting own cookie sounds like the way to go. There is even a module for that (D6 at least): drupal.org/project/logincookie – uwe Apr 27 '12 at 20:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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