Python django.core.exceptions.PermissionDenied() Examples

The following are 30 code examples for showing how to use django.core.exceptions.PermissionDenied(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.core.exceptions , or try the search function .

Example 1
Project: open-synthesis   Author: twschiller   File: boards.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 2
Project: open-synthesis   Author: twschiller   File: teams.py    License: GNU General Public License v3.0 6 votes vote down vote up
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
Project: seqr   Author: macarthur-lab   File: json_to_orm_utils.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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 4
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 5
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 6
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 7
Project: arches   Author: archesproject   File: resource.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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 8
Project: StormOnline   Author: stormsha   File: dashboard.py    License: Apache License 2.0 6 votes vote down vote up
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 9
Project: GTDWeb   Author: lanbing510   File: __init__.py    License: GNU General Public License v2.0 6 votes vote down vote up
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 10
Project: GTDWeb   Author: lanbing510   File: decorators.py    License: GNU General Public License v2.0 6 votes vote down vote up
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 11
Project: koku   Author: project-koku   File: tests_query_params.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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 12
Project: koku   Author: project-koku   File: middleware.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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 13
Project: FIR   Author: certsocietegenerale   File: files.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 14
Project: FIR   Author: certsocietegenerale   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 15
Project: kobo-predict   Author: awemulya   File: logger_tools.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 16
Project: kobo-predict   Author: awemulya   File: fieldsight_logger_tools.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 17
Project: kobo-predict   Author: awemulya   File: data_viewset.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 18
Project: kobo-predict   Author: awemulya   File: rolemixins.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 19
Project: kobo-predict   Author: awemulya   File: rolemixins.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 20
Project: donation-tracker   Author: GamesDoneQuick   File: test_search_filters.py    License: Apache License 2.0 5 votes vote down vote up
def test_all_feed_without_permission(self):
        with self.assertRaises(PermissionDenied):
            apply_feed_filter(self.query, 'prize', 'all') 
Example 21
Project: donation-tracker   Author: GamesDoneQuick   File: test_search_filters.py    License: Apache License 2.0 5 votes vote down vote up
def test_all_feed_without_permission(self):
        with self.assertRaises(PermissionDenied):
            apply_feed_filter(self.query, 'bid', 'all') 
Example 22
Project: donation-tracker   Author: GamesDoneQuick   File: test_search_filters.py    License: Apache License 2.0 5 votes vote down vote up
def test_pending_feed_without_permission(self):
        with self.assertRaises(PermissionDenied):
            apply_feed_filter(self.query, 'bid', 'pending') 
Example 23
Project: donation-tracker   Author: GamesDoneQuick   File: test_search_filters.py    License: Apache License 2.0 5 votes vote down vote up
def test_hidden_states_without_permission(self):
        for state in ['PENDING', 'HIDDEN', 'DENIED']:
            with self.assertRaises(PermissionDenied):
                run_model_query('allbids', {'state': state}) 
Example 24
Project: donation-tracker   Author: GamesDoneQuick   File: test_search_filters.py    License: Apache License 2.0 5 votes vote down vote up
def test_all_feed_without_permission(self):
        with self.assertRaises(PermissionDenied):
            apply_feed_filter(self.query, 'donation', 'all') 
Example 25
Project: open-synthesis   Author: twschiller   File: util.py    License: GNU General Public License v3.0 5 votes vote down vote up
def remove_and_redirect(request, removable, message_detail):
    """Mark a model as removed and redirect the user to the associated board detail page."""
    if getattr(settings, 'EDIT_REMOVE_ENABLED', True):
        removable.removed = True
        removable.save()
        class_name = removable._meta.verbose_name.title()  # pylint: disable=protected-access
        class_ = class_name[:1].lower() + class_name[1:] if class_name else ''
        messages.success(request, _('Removed {object_type}: {detail}').format(object_type=class_, detail=message_detail))  # nopep8
        return HttpResponseRedirect(reverse('openach:detail', args=(removable.board.id,)))
    else:
        raise PermissionDenied() 
Example 26
Project: open-synthesis   Author: twschiller   File: hypotheses.py    License: GNU General Public License v3.0 5 votes vote down vote up
def add_hypothesis(request, board_id):
    """Return a view for adding a hypothesis, or handle form submission."""
    board = get_object_or_404(Board, pk=board_id)
    existing = Hypothesis.objects.filter(board=board)

    if 'add_elements' not in board.permissions.for_user(request.user):
        raise PermissionDenied()

    if request.method == 'POST':
        form = HypothesisForm(request.POST)
        if form.is_valid():
            hypothesis = form.save(commit=False)
            hypothesis.board = board
            hypothesis.creator = request.user
            hypothesis.save()
            BoardFollower.objects.update_or_create(board=board, user=request.user, defaults={
                'is_contributor': True,
            })
            notify_add(board, actor=request.user, action_object=hypothesis)
            return HttpResponseRedirect(reverse('openach:detail', args=(board.id,)))
    else:
        form = HypothesisForm()

    context = {
        'form': form,
        'board': board,
        'hypotheses': existing,
    }
    return render(request, 'boards/add_hypothesis.html', context) 
Example 27
Project: open-synthesis   Author: twschiller   File: evidence.py    License: GNU General Public License v3.0 5 votes vote down vote up
def add_evidence(request, board_id):
    """Return a view of adding evidence (with a source), or handle the form submission."""
    board = get_object_or_404(Board, pk=board_id)

    if 'add_elements' not in board.permissions.for_user(request.user):
        raise PermissionDenied()

    require_source = getattr(settings, 'EVIDENCE_REQUIRE_SOURCE', True)

    if request.method == 'POST':
        evidence_form = EvidenceForm(request.POST)
        source_form = EvidenceSourceForm(request.POST, require=require_source)
        if evidence_form.is_valid() and source_form.is_valid():
            with transaction.atomic():
                evidence = evidence_form.save(commit=False)
                evidence.board = board
                evidence.creator = request.user
                evidence.save()

                if source_form.cleaned_data.get('source_url'):
                    source = source_form.save(commit=False)
                    source.evidence = evidence
                    source.uploader = request.user
                    source.save()
                    fetch_source_metadata.delay(source.id)

                BoardFollower.objects.update_or_create(board=board, user=request.user, defaults={
                    'is_contributor': True,
                })
            notify_add(board, actor=request.user, action_object=evidence)
            return HttpResponseRedirect(reverse('openach:detail', args=(board.id,)))
    else:
        evidence_form = EvidenceForm()
        source_form = EvidenceSourceForm(require=require_source, initial={'corroborating': True})

    context = {
        'board': board,
        'evidence_form': evidence_form,
        'source_form': source_form,
    }
    return render(request, 'boards/add_evidence.html', context) 
Example 28
Project: open-synthesis   Author: twschiller   File: boards.py    License: GNU General Public License v3.0 5 votes vote down vote up
def edit_board(request, board_id):
    """Return a board edit view, or handle the form submission."""
    board = get_object_or_404(Board, pk=board_id)

    if 'edit_board' not in board.permissions.for_user(request.user):
        raise PermissionDenied()

    allow_remove = request.user.is_staff and getattr(settings, 'EDIT_REMOVE_ENABLED', True)

    if request.method == 'POST':
        form = BoardForm(request.POST, instance=board)
        if 'remove' in form.data:
            if allow_remove:
                board.removed = True
                board.save()
                messages.success(request, _('Removed board {name}').format(name=board.board_title))
                return HttpResponseRedirect(reverse('openach:index'))
            else:
                raise PermissionDenied()

        elif form.is_valid():
            form.save()
            messages.success(request, _('Updated board title and/or description.'))
            return HttpResponseRedirect(reverse('openach:detail', args=(board.id,)))
    else:
        form = BoardForm(instance=board)

    context = {
        'form': form,
        'board': board,
        'allow_remove': allow_remove
    }

    return render(request, 'boards/edit_board.html', context) 
Example 29
Project: open-synthesis   Author: twschiller   File: teams.py    License: GNU General Public License v3.0 5 votes vote down vote up
def team_members(request, team_id):
    """Return a listing of members for the given team."""
    team = get_object_or_404(Team, pk=team_id)

    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/members.html', {
        'team': team,
        'members': make_paginator(request, team.members.order_by(Lower('username'))),
        'is_owner': team.owner == request.user,
    }) 
Example 30
Project: open-synthesis   Author: twschiller   File: auth.py    License: GNU General Public License v3.0 5 votes vote down vote up
def check_edit_authorization(request, board, has_creator=None):
    """Raise a PermissionDenied exception if the user does not have edit rights for the resource.

    :param request: a Django request object
    :param board: the Board context
    :param has_creator: a model that has a creator member, or None
    """
    if not has_edit_authorization(request, board, has_creator=has_creator):
        raise PermissionDenied()