Source

django-publicauth / auth / forms.py

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login
from django.utils.translation import ugettext as _
from django.template import loader

from annoying.functions import get_object_or_None
from annoying.decorators import autostrip

from auth.models import Confirmation



class UsernameField(forms.CharField):
    """
    Form field for username handling.
    """

    def __init__(self, *args, **kwargs):
        super(UsernameField, self).__init__(*args, **kwargs)
        self.label = _(u'Login')


    def clean(self, value):
        super(UsernameField, self).clean(value)

        if len(value) < auth.settings.USERNAME_MIN_LENGTH:
            raise forms.ValidationError(_(u'Login length is less than %(min)d') % {'min': auth.settings.USERNAME_MIN_LENGTH})
        if len(value) > auth.settings.USERNAME_MAX_LENGTH:
            raise forms.ValidationError(_(u'Login length is more than %(max)d') % {'max': auth.settings.USERNAME_MAX_LENGTH})
        if not auth.settings.USERNAME_REGEX.match(value):
            raise forms.ValidationError(_(u'Login contains restricted symbols'))

        try:
            User.objects.get(username__exact=value)
        except User.DoesNotExist:
            return value
        else:
            raise forms.ValidationError(_(u'This login already registered'))


class PasswordField(forms.CharField):
    """
    Form field for password handling.
    """

    def __init__(self, *args, **kwargs):
        super(PasswordField, self).__init__(*args, **kwargs)
        self.widget = forms.PasswordInput(attrs=auth.settings.PASSWORD_FIELD_ATTRIBUTES)
        self.help_text = ''


    def clean(self, value):
        super(PasswordField, self).clean(value)
        if len(value) < auth.settings.PASSWORD_MIN_LENGTH:
            raise forms.ValidationError(_(u'Password length is less than %(min)d') % {'min': PASSWORD_MIN_LENGTH})
        if len(value) > auth.settings.PASSWORD_MAX_LENGTH:
            raise forms.ValidationError(_(u'Password length is more than %(max)d') % {'max': PASSWORD_MAX_LENGTH})
        return value


class RegistrationForm(forms.Form):
    username = forms.CharField(label=_('Nickname'), max_length=30)
    email = forms.EmailField(label=_('Email'))
    password = PasswordField(label=_('Password'))
    password_dup = PasswordField(label=_('Password (confirmation)'))

    
    def clean_email(self):
        #return self.cleaned_data.get('email','')
        try:
            User.objects.get(email__exact=self.cleaned_data['email'].lower())
        except User.DoesNotExist:
            return self.cleaned_data['email']
        except KeyError:
            pass
        else:
            raise forms.ValidationError(_(u'This email already registered'))

    
    def clean(self):
        pwd1 = self.cleaned_data.get('password')
        pwd2 = self.cleaned_data.get('password_dup')
        if pwd1 and pwd2:
            if pwd1 != pwd2:
                raise forms.ValidationError(_(u'Passwords do not match'))
        return self.cleaned_data


    def save(self):
        username = self.cleaned_data['username']
        email = self.cleaned_data['email'].lower()
        password = self.cleaned_data['password']
        user = User.objects.create_user(username, email, password=password)
        return user

RegistrationForm = autostrip(RegistrationForm)


class RestorePasswordForm(forms.Form):
    email = forms.EmailField(label=_('Email'), widget=forms.TextInput(attrs={'class': 'field_input'}))

    def clean_email(self):
        if 'email' in self.cleaned_data:
            email = self.cleaned_data['email'].lower()
            if User.objects.filter(email=email).count():
                return email
            else:
                raise forms.ValidationError(_(u'This email is not registered'))


RestorePasswordForm = autostrip(RestorePasswordForm)


class LoginForm(forms.Form):
    email = forms.EmailField(label=_('Email'))
    password = forms.CharField(label=_('Password'), widget=forms.PasswordInput)

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request')
        self.base_fields['email'].help_text = ''
        #self.base_fields['password'].widget = forms.PasswordInput()
        self.base_fields['password'].help_text = ''
        super(LoginForm, self).__init__(*args, **kwargs)


    def clean(self):
        super(LoginForm, self).clean()
        if self.is_valid():
            email = self.cleaned_data['email'].lower()
            password = self.cleaned_data['password']
            user = get_object_or_None(User, email=email)
            if user and  user.check_password(password):
                if user.is_active:
                    user.backend = 'django.contrib.auth.backends.ModelBackend'
                    login(self.request, user)
                    return self.cleaned_data
                else:
                    raise forms.ValidationError(_(u'Your account is not active. Please activate it.'))
            else:
                raise forms.ValidationError(_(u'Incorrect email or password'))

LoginForm = autostrip(LoginForm)


class NewPasswordForm(forms.Form):
    """
    Form for changing user's password.
    """

    password = PasswordField(label=_(u'Password'))
    password_confirmation = PasswordField(label=_(u'Password (confirmation)'))



    def clean_password_confirmation(self):
        pass1 = self.cleaned_data['password']
        pass2 = self.cleaned_data['password_confirmation']
        if pass1 != pass2:
            raise forms.ValidationError(_(u'The passwords do not match'))
        else:
            return pass1


    def save(self, user):
        user.set_password(self.cleaned_data['password'])
        user.save()
        return user

NewPasswordForm = autostrip(NewPasswordForm)


class NewEmailForm(forms.Form):
    """
    Form for email chanage.
    """

    email = forms.EmailField(label=_(u'New email'))

    def save(self):
        pass


class EditUserForm(forms.Form):
    def __init__(self, user, *args, **kwargs):
        super(EditUserForm, self).__init__(*args, **kwargs)
        self.user = user

    username = forms.CharField(widget=forms.TextInput(attrs={'class':'field_input'}))
    country = forms.CharField(widget=forms.TextInput(attrs={'class':'field_input'}), required=False)
    jabber = forms.EmailField(widget=forms.TextInput(attrs={'class':'field_input'}), required=False)
    about = forms.CharField(widget=forms.Textarea(attrs={'class':'field_input f130', 'style': 'height: 250px'}), required=False)



    def save(self):
        user = self.user
        profile = user.profile
        user.username = self.cleaned_data['username']
        profile.country = self.cleaned_data['country']
        profile.jabber = self.cleaned_data['jabber']
        profile.about = self.cleaned_data['about']
        user.save()
        profile.save()
        return user

EditUserForm = autostrip(EditUserForm)