credentialchange.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. """
  2. Changed credentials service
  3. Stores new e-mail and password in cache
  4. """
  5. from hashlib import sha256
  6. from django.conf import settings
  7. from django.utils import six
  8. from django.utils.encoding import force_bytes
  9. def store_new_credential(request, credential_type, credential_value):
  10. credential_key = 'new_credential_%s' % credential_type
  11. token = _make_change_token(request.user, credential_type)
  12. request.session[credential_key] = {
  13. 'user_pk': request.user.pk,
  14. 'credential': credential_value,
  15. 'token': token,
  16. }
  17. return token
  18. def read_new_credential(request, credential_type, link_token):
  19. try:
  20. credential_key = 'new_credential_%s' % credential_type
  21. new_credential = request.session.pop(credential_key)
  22. except KeyError:
  23. return None
  24. if new_credential['user_pk'] != request.user.pk:
  25. return None
  26. current_token = _make_change_token(request.user, credential_type)
  27. if link_token != current_token:
  28. return None
  29. if new_credential['token'] != current_token:
  30. return None
  31. return new_credential['credential']
  32. def _make_change_token(user, token_type):
  33. seeds = (
  34. user.pk, user.email, user.password, user.last_login.replace(microsecond=0, tzinfo=None),
  35. settings.SECRET_KEY, six.text_type(token_type)
  36. )
  37. return sha256(force_bytes('+'.join([six.text_type(s) for s in seeds]))).hexdigest()