我们从Python开源项目中,提取了以下48个代码示例,用于说明如何使用django.core.exceptions.PermissionDenied()。
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()
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 })
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)
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))
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))
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
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
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
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)
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
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')
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)
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)
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
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)
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)
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
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)
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
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)
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}))
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)
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__name="Project Manager") 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__name="Organization Admin") if user_role_asorgadmin: return super(ProjectRoleMixin, self).dispatch(request, *args, **kwargs) raise PermissionDenied()
def dispatch(self, request, *args, **kwargs): if request.group.name == "Super Admin": return super(ReviewerRoleMixin, self).dispatch(request, *args, **kwargs) site_id = self.kwargs.get('pk') user_id = request.user.id user_role = request.roles.filter(user_id = user_id, site_id = site_id, group__name="Reviewer") if user_role: return super(ReviewerRoleMixin, self).dispatch(request, *args, **kwargs) project = Site.objects.get(pk=site_id).project user_role_aspadmin = request.roles.filter(user_id = user_id, project_id = project.id, group__name="Project Manager") if user_role_aspadmin: return super(ReviewerRoleMixin, self).dispatch(request, *args, **kwargs) organization_id = project.organization.id user_role_asorgadmin = request.roles.filter(user_id = user_id, organization_id = organization_id, group__name="Organization Admin") if user_role_asorgadmin: return super(ReviewerRoleMixin, self).dispatch(request, *args, **kwargs) raise PermissionDenied()
def dispatch(self, request, *args, **kwargs): if request.group.name == "Super Admin": return super(ReviewerRoleMixin, self).dispatch(request, *args, **kwargs) site_id = self.kwargs.get('pk') user_id = request.user.id user_role = request.roles.filter(user_id = user_id, site_id = site_id, group__name="Site Supervisor") if user_role: return super(SiteSupervisorRoleMixin, self).dispatch(request, *args, **kwargs) project = Site.objects.get(pk=site_id).project user_role_aspadmin = request.roles.filter(user_id = user_id, project_id = project.id, group__name="Project Manager") if user_role_aspadmin: return super(SiteSupervisorRoleMixin, self).dispatch(request, *args, **kwargs) organization_id = project.organization.id user_role_asorgadmin = request.roles.filter(user_id = user_id, organization_id = organization_id, group__name="Organization Admin") if user_role_asorgadmin: return super(SiteSupervisorRoleMixin, self).dispatch(request, *args, **kwargs) raise PermissionDenied()
def dispatch(self, request, *args, **kwargs): if request.group.name == "Super Admin": return super(SiteDeleteRoleMixin, self).dispatch(request, *args, **kwargs) site_id = self.kwargs.get('pk') user_id = request.user.id project = Site.objects.get(pk=site_id).project user_role_aspadmin = request.roles.filter(user_id = user_id, project_id = project.id, group__name="Project Manager") if user_role_aspadmin: return super(SiteDeleteRoleMixin, self).dispatch(request, *args, **kwargs) organization_id = project.organization.id user_role_asorgadmin = request.roles.filter(user_id = user_id, organization_id = organization_id, group__name="Organization Admin") if user_role_asorgadmin: return super(SiteDeleteRoleMixin, self).dispatch(request, *args, **kwargs) raise PermissionDenied()
def dispatch(self, request, *args, **kwargs): if request.group.name == "Super Admin": return super(ReviewerRoleMixinDeleteView, self).dispatch(request, *args, **kwargs) site_id = self.kwargs.get('pk') user_id = request.user.id user_role = request.roles.filter(user_id = user_id, site_id = site_id, group__name="Reviewer") if user_role: return super(SiteSupervisorRoleMixin, self).dispatch(request, *args, **kwargs) project = Site.objects.get(pk=site_id).project user_role_aspadmin = request.roles.filter(user_id = user_id, project_id = project.id, group__name="Project Manager") if user_role_aspadmin: return super(ReviewerRoleMixinDeleteView, self).dispatch(request, *args, **kwargs) organization_id = project.organization.id user_role_asorgadmin = request.roles.filter(user_id = user_id, organization_id = organization_id, group__name="Organization Admin") if user_role_asorgadmin: return super(ReviewerRoleMixinDeleteView, self).dispatch(request, *args, **kwargs) raise PermissionDenied()
def dispatch(self, request, *args, **kwargs): if request.user.is_authenticated(): if request.group.name == "Super Admin": return super(ReviewerMixin, self).dispatch(request, *args, **kwargs) elif request.group.name == "Organization Admin": pk = self.kwargs.get('pk', False) if not pk: return super(ReviewerMixin, self).dispatch(request, *args, **kwargs) else: site = Site.objects.get(pk=pk) organization = site.project.organization if organization == request.organization: return super(ReviewerMixin, self).dispatch(request, *args, **kwargs) elif request.role.group.name in USURPERS['Reviewer']: pk = self.kwargs.get('pk', False) if not pk: return super(ReviewerMixin, self).dispatch(request, *args, **kwargs) else: site = Site.objects.get(pk=pk) if site.project == request.project: return super(ReviewerMixin, self).dispatch(request, *args, **kwargs) raise PermissionDenied()
def addcard(request, card): if request.method != "POST": raise PermissionDenied() collection = 'collection' in request.GET queryset = models.Card if not collection: # Note: calling filterCards will add extra info need to display the card queryset = filters.filterCards(models.Card.objects.all(), {}, request) card = get_object_or_404(queryset, pk=card) account = get_object_or_404(models.Account, pk=request.POST.get('account', None), owner=request.user) models.OwnedCard.objects.create(card=card, account=account) if not collection: card.total_owned += 1 if collection: return cardcollection(request, card.id) else: return item_view(request, 'card', ENABLED_COLLECTIONS['card'], pk=card.id, item=card, ajax=True)
def filterOwnedCards(queryset, parameters, request): if 'account' in parameters: queryset = queryset.filter(account_id=parameters['account']) elif 'ids' in parameters and parameters['ids']: queryset = queryset.filter(id__in=parameters['ids'].split(',')) else: raise PermissionDenied() if 'search' in parameters and parameters['search']: terms = parameters['search'].split(' ') for term in terms: queryset = queryset.filter(Q(card__title__icontains=term) | Q(card__idol__name__icontains=term) ) if 'i_rarity' in parameters and parameters['i_rarity']: queryset = queryset.filter(card__i_rarity=parameters['i_rarity']) if 'is_event' in parameters and parameters['is_event']: if parameters['is_event'] == '2': queryset = queryset.filter(card__event__isnull=False) elif parameters['is_event'] == '3': queryset = queryset.filter(card__event__isnull=True) if 'type' in parameters and parameters['type']: queryset = queryset.filter(card__idol__i_type=parameters['type']) if 'i_skill' in parameters and parameters['i_skill']: queryset = queryset.filter(card__i_skill=parameters['i_skill']) return queryset