本文整理汇总了Python中django.core.exceptions.PermissionDenied方法的典型用法代码示例。如果您正苦于以下问题:Python exceptions.PermissionDenied方法的具体用法?Python exceptions.PermissionDenied怎么用?Python exceptions.PermissionDenied使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.core.exceptions
的用法示例。
在下文中一共展示了exceptions.PermissionDenied方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: board_history
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import PermissionDenied [as 别名]
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})
示例2: view_team
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import PermissionDenied [as 别名]
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,
})
示例3: update_model_from_json
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import PermissionDenied [as 别名]
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
示例4: generate_pdf
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import PermissionDenied [as 别名]
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)
示例5: change_event_status
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import PermissionDenied [as 别名]
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())
示例6: view_attachment
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import PermissionDenied [as 别名]
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
示例7: delete
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import PermissionDenied [as 别名]
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)
示例8: get_init_widget
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import PermissionDenied [as 别名]
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
示例9: authenticate
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import PermissionDenied [as 别名]
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))
示例10: permission_required
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import PermissionDenied [as 别名]
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)
示例11: test_access_empty_intersection
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import PermissionDenied [as 别名]
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)
示例12: process_request
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import PermissionDenied [as 别名]
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})
示例13: do_download_archive
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import PermissionDenied [as 别名]
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
示例14: toggle_status
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import PermissionDenied [as 别名]
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})
示例15: check_submission_permissions
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import PermissionDenied [as 别名]
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}))