Search code examples
pythongoogle-app-engineopenidfederated-identity

New User with Federated Login Not being Recognized


I am using the Google App Engine Python Federated Login which uses OpenID to let users log in with existing accounts. I want the user to be directed to a page where they fill out some extra information about them such as a username and short bio. Right now after logging in users are being directed to this handler and then if they have a username I want them to stay on this page otherwise I want them redirected to /profile

class Tester(BlogHandler):
    def get(self):
        global visits
        logout = users.create_logout_url(self.request.uri) 

        user = users.get_current_user()
        if user:
            currentregistereduser = None
            try:
                user_db_qry = User.query(User.theid == user.federated_identity())
                user_db_list = user_db_qry.fetch(1)
                #this is the line that is causing the error
                currentregistereduser = user_db_list[0]
            except IndexError:
                #I could do something here to fix it but I am not sure what
            if currentregistereduser:
                if not currentregistereduser.username:
                    self.redirect("/profile")
                else:
                    self.render("tester.html", user=user, logout=logout)

The problem is that I am getting an IndexError when I try to do currentregistereduser = user_db_list[0] on a new user but it works fine on an existing user. Does anyone know what could be causing this? I have to do the same thing on my /profile page to identify the user so I doesn't help much to just redirect them there.


Solution

  • The reason that is happening is because your query to the datastore is coming back empty (which is expected in the case of a new user in your situation). One way to get around that would be to check if the lists exists, and if so, process:

    class Tester(BlogHandler):
        def get(self):
            global visits
            logout = users.create_logout_url(self.request.uri)
            user = users.get_current_user()
    
            if user:
                currentregistereduser = None
                user_db_qry = User.query(User.theid == user.federated_identity())
                user_db_list = user_db_qry.fetch(1)
                # Check to see if the query returned anything at all - if so, assign
                # the value to currentregistereduser; it not, it will remain None
                if user_db_list:
                  currentregistereduser = user_db_list[0]
    
                if currentregistereduser:
                    if not currentregistereduser.username:
                        self.redirect("/profile")
                    else:
                        self.render("tester.html", user=user, logout=logout)
    
            # Assuming the code continues here...