Guest User

Untitled

a guest
Sep 20th, 2018
213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.22 KB | None | 0 0
  1. """
  2. This file enables email-based authentication for Django. The only steps required are
  3. 1. Add 'EmailAuthenticationBackend' to your settings' AUTHENTICATION_BACKENDS file
  4. 2. Add the {'authentication_form': EmailAuthenticationForm} to your login view (if using 'django.contrib.auth.views.login')
  5. 3. When saving a User instance, generate the username from the email using the 'generate_hash_from_email' function
  6. """
  7.  
  8. import hashlib
  9.  
  10. from django import forms
  11. from django.contrib.auth.models import User, check_password
  12. from django.contrib.auth import authenticate
  13. from django.core.exceptions import MultipleObjectsReturned
  14. from django.core.validators import email_re
  15.  
  16. def generate_hash_from_email(email_string):
  17. """
  18. Make a hash of the email to store as a username (no longer than 30 characters)
  19. This ensures that the emails stay unique as only the username field in the User model is required to be unique.
  20. """
  21. m = hashlib.md5()
  22. m.update(email_string.lower())
  23. return m.hexdigest()[:30]
  24.  
  25. class BasicBackend:
  26. """Basic backend: used by EmailAuthenticationBackend"""
  27. def get_user(self, user_id):
  28. try:
  29. return User.objects.get(pk=user_id)
  30. except User.DoesNotExist:
  31. return None
  32.  
  33.  
  34. class EmailAuthenticationBackend(BasicBackend):
  35. """Backend used by django authentication: set in base.py"""
  36.  
  37. def authenticate(self, email=None, password=None):
  38. if email_re.search(email):
  39. try:
  40. user = User.objects.get(email=email)
  41. except User.DoesNotExist:
  42. user = None
  43. except MultipleObjectsReturned:
  44. user = None
  45. else:
  46. if not user.check_password(password):
  47. user = None
  48. finally:
  49. return user
  50. return None
  51.  
  52.  
  53. class EmailAuthenticationForm(forms.Form):
  54. """Email login form: passed to django.contrib.auth.login"""
  55.  
  56. email = forms.CharField(label="Email", max_length=75)
  57. password = forms.CharField(label="Password", widget=forms.PasswordInput)
  58.  
  59. def __init__(self, request=None, *args, **kwargs):
  60. self.request = request
  61. self.user_cache = None
  62. super(EmailAuthenticationForm, self).__init__(*args, **kwargs)
  63.  
  64. def clean(self):
  65. email = self.cleaned_data.get('email')
  66. password = self.cleaned_data.get('password')
  67.  
  68. if email and password:
  69. self.user_cache = authenticate(email=email, password=password)
  70. if not email_re.search(email):
  71. raise forms.ValidationError("Please enter a valid email")
  72. if self.user_cache is None:
  73. raise forms.ValidationError("Please enter a correct email and password.")
  74. elif not self.user_cache.is_active:
  75. raise forms.ValidationError("This account is inactive.")
  76.  
  77. if self.request:
  78. if not self.request.session.test_cookie_worked():
  79. raise forms.ValidationError("Your Web browser doesn't appear to have cookies enabled. Cookies are required for logging in.")
  80.  
  81. return self.cleaned_data
  82.  
  83. def get_user_id(self):
  84. if self.user_cache:
  85. return self.user_cache.id
  86. return None
  87.  
  88. def get_user(self):
  89. return self.user_cache
Add Comment
Please, Sign In to add comment