credentialchange.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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,
  35. user.email,
  36. user.password,
  37. user.last_login.replace(microsecond=0, tzinfo=None),
  38. settings.SECRET_KEY,
  39. six.text_type(token_type)
  40. )
  41. return sha256(
  42. force_bytes('+'.join([six.text_type(s) for s in seeds]))).hexdigest()