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()
python类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 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.
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 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(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 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 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 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 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(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 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 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 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.
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 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)