Search code examples
pythondjangotastypie

Tastypie: define authentication for all resources


What is the best approach to define authentication/authorization for all tastypie resources? I have many resources and don't want to copy the authentication line every time. Right now, I defined a function

def create_auth():
    return MultiAuthentication(ApiKeyAuthentication(), BasicAuthentication())

and am calling it in each resource' meta class:

class SomeResource(ModelResource):
    class Meta:
        authentication = create_auth()

Is there a better solution for this? Is a 'metametaclass' solution possible/better? E.g.

class AuthMeta:
    authentication = MultiAuthentication(ApiKeyAuthentication(), BasicAuthentication())

class SomeResource(ModelResource):
    class Meta(AuthMeta):
        # further settings

class SomeOtherResourceNonORM(Resource):
    class Meta(AuthMeta):
        # further settings

Solution

  • You should do the metametaclass as recomended for both tastypie and django.

    classs YourBaseResource(ModelResource):
        class Meta:
            authentication = MultiAuthentication(ApiKeyAuthentication(), BasicAuthentication())
    
    class SomeResource(YourBaseResource):
        class Meta(YourBaseResource.Meta):
            # further settings
    
    class SomeOtherResourceNonORM(YourBaseResource):
        class Meta(YourBaseResource.Meta):
            # further settings
    

    update: using the correct base resource