1. offline
  2. django-publicauth

Source

django-publicauth / openauth / 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

import openauth
from openauth.models import Confirmation



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

    def __init__(self, login=True, *args, **kwargs):
        super(UsernameField, self).__init__(*args, **kwargs)
        self.label = openauth.settings.USERNAME_LABEL


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

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

        if openauth.settings.UNIQUE_USERNAME and not login and get_object_or_None(User, username=value):
            raise forms.ValidationError(_(u'This login already registered'))
        return value


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

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


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


class RegistrationForm(forms.Form):

    username = UsernameField(login=False)
    email = forms.EmailField(label=_('Email'))
    password = PasswordField(label=_('Password'))
    password_dup = PasswordField(label=_('Password (confirmation)'))


    def clean_email(self):
        if get_object_or_None(User, email=self.cleaned_data['email'].lower()):
            raise forms.ValidationError(_(u'This email already registered'))
        return self.cleaned_data['email']


    def clean_username(self):
        if openauth.settings.UNIQUE_USERNAME:
            if get_object_or_None(User, username=self.cleaned_data['username']):
                raise forms.ValidationError(_(u'This username already registered'))
        return self.cleaned_data['username']


    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 ResetPasswordForm(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'))


ResetPasswordForm = autostrip(ResetPasswordForm)


class LoginForm(forms.Form):
    username = UsernameField()
    password = PasswordField()

    def __init__(self, request, *args, **kwargs):
        self.request = request
        super(LoginForm, self).__init__(*args, **kwargs)

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

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)