credentialchange.py 1.3 KB

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