Here are the examples of the python api django.core.exceptions.PermissionDenied taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
162 Examples
3
Example 1
def update_in_place(self, request, original_bundle, new_data):
"""
Override to restrict modification of object fields to those set in allowed_update_fields
"""
if set(new_data.keys()) - set(self._meta.allowed_update_fields):
raise PermissionDenied(
'Kun oppdatering av %s er tillatt.' % ', '.join(self._meta.allowed_update_fields)
)
logging.getLogger(__name__).debug('Attendee created: %s' % self.user)
return super(AttendeeResource, self).update_in_place(request, original_bundle, new_data)
3
Example 2
@login_required
def delete(req, id):
upload = get_object_or_404(Upload, import_id=id)
if req.user != upload.user:
raise PermissionDenied()
upload.delete()
return json_response(dict(
success=True,
))
3
Example 3
def hide_thread(self, comment):
""" `comment` can be a Comment or CommentDetails. """
user = User.objects.get(id=self.user_id)
if not is_dismissable(comment, user):
raise PermissionDenied("User cannot dismiss this thread.")
self.sadd(comment.thread_op_comment_id)
3
Example 4
def save(self, *args, **kwargs):
if not self.basket.can_be_edited:
raise PermissionDenied(
_("You cannot modify a %s basket") % (
self.basket.status.lower(),))
return super(AbstractLine, self).save(*args, **kwargs)
3
Example 5
def notify(self, pha, content, docuement_id=None, app_url=None):
# make sure that the docuement belongs to the record
docuement = None
if docuement_id:
docuement = Docuement.objects.get(id = docuement_id)
if docuement.record != self:
raise PermissionDenied()
# go through all of the accounts that need to be notified
for account in self.get_accounts_to_notify():
Notification.objects.create(record = self,
sender = pha,
account = account,
content = content,
creator = pha,
docuement = docuement,
app_url = app_url)
3
Example 6
Project: kala-app Source File: mixins.py
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
user = get_user(request)
if not user.is_admin:
raise PermissionDenied()
return super(AdminRequiredMixin, self).dispatch(request, *args, **kwargs)
3
Example 7
Project: formly Source File: design.py
@require_POST
@login_required
def survey_publish(request, pk):
survey = get_object_or_404(Survey, pk=pk)
if not request.user.has_perm("formly.publish_survey", obj=survey):
raise PermissionDenied()
survey.publish()
return redirect("formly_dt_survey_list")
3
Example 8
Project: django-daydreamer Source File: behaviors.py
def get_denial_exception(self, prefix):
"""
A hook to customize resolution of the exception value to raise
used by deny().
The default implementation returns self.<prefix>_exception,
defaulting to django.core.exceptions.PermissionDenied when falsy.
"""
return (
self.get_denial_attr(prefix, "exception") or
exceptions.PermissionDenied)
3
Example 9
def get_user_from_request(self, request):
user = self.authenticate(settings.SITE.default_user)
# print 20150701, user.profile.role
if user is None:
# print("20130514 Unknown username %s from request %s" % (
# username, request))
#~ raise Exception(
#~ raise exceptions.PermissionDenied("Unknown or inactive username %r. Please contact your system administrator."
# logger.info("Unknown or inactive username %r.", username)
raise exceptions.PermissionDenied(
"default_user {0} does not exist".format(
settings.SITE.default_user))
return user
3
Example 10
Project: django-extras Source File: shortcuts.py
def get_owned_object_or_40x(klass, owner, include_staff=False,
include_superuser=True, *args, **kwargs):
"""
Returns an object if it can be found (using get_object_or_404).
If the object is not owned by the supplied owner a 403 will be raised.
"""
obj = get_object_or_404(klass, *args, **kwargs)
if obj.is_not_owned_by(owner, include_staff, include_superuser):
raise PermissionDenied()
return obj
3
Example 11
Project: django-leonardo Source File: decorators.py
def staff_member(view_func):
"""Performs user authentication check.
Similar to Django's `login_required` decorator, except that this throws
:exc:`~leonardo.exceptions.NotAuthenticated` exception if the user is not
signed-in.
"""
@functools.wraps(view_func, assigned=available_attrs(view_func))
def dec(request, *args, **kwargs):
if request.user.is_staff:
return view_func(request, *args, **kwargs)
raise PermissionDenied(_("You haven't permissions to do this action."))
return dec
3
Example 12
Project: inthe.am Source File: decorators.py
def requires_task_store(f):
@wraps(f)
def wrapper(self, *args, **kwargs):
request = args[0]
if not request.user.is_authenticated():
raise PermissionDenied()
store = models.TaskStore.get_for_user(request.user)
kwargs['store'] = store
result = f(self, *args, **kwargs)
return result
return wrapper
3
Example 13
def dispatch(self, request, *args, **kwargs):
if not request.user.is_superuser:
msg = _('You do not have rights to administer Pootle.')
raise PermissionDenied(msg)
return super(SuperuserRequiredMixin, self).dispatch(request, *args,
**kwargs)
3
Example 14
def _get_real_admin_by_model(self, model_class, super_if_self=True):
# In case of a ?ct_id=### parameter, the view is already checked for permissions.
# Hence, make sure this is a derived object, or risk exposing other admin interfaces.
if model_class not in self._child_models:
raise PermissionDenied("Invalid model '{0}', it must be registered as child model.".format(model_class))
try:
# HACK: the only way to get the instance of an model admin,
# is to read the registry of the AdminSite.
real_admin = self._child_admin_site._registry[model_class]
except KeyError:
raise ChildAdminNotRegistered("No child admin site was registered for a '{0}' model.".format(model_class))
if super_if_self and real_admin is self:
return super(PolymorphicParentModelAdmin, self)
else:
return real_admin
3
Example 15
Project: oioioi Source File: views.py
def friend_action(request, other_name, action):
other_user = get_object_or_404(User.objects, username=other_name)
friends = UserFriends(request.user)
func = getattr(friends, action)
try:
if action in ['send_friendship_request', 'remove_friend']:
func(other_user)
else:
try:
friendship_request = friends.request_from(other_user)
except FriendshipRequest.DoesNotExist:
return redirect('view_profile', username=other_name)
func(friendship_request)
except ValueError as e:
raise PermissionDenied(str(e))
return redirect('view_profile', username=other_name)
3
Example 16
Project: formly Source File: design.py
@login_required
def survey_create(request):
if not request.user.has_perm("formly.create_survey"):
raise PermissionDenied()
if request.method == "POST":
form = SurveyCreateForm(request.POST, user=request.user)
if form.is_valid():
survey = form.save()
return redirect(survey.first_page())
else:
form = SurveyCreateForm(user=request.user)
return render(request, "formly/design/survey_form.html", {
"form": form,
})
3
Example 17
@check_comment_editable
def edit_comment(request, comment_id=None, comment=None):
if not request.user.is_active:
raise PermissionDenied
if settings.COMMENTS_OPEN == False:
raise PermissionDenied("Comments are disabled currently.")
form = CommentForm(request.POST or None, initial={
'comment': comment.comment
})
if form.is_valid():
comment.comment = form.cleaned_data['comment']
comment.modified = datetime.datetime.now()
comment.save()
return redirect(comment.get_absolute_url())
return render(request, "comments/edit_comment.html", {
'comment': comment,
'form': form,
})
3
Example 18
def get_redirect_url(self, pk, commit_pk):
vt = get_object_or_404(self.get_queryset(), pk=pk)
commit = get_object_or_404(vt.commits.select_related('root_node'),
pk=commit_pk)
commit.tracker = vt
if not self.site.has_change_permission(self.request, commit.reviewedversioncommit):
raise PermissionDenied(_("You don't have permission to approve commits."))
self.action(commit)
history_url = self.site.reverse(self.site.history_view, kwargs={
'pk': vt.pk
})
messages.success(self.request, self.get_message(commit, history_url))
return history_url
3
Example 19
Project: django-shop Source File: order.py
def filter_from_request(self, request):
"""
Return a queryset containing the orders for the customer associated with the given
request object.
"""
if request.customer.is_visitor():
msg = _("Only signed in customers can view their orders")
raise PermissionDenied(msg)
return self.get_queryset().filter(customer=request.customer).order_by('-updated_at', )
3
Example 20
def destroy(self, request, *args, **kwargs):
self.object = self.get_object()
if isinstance(self.object, XForm):
raise ParseError(_(u"Data id not provided."))
elif isinstance(self.object, Instance):
if request.user.has_perm("delete_xform", self.object.xform):
self.object.delete()
else:
raise PermissionDenied(_(u"You do not have delete "
u"permissions."))
return Response(status=status.HTTP_204_NO_CONTENT)
3
Example 21
def queryset(self, request, queryset):
try:
value = int(self.value())
except TypeError:
value = None
if value:
# ensure the content type is allowed
for choice_value, _ in self.lookup_choices:
if choice_value == value:
return queryset.filter(polymorphic_ctype_id=choice_value)
raise PermissionDenied(
'Invalid ContentType "{0}". It must be registered as child model.'.format(value))
return queryset
3
Example 22
def _get_real_admin_by_model(self, model_class):
# In case of a ?ct_id=### parameter, the view is already checked for permissions.
# Hence, make sure this is a derived object, or risk exposing other admin interfaces.
if model_class not in self._child_models:
raise PermissionDenied("Invalid model '{0}', it must be registered as child model.".format(model_class))
try:
# HACK: the only way to get the instance of an model admin,
# is to read the registry of the AdminSite.
return self._child_admin_site._registry[model_class]
except KeyError:
raise ChildAdminNotRegistered("No child admin site was registered for a '{0}' model.".format(model_class))
3
Example 23
Project: pleft Source File: views.py
@never_cache
def appointment_menu(request):
user = plauth.models.User.get_signed_in(request)
if not user:
raise exceptions.PermissionDenied
memkey = plapp.get_menu_cache_key(user)
data = cache.get(memkey)
if not data:
appts = plapp.models.Appointment.get_unarchived_for_user(user)
data = ','.join(['[%s,"%s"]' % (app.id, html.escape(app.get_title()))
for app in appts])
data = '[%s]' % data
cache.set(memkey, data, 60*60*24*7)
return http.HttpResponse('{"a":%s}' % data, mimetype='application/javascript')
3
Example 24
Project: inthe.am Source File: decorators.py
def process_authentication(required=True):
def authenticate(f):
@wraps(f)
def wrapper(self, request, *args, **kwargs):
self._meta.authentication.is_authenticated(request)
if required and not request.user.is_authenticated():
raise PermissionDenied()
return f(self, request, *args, **kwargs)
return wrapper
return authenticate
3
Example 25
def dispatch(self, request, *args, **kwargs):
self.request = request
self.args = args
self.kwargs = kwargs
self.organization = self.get_organization()
if not self.organization.is_member(request.user) and not \
request.user.is_superuser:
raise PermissionDenied(_("Wrong organization"))
return super(MembershipRequiredMixin, self).dispatch(request, *args,
**kwargs)
3
Example 26
Project: django-cms Source File: api.py
def publish_page(page, user, language):
"""
Publish a page. This sets `page.published` to `True` and calls publish()
which does the actual publishing.
See docs/extending_cms/api_reference.rst for more info
"""
page = page.reload()
if not page.has_publish_permission(user):
raise PermissionDenied()
# Set the current_user to have the page's changed_by
# attribute set correctly.
# 'user' is a user object, but current_user() just wants the username (a string).
with current_user(user.get_username()):
page.publish(language)
return page.reload()
3
Example 27
def update_story(self, obj_id, status):
obj = self.get_object()
if obj is not None:
if not obj.has_perm(self.request.user, 'change'):
raise PermissionDenied(_(u"You are not authorized to edit this story"))
obj.status = status
obj.save()
3
Example 28
def dispatch(self, request, *args, **kwargs):
self.request = request
self.args = args
self.kwargs = kwargs
self.organization = self.get_organization()
if self.organization.owner.organization_user.user != request.user \
and not request.user.is_superuser:
raise PermissionDenied(_("You are not the organization owner"))
return super(OwnerRequiredMixin, self).dispatch(request, *args,
**kwargs)
3
Example 29
def flush(self):
"""
Remove all lines from basket.
"""
if self.status == self.FROZEN:
raise PermissionDenied("A frozen basket cannot be flushed")
self.lines.all().delete()
self._lines = None
3
Example 30
Project: SchoolIdolAPI Source File: views.py
@detail_route(methods=['POST', 'DELETE'])
def follow(self, request, username=None):
if not request.user.is_authenticated():
raise PermissionDenied()
user = get_object_or_404(User, username=username)
if request.method == 'POST':
request.user.preferences.following.add(user)
request.user.preferences.save()
return JsonResponse({'follow': 'followed'})
if request.method == 'DELETE':
request.user.preferences.following.remove(user)
request.user.preferences.save()
return JsonResponse({'follow': 'unfollowed'})
3
Example 31
Project: django-oscar-api Source File: middleware.py
def process_request(self, request):
if self.is_api_request(request):
key = authentication.get_authorization_header(request)
if models.ApiKey.objects.filter(key=key).exists():
return None
logger.error('Invalid credentials provided for %s:%s by %s' % (
request.method,
request.path,
request.META.get('REMOTE_ADDR', '<unknown>')
))
raise PermissionDenied()
return None
3
Example 32
Project: open-synthesis Source File: auth.py
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 has_edit_authorization(request, board, has_creator=has_creator):
pass
else:
raise PermissionDenied()
3
Example 33
def get_object(self, queryset=None):
object = super(OrganizationRequestDetail, self).get_object(queryset)
profile = self.request.user.profile
if object.user_id != profile.id and not object.organization.admins.filter(id=profile.id).exists():
raise PermissionDenied()
return object
3
Example 34
Project: pretix Source File: permissions.py
def administrator_permission_required():
"""
This view decorator rejects all requests with a 403 response which are not from
users with the is_superuser flag.
"""
def decorator(function):
def wrapper(request, *args, **kw):
if not request.user.is_authenticated: # NOQA
# just a double check, should not ever happen
raise PermissionDenied()
if not request.user.is_superuser:
raise PermissionDenied(_('You do not have permission to view this content.'))
return function(request, *args, **kw)
return wrapper
return decorator
3
Example 35
def update_in_place(self, request, original_bundle, new_data):
"""
Override to restrict patching of user fields to those specified in allowed_update_fields
"""
if set(new_data.keys()) - set(self._meta.allowed_update_fields):
raise PermissionDenied(
'Kun oppdatering av %s er tillatt.' % ', '.join(self._meta.allowed_update_fields)
)
# logging.getLogger(__name__).debug('User patched: %s' % str(original_bundle))
return super(UserResource, self).update_in_place(request, original_bundle, new_data)
3
Example 36
def __call__(self, method):
perms = self.perms
@wraps(method)
def wrapped(self, request, *args, **kwargs):
for perm in perms:
if not request.user.has_perm(perm):
raise PermissionDenied()
return method(self, request, *args, **kwargs)
return wrapped
3
Example 37
Project: formly Source File: design.py
@require_POST
@login_required
def survey_change_name(request, pk):
"""
Works well with:
http://www.appelsiini.net/projects/jeditable
"""
survey = get_object_or_404(Survey, pk=pk)
if not request.user.has_perm("formly.change_survey_name", obj=survey):
raise PermissionDenied()
survey.name = request.POST.get("name")
survey.save()
return HttpResponse(json.dumps({
"status": "OK",
"name": survey.name
}), mimetype="application/json")
3
Example 38
def permission_denied(self, debug_message=""):
"""
Raises a PermissionDenied exception to trigger the 403 forbidden
response machinery. Even though this raises an exception, it is
recommended to return it for stylistic consistency:
return self.permission_denied()
"""
raise exceptions.PermissionDenied(debug_message)
3
Example 39
Project: feincms Source File: models.py
def delete(self, *args, **kwargs):
if not settings.FEINCMS_SINGLETON_TEMPLATE_DELETION_ALLOWED:
if self.template.singleton:
raise PermissionDenied(_(
'This %(page_class)s uses a singleton template, and '
'FEINCMS_SINGLETON_TEMPLATE_DELETION_ALLOWED=False' % {
'page_class': self._meta.verbose_name}))
super(BasePage, self).delete(*args, **kwargs)
3
Example 40
def hide_comment(self, comment):
""" `comment` can be a Comment instance, CommentDetails instance, or comment ID. """
user = User.objects.get(id=self.user_id)
if not is_dismissable(comment, user):
raise PermissionDenied("User cannot dismiss this comment.")
try:
self.sadd(comment.id)
except AttributeError:
self.sadd(comment)
3
Example 41
def put(self, request, app_label, object_name, object_pk):
obj = self.get_object(app_label, object_name, object_pk)
if not self.site.has_change_permission(request, obj):
raise PermissionDenied(_("You don't have permission to edit this widget."))
data = self.data()['attributes']
form = obj.get_form(request, data=data)
if not form.is_valid():
raise ValidationError(form.errors)
form.save()
return self.render_to_response(form.instance.to_json(self.site),
status=200)
3
Example 42
Project: django-allauth Source File: models.py
@classmethod
def verify_and_unstash_state(cls, request, verifier):
if 'socialaccount_state' not in request.session:
raise PermissionDenied()
state, verifier2 = request.session.pop('socialaccount_state')
if verifier != verifier2:
raise PermissionDenied()
return state
3
Example 43
def staff_required(fn):
@login_required
@wraps(fn)
def wrapper(request, *args, **kwargs):
if not request.user.is_staff:
raise PermissionDenied("You are not an admin")
return fn(request, *args, **kwargs)
return wrapper
3
Example 44
Project: osf.io Source File: utils.py
def handle_no_permission(self):
if not self.request.user.is_authenticated():
return redirect_to_login(self.request.get_full_path(),
self.get_login_url(),
self.get_redirect_field_name())
else:
raise PermissionDenied(self.get_permission_denied_message())
3
Example 45
Project: smart_server Source File: direct_access.py
def session_from_direct_url(request):
token = request.GET['token']
p = request.GET.get("pin", None)
login_token = RecordDirectAccessToken.objects.get(token=token)
if (login_token.token_secret != p):
raise PermissionDenied("Wrong pin for token")
# TODO: move this to security function on chrome consumer
if (datetime.datetime.utcnow() > login_token.expires_at):
return HttpResponseForbidden("Expired token %s" % token)
session_token = SESSION_OAUTH_SERVER.generate_and_preauthorize_access_token(request.principal, user=login_token.account)
session_token.save()
return render_template('login_token', {'record': login_token.record, 'token': str(session_token)}, type='xml')
3
Example 46
Project: django-allauth Source File: models.py
@classmethod
def unstash_state(cls, request):
if 'socialaccount_state' not in request.session:
raise PermissionDenied()
state, verifier = request.session.pop('socialaccount_state')
return state
3
Example 47
Project: django-private-files Source File: views.py
def get_file(request, app_label, model_name, field_name, object_id, filename):
model = get_model(app_label, model_name)
instance = get_object_or_404(model, pk =unquote(object_id))
condition = getattr(instance, field_name).condition
if not model:
raise Http404("")
if not hasattr(instance, field_name):
raise Http404("")
if condition(request, instance):
pre_download.send(sender = model, instance = instance, field_name = field_name, request = request)
return METHOD(request, instance, field_name)
else:
raise PermissionDenied()
3
Example 48
def me(self, request, *args, **kwargs):
if request.user.is_authenticated():
if 'expand_accounts' in request.GET:
request.user.all_accounts = request.user.accounts_set.all()
if 'expand_links' in request.GET:
request.user.all_links = request.user.links.all()
serializer = serializers.UserSerializer(request.user, context={'request':request})
return Response(serializer.data)
raise PermissionDenied()
3
Example 49
def dispatch(self, request, *args, **kwargs):
self.request = request
self.args = args
self.kwargs = kwargs
self.organization = self.get_organization()
if not self.organization.is_admin(request.user) and not \
request.user.is_superuser:
raise PermissionDenied(_("Sorry, admins only"))
return super(AdminRequiredMixin, self).dispatch(request, *args,
**kwargs)
3
Example 50
def get_object(self):
"""Retrieve the object by it's model specific id instead of pk"""
queryset = self.get_queryset()
obj_id_name = 'story_id'
obj_id = self.kwargs.get(obj_id_name, None)
if obj_id is not None:
filter_args = {obj_id_name: obj_id}
queryset = queryset.filter(**filter_args)
try:
obj = queryset.get()
except ObjectDoesNotExist:
raise Http404(_(u"No %(verbose_name)s found matching the query") %
{'verbose_name': queryset.model._meta.verbose_name})
if not obj.has_perm(self.request.user, 'change'):
raise PermissionDenied(_(u"You are not authorized to edit this story"))
return obj
else:
return None