Decorating Django views that require Google Authorization with python decorators

In a project that I am currently involved, we needed to authenticate with Google Analytics in order to query statistics. As you may know currently Google supports three authentication mechanisms to allow other applications to authenticate on someone’s behalf.

  • ClientLogin: You give your username, password and the application does the rest for you. I don’t think there are still people out there who can give away their passwords to applications to be used on their behalf.
  • AuthSub: Google’s proprietary authorization API, just available as an alternative to OAuth.
  • OAuth: Provides authorization for all Google APIs and Google also suggests to migrate application that uses to OAuth.

As can be seen from the list that there are not so many logical alternatives, the suggested way is to use OAuth which is also an open standard. After deciding which authorization API to use, I used some time to investigate the usage and find some practical examples. However I could not find anything that fits to my needs completely.

  • I found one but that was using gdata v1.
  • I found another one but it was not using Django.
  • I found one that uses Django but I did not like the way it is designed.

Anyway, I decided to write my own. I spent some time thinking the best way to implement something that is pluggable and does not do stupid redirects between views and I decided to write a decorator that can be applied to Django views. I mainly choose to do so because of the following reasons, please comment on it if you think my reasoning is not right or there is a better way to do it.

  • It is declarative, means; it is pluggable
  • It is clean, it does not pollutes the actual view code
  • In place configuration, you can also accompany the configuration while applying it

So what I did was;

  • Creating a decorator to do the authorization
  • Creating a helper containing functions to load/save received tokens
  • Applying the decorators wherever necessary

The following is the source of the decorator.

  • It checks if there is an access token matching the provided settings
    • If so return the original view function
    • If not check if there is a matching request token
      • If so upgrade the request token to an access token and return the original view function
      • If not get a request token, redirect to the generated authorization url while setting the callback url to the url of the about to be executed view

What is important is that, after a successful authorization the user will return to this view again since we are setting the callback url accordingly before redirecting the user to Google.

Read Also:  Learn Android: Hello World App – Making it Personal

Applying the decorator is also very straight forward. See the following usage within

I hope it helps.

Leave a Reply

Your email address will not be published. Required fields are marked *