Search code examples
pythongoogle-app-enginepython-2.7webapp2

GAE users.get_current_user() returns None


I am trying to get the current user object in a Google App Engine app however it seems to be returning nothing.

I used the example code at https://github.com/takatama/gae-webapp2-auth/blob/master/handlers.py to write the user handler.

My app logs in succesfully, however get_current_user() is returning NoneType. Is it this function call is in an AJAX POST and the session is not initialised? Do I have to add a decorator somewhere?


Solution

  • The function get_current_user returns None if the user is not currently logged in. One normal way to handle this is to first call user = users.get_current_user() and then use an if block to determine if they are logged in (this example taken from the docs):

    user = users.get_current_user()
    if user:
        greeting = ("Welcome, %s! (<a href=\"%s\">sign out</a>)" %
                    (user.nickname(), users.create_logout_url("/")))
    else:
        greeting = ("<a href=\"%s\">Sign in or register</a>." %
                    users.create_login_url("/"))
    
    self.response.out.write("<html><body>%s</body></html>" % greeting)
    

    If get_current_user() returns None, we know that the user is not logged in, so we use users.create_login_url() to create a link that will allow the user to authenticate, after which get_current_user() will return the User object for that user (did I say 'user' enough? :) ).