Python rest_framework.exceptions.PermissionDenied() Examples
The following are 30
code examples of rest_framework.exceptions.PermissionDenied().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
rest_framework.exceptions
, or try the search function
.
Example #1
Source File: views.py From cmdb with GNU Lesser General Public License v3.0 | 6 votes |
def get_indices(self, input_indices): tables = mgmt_models.Table.objects.all() all_indices = [table.name for table in tables] not_exit_indices = list(set(input_indices) - set(all_indices)) if not_exit_indices: raise exceptions.ParseError(f"{not_exit_indices}不存在") all_perm_name = self.request.user.get_all_permission_names() if "read_all" in all_perm_name or self.request.user.is_staff: if not input_indices: return all_indices return input_indices has_perm_indices = [perm_name.split(".read")[0] for perm_name in all_perm_name if re.match( "^[a-z][a-z-0-9]*\.read", perm_name)] if not input_indices: if not has_perm_indices: raise exceptions.ParseError("您没有任何表读取权限 请联系管理员分配权限") return has_perm_indices no_perm_index = list(set(input_indices) - set(has_perm_indices)) if no_perm_index: raise exceptions.PermissionDenied(f"你没有{no_perm_index}表权限") return input_indices
Example #2
Source File: tests.py From controller with MIT License | 6 votes |
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')
Example #3
Source File: tests.py From controller with MIT License | 6 votes |
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' )
Example #4
Source File: views.py From controller with MIT License | 6 votes |
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)
Example #5
Source File: views.py From controller with MIT License | 6 votes |
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)
Example #6
Source File: views.py From controller with MIT License | 6 votes |
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'})
Example #7
Source File: permissions.py From controller with MIT License | 6 votes |
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
Example #8
Source File: utils.py From resolwe with Apache License 2.0 | 6 votes |
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" )
Example #9
Source File: data.py From resolwe with Apache License 2.0 | 6 votes |
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
Example #10
Source File: xform_viewset.py From kobo-predict with BSD 2-Clause "Simplified" License | 6 votes |
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)
Example #11
Source File: xform_viewset.py From kobo-predict with BSD 2-Clause "Simplified" License | 6 votes |
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)
Example #12
Source File: api.py From linkedevents with MIT License | 6 votes |
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)
Example #13
Source File: views.py From lego with MIT License | 6 votes |
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)
Example #14
Source File: permissions.py From controller with MIT License | 6 votes |
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
Example #15
Source File: views.py From controller with MIT License | 6 votes |
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)
Example #16
Source File: views.py From controller with MIT License | 6 votes |
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'})
Example #17
Source File: views.py From controller with MIT License | 6 votes |
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)
Example #18
Source File: views.py From controller with MIT License | 6 votes |
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)
Example #19
Source File: tests.py From controller with MIT License | 6 votes |
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' )
Example #20
Source File: tests.py From controller with MIT License | 6 votes |
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')
Example #21
Source File: access_control.py From drf-to-s3 with MIT License | 6 votes |
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()
Example #22
Source File: access_control.py From drf-to-s3 with MIT License | 6 votes |
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 )
Example #23
Source File: access_control.py From drf-to-s3 with MIT License | 6 votes |
def check_upload_permissions(request, bucket, key): ''' Check permissions on the given upload policy. Raises rest_framework.exceptions.PermissionDenied in case of error. ''' from django.core.exceptions import ImproperlyConfigured from rest_framework.exceptions import PermissionDenied if bucket != upload_bucket(): raise PermissionDenied(_("Bucket should be '%s'" % upload_bucket())) upload_prefix = upload_prefix_for_request(request) if upload_prefix is None or len(upload_prefix) == 0: raise ImproperlyConfigured( _('Upload prefix must be non-zero-length and should be unique for each user') ) if not key.startswith(upload_prefix + '/'): raise PermissionDenied(_("Key should start with '%s/'" % upload_prefix))
Example #24
Source File: course_runs.py From course-discovery with GNU Affero General Public License v3.0 | 6 votes |
def writable_request_wrapper(method): def inner(*args, **kwargs): try: with transaction.atomic(): return method(*args, **kwargs) except (PermissionDenied, ValidationError, Http404): raise # just pass these along except Exception as e: # pylint: disable=broad-except content = e.content.decode('utf8') if hasattr(e, 'content') else str(e) msg = _('Failed to set course run data: {}').format(content) log.exception(msg) return Response(msg, status=status.HTTP_400_BAD_REQUEST) return inner # pylint: disable=useless-super-delegation
Example #25
Source File: courses.py From course-discovery with GNU Affero General Public License v3.0 | 6 votes |
def writable_request_wrapper(method): def inner(*args, **kwargs): try: with transaction.atomic(): return method(*args, **kwargs) except ValidationError as exc: return Response(exc.message if hasattr(exc, 'message') else str(exc), status=status.HTTP_400_BAD_REQUEST) except (PermissionDenied, Http404): raise # just pass these along except Exception as e: # pylint: disable=broad-except content = e.content.decode('utf8') if hasattr(e, 'content') else str(e) msg = _('Failed to set data: {}').format(content) logger.exception(msg) return Response(msg, status=status.HTTP_400_BAD_REQUEST) return inner # pylint: disable=useless-super-delegation
Example #26
Source File: course_editors.py From course-discovery with GNU Affero General Public License v3.0 | 6 votes |
def create(self, request, *args, **kwargs): """The User who performs creation must be staff or belonging to the associated organization, the user being assigned must belong to the associated organization""" if 'user_id' not in request.data: request.data['user_id'] = request.user.id user_model = get_user_model() editor = get_object_or_404(user_model, pk=request.data['user_id']) authoring_orgs = self.course.authoring_organizations.all() users_in_authoring_orgs = user_model.objects.filter( groups__organization_extension__organization__in=authoring_orgs ).distinct() if editor not in users_in_authoring_orgs: raise PermissionDenied('Editor does not belong to an authoring organization of this course.') return super().create(request)
Example #27
Source File: views.py From controller with MIT License | 6 votes |
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)
Example #28
Source File: dockerclient.py From controller with MIT License | 5 votes |
def login(self, repository, creds=None): """Log into a registry if auth is provided""" if not creds: return # parse out the hostname since repo variable is hostname + path registry, _ = auth.resolve_repository_name(repository) registry_auth = { 'username': None, 'password': None, 'email': None, 'registry': registry } registry_auth.update(creds) if not registry_auth['username'] or not registry_auth['password']: msg = 'Registry auth requires a username and a password' logger.error(msg) raise PermissionDenied(msg) logger.info('Logging into Registry {} with username {}'.format(repository, registry_auth['username'])) # noqa response = self.client.login(**registry_auth) success = response.get('Status') == 'Login Succeeded' or response.get('username') == registry_auth['username'] # noqa if not success: raise PermissionDenied('Could not log into {} with username {}'.format(repository, registry_auth['username'])) # noqa logger.info('Successfully logged into {} with {}'.format(repository, registry_auth['username'])) # noqa
Example #29
Source File: test_permissions.py From resolwe with Apache License 2.0 | 5 votes |
def test_filter_owner_permission(self): """Check that ``owner`` permission is catched everywhere""" data_template = { "users": { "add": {1: ["view"], 2: ["view", "edit"]}, "remove": {3: ["view", "edit"]}, }, "groups": {"add": {1: ["view", "edit"]}, "remove": {2: ["view"]}}, } check_owner_permission(data_template, False) data = deepcopy(data_template) data["users"]["add"][1].append("owner") with self.assertRaises(exceptions.PermissionDenied): check_owner_permission(data, False) check_owner_permission(data, True) data = deepcopy(data_template) data["users"]["remove"][3].append("owner") with self.assertRaises(exceptions.PermissionDenied): check_owner_permission(data, False) check_owner_permission(data, True) data = deepcopy(data_template) data["groups"]["add"][1].append("owner") with self.assertRaises(exceptions.ParseError): check_owner_permission(data, False) with self.assertRaises(exceptions.ParseError): check_owner_permission(data, True) data = deepcopy(data_template) data["groups"]["remove"][2].append("owner") with self.assertRaises(exceptions.ParseError): check_owner_permission(data, False) with self.assertRaises(exceptions.ParseError): check_owner_permission(data, True)
Example #30
Source File: tests.py From controller with MIT License | 5 votes |
def test_pull(self, mock_client): self.client = DockerClient() self.client.pull('alpine', '3.2') docker_pull = self.client.client.pull docker_pull.assert_called_once_with('alpine', tag='3.2', decode=True, stream=True) # Test that blacklisted image names can't be pulled with self.assertRaises(PermissionDenied): self.client.pull('deis/controller', 'v1.11.1') with self.assertRaises(PermissionDenied): self.client.pull('localhost:5000/deis/controller', 'v1.11.1')