/registration_backends/email_as_username/forms.py

https://github.com/occupyhack/web-cop-watch · Python · 121 lines · 61 code · 20 blank · 40 comment · 14 complexity · 5561070d3ad89e96cdf0fc6b27fb9e47 MD5 · raw file

  1. import random
  2. import string
  3. from django import forms
  4. from django.contrib.auth.models import User
  5. from django.contrib.auth import authenticate
  6. from django.utils.translation import ugettext_lazy as _
  7. import registration.forms
  8. import django.contrib.auth.forms
  9. class RegistrationFormArbitraryUsername (registration.forms.RegistrationFormUniqueEmail):
  10. """
  11. Subclass of ``RegistrationFormUniqueEmail`` which generates a unique user
  12. name is none is supplied.
  13. """
  14. username = forms.RegexField(regex=r'^[\w.@+-]+$',
  15. max_length=30,
  16. required=False,
  17. widget=forms.HiddenInput(attrs=registration.forms.attrs_dict),
  18. error_messages={'invalid': registration.forms._("This value must contain only letters, numbers and underscores.")})
  19. def _get_random_unique_username(self):
  20. """
  21. Make an arbitrary and unique username
  22. """
  23. while True:
  24. try:
  25. # Use the first 15 characters of the email_user, concatenated
  26. # with 15 random letters/numbers.
  27. username = ''.join(random.choice(string.ascii_letters + string.digits)
  28. for i in xrange(30))
  29. user = User.objects.get(username__iexact=username)
  30. except User.DoesNotExist:
  31. return username
  32. def clean_username(self):
  33. """
  34. Provide an arbitrary username based off of the email address if no
  35. username is provided.
  36. """
  37. if self.cleaned_data['username'] in ('', None):
  38. self.cleaned_data['username'] = \
  39. self._get_random_unique_username()
  40. return super(RegistrationFormArbitraryUsername, self).clean_username()
  41. class AuthenticationFormByEmail(forms.Form):
  42. """
  43. Base class for authenticating users by email. Extend this to get a form
  44. that accepts email/password logins.
  45. Mostly a clone of django.contrib.auth.forms.AuthenticationForm
  46. """
  47. email = forms.CharField(label=_("Email"))
  48. password = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
  49. def __init__(self, request=None, *args, **kwargs):
  50. """
  51. If request is passed in, the form will validate that cookies are
  52. enabled. Note that the request (a HttpRequest object) must have set a
  53. cookie with the key TEST_COOKIE_NAME and value TEST_COOKIE_VALUE before
  54. running this validation.
  55. """
  56. self.request = request
  57. self.user_cache = None
  58. super(AuthenticationFormByEmail, self).__init__(*args, **kwargs)
  59. def clean(self):
  60. email = self.cleaned_data.get('email')
  61. password = self.cleaned_data.get('password')
  62. try:
  63. user = User.objects.get(email=email)
  64. username = user.username
  65. except User.DoesNotExist:
  66. raise forms.ValidationError(_("Could not find a user with the email address."))
  67. if username and password:
  68. self.user_cache = authenticate(username=username, password=password)
  69. if self.user_cache is None:
  70. raise forms.ValidationError(_("Please enter a correct email and password. Note that both fields are case-sensitive."))
  71. elif not self.user_cache.is_active:
  72. raise forms.ValidationError(_("This account is inactive."))
  73. self.check_for_test_cookie()
  74. return self.cleaned_data
  75. def check_for_test_cookie(self):
  76. if self.request and not self.request.session.test_cookie_worked():
  77. raise forms.ValidationError(
  78. _("Your Web browser doesn't appear to have cookies enabled. "
  79. "Cookies are required for logging in."))
  80. def get_user_id(self):
  81. if self.user_cache:
  82. return self.user_cache.id
  83. return None
  84. def get_user(self):
  85. return self.user_cache
  86. #class AuthenticationFormByEmail (django.contrib.auth.forms.AuthenticationForm):
  87. # username = forms.HiddenInput()
  88. # email = forms.CharField(label=_("Email"))
  89. # def clean(self):
  90. # email = self.cleaned_data.get('email')
  91. # try:
  92. # user = User.objects.get(email=email)
  93. # self.cleaned_data['username'] = user.username
  94. # except User.DoesNotExist:
  95. # raise forms.ValidationError(_("Could not find a user with the email address."))
  96. # return super(AuthenticationFormByEmail, self).clean()