本文整理汇总了Python中django.utils.crypto.constant_time_compare方法的典型用法代码示例。如果您正苦于以下问题:Python crypto.constant_time_compare方法的具体用法?Python crypto.constant_time_compare怎么用?Python crypto.constant_time_compare使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.utils.crypto
的用法示例。
在下文中一共展示了crypto.constant_time_compare方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: verify
# 需要导入模块: from django.utils import crypto [as 别名]
# 或者: from django.utils.crypto import constant_time_compare [as 别名]
def verify(self):
data = self._data
signature = data.get(self.SIGNATURE_FIELD, None)
if signature is None:
raise BadSignature()
expected_signature = self.calculate_signature()
if not constant_time_compare(signature, expected_signature):
raise BadSignature()
valid_period = self.get_valid_period()
if self.USE_TIMESTAMP and valid_period is not None:
timestamp = data[self.TIMESTAMP_FIELD]
timestamp = int(timestamp)
current_timestamp = get_current_timestamp()
valid_period_secs = valid_period.total_seconds()
if current_timestamp - timestamp > valid_period_secs:
raise SignatureExpired()
示例2: _decode
# 需要导入模块: from django.utils import crypto [as 别名]
# 或者: from django.utils.crypto import constant_time_compare [as 别名]
def _decode(self, data):
"""
Safely decodes an encoded text stream back into a list of messages.
If the encoded text stream contained an invalid hash or was in an
invalid format, ``None`` is returned.
"""
if not data:
return None
bits = data.split('$', 1)
if len(bits) == 2:
hash, value = bits
if constant_time_compare(hash, self._hash(value)):
try:
# If we get here (and the JSON decode works), everything is
# good. In any other case, drop back and return None.
return json.loads(value, cls=MessageDecoder)
except ValueError:
pass
# Mark the data as used (so it gets removed) since something was wrong
# with the data.
self.used = True
return None
示例3: check_token
# 需要导入模块: from django.utils import crypto [as 别名]
# 或者: from django.utils.crypto import constant_time_compare [as 别名]
def check_token(self, user, token):
"""
Check that a password reset token is correct for a given user.
"""
# Parse the token
try:
ts_b36, hash = token.split("-")
except ValueError:
return False
try:
ts = base36_to_int(ts_b36)
except ValueError:
return False
# Check that the timestamp/uid has not been tampered with
if not constant_time_compare(self._make_token_with_timestamp(user, ts), token):
return False
# Check the timestamp is within limit
if (self._num_days(self._today()) - ts) > settings.PASSWORD_RESET_TIMEOUT_DAYS:
return False
return True
示例4: _decode
# 需要导入模块: from django.utils import crypto [as 别名]
# 或者: from django.utils.crypto import constant_time_compare [as 别名]
def _decode(self, data):
"""
Safely decode an encoded text stream back into a list of messages.
If the encoded text stream contained an invalid hash or was in an
invalid format, return None.
"""
if not data:
return None
bits = data.split('$', 1)
if len(bits) == 2:
hash, value = bits
if constant_time_compare(hash, self._hash(value)):
try:
# If we get here (and the JSON decode works), everything is
# good. In any other case, drop back and return None.
return json.loads(value, cls=MessageDecoder)
except ValueError:
pass
# Mark the data as used (so it gets removed) since something was wrong
# with the data.
self.used = True
return None
示例5: check_token
# 需要导入模块: from django.utils import crypto [as 别名]
# 或者: from django.utils.crypto import constant_time_compare [as 别名]
def check_token(self, user, token):
"""
Check that a activation token is correct for a given user.
"""
# Parse the token
try:
ts_b36, hash = token.split('-')
except ValueError:
return False
try:
ts = base36_to_int(ts_b36)
except ValueError:
return False
# Check that the timestamp/uid has not been tampered with
if not constant_time_compare(self._make_token_with_timestamp(user, ts), token):
return False
# Check the timestamp is within limit
if (self._num_days(self._today()) - ts) > settings.USERS_EMAIL_CONFIRMATION_TIMEOUT_DAYS:
return False
return True
示例6: complete_zoom_user_in_realm
# 需要导入模块: from django.utils import crypto [as 别名]
# 或者: from django.utils.crypto import constant_time_compare [as 别名]
def complete_zoom_user_in_realm(
request: HttpRequest,
code: str = REQ(),
state: Dict[str, str] = REQ(validator=check_dict([("sid", check_string)], value_validator=check_string)),
) -> HttpResponse:
if not constant_time_compare(state["sid"], get_zoom_sid(request)):
raise JsonableError(_("Invalid Zoom session identifier"))
oauth = get_zoom_session(request.user)
try:
token = oauth.fetch_token(
"https://zoom.us/oauth/token",
code=code,
client_secret=settings.VIDEO_ZOOM_CLIENT_SECRET,
)
except OAuth2Error:
raise JsonableError(_("Invalid Zoom credentials"))
do_set_zoom_token(request.user, token)
return render(request, "zerver/close_window.html")
示例7: _decode
# 需要导入模块: from django.utils import crypto [as 别名]
# 或者: from django.utils.crypto import constant_time_compare [as 别名]
def _decode(self, data):
"""
Safely decode an encoded text stream back into a list of messages.
If the encoded text stream contained an invalid hash or was in an
invalid format, return None.
"""
if not data:
return None
bits = data.split('$', 1)
if len(bits) == 2:
hash, value = bits
if constant_time_compare(hash, self._hash(value)):
try:
# If we get here (and the JSON decode works), everything is
# good. In any other case, drop back and return None.
return json.loads(value, cls=MessageDecoder)
except json.JSONDecodeError:
pass
# Mark the data as used (so it gets removed) since something was wrong
# with the data.
self.used = True
return None
示例8: get_user
# 需要导入模块: from django.utils import crypto [as 别名]
# 或者: from django.utils.crypto import constant_time_compare [as 别名]
def get_user(request):
"""
Returns the user model instance associated with the given request session.
If no user is retrieved an instance of `AnonymousUser` is returned.
"""
from .models import AnonymousUser
user = None
try:
user_id = _get_user_session_key(request)
backend_path = request.session[BACKEND_SESSION_KEY]
except KeyError:
pass
else:
if backend_path in settings.AUTHENTICATION_BACKENDS:
backend = load_backend(backend_path)
user = backend.get_user(user_id)
# Verify the session
if ('django.contrib.auth.middleware.SessionAuthenticationMiddleware'
in settings.MIDDLEWARE_CLASSES and hasattr(user, 'get_session_auth_hash')):
session_hash = request.session.get(HASH_SESSION_KEY)
session_hash_verified = session_hash and constant_time_compare(
session_hash,
user.get_session_auth_hash()
)
if not session_hash_verified:
request.session.flush()
user = None
return user or AnonymousUser()
示例9: unsign
# 需要导入模块: from django.utils import crypto [as 别名]
# 或者: from django.utils.crypto import constant_time_compare [as 别名]
def unsign(self, signed_value):
signed_value = force_str(signed_value)
if self.sep not in signed_value:
raise BadSignature('No "%s" found in value' % self.sep)
value, sig = signed_value.rsplit(self.sep, 1)
if constant_time_compare(sig, self.signature(value)):
return force_text(value)
raise BadSignature('Signature "%s" does not match' % sig)
示例10: _compare_salted_tokens
# 需要导入模块: from django.utils import crypto [as 别名]
# 或者: from django.utils.crypto import constant_time_compare [as 别名]
def _compare_salted_tokens(request_csrf_token, csrf_token):
# Assume both arguments are sanitized -- that is, strings of
# length CSRF_TOKEN_LENGTH, all CSRF_ALLOWED_CHARS.
return constant_time_compare(
_unsalt_cipher_token(request_csrf_token),
_unsalt_cipher_token(csrf_token),
)
示例11: get_user
# 需要导入模块: from django.utils import crypto [as 别名]
# 或者: from django.utils.crypto import constant_time_compare [as 别名]
def get_user(request):
"""
Return the user model instance associated with the given request session.
If no user is retrieved, return an instance of `AnonymousUser`.
"""
from .models import AnonymousUser
user = None
try:
user_id = _get_user_session_key(request)
backend_path = request.session[BACKEND_SESSION_KEY]
except KeyError:
pass
else:
if backend_path in settings.AUTHENTICATION_BACKENDS:
backend = load_backend(backend_path)
user = backend.get_user(user_id)
# Verify the session
if hasattr(user, 'get_session_auth_hash'):
session_hash = request.session.get(HASH_SESSION_KEY)
session_hash_verified = session_hash and constant_time_compare(
session_hash,
user.get_session_auth_hash()
)
if not session_hash_verified:
request.session.flush()
user = None
return user or AnonymousUser()
示例12: check_token
# 需要导入模块: from django.utils import crypto [as 别名]
# 或者: from django.utils.crypto import constant_time_compare [as 别名]
def check_token(self, user, token):
"""
Check that a password reset token is correct for a given user.
"""
if not (user and token):
return False
# Parse the token
try:
ts_b36, hash = token.split("-")
except ValueError:
return False
try:
ts = base36_to_int(ts_b36)
except ValueError:
return False
# Check that the timestamp/uid has not been tampered with
if not constant_time_compare(self._make_token_with_timestamp(user, ts), token):
return False
# Check the timestamp is within limit
if (self._num_days(self._today()) - ts) > settings.PASSWORD_RESET_TIMEOUT_DAYS:
return False
return True
示例13: has_sudo_privileges
# 需要导入模块: from django.utils import crypto [as 别名]
# 或者: from django.utils.crypto import constant_time_compare [as 别名]
def has_sudo_privileges(request):
"""
Check if a request is allowed to perform sudo actions
"""
if getattr(request, "_sudo", None) is None:
try:
request._sudo = request.user.is_authenticated() and constant_time_compare(
request.get_signed_cookie(
COOKIE_NAME, salt=COOKIE_SALT, max_age=COOKIE_AGE
),
request.session[COOKIE_NAME],
)
except (KeyError, BadSignature):
request._sudo = False
return request._sudo
示例14: unsign
# 需要导入模块: from django.utils import crypto [as 别名]
# 或者: from django.utils.crypto import constant_time_compare [as 别名]
def unsign(self, signed_value):
signed_value = force_str(signed_value)
if self.sep not in signed_value:
raise BadSignature('No "%s" found in value' % self.sep)
value, sig = signed_value.rsplit(self.sep, 1)
if constant_time_compare(sig, self.signature(value)):
return force_str(value)
raise BadSignature('Signature "%s" does not match' % sig)
示例15: update_settings
# 需要导入模块: from django.utils import crypto [as 别名]
# 或者: from django.utils.crypto import constant_time_compare [as 别名]
def update_settings(request):
is_ok = None
if request.method == 'POST': # Confirmed from mail link
is_ok = 'yes' in request.POST
username = request.POST.get('username')
token = request.POST.get('token')
elif request.method == 'GET': # Clicked on mail link
username = request.GET.get('username')
token = request.GET.get('token')
expected_token = compute_token(NEWS_SALT, username)
if not constant_time_compare(token, expected_token):
# If the token is invalid, add an error message
messages.error(request,
'Vous n\'êtes pas autorisé à effectuer cette action.')
return render(request, 'settings.html', status=401) # Unauthorized
elif is_ok is not None:
message = 'Votre profil a bien été mis à jour. '
if is_ok:
message += 'Profitez bien de Mangaki !'
else:
message += 'Vous ne recevrez plus de mails de notre part.'
Profile.objects.filter(
user__username=username).update(newsletter_ok=is_ok)
messages.success(request, message)
return render(request, 'settings.html')
return render(request, 'settings.html', {'username': username,
'token': token})