Advertisement
Guest User

Untitled

a guest
Mar 15th, 2019
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.63 KB | None | 0 0
  1. from django import forms
  2. from django.utils.translation import ugettext_lazy as _
  3. from django.contrib.auth import authenticate
  4. from django.contrib.auth.password_validation import validate_password
  5. from django.contrib.auth.forms import ReadOnlyPasswordHashField
  6. from django.contrib.auth.forms import UsernameField
  7. from django.utils.text import capfirst
  8.  
  9. from .models import User
  10. from emails.exception_handlers import EmailNotConfirmed
  11.  
  12.  
  13. class AuthenticationForm(forms.Form):
  14. """
  15. Base class for authenticating users. Extend this to get a form that accepts
  16. username/password logins.
  17. """
  18. username = UsernameField(
  19. max_length=254,
  20. widget=forms.TextInput(attrs={'autofocus': True}),
  21. )
  22. password = forms.CharField(
  23. label=_("Password"),
  24. strip=False,
  25. widget=forms.PasswordInput,
  26. )
  27.  
  28. error_messages = {
  29. 'invalid_login': _(
  30. "Please enter a correct %(username)s and password. Note that both "
  31. "fields may be case-sensitive."
  32. ),
  33. 'inactive': _(
  34. "This account is inactive."
  35. "Please check your email, or get new activation link"
  36. ),
  37. }
  38.  
  39. def __init__(self, request=None, *args, **kwargs):
  40. """
  41. The 'request' parameter is set for custom auth use by subclasses.
  42. The form data comes in via the standard 'data' kwarg.
  43. """
  44. super().__init__(*args, **kwargs)
  45. self.request = request
  46. self.user_cache = None
  47. self.error = None
  48.  
  49. # Set the label for the "username" field.
  50. self.username_field = User._meta.get_field(User.USERNAME_FIELD)
  51. if self.fields['username'].label is None:
  52. self.fields['username'].label = capfirst(self.username_field.verbose_name)
  53.  
  54. def clean(self):
  55. username = self.cleaned_data.get('username')
  56. password = self.cleaned_data.get('password')
  57.  
  58. if username and password:
  59. self.user_cache = authenticate(self.request, username=username,
  60. password=password)
  61. print(self.user_cache)
  62. if self.user_cache is None:
  63. self.error = 'invalid'
  64. raise forms.ValidationError(
  65. self.error_messages['invalid_login'],
  66. code='invalid_login',
  67. params={'username': self.username_field.verbose_name},
  68. )
  69. else:
  70. self.confirm_login_allowed(self.user_cache)
  71. return self.cleaned_data
  72.  
  73. def confirm_login_allowed(self, user):
  74. """
  75. Controls whether the given User may log in. This is a policy setting,
  76. independent of end-user authentication. This default behavior is to
  77. allow login by active users, and reject login by inactive users.
  78.  
  79. If the given user cannot log in, this method should raise a
  80. ``forms.ValidationError``.
  81.  
  82. If the given user may log in, this method should return None.
  83. """
  84. if not user.is_active:
  85. self.error = 'inactive'
  86. raise forms.ValidationError(
  87. self.error_messages['inactive'],
  88. code='inactive',
  89. )
  90.  
  91. def get_user_id(self):
  92. if self.user_cache:
  93. return self.user_cache.id
  94. return None
  95.  
  96. def get_user(self):
  97. return self.user_cache
  98.  
  99.  
  100. class UserChangeForm(forms.ModelForm):
  101. """A form for updating users. Includes all the fields on
  102. the user, but replaces the password field with admin's
  103. password hash display field.
  104. """
  105. password = ReadOnlyPasswordHashField(
  106. label=_("password"),
  107. help_text=_(
  108. "raw passwords are not stored, so there is no way to see this "
  109. "user's password, but you can change the password using "
  110. "<a href=\"../password/\">this form</a>."
  111. ),
  112. )
  113.  
  114. class Meta:
  115. model = User
  116. fields = (
  117. 'email', 'password')
  118.  
  119. def clean_password(self):
  120. # Regardless of what the user provides, return the initial value.
  121. # This is done here, rather than on the field, because the
  122. # field does not have access to the initial value
  123. return self.initial["password"]
  124.  
  125.  
  126. class UserCreationForm(forms.ModelForm):
  127. """A form for creating new users. Includes all the required
  128. fields, plus a repeated password."""
  129. password1 = forms.CharField(
  130. label=_('password'), widget=forms.PasswordInput)
  131. password2 = forms.CharField(
  132. label=_('password confirmation'), widget=forms.PasswordInput)
  133. is_agree_process_personal_data = forms.BooleanField(
  134. label=_(
  135. '<a href="/info/personal-data/" target="_blank">'
  136. 'i agree to the personal data processing policy</a>'))
  137. is_agree_with_public_offer = forms.BooleanField(
  138. label=_(
  139. '<a href="/info/public-offer/" target="_blank">'
  140. 'i have read and agree with the rules of the platform</a>'))
  141.  
  142. class Meta:
  143. model = User
  144. fields = ('full_name', 'email', 'phone_number', 'invite_code')
  145.  
  146. def __init__(self, *args, **kwargs):
  147. super(UserCreationForm, self).__init__(*args, **kwargs)
  148.  
  149. def clean_invite_code(self):
  150. invite_code = self.cleaned_data['invite_code']
  151. # if not User.objects.filter(referral_code=invite_code).exists():
  152. # raise forms.ValidationError(
  153. # Setting.objects.get_setting(
  154. # 'WRONG_INVITE_CODE_MESSAGE', ''))
  155. return invite_code
  156.  
  157. def clean_email(self):
  158. cleaned_email = self.cleaned_data['email'].lower()
  159. if User.objects.filter(email=cleaned_email).exists():
  160. raise forms.ValidationError(_('email already registered'))
  161. return cleaned_email
  162.  
  163. def clean_password2(self):
  164. # Check that the two password entries match
  165. password1 = self.cleaned_data.get('password1')
  166. password2 = self.cleaned_data.get('password2')
  167. if password1 and password2 and password1 != password2:
  168. raise forms.ValidationError(_('paswords do not match'))
  169. validate_password(password1)
  170. return password2
  171.  
  172. def create(self):
  173. user = User.objects.create_user(
  174. email=self.cleaned_data.get('email'),
  175. password=self.cleaned_data['password1'],
  176. )
  177. return user
  178.  
  179. def save(self, commit=True):
  180. # Save the provided password in hashed format
  181. # invite_code = self.cleaned_data['invite_code']
  182. user = super(UserCreationForm, self).save(commit=commit)
  183. # user.parent = User.objects.get(referral_code=invite_code)
  184. user.set_password(self.cleaned_data['password1'])
  185. if commit:
  186. user.save()
  187. return user
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement