當前位置: 首頁>>代碼示例>>Python>>正文


Python exceptions.PermissionDenied方法代碼示例

本文整理匯總了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 
開發者ID:deis,項目名稱:controller,代碼行數:21,代碼來源:permissions.py

示例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) 
開發者ID:deis,項目名稱:controller,代碼行數:23,代碼來源:views.py

示例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'}) 
開發者ID:deis,項目名稱:controller,代碼行數:24,代碼來源:views.py

示例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) 
開發者ID:deis,項目名稱:controller,代碼行數:18,代碼來源:views.py

示例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) 
開發者ID:deis,項目名稱:controller,代碼行數:24,代碼來源:views.py

示例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'
            ) 
開發者ID:deis,項目名稱:controller,代碼行數:24,代碼來源:tests.py

示例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') 
開發者ID:deis,項目名稱:controller,代碼行數:20,代碼來源:tests.py

示例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"
                    ) 
開發者ID:genialis,項目名稱:resolwe,代碼行數:19,代碼來源:utils.py

示例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 
開發者ID:genialis,項目名稱:resolwe,代碼行數:25,代碼來源:data.py

示例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) 
開發者ID:awemulya,項目名稱:kobo-predict,代碼行數:24,代碼來源:xform_viewset.py

示例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) 
開發者ID:awemulya,項目名稱:kobo-predict,代碼行數:26,代碼來源:xform_viewset.py

示例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) 
開發者ID:City-of-Helsinki,項目名稱:linkedevents,代碼行數:26,代碼來源:api.py

示例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) 
開發者ID:webkom,項目名稱:lego,代碼行數:24,代碼來源:views.py

示例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() 
開發者ID:metabolize,項目名稱:drf-to-s3,代碼行數:24,代碼來源:access_control.py

示例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
    ) 
開發者ID:metabolize,項目名稱:drf-to-s3,代碼行數:24,代碼來源:access_control.py


注:本文中的rest_framework.exceptions.PermissionDenied方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。