Python django.core.exceptions.PermissionDenied() Examples
The following are 30
code examples of django.core.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
django.core.exceptions
, or try the search function
.
Example #1
Source File: middleware.py From koku with GNU Affero General Public License v3.0 | 6 votes |
def process_request(self, request): """Check before super.""" connection.set_schema_to_public() if not is_no_auth(request): if hasattr(request, "user") and hasattr(request.user, "username"): username = request.user.username try: if username not in USER_CACHE: USER_CACHE[username] = User.objects.get(username=username) LOG.debug(f"User added to cache: {username}") except User.DoesNotExist: return HttpResponseUnauthorizedRequest() if not request.user.admin and request.user.access is None: LOG.warning("User %s is does not have permissions for Cost Management.", username) raise PermissionDenied() else: return HttpResponseUnauthorizedRequest() try: super().process_request(request) except OperationalError as err: LOG.error("Request resulted in OperationalError: %s", err) DB_CONNECTION_ERRORS_COUNTER.inc() return HttpResponseFailedDependency({"source": "Database", "exception": err})
Example #2
Source File: teams.py From open-synthesis with GNU General Public License v3.0 | 6 votes |
def view_team(request, team_id): team = get_object_or_404(Team, pk=team_id) if team.owner_id is not None and team.owner_id == request.user.id: return manage_team(request, team) is_member, pending_invitation = member_status(request.user, team) if not is_member and not team.public and not pending_invitation: raise PermissionDenied() return render(request, 'teams/view_team.html', context={ 'team': team, 'is_member': is_member, 'pending_request': request.user.is_authenticated and TeamRequest.objects.filter(team_id=team, inviter__isnull=True, invitee=request.user).exists(), 'pending_invitation': pending_invitation, })
Example #3
Source File: boards.py From open-synthesis with GNU General Public License v3.0 | 6 votes |
def board_history(request, board_id): """Return a view with the modification history (board details, evidence, hypotheses) for the board.""" # this approach to grabbing the history will likely be too slow for big boards def _get_history(models): changes = [FieldHistory.objects.get_for_model(x).select_related('user') for x in models] return itertools.chain(*changes) board = get_object_or_404(Board, pk=board_id) if 'read_board' not in board.permissions.for_user(request.user): raise PermissionDenied() history = [ _get_history([board]), _get_history(Evidence.all_objects.filter(board=board)), _get_history(Hypothesis.all_objects.filter(board=board)), ] history = list(itertools.chain(*history)) history.sort(key=lambda x: x.date_created, reverse=True) return render(request, 'boards/board_audit.html', {'board': board, 'history': history})
Example #4
Source File: rolemixins.py From kobo-predict with BSD 2-Clause "Simplified" License | 6 votes |
def dispatch(self, request, *args, **kwargs): if request.group.name == "Super Admin": return super(ProjectRoleMixin, self).dispatch(request, *args, **kwargs) project_id = self.kwargs.get('pk') user_id = request.user.id user_role = request.roles.filter(user_id = user_id, project_id = project_id, group_id=2) if user_role: return super(ProjectRoleMixin, self).dispatch(request, *args, **kwargs) organization_id = Project.objects.get(pk=project_id).organization.id user_role_asorgadmin = request.roles.filter(user_id = user_id, organization_id = organization_id, group_id=1) if user_role_asorgadmin: return super(ProjectRoleMixin, self).dispatch(request, *args, **kwargs) raise PermissionDenied() #use when project role and doner role is required mostly it is like readonly because doner is only allowed to read only
Example #5
Source File: json_to_orm_utils.py From seqr with GNU Affero General Public License v3.0 | 6 votes |
def update_model_from_json(model_obj, json, user=None, allow_unknown_keys=False, immutable_keys=None): immutable_keys = (immutable_keys or []) + ['created_by', 'created_date', 'last_modified_date', 'id'] internal_fields = model_obj._meta.internal_json_fields if hasattr(model_obj._meta, 'internal_json_fields') else [] has_updates = False for json_key, value in json.items(): orm_key = _to_snake_case(json_key) if orm_key in immutable_keys: if allow_unknown_keys: continue raise ValueError('Cannot edit field {}'.format(orm_key)) if allow_unknown_keys and not hasattr(model_obj, orm_key): continue if getattr(model_obj, orm_key) != value: if orm_key in internal_fields and not (user and user.is_staff): raise PermissionDenied('User {0} is not authorized to edit the internal field {1}'.format(user, orm_key)) has_updates = True setattr(model_obj, orm_key, value) if has_updates: model_obj.save() return has_updates
Example #6
Source File: views.py From coursys with GNU General Public License v3.0 | 6 votes |
def generate_pdf(request, userid, event_slug, pdf_key): """ Generate the PDF for a given event, faculty member, and PDF type (dictated by the handler) """ person, member_units = _get_faculty_or_404(request.units, userid) instance = _get_event_or_404(units=request.units, slug=event_slug, person=person) editor = get_object_or_404(Person, userid=request.user.username) handler = instance.get_handler() if not handler.can_view(editor): raise PermissionDenied("'%s' not allowed to view this event" % editor) if pdf_key not in handler.PDFS: raise PermissionDenied("No such PDF for this handler") return handler.generate_pdf(pdf_key)
Example #7
Source File: views.py From coursys with GNU General Public License v3.0 | 6 votes |
def change_event_status(request, userid, event_slug): """ Change status of event, if the editor has such privileges. """ person, member_units = _get_faculty_or_404(request.units, userid) instance = _get_event_or_404(units=request.units, slug=event_slug, person=person) editor = get_object_or_404(Person, userid=request.user.username) handler = instance.get_handler() if not handler.can_approve(editor): raise PermissionDenied("You cannot change status of this event") form = ApprovalForm(request.POST, instance=instance) if form.is_valid(): event = form.save(commit=False) event.get_handler().save(editor) l = LogEntry(userid=request.user.username, description="Changed event %s status for %s" % (event, person), related_object=event) l.save() return HttpResponseRedirect(event.get_absolute_url())
Example #8
Source File: views.py From coursys with GNU General Public License v3.0 | 6 votes |
def view_attachment(request, userid, event_slug, attach_slug): person, member_units = _get_faculty_or_404(request.units, userid) event = _get_event_or_404(units=request.units, slug=event_slug, person=person) viewer = get_object_or_404(Person, userid=request.user.username) attachment = get_object_or_404(event.attachments.all(), slug=attach_slug) handler = event.get_handler() if not handler.can_view(viewer): raise PermissionDenied("Not allowed to view this attachment") filename = attachment.contents.name.rsplit('/')[-1] resp = StreamingHttpResponse(attachment.contents.chunks(), content_type=attachment.mediatype) resp['Content-Disposition'] = 'inline; filename="' + filename + '"' resp['Content-Length'] = attachment.contents.size return resp
Example #9
Source File: data_viewset.py From kobo-predict with BSD 2-Clause "Simplified" License | 6 votes |
def enketo(self, request, *args, **kwargs): self.object = self.get_object() data = {} if isinstance(self.object, XForm): raise ParseError(_(u"Data id not provided.")) elif(isinstance(self.object, Instance)): if request.user.has_perm("change_xform", self.object.xform): return_url = request.query_params.get('return_url') if not return_url: raise ParseError(_(u"return_url not provided.")) try: data["url"] = get_enketo_edit_url( request, self.object, return_url) except EnketoError as e: data['detail'] = "{}".format(e) else: raise PermissionDenied(_(u"You do not have edit permissions.")) return Response(data=data)
Example #10
Source File: resource.py From arches with GNU Affero General Public License v3.0 | 6 votes |
def delete(self, request, resourceid=None): delete_error = _("Unable to Delete Resource") delete_msg = _("User does not have permissions to delete this instance because the instance or its data is restricted") try: if resourceid is not None: if user_can_delete_resource(request.user, resourceid) is False: return JSONErrorResponse(delete_error, delete_msg) ret = Resource.objects.get(pk=resourceid) try: deleted = ret.delete(user=request.user) except ModelInactiveError as e: message = _("Unable to delete. Please verify the model status is active") return JSONResponse({"status": "false", "message": [_(e.title), _(str(message))]}, status=500) except PermissionDenied: return JSONErrorResponse(delete_error, delete_msg) if deleted is True: return JSONResponse(ret) else: return JSONErrorResponse(delete_error, delete_msg) return HttpResponseNotFound() except PermissionDenied: return JSONErrorResponse(delete_error, delete_msg)
Example #11
Source File: dashboard.py From StormOnline with Apache License 2.0 | 6 votes |
def get_init_widget(self): portal = [] widgets = self.widgets for col in widgets: portal_col = [] for opts in col: try: widget = UserWidget(user=self.user, page_id=self.get_page_id(), widget_type=opts['type']) widget.set_value(opts) widget.save() portal_col.append(self.get_widget(widget)) except (PermissionDenied, WidgetDataError): widget.delete() continue portal.append(portal_col) UserSettings( user=self.user, key="dashboard:%s:pos" % self.get_page_id(), value='|'.join([','.join([str(w.id) for w in col]) for col in portal])).save() return portal
Example #12
Source File: rolemixins.py From kobo-predict with BSD 2-Clause "Simplified" License | 6 votes |
def dispatch(self, request, *args, **kwargs): if request.group.name == "Super Admin": return super(ReadonlyProjectLevelRoleMixin, self).dispatch(request, is_donor_only=False, *args, **kwargs) project_id = self.kwargs.get('pk') user_id = request.user.id user_role = request.roles.filter(project_id = project_id, group_id=2) if user_role: return super(ReadonlyProjectLevelRoleMixin, self).dispatch(request, is_donor_only=False, *args, **kwargs) organization_id = Project.objects.get(pk=project_id).organization.id user_role_asorgadmin = request.roles.filter(organization_id = organization_id, group_id=1) if user_role_asorgadmin: return super(ReadonlyProjectLevelRoleMixin, self).dispatch(request, is_donor_only=False, *args, **kwargs) user_role_asdonor = request.roles.filter(project_id = project_id, group_id=7) if user_role_asdonor: return super(ReadonlyProjectLevelRoleMixin, self).dispatch(request, is_donor_only=True, *args, **kwargs) raise PermissionDenied()
Example #13
Source File: tests_query_params.py From koku with GNU Affero General Public License v3.0 | 6 votes |
def test_access_empty_intersection(self): """Test that a group by cluster filtered list causes 403 with empty intersection.""" fake_uri = "group_by[cluster]=cluster1&" "group_by[cluster]=cluster3" test_access = {"openshift.cluster": {"read": ["cluster4", "cluster2"]}} fake_request = Mock( spec=HttpRequest, user=Mock(access=test_access, customer=Mock(schema_name="acct10001")), GET=Mock(urlencode=Mock(return_value=fake_uri)), ) fake_view = Mock( spec=ReportView, provider=self.FAKE.word(), query_handler=Mock(provider=Provider.PROVIDER_OCP), report=self.FAKE.word(), serializer=Mock, tag_handler=[], ) with self.assertRaises(PermissionDenied): QueryParameters(fake_request, fake_view)
Example #14
Source File: files.py From FIR with GNU General Public License v3.0 | 6 votes |
def do_download_archive(request, content_type, object_id): object_type = ContentType.objects.get(pk=content_type) obj = get_object_or_404(object_type.model_class(), pk=object_id) if not request.user.has_perm('incidents.view_incidents', obj=obj): raise PermissionDenied() if obj.file_set.count() == 0: raise Http404 temp = BytesIO() with zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED) as archive: media_root = settings.MEDIA_ROOT for file in obj.file_set.all(): path = os.path.join(media_root, file.file.path) archive.write(path, os.path.basename(path)) file_size = temp.tell() temp.seek(0) wrapper = FileWrapper(temp) response = HttpResponse(wrapper, content_type='application/zip') response['Content-Disposition'] = 'attachment; filename=archive_%s_%s.zip' % (object_type.model, object_id) response['Content-Length'] = file_size return response
Example #15
Source File: decorators.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
def permission_required(perm, login_url=None, raise_exception=False): """ Decorator for views that checks whether a user has a particular permission enabled, redirecting to the log-in page if necessary. If the raise_exception parameter is given the PermissionDenied exception is raised. """ def check_perms(user): if not isinstance(perm, (list, tuple)): perms = (perm, ) else: perms = perm # First check if the user has the permission (even anon users) if user.has_perms(perms): return True # In case the 403 handler should be called raise the exception if raise_exception: raise PermissionDenied # As the last resort, show the login form return False return user_passes_test(check_perms, login_url=login_url)
Example #16
Source File: __init__.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
def authenticate(**credentials): """ If the given credentials are valid, return a User object. """ for backend, backend_path in _get_backends(return_tuples=True): try: inspect.getcallargs(backend.authenticate, **credentials) except TypeError: # This backend doesn't accept these credentials as arguments. Try the next one. continue try: user = backend.authenticate(**credentials) except PermissionDenied: # This backend says to stop in our tracks - this user should not be allowed in at all. return None if user is None: continue # Annotate the user object with the path of the backend. user.backend = backend_path return user # The credentials supplied are invalid to all backends, fire signal user_login_failed.send(sender=__name__, credentials=_clean_credentials(credentials))
Example #17
Source File: views.py From FIR with GNU General Public License v3.0 | 6 votes |
def toggle_status(request, todo_id): todo = get_object_or_404(TodoItem, pk=todo_id) if (todo.business_line and request.user.has_perm('incidents.view_incidents', obj=todo.business_line)) or \ request.user.has_perm('incidents.handle_incidents', obj=todo.incident): todo.done = not todo.done if todo.done: todo.done_time = datetime.datetime.now() todo.save() else: raise PermissionDenied() referer = request.META.get('HTTP_REFERER', None) dashboard = False if ('/incidents/' not in referer) and ('/events/' not in referer): dashboard = True return render(request, 'fir_todos/single.html', {'item': todo, 'dashboard': dashboard})
Example #18
Source File: logger_tools.py From kobo-predict with BSD 2-Clause "Simplified" License | 6 votes |
def check_submission_permissions(request, xform): """Check that permission is required and the request user has permission. The user does no have permissions iff: * the user is authed, * either the profile or the form require auth, * the xform user is not submitting. Since we have a username, the Instance creation logic will handle checking for the forms existence by its id_string. :returns: None. :raises: PermissionDenied based on the above criteria. """ profile = UserProfile.objects.get_or_create(user=xform.user)[0] if request and (profile.require_auth or xform.require_auth or request.path == '/submission')\ and xform.user != request.user\ and not request.user.has_perm('report_xform', xform): raise PermissionDenied( _(u"%(request_user)s is not allowed to make submissions " u"to %(form_user)s's %(form_title)s form." % { 'request_user': request.user, 'form_user': xform.user, 'form_title': xform.title}))
Example #19
Source File: fieldsight_logger_tools.py From kobo-predict with BSD 2-Clause "Simplified" License | 6 votes |
def check_submission_permissions(request, xform): """Check that permission is required and the request user has permission. The user does no have permissions iff: * the user is authed, * either the profile or the form require auth, * the xform user is not submitting. Since we have a username, the Instance creation logic will handle checking for the forms existence by its id_string. :returns: None. :raises: PermissionDenied based on the above criteria. """ profile = UserProfile.objects.get_or_create(user=xform.user)[0] if request and (profile.require_auth or xform.require_auth or request.path == '/submission')\ and xform.user != request.user\ and not request.user.has_perm('report_xform', xform): raise PermissionDenied( _(u"%(request_user)s is not allowed to make submissions " u"to %(form_user)s's %(form_title)s form." % { 'request_user': request.user, 'form_user': xform.user, 'form_title': xform.title}))
Example #20
Source File: views.py From FIR with GNU General Public License v3.0 | 5 votes |
def delete_comment(request, incident_id, comment_id): c = get_object_or_404(Comments, pk=comment_id, incident_id=incident_id) i = c.incident if not request.user.has_perm('incidents.handle_incidents', obj=i) and not c.opened_by == request.user: raise PermissionDenied() if request.method == "POST": msg = "Comment '%s' deleted." % (c.comment[:20] + "...") c.delete() log(msg, request.user, incident=Incident.objects.get(id=incident_id)) return redirect('incidents:details', incident_id=c.incident_id) else: return redirect('incidents:details', incident_id=c.incident_id)
Example #21
Source File: mixins.py From kobo-predict with BSD 2-Clause "Simplified" License | 5 votes |
def dispatch(self, request, *args, **kwargs): if request.user.is_authenticated(): if request.role.group.name in ['Super Admin']: return super(MyOwnProjectMixin, self).dispatch(request, *args, **kwargs) if request.role.group.name in ['Organization Admin']: if request.role.organization == Project.objects.get(pk=kwargs.get('pk', 0)).organization: return super(MyOwnProjectMixin, self).dispatch(request, *args, **kwargs) if request.role.group.name in ['Reviewer', 'Project Manager']: if request.role.project.pk == int(self.kwargs.get('pk', '0')): return super(MyOwnProjectMixin, self).dispatch(request, *args, **kwargs) raise PermissionDenied()
Example #22
Source File: mixins.py From kobo-predict with BSD 2-Clause "Simplified" License | 5 votes |
def dispatch(self, request, *args, **kwargs): if request.user.is_authenticated(): if request.role.group.name in USURPERS['admin']: return super(SuperAdminMixin, self).dispatch(request, *args, **kwargs) raise PermissionDenied() # use in all view functions
Example #23
Source File: rolemixins.py From kobo-predict with BSD 2-Clause "Simplified" License | 5 votes |
def dispatch(self, request, *args, **kwargs): if request.group.name == "Super Admin": return super(OrganizationRoleMixin, self).dispatch(request, *args, **kwargs) organization_id = self.kwargs.get('pk') user_id = request.user.id user_role = request.roles.filter(organization_id = organization_id, group_id=1) if user_role: return super(OrganizationRoleMixin, self).dispatch(request, *args, **kwargs) raise PermissionDenied()
Example #24
Source File: views.py From FIR with GNU General Public License v3.0 | 5 votes |
def delete(request, todo_id): todo = get_object_or_404(TodoItem, pk=todo_id) if not request.user.has_perm(todo.incident, 'incidents.handle_incidents'): raise PermissionDenied() todo.delete() return HttpResponse('')
Example #25
Source File: decorator.py From FIR with GNU General Public License v3.0 | 5 votes |
def authorization_required(perm, model, view_arg=None): def _decorator(view_func): def _view(request, *args, **kwargs): obj = model if isinstance(view_arg, six.string_types): try: obj_id = kwargs.get(view_arg) obj = model.authorization.for_user(request.user, perm).get(pk=obj_id) except: raise PermissionDenied() elif isinstance(view_arg, int): try: obj = model.authorization.for_user(request.user, perm).get(pk=args[view_arg]) except: raise PermissionDenied() else: if not request.user.has_perm(perm, obj=model): raise PermissionDenied() kwargs['authorization_target'] = obj return view_func(request, *args, **kwargs) _view.__name__ = view_func.__name__ _view.__dict__ = view_func.__dict__ _view.__doc__ = view_func.__doc__ return _view return _decorator
Example #26
Source File: files.py From FIR with GNU General Public License v3.0 | 5 votes |
def do_download(request, file_id): f = get_object_or_404(File, pk=file_id) if not request.user.has_perm('incidents.view_incidents', obj=f.get_related()): raise PermissionDenied() wrapper = FileWrapper(f.file) content_type = mimetypes.guess_type(f.file.name) response = HttpResponse(wrapper, content_type=content_type) response['Content-Disposition'] = 'attachment; filename=%s' % (f.getfilename()) response['Content-Length'] = os.path.getsize(str(f.file.file)) return response
Example #27
Source File: views.py From FIR with GNU General Public License v3.0 | 5 votes |
def detach_artifact(request, artifact_id, relation_name, relation_id): a = get_object_or_404(Artifact, pk=artifact_id) relation = getattr(a, relation_name, None) if relation is None: raise Http404("Unknown relation") try: related = relation.get(pk=relation_id) except: raise Http404("Unknown related object") if not request.user.has_perm('incidents.handle_incidents', obj=related): raise PermissionDenied() a.relations.remove(related) if a.relations.count() == 0: a.delete() return redirect('%s:details' % relation_name, relation_id)
Example #28
Source File: files.py From FIR with GNU General Public License v3.0 | 5 votes |
def do_upload_file(request, content_type, object_id): if request.method == 'POST': object_type = ContentType.objects.get(pk=content_type) obj = get_object_or_404(object_type.model_class(), pk=object_id) if not request.user.has_perm('incidents.handle_incidents', obj=obj): raise PermissionDenied() descriptions = request.POST.getlist('description') files = request.FILES.getlist('file') if len(descriptions) == len(files): # consider this as a valid upload form? for i, file in enumerate(files): handle_uploaded_file(file, descriptions[i], obj) return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
Example #29
Source File: admin.py From dingtalk-django-example with GNU General Public License v3.0 | 5 votes |
def delete_view(self, *args, **kwargs): raise PermissionDenied('No Delete Permission Allowed')
Example #30
Source File: mixins.py From kobo-predict with BSD 2-Clause "Simplified" License | 5 votes |
def dispatch(self, request, *args, **kwargs): if request.user.is_authenticated(): if request.role.group.name in ['Super Admin']: return super(MyOwnOrganizationMixin, self).dispatch(request, *args, **kwargs) if request.role.group.name in ['Organization Admin']: if request.role.organization.pk == int(self.kwargs.get('pk','0')): return super(MyOwnOrganizationMixin, self).dispatch(request, *args, **kwargs) raise PermissionDenied()