Blog Archive

Google App Engine Python User Authentication Example

One of the services provided by the Google App Engine is the Users service. You can integrate your application with the Google user accounts with the help of this service. Existing google users can then login to your application and new users have to sign up for the Google account before accessing your application. This way you can provide back-end services for your android mobiles apps using the app engine as it can also authenticate using the Google accounts registered on their mobile devices such as smart phones or tablets.

Google App Engine Python User Login
Google App Engine Python User Logout
The application can access the User instance for the current user by calling the users.get_current_user() function. To check if the current user is an administrator your application can use the function users.is_current_user_admin() which returns True or False.

Example:
from google.appengine.api import users

user = users.get_current_user()
if not user:
    # The user is not signed in.
else:
    # The user is signed in.
A User instance provides the following methods
  • nickname()
  • email()
  • user_id()
  • federated_identity()
  • federated_provider()
In this example we create a web application that displays the user name when logged in and provides a link to logout from the Google account. If the user is not logged in then it will display a login link that will redirect the user to the login/register with Google accounts. In addition to that we review the Python Application Configuration file to indicate which pages in the application require the user to be logged in or pages that are only allowed to be visited by the admin user.

The URL handler can have a login setting to restrict visitors. Here are three possible values:

  • optional (the default)
    • Does not require that the user to be signed in.
  • required
    • If the user has signed in you get access to the page. Otherwise, depending on the auth_fail_action setting you either get a HTTP status code of 401 and an error message or user is redirected to the Google sign-in page. If you don't specify the auth_fail_action setting then the default is redirect to the sign-in page. 
  • admin
    • It pretty much works the same as the required option but the user logged in must have administrator privileges.

Python Web Application - asklogin.py

import webapp2
from google.appengine.api import users

class MyHandler(webapp2.RequestHandler):
    def get(self):
        
        user = users.get_current_user()
        myPage = """
          <html>
            <body>
                <div>
                    <h2>Google App Engine Login - Python Web app</h2>
                    <h3>Welcome, {0}. This is a sample page!</h3>
                    <a href="{1}"><b>Click here to {2}</b></a>
                </div>
            </body>
          </html>
          """
      
        if user:
            myData = myPage.format(user.nickname(), users.create_logout_url("/"),'logout' )
        else:
            myData = myPage.format('Guest', users.create_login_url("/"),'login' )
            
        self.response.out.write(myData)
        
class SecuredPage(webapp2.RequestHandler):
    def get(self):
        myPage = """
          <html>
            <body>
                <div>
                    <h2>Google App Engine Login - Python Web app</h2>
                    <h3>Welcome, {0}. This page is secured! Nice that you could login.</h3>
                    <a href="{1}"><b>Click here to {2}</b></a>
                </div>
            </body>
          </html>
          """
        
        user = users.get_current_user()
        myData = myPage.format(user.nickname(), users.create_logout_url("/"),'logout' )
        self.response.out.write(myData) 
        
       
app = webapp2.WSGIApplication([('/', MyHandler),
                               ('/secured',SecuredPage)],
                              debug=True)      

Python Application Configuration file - app.yaml

application: my-sample-code
version: 1
runtime: python27
api_version: 1
threadsafe: yes

handlers:

- url: /secured
  script: asklogin.app
  login: required # page is now restricted to signed in users only  
  auth_fail_action: unauthorized  # display HTTP status code of 401 and an error message
    
# anyone can reach all the other URLs    
- url: /.*
  script: asklogin.app
  
libraries:
- name: webapp2
  version: "2.5.1"  

References