offline avatar offline committed 2bd7cc7

files moved to right directory

Comments (0)

Files changed (6)

+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)
+from annoying.functions import get_config
+
+
+MESSAGE_TYPE = get_config("MESSAGE_TYPE", "flash")
+CUSTOM_CONFIRMATION = get_config("CUSTOM_CONFIRMATION", None) # custom confirmation function
+REGISTRATION_ALOWED = get_config("REGISTRATION_ALLOWED", True)
+REGISTRATION_FORM = get_config("REGISTRATION_FORM", "auth.forms.RegistrationForm")
+
+GRAVATAR_URL = get_config("GRAVATAR_URL", "http://www.gravatar.com/avatar.php?")
+GRAVATAR_SIZE = get_config("GRAVATAR_SIZE", (25, 25))
+GRAVATAR_TYPE = get_config("GRAVATAR_TYPE", "identicon")
+
+ACTIVATION_REQUIRED = get_config("ACTIVATION_REQUIRED", True)
+ACTIVATION_AUTOLOGIN = get_config("ACTIVATION_AUTOLOGIN", True)
+
+ACTIVATION_CONFIRMATION_TYPE = get_config("ACTIVATION_CONFIRMATION_TYPE", 1)
+PASSWORD_RESET_CONFIRMATION_TYPE = get_config("PASSWORD_RESET_CONFIRMATION_TYPE", 2)
+
+LOGIN_REDIRECT_URL = get_config("LOGIN_REDIRECT_URL", "/auth/login/")
+
+USERNAME_REGEX = get_config("USERNAME_REGEX", re.compile(r"[a-z0-9][_a-z0-9]*[a-z0-9]$", re.I))
+USERNAME_MIN_LENGTH = get_config("ACCOUNT_USERNAME_MIN_LENGTH", 3)
+USERNAME_MAX_LENGTH = get_config("ACCOUNT_USERNAME_MAX_LENGTH", 30)
+
+PASSWORD_MIN_LENGTH = get_config("ACCOUNT_PASSWORD_MIN_LENGTH", 1)
+PASSWORD_MAX_LENGTH = get_config("ACCOUNT_PASSWORD_MAX_LENGTH", 30)
+PASSWORD_FIELD_ATTRIBUTES = get_config("PASSWORD_FIELD_ATTRIBUTES", {})
+def unicode_urlencode(params):
+    """A unicode aware version of urllib.urlencode"""
+    from urllib import urlencode
+
+    if isinstance(params, dict):
+        params = params.items()
+    return urlencode([(k, isinstance(v, unicode) and v.encode('utf-8') or v) for k, v in params])
+
+
+def generate_hash(string=None):
+    import time
+    try:                                                           
+        from hashlib import md5                                    
+    except ImportError:                                            
+        import md5                                                 
+        md5 = md5.new
+
+    if not string:
+        string = str(time.time())
+    hash = md5(string).hexdigest()
+    return hash
+
+
+def build_redirect_url(request, default_url):
+    """
+    Retrieve redirect url from session.
+
+    Use default if retrieved one is broken or not safe.
+    """
+    url = request.session.get('login_redirect_url')
+    if not url or '//' in url or ' ' in url:
+        url = default_url
+    try:
+        del request.session['login_redirect_url']
+    except KeyError:
+        pass
+    return url
+
+
+def parse_template(template_path, **kwargs):
+    """                                     
+    Load and render template.               
+
+    First line of template should contain the subject of email.
+    Return tuple with subject and content.                     
+    """                                                        
+    import re
+
+    from django.template.loader import get_template
+    from django.template import Context
+
+    template = get_template(template_path)
+    context = Context(kwargs)             
+    data = template.render(context).strip()
+    subject, content = re.split(r'\r?\n', data, 1)
+    return (subject.strip(), content.strip())     
+
+
+def email_template(rcpt, template_path, **kwargs):
+    """
+    Load, render and email template.
+
+    **kwargs may contain variables for template rendering.
+    """
+    from django.conf import settings
+    from django.core.mail import send_mail 
+
+    subject, content = parse_template(template_path, **kwargs)
+    count = send_mail(subject, content, settings.DEFAULT_FROM_EMAIL,
+                      [rcpt], fail_silently=True)
+    return bool(count)
+

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)

settings.py

-from annoying.functions import get_config
-
-
-MESSAGE_TYPE = get_config("MESSAGE_TYPE", "flash")
-CUSTOM_CONFIRMATION = get_config("CUSTOM_CONFIRMATION", None) # custom confirmation function
-REGISTRATION_ALOWED = get_config("REGISTRATION_ALLOWED", True)
-REGISTRATION_FORM = get_config("REGISTRATION_FORM", "auth.forms.RegistrationForm")
-
-GRAVATAR_URL = get_config("GRAVATAR_URL", "http://www.gravatar.com/avatar.php?")
-GRAVATAR_SIZE = get_config("GRAVATAR_SIZE", (25, 25))
-GRAVATAR_TYPE = get_config("GRAVATAR_TYPE", "identicon")
-
-ACTIVATION_REQUIRED = get_config("ACTIVATION_REQUIRED", True)
-ACTIVATION_AUTOLOGIN = get_config("ACTIVATION_AUTOLOGIN", True)
-
-ACTIVATION_CONFIRMATION_TYPE = get_config("ACTIVATION_CONFIRMATION_TYPE", 1)
-PASSWORD_RESET_CONFIRMATION_TYPE = get_config("PASSWORD_RESET_CONFIRMATION_TYPE", 2)
-
-LOGIN_REDIRECT_URL = get_config("LOGIN_REDIRECT_URL", "/auth/login/")
-
-USERNAME_REGEX = get_config("USERNAME_REGEX", re.compile(r"[a-z0-9][_a-z0-9]*[a-z0-9]$", re.I))
-USERNAME_MIN_LENGTH = get_config("ACCOUNT_USERNAME_MIN_LENGTH", 3)
-USERNAME_MAX_LENGTH = get_config("ACCOUNT_USERNAME_MAX_LENGTH", 30)
-
-PASSWORD_MIN_LENGTH = get_config("ACCOUNT_PASSWORD_MIN_LENGTH", 1)
-PASSWORD_MAX_LENGTH = get_config("ACCOUNT_PASSWORD_MAX_LENGTH", 30)
-PASSWORD_FIELD_ATTRIBUTES = get_config("PASSWORD_FIELD_ATTRIBUTES", {})

utils.py

-def unicode_urlencode(params):
-    """A unicode aware version of urllib.urlencode"""
-    from urllib import urlencode
-
-    if isinstance(params, dict):
-        params = params.items()
-    return urlencode([(k, isinstance(v, unicode) and v.encode('utf-8') or v) for k, v in params])
-
-
-def generate_hash(string=None):
-    import time
-    try:                                                           
-        from hashlib import md5                                    
-    except ImportError:                                            
-        import md5                                                 
-        md5 = md5.new
-
-    if not string:
-        string = str(time.time())
-    hash = md5(string).hexdigest()
-    return hash
-
-
-def build_redirect_url(request, default_url):
-    """
-    Retrieve redirect url from session.
-
-    Use default if retrieved one is broken or not safe.
-    """
-    url = request.session.get('login_redirect_url')
-    if not url or '//' in url or ' ' in url:
-        url = default_url
-    try:
-        del request.session['login_redirect_url']
-    except KeyError:
-        pass
-    return url
-
-
-def parse_template(template_path, **kwargs):
-    """                                     
-    Load and render template.               
-
-    First line of template should contain the subject of email.
-    Return tuple with subject and content.                     
-    """                                                        
-    import re
-
-    from django.template.loader import get_template
-    from django.template import Context
-
-    template = get_template(template_path)
-    context = Context(kwargs)             
-    data = template.render(context).strip()
-    subject, content = re.split(r'\r?\n', data, 1)
-    return (subject.strip(), content.strip())     
-
-
-def email_template(rcpt, template_path, **kwargs):
-    """
-    Load, render and email template.
-
-    **kwargs may contain variables for template rendering.
-    """
-    from django.conf import settings
-    from django.core.mail import send_mail 
-
-    subject, content = parse_template(template_path, **kwargs)
-    count = send_mail(subject, content, settings.DEFAULT_FROM_EMAIL,
-                      [rcpt], fail_silently=True)
-    return bool(count)
-
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.