credentialchange.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. from misago.core import serializer
  10. __all__ = ['create_change_token', 'read_token']
  11. def store_new_credential(request, credential_type, credential_value):
  12. credential_key = 'new_credential_%s' % credential_type
  13. token = _make_change_token(request.user, credential_type)
  14. request.session[credential_key] = {
  15. 'user_pk': request.user.pk,
  16. 'credential': credential_value,
  17. 'token': token,
  18. }
  19. return token
  20. def read_new_credential(request, credential_type, link_token):
  21. try:
  22. credential_key = 'new_credential_%s' % credential_type
  23. new_credential = request.session.pop(credential_key)
  24. except KeyError:
  25. return None
  26. if new_credential['user_pk'] != request.user.pk:
  27. return None
  28. current_token = _make_change_token(request.user, credential_type)
  29. if link_token != current_token:
  30. return None
  31. if new_credential['token'] != current_token:
  32. return None
  33. return new_credential['credential']
  34. def _make_change_token(user, token_type):
  35. seeds = (
  36. user.pk,
  37. user.email,
  38. user.password,
  39. user.last_login.replace(microsecond=0, tzinfo=None),
  40. settings.SECRET_KEY,
  41. six.text_type(token_type)
  42. )
  43. return sha256(
  44. force_bytes('+'.join([six.text_type(s) for s in seeds]))).hexdigest()