jquerybottlebeaker

How to show div based on Beaker session status with jQuery?


Content is loaded in a main_content area via jQuery Ajax.

Outside of the main_content area is a login link.

Clicking on this link loads a form in the main_content area which, when submitted, performs login authorisation with Beaker. On success, an admin page is loaded in the main_content area.

I want to change the login link to a logout link after successful authorisation.

Is there a way to show/hide divs based on session status in Beaker, with something like:

if (beaker.session.id) {
    $('#login').hide();
    $('#logout').show();
}

I would call this in the jQuery block dealing with successful login and then swap the divs in the block dealing with logout.

Edit

In Firebug, in the login POST response, I go to "Cookies" > "Received Cookies" and can see a listing for:

beaker.session.id

If I right-click on this link and select "Use in Command Line", the following pops up in the command line area:

$p

If I then run the following in the Firebug command line area, I get an alert pop up with the specified message:

if ($p) {alert("you have an id!")}

So I tried to add this to the code that processes the login but I didn't get an alert:

<script>
$(document).on("submit","#login", function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/login',
data: $(this).serialize(),
dataType: 'json',
success: function(results) {
$("#main_content").html("");
$("#main_content").append(results.content);
href = results.title;
history.pushState('', 'New URL: '+href, href);
reinit1();
reinit2();
reinit3();
if ($p) { // <-- here is the alert
alert("Yes you have an ID!")
}
}
});
});
</script>

I get error:

ReferenceError: $p is not defined

Solution

  • I couldn't find a solution as to how to access the beaker.session.id cookie, so I just created a jQuery cookie on login success, and then created an if statement which displayed the logout link if the newly created login existed (and I'll remove the cookie on logout to reverse the process):

    <script>
    // login processing as shown above
    reinit1();
    reinit2();
    reinit3();
    $.cookie('logged-in', "YES", { path: '/'}); // set cookie and assign name and value
    if ($.cookie('logged-in') == "YES") { //  check the value of the cookie
    $('.login').hide();
    $('.logout').show();
    }
    }
    }
    });
    });
    </script>