Yamil Abugattas
Yamil Abugattas

Reputation: 418

How can I manage authorization in GAE using Google Accounts?

So far I have used oauth2 to manage authentication using Google Accounts for my app, which gives me some data to complete a basic profile. The problem is that I now want to manage permissions to view and edit a lot of the content in the app, with different groups of people being able to view/edit different parts of the app.

I want some parts of my application to be accessed by users with permission for A, some for B, C, etc. The way I started doing this was using a decorator in the get and post method of each handler, like this:

class SomeHandler(Handler):
    @validate_access
    def get(self):
        pass

    @validate_access
    def post(self):
        pass

Where @validate_access executes the code in the function only if the user has permission for it, and returning an authorization error if not. This seemed to be a good solution a while back, but since there are many handlers I have to use that decorator everywhere, which is annoying and dangerous, since I may forget to put it in some functions.

Is there a way to put this validations in the initialization of the base handler, so that I don't have to use that decorator everywhere? I imagine something like this:

class BaseHandler(webapp2.RequestHandler):

def initialize(self, request, response):
    super(Handler, self).initialize(request, response)

    self.user = users.get_current_user()
    employee = Employee.query(user_id=self.user.user_id).get()

    if employee.auth_level > 3:
        #See the content: Do whatever the "get" method of the corresponding handler does.
        pass
    else:
        #Raise authorization error
        pass

Or is there a better way to do this? (Sorry if it's a basic question, I've never done this before)

Upvotes: 0

Views: 75

Answers (1)

voscausa
voscausa

Reputation: 11706

Yes, you can overwrite the webapp2 dispatch handler for this purpose. I used this method to enforce role based access control (RBAC).

Example code:

class BaseHandler(webapp2.RequestHandler):
    """ webapp2 base handler """

    def dispatch(self):

        # UserAccess aborts if the user does not have permission to use a handler 
        UserAccess(self.request)
        super(BaseHandler, self).dispatch()
        .... 


class ExampleHandler(BaseHandler):

    def get(self):

        .....

I use a config file with the allowed roles for a handler. This file is also used to create the webapp2 routes and the dynamic user menu.

Upvotes: 1

Related Questions