I use tastypie 0.12.2-dev
to create API for my django
site. I wrote a class authorization (ApprovedLaptopsAuthorization) and used it in my ModelResource (RecordResource) class. The endpoint of RecordResource
is http://myserver/book/api/record.
HTTP GET Request to that endpoint is working correctly. (permissions are checked in read_list() method of ApprovedLaptopsAuthorization class). Now I try to check HTTP POST Request by sending correct JSON data. The problem is that any of ApprovedLaptopsAuthorization methods (create_list(), create_detail()) does not running during that operation. As a result, I can not restrict access to create object operation and any user can create object in any time. Where the mistake in my code?
class ApprovedLaptopsAuthorization(Authorization):
"""
Авторизация путем проверки наличия разрешения на использоание планшета, с которого осуществляется запрос
"""
def __init__(self):
pass
def read_list(self, object_list, bundle):
if not bundle.request.user.laptop.approved:
raise Unauthorized(u"Доступ планшета к данным не подтвержден администратором.")
return object_list
def read_detail(self, object_list, bundle):
if not bundle.request.user.laptop.approved:
raise Unauthorized(u"Доступ планшета к данным не подтвержден администратором.")
return True
def create_list(self, object_list, bundle):
print "create list"
if not bundle.request.user.laptop.approved:
raise Unauthorized(u"Доступ планшета к данным не подтвержден администратором.")
return object_list
def create_detail(self, object_list, bundle):
print "create detail"
raise BadRequest(u"Выполнение данной операции запрещено.")
def update_list(self, object_list, bundle):
raise BadRequest(u"Выполнение данной операции запрещено.")
def update_detail(self, object_list, bundle):
raise BadRequest(u"Выполнение данной операции запрещено.")
def delete_list(self, object_list, bundle):
raise BadRequest(u"Выполнение данной операции запрещено.")
def delete_detail(self, object_list, bundle):
raise BadRequest(u"Выполнение данной операции запрещено.")
class RecordResource(ModelResource):
"""
Точка доступа к записям
"""
pages = ToManyField(PageResource, 'pages', full=True)
class Meta:
queryset = Record.objects.all()
limit = 0
max_limit = 0
resource_name = 'record'
list_allowed_methods = ['get', 'post']
detail_allowed_methods = []
authentication = ApiKeyAuthentication()
authorization = ApprovedLaptopsAuthorization()
serializer = CommonSerializer(formats=['json'])
always_return_data = True
def detail_uri_kwargs(self, bundle_or_obj):
return {}
@staticmethod
def unauthorized_result(exception):
raise ImmediateHttpResponse(
response=HttpUnauthorized(
json.dumps({'error': exception.message}, ensure_ascii=False).encode('utf-8')
)
)
def obj_get_list(self, bundle, **kwargs):
"""
:param bundle: tastypie bundle
:param kwargs: tastypie params
:return: Возвращает список записей и страниц на них
"""
bundle.request.user.laptop.ip = ip_from_bundle(bundle)
bundle.request.user.laptop.save()
return super(RecordResource, self).obj_get_list(bundle, **kwargs)
def obj_create(self, bundle, **kwargs):
"""
:param bundle: tastypie bundle
:param kwargs: tastypie params
:return: Создает запись и страницы на основе переданного JSON-а
"""
bundle.request.user.laptop.ip = ip_from_bundle(bundle)
bundle.request.user.laptop.save()
records = bundle.data.get('records', '')
if not records:
raise BadRequest(u"Поле записей для загрузки на сервер (records) не заполнено")
for recidx, record in enumerate(records):
pages = record.get('pages', '')
if not pages:
raise BadRequest(u"Поле страниц для загрузки на сервер (pages) не заполнено (запись {})".format(recidx))
for pageidx, page in enumerate(pages):
image = page.get('image', '')
if not image:
BadRequest(u"Поле картинки для загрузки на сервер (image) не заполнено (запись {}, страница {})".
format(recidx, pageidx))
for record in records:
new_rec = Record.objects.create(author=BookConfiguration.get_solo().record_author_default +
' (' + timezone.localtime(timezone.now()).strftime('%Y-%m-%d %H:%M:%S') + ')')
new_rec.save()
pages = record['pages']
for page in pages:
new_page = Page.objects.create(image=SimpleUploadedFile(page['image']['name'],
base64.b64decode(page['image']['file']),
page['image'].get('content_type',
'application/octet-stream')), record=new_rec, updated=timezone.now())
new_page.save()
bundle.obj = new_rec
return bundle
I have not received an answer to my question, and added these lines to the top of the method RecordResource.obj_create():