Reputation: 20360
While developing a Google App Engine app, how can client code (i.e., javascript) detect if a user is logged in or not? Note I am referring to detection on the client (not server).
Upvotes: 2
Views: 1447
Reputation: 2048
For something like this, you really need a custom solution. The Users API will tell you what you need to know on the server-side, but it's up to you to send this information to the Javascript on the client-side. I usually add a snippet to the template. Something like:
<script>var username="{{ user.username }}";</script>
If the username variable is an empty string, the user is not logged in, otherwise, you have their username ready to go. Of course you can always just use a boolean value, but this supports a bit more functionality if you need it later.
EDIT: I don't know if this is a recommended way to do it, but there's another way I've tried since posting this answer. Simply serve your main page as normal, but add a script tag:
<script src="/myapi/userinfo"></script>
Then create a /myapi/userinfo
endpoint which responds with var user = {/* User Stuff */};
if the user is logged in, and var user = null;
if not.
The main advantage to this is your pages can be cached and served without the need to re-render them for each user. However, this means that you need some JavaScript that will customize the page once it's on the client (show their username, logout button, etc).
Upvotes: 7