Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from django import forms
- from django.utils.translation import ugettext_lazy as _
- from django.contrib.auth import authenticate
- from django.contrib.auth.password_validation import validate_password
- from django.contrib.auth.forms import ReadOnlyPasswordHashField
- from django.contrib.auth.forms import UsernameField
- from django.utils.text import capfirst
- from .models import User
- from emails.exception_handlers import EmailNotConfirmed
- class AuthenticationForm(forms.Form):
- """
- Base class for authenticating users. Extend this to get a form that accepts
- username/password logins.
- """
- username = UsernameField(
- max_length=254,
- widget=forms.TextInput(attrs={'autofocus': True}),
- )
- password = forms.CharField(
- label=_("Password"),
- strip=False,
- widget=forms.PasswordInput,
- )
- error_messages = {
- 'invalid_login': _(
- "Please enter a correct %(username)s and password. Note that both "
- "fields may be case-sensitive."
- ),
- 'inactive': _(
- "This account is inactive."
- "Please check your email, or get new activation link"
- ),
- }
- def __init__(self, request=None, *args, **kwargs):
- """
- The 'request' parameter is set for custom auth use by subclasses.
- The form data comes in via the standard 'data' kwarg.
- """
- super().__init__(*args, **kwargs)
- self.request = request
- self.user_cache = None
- self.error = None
- # Set the label for the "username" field.
- self.username_field = User._meta.get_field(User.USERNAME_FIELD)
- if self.fields['username'].label is None:
- self.fields['username'].label = capfirst(self.username_field.verbose_name)
- def clean(self):
- username = self.cleaned_data.get('username')
- password = self.cleaned_data.get('password')
- if username and password:
- self.user_cache = authenticate(self.request, username=username,
- password=password)
- print(self.user_cache)
- if self.user_cache is None:
- self.error = 'invalid'
- raise forms.ValidationError(
- self.error_messages['invalid_login'],
- code='invalid_login',
- params={'username': self.username_field.verbose_name},
- )
- else:
- self.confirm_login_allowed(self.user_cache)
- return self.cleaned_data
- def confirm_login_allowed(self, user):
- """
- Controls whether the given User may log in. This is a policy setting,
- independent of end-user authentication. This default behavior is to
- allow login by active users, and reject login by inactive users.
- If the given user cannot log in, this method should raise a
- ``forms.ValidationError``.
- If the given user may log in, this method should return None.
- """
- if not user.is_active:
- self.error = 'inactive'
- raise forms.ValidationError(
- self.error_messages['inactive'],
- code='inactive',
- )
- def get_user_id(self):
- if self.user_cache:
- return self.user_cache.id
- return None
- def get_user(self):
- return self.user_cache
- class UserChangeForm(forms.ModelForm):
- """A form for updating users. Includes all the fields on
- the user, but replaces the password field with admin's
- password hash display field.
- """
- password = ReadOnlyPasswordHashField(
- label=_("password"),
- help_text=_(
- "raw passwords are not stored, so there is no way to see this "
- "user's password, but you can change the password using "
- "<a href=\"../password/\">this form</a>."
- ),
- )
- class Meta:
- model = User
- fields = (
- 'email', 'password')
- def clean_password(self):
- # Regardless of what the user provides, return the initial value.
- # This is done here, rather than on the field, because the
- # field does not have access to the initial value
- return self.initial["password"]
- class UserCreationForm(forms.ModelForm):
- """A form for creating new users. Includes all the required
- fields, plus a repeated password."""
- password1 = forms.CharField(
- label=_('password'), widget=forms.PasswordInput)
- password2 = forms.CharField(
- label=_('password confirmation'), widget=forms.PasswordInput)
- is_agree_process_personal_data = forms.BooleanField(
- label=_(
- '<a href="/info/personal-data/" target="_blank">'
- 'i agree to the personal data processing policy</a>'))
- is_agree_with_public_offer = forms.BooleanField(
- label=_(
- '<a href="/info/public-offer/" target="_blank">'
- 'i have read and agree with the rules of the platform</a>'))
- class Meta:
- model = User
- fields = ('full_name', 'email', 'phone_number', 'invite_code')
- def __init__(self, *args, **kwargs):
- super(UserCreationForm, self).__init__(*args, **kwargs)
- def clean_invite_code(self):
- invite_code = self.cleaned_data['invite_code']
- # if not User.objects.filter(referral_code=invite_code).exists():
- # raise forms.ValidationError(
- # Setting.objects.get_setting(
- # 'WRONG_INVITE_CODE_MESSAGE', ''))
- return invite_code
- def clean_email(self):
- cleaned_email = self.cleaned_data['email'].lower()
- if User.objects.filter(email=cleaned_email).exists():
- raise forms.ValidationError(_('email already registered'))
- return cleaned_email
- def clean_password2(self):
- # Check that the two password entries match
- password1 = self.cleaned_data.get('password1')
- password2 = self.cleaned_data.get('password2')
- if password1 and password2 and password1 != password2:
- raise forms.ValidationError(_('paswords do not match'))
- validate_password(password1)
- return password2
- def create(self):
- user = User.objects.create_user(
- email=self.cleaned_data.get('email'),
- password=self.cleaned_data['password1'],
- )
- return user
- def save(self, commit=True):
- # Save the provided password in hashed format
- # invite_code = self.cleaned_data['invite_code']
- user = super(UserCreationForm, self).save(commit=commit)
- # user.parent = User.objects.get(referral_code=invite_code)
- user.set_password(self.cleaned_data['password1'])
- if commit:
- user.save()
- return user
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement