python类PermissionDenied()的实例源码

views.py 文件源码 项目:taiga-contrib-saml-auth 作者: jgiannuzzi 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def complete_login(request):
    auth = get_saml_auth(request)
    auth.process_response()
    errors = auth.get_errors()

    if errors:
        logger.error(auth.get_last_error_reason(), exc_info=True)
        return HttpResponseBadRequest(
                content='Error when processing SAML Response: {}'.format(', '.join(errors))
                )

    if auth.is_authenticated():
        request.session['saml_attributes'] = auth.get_attributes()
        request.session['saml_nameid'] = auth.get_nameid()
        request.session['saml_session_index'] = auth.get_session_index()

        params = {'state': 'saml'}
        url = request.POST.get('RelayState', '/login')

        return HttpResponseRedirect(auth.redirect_to(url, parameters=params))

    else:
        raise PermissionDenied()
views.py 文件源码 项目:Bitpoll 作者: fsinfuhh 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def invite(request, group_name):
    group = get_object_or_404(Group, name=group_name)
    if not group.properties.admins.filter(pk=request.user.pk):
        raise PermissionDenied()

    if request.method == 'POST':
        form = InvitationForm(request.POST, group=group,
                              user=request.user)
        if form.is_valid():
            subject = u'Neue Gruppeneinladung / new group invitation'
            invitations = form.get_invitations()
            for invitation in invitations:
                invitation.save()
                _send_invitation_mail(request, invitation, subject, 'new_invitation')
            messages.success(request, _('Invitation was sent.'))
            return redirect('groups_show', group_name)
    else:
        form = InvitationForm(group=group, user=request.user)

    return TemplateResponse(request, 'groups/invite.html', {
        'group': group,
        'form': form
    })
decorators.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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 isinstance(perm, six.string_types):
            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)
__init__.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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))
decorators.py 文件源码 项目:NarshaTech 作者: KimJangHyeon 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
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 isinstance(perm, six.string_types):
            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)
__init__.py 文件源码 项目:NarshaTech 作者: KimJangHyeon 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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.
            break
        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))
utils.py 文件源码 项目:django-rest-framework-passwordless 作者: aaronn 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def authenticate_by_token(callback_token):
    try:
        token = CallbackToken.objects.get(key=callback_token, is_active=True)

        # Returning a user designates a successful authentication.
        token.user = User.objects.get(pk=token.user.pk)
        token.is_active = False  # Mark this token as used.
        token.save()

        return token.user

    except CallbackToken.DoesNotExist:
        log.debug("drfpasswordless: Challenged with a callback token that doesn't exist.")
    except User.DoesNotExist:
        log.debug("drfpasswordless: Authenticated user somehow doesn't exist.")
    except PermissionDenied:
        log.debug("drfpasswordless: Permission denied while authenticating.")

    return None
decorators.py 文件源码 项目:tecken 作者: mozilla-services 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def api_login_required(view_func):
    """similar to django.contrib.auth.decorators.login_required
    except instead of redirecting it returns a 403 message if not
    authenticated."""
    @wraps(view_func)
    def inner(request, *args, **kwargs):
        if not request.user.is_active:
            error_msg = (
                'This requires an Auth-Token to authenticate the request'
            )
            if not settings.ENABLE_TOKENS_AUTHENTICATION:  # pragma: no cover
                error_msg += ' (ENABLE_TOKENS_AUTHENTICATION is False)'
            raise PermissionDenied(error_msg)
        return view_func(request, *args, **kwargs)

    return inner
decorators.py 文件源码 项目:zing 作者: evernote 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def requires_permission(permission):

    def class_wrapper(f):

        @functools.wraps(f)
        def method_wrapper(self, request, *args, **kwargs):
            directory_permission = check_directory_permission(
                permission, request, self.permission_context)
            check_class_permission = (
                directory_permission
                and hasattr(self, "required_permission")
                and permission != self.required_permission)
            if check_class_permission:
                directory_permission = check_directory_permission(
                    self.required_permission, request, self.permission_context)
            if not directory_permission:
                raise PermissionDenied(
                    _("Insufficient rights to access this page."), )
            return f(self, request, *args, **kwargs)
        return method_wrapper
    return class_wrapper
views.py 文件源码 项目:zing 作者: evernote 项目源码 文件源码 阅读 60 收藏 0 点赞 0 评论 0
def reject_suggestion(request, unit, suggid):
    try:
        sugg = unit.suggestion_set.get(id=suggid)
    except ObjectDoesNotExist:
        raise Http404

    # In order to be able to reject a suggestion, users have to either:
    # 1. Have `review` rights, or
    # 2. Be the author of the suggestion being rejected
    if (not check_permission('review', request) and
        (request.user.is_anonymous or request.user != sugg.user)):
        raise PermissionDenied(_('Insufficient rights to access review mode.'))

    unit.reject_suggestion(sugg, request.translation_project, request.user)
    r_data = QueryDict(request.body)
    if "comment" in r_data and r_data["comment"]:
        handle_suggestion_comment(request, sugg, unit, r_data["comment"],
                                  "rejected")

    json = {
        'udbid': unit.id,
        'sugid': suggid,
        'user_score': request.user.public_score,
    }
    return JsonResponse(json)
dashboard.py 文件源码 项目:blog_django 作者: chnpmy 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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
views.py 文件源码 项目:SpongeAuth 作者: lukegb 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def verify_step2(request, uidb64, token):
    bytes_uid = urlsafe_base64_decode(uidb64)
    try:
        uid = int(bytes_uid)
    except ValueError:
        raise SuspiciousOperation('verify_step2 received invalid base64 user ID: {}'.format(
            bytes_uid))
    if uid != request.user.id:
        raise PermissionDenied('UID mismatch - user is {}, request was for {}'.format(
            request.user.id, uid))
    user = get_object_or_404(models.User, pk=uid)
    if not verify_token_generator.check_token(user, token):
        raise Http404('token invalid')

    if not user.email_verified:
        user.email_verified = True
        user.save()
        messages.success(request, _('Your email has been verified successfully. Thanks!'))
    else:
        messages.info(request, _('Your email address has already been verified.'))
    return redirect('index')
decorators.py 文件源码 项目:Scrum 作者: prakharchoudhary 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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 isinstance(perm, six.string_types):
            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)
__init__.py 文件源码 项目:Scrum 作者: prakharchoudhary 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def authenticate(request=None, **credentials):
    """
    If the given credentials are valid, return a User object.
    """
    for backend, backend_path in _get_backends(return_tuples=True):
        try:
            user = _authenticate_with_backend(backend, backend_path, request, credentials)
        except PermissionDenied:
            # This backend says to stop in our tracks - this user should not be allowed in at all.
            break
        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), request=request)
dashboard.py 文件源码 项目:dream_blog 作者: fanlion 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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
dashboard.py 文件源码 项目:MxOnline 作者: myTeemo 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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
dashboard.py 文件源码 项目:djangoblog 作者: liuhuipy 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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
decorators.py 文件源码 项目:django 作者: alexsukhrin 项目源码 文件源码 阅读 37 收藏 0 点赞 0 评论 0
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 isinstance(perm, six.string_types):
            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)
__init__.py 文件源码 项目:django 作者: alexsukhrin 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def authenticate(request=None, **credentials):
    """
    If the given credentials are valid, return a User object.
    """
    for backend, backend_path in _get_backends(return_tuples=True):
        try:
            user = _authenticate_with_backend(backend, backend_path, request, credentials)
        except PermissionDenied:
            # This backend says to stop in our tracks - this user should not be allowed in at all.
            break
        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), request=request)
decorators.py 文件源码 项目:habilitacion 作者: GabrielBD 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def group_required(group_name, login_url=None, raise_exception=False):
    """
    Decorator for views that checks whether a user belongs to a particular
    group, redirecting to the log-in page if necessary.
    If the raise_exception parameter is given the PermissionDenied exception
    is raised.
    """
    def check_group(user):
        # First check if the user belongs to the group
        if user.groups.filter(name=group_name).exists():
            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_group, login_url=login_url)
dashboard.py 文件源码 项目:sdining 作者: Lurance 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
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
common_helpers.py 文件源码 项目:State-TalentMAP-API 作者: 18F 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def in_group_or_403(user, group_name):
    '''
    This function mimics the functionality of get_object_or_404, but for permission groups.
    The function accepts a user and group name, doing nothing if the user is present in
    the permission group; otherwise, throws a PermissionDenied error

    Args:
        - user (Object) - The user instance
        - group_name (String) - The name of the permission group
    '''
    try:
        group = get_group_by_name(group_name)
    except:
        raise PermissionDenied
    if group not in user.groups.all():
        raise PermissionDenied
views.py 文件源码 项目:aurora 作者: carnby 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def follow(request):
    #print 'follow'
    #print request.POST
    auth_user = request.user

    source_user = request.POST.get('source', '')
    if not source_user or auth_user.username != source_user:
        print(auth_user.username, len(auth_user.username), source_user, len(source_user))
        raise PermissionDenied

    portrait = get_object_or_404(Portrait, auth_screen_name=auth_user.username.lower())

    target_user_id = request.POST.get('target', '')[:100]
    if not target_user_id:
        raise Http404

    try:
        followed = portrait_follow(portrait, target_user_id)
    except:
        followed = False

    return render_json(request, followed)
views.py 文件源码 项目:aurora 作者: carnby 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def share(request):
    auth_user = request.user

    source_user = request.POST.get('source', '')
    if not source_user or auth_user.username.lower() != source_user.lower():
        print(auth_user.username, len(auth_user.username), source_user, len(source_user))
        raise PermissionDenied

    portrait = get_object_or_404(Portrait, auth_screen_name=auth_user.username.lower())

    try:
        followed = portrait_share(portrait)
    except Exception as err:
        print(err)
        followed = False

    print('share result', followed)

    return render_json(request, followed)
views.py 文件源码 项目:django-sysinfo 作者: saxix 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def http_basic_auth(func):
    @wraps(func)
    def _decorator(request, *args, **kwargs):
        from django.contrib.auth import authenticate, login

        if "HTTP_AUTHORIZATION" in request.META:
            authmeth, auth = request.META["HTTP_AUTHORIZATION"].split(b" ", 1)
            if authmeth.lower() == b"basic":
                auth = codecs.decode(auth.strip(), "base64")
                username, password = auth.split(b":", 1)
                user = authenticate(username=username, password=password)
                if user and is_authorized(user):
                    login(request, user)
                else:
                    raise PermissionDenied()
        return func(request, *args, **kwargs)

    return _decorator
views.py 文件源码 项目:Hoshimori_Project 作者: kokonguyen191 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def addcard(request, card):
    if request.method != "POST":
        raise PermissionDenied()
    collection = 'collection' in request.GET
    queryset = Card
    if not collection:
        # Note: calling filterCards will add extra info need to display the card
        queryset = filterCards(Card.objects.all(), {}, request)
    card = get_object_or_404(queryset, pk=card)
    account = get_object_or_404(Account, pk=request.POST.get('account', None), owner=request.user)
    OwnedCard.objects.create(card=card, account=account, evolved=card.evolvable, level=card.max_level)
    OwnedCard.objects.get(card=card, account=account).force_cache_stats()
    if not collection:
        card.total_owned += 1
    if collection:
        return cardcollection(request, card.id)
    else:
        context = web_globalContext(request)
        return item_view(request, context, 'card', CardCollection, pk=card.id, item=card, ajax=True)
exception.py 文件源码 项目:Gypsy 作者: benticarlos 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def convert_exception_to_response(get_response):
    """
    Wrap the given get_response callable in exception-to-response conversion.

    All exceptions will be converted. All known 4xx exceptions (Http404,
    PermissionDenied, MultiPartParserError, SuspiciousOperation) will be
    converted to the appropriate response, and all other exceptions will be
    converted to 500 responses.

    This decorator is automatically applied to all middleware to ensure that
    no middleware leaks an exception and that the next middleware in the stack
    can rely on getting a response instead of an exception.
    """
    @wraps(get_response, assigned=available_attrs(get_response))
    def inner(request):
        try:
            response = get_response(request)
        except Exception as exc:
            response = response_for_exception(request, exc)
        return response
    return inner
decorators.py 文件源码 项目:Gypsy 作者: benticarlos 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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 isinstance(perm, six.string_types):
            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)
__init__.py 文件源码 项目:Gypsy 作者: benticarlos 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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.
            break
        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))
decorators.py 文件源码 项目:DjangoBlog 作者: 0daybug 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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)


问题


面经


文章

微信
公众号

扫码关注公众号