本文整理汇总了Python中django.core.exceptions.SuspiciousOperation方法的典型用法代码示例。如果您正苦于以下问题:Python exceptions.SuspiciousOperation方法的具体用法?Python exceptions.SuspiciousOperation怎么用?Python exceptions.SuspiciousOperation使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.core.exceptions
的用法示例。
在下文中一共展示了exceptions.SuspiciousOperation方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: edit_team
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import SuspiciousOperation [as 别名]
def edit_team(request, team_id):
"""Return a team edit view, or handle the form submission."""
# TODO: if user turns off invitation-required, let everyone in who had outstanding membership requests
team = get_object_or_404(Team, pk=team_id)
if team.owner_id is None or team.owner_id != request.user.id:
raise SuspiciousOperation(_('User is not the owner of the team'))
if request.method == 'POST':
form = TeamCreateForm(request.POST, instance=team)
if form.is_valid():
form.save()
messages.success(request, _('Updated team information'))
return HttpResponseRedirect(reverse('openach:view_team', args=(team.id,)))
else:
form = TeamCreateForm(instance=team)
return render(request, 'teams/edit_team.html', context={
'team': team,
'form': form
})
示例2: invite_members
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import SuspiciousOperation [as 别名]
def invite_members(request, team_id):
"""Return a team edit view, or handle the form submission."""
team = get_object_or_404(Team, pk=team_id)
if team.owner_id is None or team.owner_id != request.user.id:
raise SuspiciousOperation(_('User is not the owner of the team'))
if request.method == 'POST':
form = TeamInviteForm(request.POST, team=team)
if form.is_valid():
to_invite = form.cleaned_data['members']
invites = [TeamRequest(team=team, inviter=request.user, invitee=x) for x in to_invite]
TeamRequest.objects.bulk_create(invites)
for user in to_invite:
notify.send(request.user, recipient=user, actor=request.user, verb='invite', action_object=team, target=user)
messages.success(request, _('Invited {count} members to the team').format(count=len(to_invite)))
return HttpResponseRedirect(reverse('openach:view_team', args=(team.id,)))
else:
form = TeamInviteForm(team=team)
return render(request, 'teams/invite.html', context={
'team': team,
'form': form
})
示例3: decide_invitation
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import SuspiciousOperation [as 别名]
def decide_invitation(request, invite_id):
invite = get_object_or_404(TeamRequest, pk=invite_id)
team = invite.team
if team.owner_id is None or team.owner_id != request.user.id:
raise SuspiciousOperation(_('User is not the owner of the team'))
elif 'accept' in request.POST:
invite.team.members.add(invite.invitee)
invite.team.save()
notify.send(request.user, recipient=invite.invitee, actor=request.user, verb='accept', action_object=team, target=invite.invitee)
messages.success(request, _('Added {name} to the team').format(name=invite.invitee.username))
elif 'reject' in request.POST:
notify.send(request.user, recipient=invite.invitee, actor=request.user, verb='reject', action_object=team, target=invite.invitee)
messages.success(request, _('Ignored {name}\'s team membership request').format(name=invite.invitee.username))
else:
return HttpResponseBadRequest(_('POST request must include either "{accept}" or "{reject}"').format(accept='accept', reject='reject'))
invite.delete()
return HttpResponseRedirect(reverse('openach:view_team', args=(team.id,)))
示例4: revoke_membership
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import SuspiciousOperation [as 别名]
def revoke_membership(request, team_id, member_id):
team = get_object_or_404(Team, pk=team_id)
user = get_object_or_404(User, pk=member_id)
if team.owner_id is None or team.owner_id != request.user.id:
raise SuspiciousOperation(_('User is not the owner of the team'))
elif user == team.owner:
raise SuspiciousOperation(_('Cannot remove the owner from the team'))
elif not team.invitation_required:
raise SuspiciousOperation(_('Cannot remove user from teams that don\'t require an invitation'))
team.members.remove(user)
team.save()
notify.send(request.user, recipient=user, actor=request.user, verb='remove', action_object=team, target=user)
messages.success(request, _('Removed {name} from team').format(name=user.username))
return HttpResponseRedirect(reverse('openach:view_team', args=(team.id,)))
示例5: join_team
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import SuspiciousOperation [as 别名]
def join_team(request, team_id):
team = get_object_or_404(Team, pk=team_id)
if team.members.filter(id=request.user.id).exists():
raise SuspiciousOperation(_('User is already a member of the team'))
elif TeamRequest.objects.filter(invitee=request.user, inviter__isnull=False, team=team).exists() or not team.invitation_required:
team.members.add(request.user)
team.save()
TeamRequest.objects.filter(invitee=request.user, team=team).delete()
messages.success(request, _('Joined team {name}').format(name=team.name))
return HttpResponseRedirect(reverse('openach:view_team', args=(team.id,)))
elif TeamRequest.objects.filter(invitee=request.user, team=team).exists():
return HttpResponseBadRequest(_('User already has a membership request with the team'))
else:
TeamRequest.objects.create(invitee=request.user, team=team)
if team.owner:
notify.send(request.user, recipient=team.owner, actor=request.user, verb='request_membership', target=team)
messages.success(request, _('Requested invitation to team {name}').format(name=team.name))
return HttpResponseRedirect(reverse('openach:view_team', args=(team.id,)))
示例6: decode
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import SuspiciousOperation [as 别名]
def decode(self, session_data):
encoded_data = base64.b64decode(force_bytes(session_data))
try:
# could produce ValueError if there is no ':'
hash, serialized = encoded_data.split(b':', 1)
expected_hash = self._hash(serialized)
if not constant_time_compare(hash.decode(), expected_hash):
raise SuspiciousSession("Session data corrupted")
else:
return self.serializer().loads(serialized)
except Exception as e:
# ValueError, SuspiciousOperation, unpickling exceptions. If any of
# these happen, just return an empty dictionary (an empty session).
if isinstance(e, SuspiciousOperation):
logger = logging.getLogger('django.security.%s' %
e.__class__.__name__)
logger.warning(force_text(e))
return {}
示例7: _normalize_name
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import SuspiciousOperation [as 别名]
def _normalize_name(self, name):
"""
Normalizes the name so that paths like /path/to/ignored/../foo.txt
work. We check to make sure that the path pointed to is not outside
the directory specified by the LOCATION setting.
"""
if name.startswith("https://") or name.startswith("http://"):
return name
base_path = force_text(self.location)
base_path = base_path.rstrip('/')
final_path = urljoin(base_path.rstrip('/') + "/", name)
base_path_len = len(base_path)
if (not final_path.startswith(base_path) or
final_path[base_path_len:base_path_len + 1] not in ('', '/')):
raise SuspiciousOperation("Attempted access to '%s' denied." %
name)
return final_path.lstrip('/')
示例8: skip_suspicious_operations
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import SuspiciousOperation [as 别名]
def skip_suspicious_operations(record):
"""Prevent django from sending 500 error
email notifications for SuspiciousOperation
events, since they are not true server errors,
especially when related to the ALLOWED_HOSTS
configuration
background and more information:
http://www.tiwoc.de/blog/2013/03/django-prevent-email-notification-on-susp\
iciousoperation/
"""
if record.exc_info:
exc_value = record.exc_info[1]
if isinstance(exc_value, SuspiciousOperation):
return False
return True
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
示例9: get_userinfo_or_introspection
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import SuspiciousOperation [as 别名]
def get_userinfo_or_introspection(self, access_token):
try:
claims = self.cached_request(
self.get_userinfo, access_token, "auth.userinfo"
)
except requests.HTTPError as e:
if not (
e.response.status_code in [401, 403] and settings.OIDC_CHECK_INTROSPECT
):
raise e
# check introspection if userinfo fails (confidental client)
claims = self.cached_request(
self.get_introspection, access_token, "auth.introspection"
)
if "client_id" not in claims:
raise SuspiciousOperation("client_id not present in introspection")
return claims
示例10: decode
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import SuspiciousOperation [as 别名]
def decode(self, session_data):
encoded_data = base64.b64decode(force_bytes(session_data))
try:
# could produce ValueError if there is no ':'
hash, serialized = encoded_data.split(b':', 1)
expected_hash = self._hash(serialized)
if not constant_time_compare(hash.decode(), expected_hash):
raise SuspiciousSession("Session data corrupted")
else:
return self.serializer().loads(serialized)
except Exception as e:
# ValueError, SuspiciousOperation, unpickling exceptions. If any of
# these happen, just return an empty dictionary (an empty session).
if isinstance(e, SuspiciousOperation):
logger = logging.getLogger('django.security.%s' % e.__class__.__name__)
logger.warning(str(e))
return {}
示例11: load
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import SuspiciousOperation [as 别名]
def load(self):
session_data = {}
try:
with open(self._key_to_file(), "rb") as session_file:
file_data = session_file.read()
# Don't fail if there is no data in the session file.
# We may have opened the empty placeholder file.
if file_data:
try:
session_data = self.decode(file_data)
except (EOFError, SuspiciousOperation) as e:
if isinstance(e, SuspiciousOperation):
logger = logging.getLogger('django.security.%s' % e.__class__.__name__)
logger.warning(str(e))
self.create()
# Remove expired sessions.
expiry_age = self.get_expiry_age(expiry=self._expiry_date(session_data))
if expiry_age <= 0:
session_data = {}
self.delete()
self.create()
except (IOError, SuspiciousOperation):
self._session_key = None
return session_data
示例12: load
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import SuspiciousOperation [as 别名]
def load(self):
try:
data = self._cache.get(self.cache_key)
except Exception:
# Some backends (e.g. memcache) raise an exception on invalid
# cache keys. If this happens, reset the session. See #17810.
data = None
if data is None:
# Duplicate DBStore.load, because we need to keep track
# of the expiry date to set it properly in the cache.
try:
s = self.model.objects.get(
session_key=self.session_key,
expire_date__gt=timezone.now()
)
data = self.decode(s.session_data)
self._cache.set(self.cache_key, data, self.get_expiry_age(expiry=s.expire_date))
except (self.model.DoesNotExist, SuspiciousOperation) as e:
if isinstance(e, SuspiciousOperation):
logger = logging.getLogger('django.security.%s' % e.__class__.__name__)
logger.warning(str(e))
self._session_key = None
data = {}
return data
示例13: _normalize_name
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import SuspiciousOperation [as 别名]
def _normalize_name(self, name):
"""
Normalizes the name so that paths like /path/to/ignored/../foo.txt
work. We check to make sure that the path pointed to is not outside
the directory specified by the LOCATION setting.
"""
base_path = force_text(self.location)
base_path = base_path.rstrip('/')
final_path = urljoin(base_path.rstrip('/') + "/", name)
base_path_len = len(base_path)
if (not final_path.startswith(base_path) or
final_path[base_path_len:base_path_len + 1] not in ('', '/')):
raise SuspiciousOperation("Attempted access to '%s' denied." %
name)
return final_path.lstrip('/')
示例14: test_get_auth_failure_tampered_session_state
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import SuspiciousOperation [as 别名]
def test_get_auth_failure_tampered_session_state(self):
"""Test authentication failure attempt for an inactive user."""
user = User.objects.create_user('example_username')
user.is_active = False
user.save()
get_data = {
'code': 'example_code',
'state': 'example_state'
}
url = reverse('oidc_authentication_callback')
request = self.factory.get(url, get_data)
request.session = {
'oidc_state': 'tampered_state'
}
callback_view = views.OIDCAuthenticationCallbackView.as_view()
with self.assertRaises(SuspiciousOperation) as context:
callback_view(request)
expected_error_message = 'Session `oidc_state` does not match the OIDC callback state'
self.assertEqual(context.exception.args, (expected_error_message,))
示例15: test_allowed_unsecured_invalid_token
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import SuspiciousOperation [as 别名]
def test_allowed_unsecured_invalid_token(self):
"""Test payload data from invalid secure token (unsecured allowed)."""
header = force_bytes(json.dumps({'alg': 'HS256', 'typ': 'JWT'}))
payload = force_bytes(json.dumps({'foo': 'bar'}))
# Compute signature
key = b'mysupersecuretestkey'
fake_key = b'mysupersecurefaketestkey'
h = hmac.HMAC(key, hashes.SHA256(), backend=default_backend())
msg = '{}.{}'.format(smart_text(b64encode(header)), smart_text(b64encode(payload)))
h.update(force_bytes(msg))
signature = b64encode(h.finalize())
token = '{}.{}.{}'.format(
smart_text(b64encode(header)),
smart_text(b64encode(payload)),
smart_text(signature)
)
token_bytes = force_bytes(token)
key_text = smart_text(fake_key)
with self.assertRaises(SuspiciousOperation) as ctx:
self.backend.get_payload_data(token_bytes, key_text)
self.assertEqual(ctx.exception.args[0], 'JWS token verification failed.')