Here are the examples of the python api django.utils.crypto.constant_time_compare taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
56 Examples
3
Source : hashers.py
with GNU General Public License v3.0
from Aghoreshwar
with GNU General Public License v3.0
from Aghoreshwar
def verify(self, password, encoded):
algorithm, iterations, salt, hash = encoded.split('$', 3)
assert algorithm == self.algorithm
encoded_2 = self.encode(password, salt, int(iterations))
return constant_time_compare(encoded, encoded_2)
def safe_summary(self, encoded):
3
Source : hashers.py
with GNU General Public License v3.0
from Aghoreshwar
with GNU General Public License v3.0
from Aghoreshwar
def verify(self, password, encoded):
algorithm, data = encoded.split('$', 1)
assert algorithm == self.algorithm
encoded_2 = self.encode(password, force_bytes(data))
return constant_time_compare(encoded, encoded_2)
def safe_summary(self, encoded):
3
Source : hashers.py
with GNU General Public License v3.0
from Aghoreshwar
with GNU General Public License v3.0
from Aghoreshwar
def verify(self, password, encoded):
algorithm, salt, hash = encoded.split('$', 2)
assert algorithm == self.algorithm
encoded_2 = self.encode(password, salt)
return constant_time_compare(encoded, encoded_2)
def safe_summary(self, encoded):
3
Source : hashers.py
with GNU General Public License v3.0
from Aghoreshwar
with GNU General Public License v3.0
from Aghoreshwar
def verify(self, password, encoded):
if len(encoded) == 37 and encoded.startswith('md5$$'):
encoded = encoded[5:]
encoded_2 = self.encode(password, '')
return constant_time_compare(encoded, encoded_2)
def safe_summary(self, encoded):
3
Source : hashers.py
with GNU General Public License v3.0
from Aghoreshwar
with GNU General Public License v3.0
from Aghoreshwar
def verify(self, password, encoded):
crypt = self._load_library()
algorithm, salt, data = encoded.split('$', 2)
assert algorithm == self.algorithm
return constant_time_compare(data, crypt.crypt(password, data))
def safe_summary(self, encoded):
3
Source : base.py
with GNU General Public License v3.0
from Aghoreshwar
with GNU General Public License v3.0
from Aghoreshwar
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 {}
def update(self, dict_):
3
Source : signing.py
with GNU General Public License v3.0
from Aghoreshwar
with GNU General Public License v3.0
from Aghoreshwar
def unsign(self, 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 value
raise BadSignature('Signature "%s" does not match' % sig)
class TimestampSigner(Signer):
3
Source : csrf.py
with GNU General Public License v3.0
from Aghoreshwar
with GNU General Public License v3.0
from Aghoreshwar
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),
)
class CsrfViewMiddleware(MiddlewareMixin):
3
Source : hashers.py
with MIT License
from Air-999
with MIT License
from Air-999
def verify(self, password, encoded):
algorithm, data = encoded.split('$', 1)
assert algorithm == self.algorithm
encoded_2 = self.encode(password, data.encode('ascii'))
return constant_time_compare(encoded, encoded_2)
def safe_summary(self, encoded):
3
Source : cookie.py
with MIT License
from Air-999
with MIT License
from Air-999
def _legacy_decode(self, data):
# RemovedInDjango40Warning: pre-Django 3.1 hashes will be invalid.
bits = data.split('$', 1)
if len(bits) == 2:
hash_, value = bits
if constant_time_compare(hash_, self._legacy_hash(value)):
return value
return None
3
Source : signing.py
with MIT License
from Air-999
with MIT License
from Air-999
def unsign(self, 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)) or (
self.legacy_algorithm and
constant_time_compare(sig, self._legacy_signature(value))
)
):
return value
raise BadSignature('Signature "%s" does not match' % sig)
class TimestampSigner(Signer):
3
Source : csrf.py
with MIT License
from Air-999
with MIT License
from Air-999
def _compare_masked_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(
_unmask_cipher_token(request_csrf_token),
_unmask_cipher_token(csrf_token),
)
class CsrfViewMiddleware(MiddlewareMixin):
3
Source : forms.py
with MIT License
from andreynovikov
with MIT License
from andreynovikov
def clean_security_hash(self):
"""Check the security hash."""
security_hash_dict = {
'content_type': self.data.get("content_type", ""),
'object_pk': self.data.get("object_pk", ""),
'timestamp': self.data.get("timestamp", ""),
}
expected_hash = self.generate_security_hash(**security_hash_dict)
actual_hash = self.cleaned_data["security_hash"]
if not constant_time_compare(expected_hash, actual_hash):
raise forms.ValidationError("Security hash check failed.")
return actual_hash
def clean_timestamp(self):
3
Source : hashers.py
with Apache License 2.0
from CARV-ICS-FORTH
with Apache License 2.0
from CARV-ICS-FORTH
def verify(self, password, encoded):
algorithm, salt, data = encoded.split('$', 2)
assert algorithm == self.algorithm
return constant_time_compare(encoded, self.encode(password, salt))
def safe_summary(self, encoded):
3
Source : hashers.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def verify(self, password, encoded):
crypt = self._load_library()
algorithm, salt, data = encoded.split('$', 2)
assert algorithm == self.algorithm
return constant_time_compare(data, crypt.crypt(force_str(password), data))
def safe_summary(self, encoded):
3
Source : base.py
with MIT License
from chunky2808
with MIT License
from chunky2808
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 {}
def update(self, dict_):
3
Source : signing.py
with MIT License
from chunky2808
with MIT License
from chunky2808
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)
class TimestampSigner(Signer):
3
Source : abstract_models.py
with GNU General Public License v3.0
from foonsun
with GNU General Public License v3.0
from foonsun
def check_verification_hash(self, hash_to_check):
"""
Checks the received verification hash against this order number.
Returns False if the verification failed, True otherwise.
"""
if self.check_deprecated_verification_hash(hash_to_check):
return True
signer = Signer(salt='oscar.apps.order.Order')
try:
signed_number = signer.unsign(hash_to_check)
except BadSignature:
return False
return constant_time_compare(signed_number, self.number)
@property
3
Source : test_crypto.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_constant_time_compare(self):
# It's hard to test for constant time, just test the result.
self.assertTrue(constant_time_compare(b'spam', b'spam'))
self.assertFalse(constant_time_compare(b'spam', b'eggs'))
self.assertTrue(constant_time_compare('spam', 'spam'))
self.assertFalse(constant_time_compare('spam', 'eggs'))
class TestUtilsCryptoPBKDF2(unittest.TestCase):
3
Source : forms.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def clean_hash(self):
hash = self.cleaned_data['hash']
if not constant_time_compare(hash, self.make_hash(self.data)):
raise ValidationError('Tamper alert')
return hash
def reformat_sql(self):
3
Source : views.py
with MIT License
from lukeburden
with MIT License
from lukeburden
def validate_secret(self):
secret_given = self.request.GET.get(self.secret_name) or self.request.POST.get(
self.secret_name
)
return secret_given is not None and constant_time_compare(
secret_given, self.secret
)
def post(self, request):
3
Source : forms.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def clean_security_hash(self):
"""Check the security hash."""
security_hash_dict = {
'content_type' : self.data.get("content_type", ""),
'object_pk' : self.data.get("object_pk", ""),
'timestamp' : self.data.get("timestamp", ""),
}
expected_hash = self.generate_security_hash(**security_hash_dict)
actual_hash = self.cleaned_data["security_hash"]
if not constant_time_compare(expected_hash, actual_hash):
raise forms.ValidationError("Security hash check failed.")
return actual_hash
def clean_timestamp(self):
3
Source : signing.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def unsign(self, signed_value):
signed_value = force_str(signed_value)
if not self.sep 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)
class TimestampSigner(Signer):
3
Source : base.py
with MIT License
from MekAkUActOR
with MIT License
from MekAkUActOR
def decode(self, session_data):
encoded_data = base64.b64decode(session_data.encode('ascii'))
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 {}
def update(self, dict_):
3
Source : hashers.py
with Apache License 2.0
from netsec-ethz
with Apache License 2.0
from netsec-ethz
def verify(self, password, encoded):
Nlog2, r, p, salt, hash = self._parse(encoded)
keyLen = len(_b64dec(hash))
encoded_2 = self.encode(password, salt, Nlog2, r, p, keyLen)
return constant_time_compare(encoded, encoded_2)
def safe_summary(self, encoded):
0
Source : hashers.py
with GNU General Public License v3.0
from Aghoreshwar
with GNU General Public License v3.0
from Aghoreshwar
def verify(self, password, encoded):
encoded_2 = self.encode(password, '')
return constant_time_compare(encoded, encoded_2)
def safe_summary(self, encoded):
0
Source : tokens.py
with GNU General Public License v3.0
from Aghoreshwar
with GNU General Public License v3.0
from Aghoreshwar
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
def _make_token_with_timestamp(self, user, timestamp):
0
Source : __init__.py
with GNU General Public License v3.0
from Aghoreshwar
with GNU General Public License v3.0
from Aghoreshwar
def login(request, user, backend=None):
"""
Persist a user id and a backend in the request. This way a user doesn't
have to reauthenticate on every request. Note that data set during
the anonymous session is retained when the user logs in.
"""
session_auth_hash = ''
if user is None:
user = request.user
if hasattr(user, 'get_session_auth_hash'):
session_auth_hash = user.get_session_auth_hash()
if SESSION_KEY in request.session:
if _get_user_session_key(request) != user.pk or (
session_auth_hash and
not constant_time_compare(request.session.get(HASH_SESSION_KEY, ''), session_auth_hash)):
# To avoid reusing another user's session, create a new, empty
# session if the existing session corresponds to a different
# authenticated user.
request.session.flush()
else:
request.session.cycle_key()
try:
backend = backend or user.backend
except AttributeError:
backends = _get_backends(return_tuples=True)
if len(backends) == 1:
_, backend = backends[0]
else:
raise ValueError(
'You have multiple authentication backends configured and '
'therefore must provide the `backend` argument or set the '
'`backend` attribute on the user.'
)
request.session[SESSION_KEY] = user._meta.pk.value_to_string(user)
request.session[BACKEND_SESSION_KEY] = backend
request.session[HASH_SESSION_KEY] = session_auth_hash
if hasattr(request, 'user'):
request.user = user
rotate_token(request)
user_logged_in.send(sender=user.__class__, request=request, user=user)
def logout(request):
0
Source : __init__.py
with GNU General Public License v3.0
from Aghoreshwar
with GNU General Public License v3.0
from Aghoreshwar
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()
def get_permission_codename(action, opts):
0
Source : cookie.py
with GNU General Public License v3.0
from Aghoreshwar
with GNU General Public License v3.0
from Aghoreshwar
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
0
Source : tokens.py
with MIT License
from Air-999
with MIT License
from Air-999
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, _ = 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):
# RemovedInDjango40Warning: when the deprecation ends, replace
# with:
# return False
if not constant_time_compare(
self._make_token_with_timestamp(user, ts, legacy=True),
token,
):
return False
# Check the timestamp is within limit.
if (self._num_seconds(self._now()) - ts) > settings.PASSWORD_RESET_TIMEOUT:
return False
return True
def _make_token_with_timestamp(self, user, timestamp, legacy=False):
0
Source : __init__.py
with MIT License
from Air-999
with MIT License
from Air-999
def login(request, user, backend=None):
"""
Persist a user id and a backend in the request. This way a user doesn't
have to reauthenticate on every request. Note that data set during
the anonymous session is retained when the user logs in.
"""
session_auth_hash = ''
if user is None:
user = request.user
if hasattr(user, 'get_session_auth_hash'):
session_auth_hash = user.get_session_auth_hash()
if SESSION_KEY in request.session:
if _get_user_session_key(request) != user.pk or (
session_auth_hash and
not constant_time_compare(request.session.get(HASH_SESSION_KEY, ''), session_auth_hash)):
# To avoid reusing another user's session, create a new, empty
# session if the existing session corresponds to a different
# authenticated user.
request.session.flush()
else:
request.session.cycle_key()
try:
backend = backend or user.backend
except AttributeError:
backends = _get_backends(return_tuples=True)
if len(backends) == 1:
_, backend = backends[0]
else:
raise ValueError(
'You have multiple authentication backends configured and '
'therefore must provide the `backend` argument or set the '
'`backend` attribute on the user.'
)
else:
if not isinstance(backend, str):
raise TypeError('backend must be a dotted import path string (got %r).' % backend)
request.session[SESSION_KEY] = user._meta.pk.value_to_string(user)
request.session[BACKEND_SESSION_KEY] = backend
request.session[HASH_SESSION_KEY] = session_auth_hash
if hasattr(request, 'user'):
request.user = user
rotate_token(request)
user_logged_in.send(sender=user.__class__, request=request, user=user)
def logout(request):
0
Source : __init__.py
with MIT License
from Air-999
with MIT License
from Air-999
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:
if not (
session_hash and
hasattr(user, '_legacy_get_session_auth_hash') and
constant_time_compare(session_hash, user._legacy_get_session_auth_hash())
):
request.session.flush()
user = None
return user or AnonymousUser()
def get_permission_codename(action, opts):
0
Source : base.py
with MIT License
from Air-999
with MIT License
from Air-999
def _legacy_decode(self, session_data):
# RemovedInDjango40Warning: pre-Django 3.1 format will be invalid.
encoded_data = base64.b64decode(session_data.encode('ascii'))
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 {}
def update(self, dict_):
0
Source : tokens.py
with GNU Affero General Public License v3.0
from betagouv
with GNU Affero General Public License v3.0
from betagouv
def check_token(self, siae, token):
"""
Check that a siae signup token is correct for a given siae.
"""
if not (siae and token):
return False
# Parse the token
try:
timestamp_b36, _ = token.split("-")
except ValueError:
return False
try:
timestamp = base36_to_int(timestamp_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(siae, timestamp), token):
return False
# Check the timestamp is within limit.
if (self._num_seconds(self._now()) - timestamp) > SIAE_SIGNUP_MAGIC_LINK_TIMEOUT:
return False
return True
def _make_token_with_timestamp(self, siae, timestamp):
0
Source : __init__.py
with MIT License
from chunky2808
with MIT License
from chunky2808
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 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()
def get_permission_codename(action, opts):
0
Source : cookie.py
with MIT License
from chunky2808
with MIT License
from chunky2808
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
0
Source : utils.py
with MIT License
from dibs-devs
with MIT License
from dibs-devs
def get_tenant_user(scope):
"""
Return the user model instance associated with the given scope.
If no user is retrieved, return an instance of `AnonymousUser`.
"""
if "session" not in scope:
raise ValueError(
"Cannot find session in scope.\
You should wrap your consumer in SessionMiddleware."
)
try:
session_key = scope['cookies']['sessionid']
except KeyError as e:
raise KeyError(
"The scope does not contain valid cookies to determine user with."
)
for key, value in scope.get('headers', []):
if key == b'host':
hostname = value.decode('ascii').split(':')[0]
user = None
try:
# get session and user using django-tenants' schema_context
# Link: https://django-tenants.readthedocs.io/en/latest/use.html#utils
from django_tenants.utils import get_tenant_domain_model
domain_model = get_tenant_domain_model()
domain = domain_model.objects.select_related('tenant').get(domain=hostname)
try:
tenant = domain.tenant
except domain_model.DoesNotExist:
raise Http404('No tenant for hostname "%s"' % hostname)
from django.db import connection
connection.set_tenant(tenant)
session = Session.objects.get(session_key=session_key)
uid = session.get_decoded().get(SESSION_KEY)
user = get_user_model().objects.get(pk=uid)
# Verifying the session
# collected from:
# https://github.com/django/channels/blob/master/channels/auth.py
# line 44 onwards
if hasattr(user, "get_session_auth_hash"):
session_hash = session.get_decoded().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:
session.flush()
user = None
except Exception as e:
print(traceback.format_exc())
pass
return user or AnonymousUser()
# Auth Middleware that attaches users to websocket scope on multitenant envs.
class MTAuthMiddleware(AuthMiddleware):
0
Source : auth.py
with GNU Affero General Public License v3.0
from epilys
with GNU Affero General Public License v3.0
from epilys
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, _ = 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
return token == user.auth_token
def _make_hash_value(self, user, timestamp):
0
Source : middleware.py
with MIT License
from EralpB
with MIT License
from EralpB
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 django.contrib.auth.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 and hasattr(settings, 'OLD_SECRET_KEY'):
key_salt = "django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash"
session_hash_verified = session_hash and constant_time_compare(
session_hash,
salted_hmac(key_salt, user.password, secret=settings.OLD_SECRET_KEY).hexdigest()
)
request.session.cycle_key()
request.session[HASH_SESSION_KEY] = user.get_session_auth_hash()
if not session_hash_verified:
request.session.flush()
user = None
return user or AnonymousUser()
def cached_get_user(request):
0
Source : abstract_models.py
with GNU General Public License v3.0
from foonsun
with GNU General Public License v3.0
from foonsun
def check_deprecated_verification_hash(self, hash_to_check):
"""
Backward compatible check for md5 hashes that were generated in
Oscar 1.5 and lower.
This must explicitly be enabled by setting OSCAR_DEPRECATED_ORDER_VERIFY_KEY,
which must not be equal to SECRET_KEY - i.e., the project must
have changed its SECRET_KEY since this change was applied.
TODO: deprecate this method in Oscar 2.0, and remove it in Oscar 2.1.
"""
old_verification_key = getattr(settings, 'OSCAR_DEPRECATED_ORDER_VERIFY_KEY', None)
if old_verification_key is None:
return False
if old_verification_key == settings.SECRET_KEY:
raise ImproperlyConfigured(
'OSCAR_DEPRECATED_ORDER_VERIFY_KEY cannot be equal to SECRET_KEY')
logger.warning('Using insecure md5 hashing for order URL hash verification.')
string_to_hash = '%s%s' % (self.number, old_verification_key)
order_hash = hashlib.md5(string_to_hash.encode('utf8')).hexdigest()
return constant_time_compare(order_hash, hash_to_check)
def check_verification_hash(self, hash_to_check):
0
Source : tokens.py
with Apache License 2.0
from i13-msrg
with Apache License 2.0
from i13-msrg
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. Timestamps are rounded to
# midnight (server time) providing a resolution of only 1 day. If a
# link is generated 5 minutes before midnight and used 6 minutes later,
# that counts as 1 day. Therefore, PASSWORD_RESET_TIMEOUT_DAYS = 1 means
# "at least 1 day, could be up to 2."
if (self._num_days(self._today()) - ts) > settings.PASSWORD_RESET_TIMEOUT_DAYS:
return False
return True
def _make_token_with_timestamp(self, user, timestamp):
0
Source : cookie.py
with Apache License 2.0
from i13-msrg
with Apache License 2.0
from i13-msrg
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
0
Source : frontapp.py
with GNU General Public License v3.0
from JustFixNYC
with GNU General Public License v3.0
from JustFixNYC
def __has_auth_secret(query_args: Dict[str, str], auth_secret: str) -> bool:
return constant_time_compare(query_args.get("auth_secret", ""), auth_secret)
def does_url_have_auth_secret(url: str, auth_secret: str) -> bool:
0
Source : password_reset.py
with GNU General Public License v3.0
from JustFixNYC
with GNU General Public License v3.0
from JustFixNYC
def verify_verification_code(request: HttpRequest, vcode: str) -> Optional[str]:
"""
Verify that the given verification code is identical to the one
stored in the request session. If anything is amiss, return a
string describing the error; otherwise, return None.
"""
# Remember that if the user submitted an invalid phone number in the
# previous step, we don't want to leak that information here.
req_vcode = request.session.get(VCODE_SESSION_KEY)
if not constant_time_compare(req_vcode, vcode):
if req_vcode is not None:
req_user_id = request.session.get(USER_ID_SESSION_KEY)
logger.info(f"Invalid verification code for user id {req_user_id}.")
return "Incorrect verification code!"
req_ts = request.session.get(TIMESTAMP_SESSION_KEY, 0)
now = time.time()
time_elapsed = now - req_ts
if time_elapsed > VERIFICATION_MAX_SECS:
return "Verification code expired. Please go back and re-enter your phone number."
del request.session[VCODE_SESSION_KEY]
del request.session[TIMESTAMP_SESSION_KEY]
request.session[VERIFIED_TIMESTAMP_SESSION_KEY] = now
return None
def get_user_id_of_password_reset_user(request: HttpRequest) -> Optional[int]:
0
Source : auth.py
with MIT License
from lorinkoz
with MIT License
from lorinkoz
def get_user(scope):
"""
Return the user model instance associated with the given scope.
If no user is retrieved, return an instance of `AnonymousUser`.
"""
if "session" not in scope:
raise ValueError("Cannot find session in scope. You should wrap your consumer in SessionMiddleware.")
user = None
session = scope["session"]
with scope["tenant"]:
try:
user_id = _get_user_session_key(session)
backend_path = 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 = 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:
session.flush()
user = None
return user or AnonymousUser()
class TenantAuthMiddleware(AuthMiddleware):
0
Source : hashers.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def verify(self, password, encoded):
algorithm, data = encoded.split('$', 1)
assert algorithm == self.algorithm
bcrypt = self._load_library()
# Hash the password prior to using bcrypt to prevent password truncation
# See: https://code.djangoproject.com/ticket/20138
if self.digest is not None:
# We use binascii.hexlify here because Python3 decided that a hex encoded
# bytestring is somehow a unicode.
password = binascii.hexlify(self.digest(force_bytes(password)).digest())
else:
password = force_bytes(password)
# Ensure that our data is a bytestring
data = force_bytes(data)
# force_bytes() necessary for py-bcrypt compatibility
hashpw = force_bytes(bcrypt.hashpw(password, data))
return constant_time_compare(data, hashpw)
def safe_summary(self, encoded):
0
Source : tokens.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
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
def _make_token_with_timestamp(self, user, timestamp):
0
Source : preview.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def _check_security_hash(self, token, request, form):
expected = self.security_hash(request, form)
return constant_time_compare(token, expected)
def post_post(self, request):
0
Source : cookie.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def _decode(self, data):
"""
Safely decodes a 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
See More Examples