本文整理汇总了Python中rest_framework.exceptions.PermissionDenied方法的典型用法代码示例。如果您正苦于以下问题:Python exceptions.PermissionDenied方法的具体用法?Python exceptions.PermissionDenied怎么用?Python exceptions.PermissionDenied使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rest_framework.exceptions
的用法示例。
在下文中一共展示了exceptions.PermissionDenied方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: has_permission
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import PermissionDenied [as 别名]
def has_permission(self, request, view):
"""
If settings.REGISTRATION_MODE does not exist, such as during a test, return True
Return `True` if permission is granted, `False` otherwise.
"""
try:
if settings.REGISTRATION_MODE == 'disabled':
raise exceptions.PermissionDenied('Registration is disabled')
if settings.REGISTRATION_MODE == 'enabled':
return True
elif settings.REGISTRATION_MODE == 'admin_only':
if not User.objects.filter(is_superuser=True).exists():
return True
return request.user.is_superuser
else:
raise Exception("{} is not a valid registation mode"
.format(settings.REGISTRATION_MODE))
except AttributeError:
return True
示例2: destroy
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import PermissionDenied [as 别名]
def destroy(self, request, **kwargs):
calling_obj = self.get_object()
target_obj = calling_obj
if request.data.get('username'):
# if you "accidentally" target yourself, that should be fine
if calling_obj.username == request.data['username'] or calling_obj.is_superuser:
target_obj = get_object_or_404(User, username=request.data['username'])
else:
raise PermissionDenied()
# A user can not be removed without apps changing ownership first
if len(models.App.objects.filter(owner=target_obj)) > 0:
msg = '{} still has applications assigned. Delete or transfer ownership'.format(str(target_obj)) # noqa
raise AlreadyExists(msg)
try:
target_obj.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
except ProtectedError as e:
raise AlreadyExists(e)
示例3: passwd
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import PermissionDenied [as 别名]
def passwd(self, request, **kwargs):
if not request.data.get('new_password'):
raise DeisException("new_password is a required field")
caller_obj = self.get_object()
target_obj = self.get_object()
if request.data.get('username'):
# if you "accidentally" target yourself, that should be fine
if caller_obj.username == request.data['username'] or caller_obj.is_superuser:
target_obj = get_object_or_404(User, username=request.data['username'])
else:
raise PermissionDenied()
if not caller_obj.is_superuser:
if not request.data.get('password'):
raise DeisException("password is a required field")
if not target_obj.check_password(request.data['password']):
raise AuthenticationFailed('Current password does not match')
target_obj.set_password(request.data['new_password'])
target_obj.save()
return Response({'status': 'password set'})
示例4: update
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import PermissionDenied [as 别名]
def update(self, request, **kwargs):
app = self.get_object()
old_owner = app.owner
if request.data.get('owner'):
if self.request.user != app.owner and not self.request.user.is_superuser:
raise PermissionDenied()
new_owner = get_object_or_404(User, username=request.data['owner'])
app.owner = new_owner
# ensure all downstream objects that are owned by this user and are part of this app
# is also updated
for downstream_model in [models.AppSettings, models.Build, models.Config,
models.Domain, models.Release, models.TLS]:
downstream_model.objects.filter(owner=old_owner, app=app).update(owner=new_owner)
app.save()
return Response(status=status.HTTP_200_OK)
示例5: users
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import PermissionDenied [as 别名]
def users(self, request, *args, **kwargs):
app = get_object_or_404(models.App, id=kwargs['id'])
request.user = get_object_or_404(User, username=kwargs['username'])
# check the user is authorized for this app
if not permissions.is_app_user(request, app):
raise PermissionDenied()
data = {request.user.username: []}
keys = models.Key.objects \
.filter(owner__username=kwargs['username']) \
.values('public', 'fingerprint') \
.order_by('created')
if not keys:
raise NotFound("No Keys match the given query.")
for info in keys:
data[request.user.username].append({
'key': info['public'],
'fingerprint': info['fingerprint']
})
return Response(data, status=status.HTTP_200_OK)
示例6: test_login_failed
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import PermissionDenied [as 别名]
def test_login_failed(self, mock_client):
self.client = DockerClient()
# failed login
client = {}
client['Status'] = 'Login Failed'
self.client.client.login.return_value = client
creds = {
'username': 'fake',
'password': 'fake',
'email': 'fake',
'registry': 'quay.io'
}
with self.assertRaises(PermissionDenied):
self.client.login('quay.io/deis/foobar', creds)
docker_login = self.client.client.login
docker_login.assert_called_with(
username='fake', password='fake',
email='fake', registry='quay.io'
)
示例7: test_tag
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import PermissionDenied [as 别名]
def test_tag(self, mock_client):
self.client = DockerClient()
self.client.tag('ozzy/embryo:git-f2a8020', 'ozzy/embryo', 'v4')
docker_tag = self.client.client.tag
docker_tag.assert_called_once_with(
'ozzy/embryo:git-f2a8020', 'ozzy/embryo', tag='v4', force=True)
# fake failed tag
self.client.client.tag.return_value = False
with self.assertRaises(RegistryException):
self.client.tag('foo/bar:latest', 'foo/bar', 'v1.11.1')
# Test that blacklisted image names can't be tagged
with self.assertRaises(PermissionDenied):
self.client.tag('deis/controller:v1.11.1', 'deis/controller', 'v1.11.1')
with self.assertRaises(PermissionDenied):
self.client.tag('localhost:5000/deis/controller:v1.11.1', 'deis/controller', 'v1.11.1')
示例8: check_owner_permission
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import PermissionDenied [as 别名]
def check_owner_permission(payload, allow_user_owner):
"""Raise ``PermissionDenied``if ``owner`` found in ``data``."""
for entity_type in ["users", "groups"]:
for perm_type in ["add", "remove"]:
for perms in payload.get(entity_type, {}).get(perm_type, {}).values():
if "owner" in perms:
if entity_type == "users" and allow_user_owner:
continue
if entity_type == "groups":
raise exceptions.ParseError(
"Owner permission cannot be assigned to a group"
)
raise exceptions.PermissionDenied(
"Only owners can grant/revoke owner permission"
)
示例9: _get_data
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import PermissionDenied [as 别名]
def _get_data(self, user, ids):
"""Return data objects queryset based on provided ids."""
queryset = get_objects_for_user(
user, "view_data", Data.objects.filter(id__in=ids)
)
actual_ids = queryset.values_list("id", flat=True)
missing_ids = list(set(ids) - set(actual_ids))
if missing_ids:
raise exceptions.ParseError(
"Data objects with the following ids not found: {}".format(
", ".join(map(str, missing_ids))
)
)
for data in queryset:
collection = data.collection
if collection and not user.has_perm("edit_collection", obj=collection):
if user.is_authenticated:
raise exceptions.PermissionDenied()
else:
raise exceptions.NotFound()
return queryset
示例10: update
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import PermissionDenied [as 别名]
def update(self, request, pk, *args, **kwargs):
if 'xls_file' in request.FILES or 'text_xls_form' in request.data:
# A new XLSForm has been uploaded and will replace the existing
# form
existing_xform = get_object_or_404(XForm, pk=pk)
# Behave like `onadata.apps.main.views.update_xform`: only allow
# the update to proceed if the user is the owner
owner = existing_xform.user
if request.user.pk != owner.pk:
raise exceptions.PermissionDenied(
detail=_("Only a form's owner can overwrite its contents"))
survey = utils.publish_xlsform(request, owner, existing_xform)
if not isinstance(survey, XForm):
if isinstance(survey, dict) and 'text' in survey:
# Typical error text; pass it along
raise exceptions.ParseError(detail=survey['text'])
else:
# Something odd; hopefully it can be coerced into a string
raise exceptions.ParseError(detail=survey)
post_update_xform.apply_async((), {'xform_id': existing_xform.id, 'user':request.user.id}, countdown=2)
return super(XFormViewSet, self).update(request, pk, *args, **kwargs)
示例11: clone
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import PermissionDenied [as 别名]
def clone(self, request, *args, **kwargs):
self.object = self.get_object()
data = {'xform': self.object.pk, 'username': request.data['username']}
serializer = CloneXFormSerializer(data=data)
if serializer.is_valid():
clone_to_user = User.objects.get(username=data['username'])
if not request.user.has_perm(
'can_add_xform',
UserProfile.objects.get_or_create(user=clone_to_user)[0]
):
raise exceptions.PermissionDenied(
detail=_(u"User %(user)s has no permission to add "
"xforms to account %(account)s" %
{'user': request.user.username,
'account': data['username']}))
xform = serializer.save()
serializer = XFormSerializer(
xform.cloned_form, context={'request': request})
return Response(data=serializer.data,
status=status.HTTP_201_CREATED)
return Response(data=serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
示例12: perform_update
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import PermissionDenied [as 别名]
def perform_update(self, serializer):
# Prevent changing an event that user does not have write permissions
# For bulk update, the editable queryset is filtered in filter_queryset
# method
if isinstance(serializer, EventSerializer) and not self.request.user.can_edit_event(
serializer.instance.publisher,
serializer.instance.publication_status,
):
raise DRFPermissionDenied()
# Prevent changing existing events to a state that user doe snot have write permissions
if isinstance(serializer.validated_data, list):
event_data_list = serializer.validated_data
else:
event_data_list = [serializer.validated_data]
for event_data in event_data_list:
org = self.organization
if hasattr(event_data, 'publisher'):
org = event_data['publisher']
if not self.request.user.can_edit_event(org, event_data['publication_status']):
raise DRFPermissionDenied()
super().perform_update(serializer)
示例13: payment
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import PermissionDenied [as 别名]
def payment(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
event_id = self.kwargs.get("pk", None)
event = Event.objects.get(id=event_id)
registration = event.get_registration(request.user)
if not event.is_priced or not event.use_stripe:
raise PermissionDenied()
if registration.has_paid():
raise APIPaymentExists()
registration.charge_status = constants.PAYMENT_PENDING
registration.save()
chain(
async_payment.s(registration.id, serializer.data["token"]),
registration_payment_save.s(registration.id),
).delay()
payment_serializer = RegistrationPaymentReadSerializer(
registration, context={"request": request}
)
return Response(data=payment_serializer.data, status=status.HTTP_202_ACCEPTED)
示例14: upload_prefix_for_request
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import PermissionDenied [as 别名]
def upload_prefix_for_request(request):
'''
Return a string which the user should prepend to all S3
keys for upload. By creating a separate namespace for
each user, you prevent a malicious user from hijacking or
claiming another user's uploads.
FIXME needs its own test?
'''
from django.conf import settings
from rest_framework.exceptions import PermissionDenied
# Allow the user to specify their own function
prefix_func = getattr(settings, 'AWS_UPLOAD_PREFIX_FUNC', None)
if prefix_func is not None:
return prefix_func(request)
if not request.user.is_authenticated():
raise PermissionDenied(_('Log in before uploading'))
return request.user.get_username()
示例15: check_policy_permissions
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import PermissionDenied [as 别名]
def check_policy_permissions(request, upload_policy):
'''
Check permissions on the given upload policy. Raises
rest_framework.exceptions.PermissionDenied in case
of error.
The acl must be 'private'. Uploading public files
using this API is a bad idea. By its nature, the
API will allow any user to upload any file. If
files are public that likely means you're exposing
the keys publicly, which means the files are
easily replaced by a user of this very API.
'''
from rest_framework.exceptions import PermissionDenied
if upload_policy['acl'].value != 'private':
raise PermissionDenied(_("ACL should be 'private'"))
check_upload_permissions(
request=request,
bucket=upload_policy['bucket'].value,
key=upload_policy['key'].value
)