まず、独自の認証クラスを作成します。このクラスでは、ユーザがビューアかどうかをチェックします。はいの場合はFalseを返します。
class MyAuthentication(BasicAuthentication):
def is_authenticated(self, request, **kwargs):
is_authenticated = super(MyAuthentication, self).is_authenticated(request, **kwargs)
if not is_authenticated:
return False
return request.user.user_type_category != 'viewer'
次に、独自の認証クラスを作成します。このクラスでは、関数[create|update|delete]_[list|detail]
を上書きし、作成/削除機能で、ユーザがユーザであるかどうかをチェックします。 「はい」の場合は、例外(詳細)を発生させるか、[]
(リスト)を返します。更新時にユーザーが自分自身を更新するかどうかを確認します。いいえの場合は、例外を発生させるか、[]
を返します。
class MyAuthorization(DjangoAuthorization):
def create_detail(self, object_list, bundle):
super(MyAuthorization, self).create_detail(object_list, bundle)
if bundle.request.user.user_type_category != 'admin':
raise Unauthorized("You are not allowed to create that resource.")
return True
def create_list(self, object_list, bundle):
if bundle.request.user.user_type_category != 'admin':
return []
return super(MyAuthorization, self).create_list(object_list, bundle)
def delete_detail(self, object_list, bundle):
super(MyAuthorization, self).delete_detail(object_list, bundle)
if bundle.request.user.user_type_category != 'admin':
raise Unauthorized("You are not allowed to delete that resource.")
return True
def delete_list(self, object_list, bundle):
if bundle.request.user.user_type_category != 'admin':
return []
return super(MyAuthorization, self).delete_list(object_list, bundle)
def update_detail(self, object_list, bundle):
super(MyAuthorization, self).delete_detail(object_list, bundle)
if bundle.request.user != bundle.obj:
raise Unauthorized("You are not allowed to update that resource.")
return True
def update_list(self, object_list, bundle):
object_list = super(MyAuthorization, self).update_list(object_list, bundle)
if object_list.count() == object_list.filter(pk=bundle.obj.pk).count():
return object_list
return []