Commits

offline  committed 993f004

openauth prefix removed from settings object

  • Participants
  • Parent commits f08b457

Comments (0)

Files changed (6)

File openauth/fields.py

 
 from annoying.functions import get_object_or_None
 
-import openauth
+from openauth import settings
 
 
 class LoginField(forms.CharField):
         to custom label defined in project settings file.
         """
         super(LoginField, self).__init__(*args, **kwargs)
-        if not openauth.settings.LOGIN_LABEL:
-            if "username" in openauth.settings.AUTHENTICATION_TYPES:
+        if not settings.LOGIN_LABEL:
+            if "username" in settings.AUTHENTICATION_TYPES:
                 self.label = _("Login")
-            if "email" in openauth.settings.AUTHENTICATION_TYPES:
+            if "email" in settings.AUTHENTICATION_TYPES:
                 self.label = _("Email")
         else:
-            self.label = openauth.settings.LOGIN_LABEL
+            self.label = settings.LOGIN_LABEL
 
     def clean(self, value):
         """
         Validate the field with min/max length restrictions and regex.
         """
         super(LoginField, self).clean(value)
-        if len(value) < openauth.settings.LOGIN_MIN_LENGTH:
-            raise forms.ValidationError(_(u'Login length is less than %(min)d') % {'min': openauth.settings.LOGIN_MIN_LENGTH})
-        if len(value) > openauth.settings.LOGIN_MAX_LENGTH:
-            raise forms.ValidationError(_(u'Login length is more than %(max)d') % {'max': openauth.settings.LOGIN_MAX_LENGTH})
-        if not openauth.settings.LOGIN_REGEX.match(value):
+        if len(value) < settings.LOGIN_MIN_LENGTH:
+            raise forms.ValidationError(_(u'Login length is less than %(min)d') % {'min': settings.LOGIN_MIN_LENGTH})
+        if len(value) > settings.LOGIN_MAX_LENGTH:
+            raise forms.ValidationError(_(u'Login length is more than %(max)d') % {'max': settings.LOGIN_MAX_LENGTH})
+        if not settings.LOGIN_REGEX.match(value):
             raise forms.ValidationError(_(u'%s contains restricted symbols') % self.label)
         return value
 
         Validate the field with min/max length restrictions and regex.
         """
         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})
-        if not openauth.settings.PASSWORD_REGEX.match(value):
+        if len(value) < settings.PASSWORD_MIN_LENGTH:
+            raise forms.ValidationError(_(u'Password length is less than %(min)d') % {'min': settings.PASSWORD_MIN_LENGTH})
+        if len(value) > settings.PASSWORD_MAX_LENGTH:
+            raise forms.ValidationError(_(u'Password length is more than %(max)d') % {'max': settings.PASSWORD_MAX_LENGTH})
+        if not settings.PASSWORD_REGEX.match(value):
             raise forms.ValidationError(_(u'Password contains restricted symbols'))
         return value
 

File openauth/forms.py

 from annoying.functions import get_object_or_None
 from annoying.decorators import autostrip
 
-import openauth
 from openauth.utils import uri_to_username, attach_openid_data
+from openauth.fields import LoginField, PasswordField
 from openauth.models import OpenID
-from openauth.fields import LoginField, PasswordField
+from openauth import settings
 
 
 class RegistrationForm(forms.Form):
     file for instractions.
     """
     def __init__(self, *args, **kwargs):
-        if openauth.settings.DISPLAYNAME_REQUIRED:
+        if settings.DISPLAYNAME_REQUIRED:
             self.base_fields['username'] = forms.CharField()
         super(RegistrationForm, self).__init__(*args, **kwargs)
 
         Validate login field according to AUTHENTIFICATION types 
         specified in settings. The login field must be unique.
         """
-        if "email" in openauth.settings.AUTHENTICATION_TYPES:
+        if "email" in settings.AUTHENTICATION_TYPES:
             if get_object_or_None(User, email=self.cleaned_data['login'].lower()):
                 raise forms.ValidationError(_(u'This email already registered'))
-        elif "username" in openauth.settings.AUTHENTICATION_TYPES:
+        elif "username" in settings.AUTHENTICATION_TYPES:
             if get_object_or_None(User, username=self.cleaned_data['login']):
                 raise forms.ValidationError(_(u'This login name is already taken'))
         return self.cleaned_data['login']
         Validate uniqeness of username in case DISPLAYNAME_REQUIRED 
         is set to True.
         """
-        if openauth.settings.UNIQUE_USERNAME:
+        if settings.UNIQUE_USERNAME:
             if get_object_or_None(User, username=self.cleaned_data['username']):
                 raise forms.ValidationError(_(u'This display name already registered'))
         return self.cleaned_data['username']
         form. The method should return User instance.
         """
         user = User()
-        if "email" in openauth.settings.AUTHENTICATION_TYPES:
+        if "email" in settings.AUTHENTICATION_TYPES:
             user.email = self.cleaned_data['login'].lower()
-            if openauth.settings.DISPLAYNAME_REQUIRED:
+            if settings.DISPLAYNAME_REQUIRED:
                 user.username = self.cleaned_data['username']
             else:
                 user.username = user.email
-        if "username" in openauth.settings.AUTHENTICATION_TYPES:
+        if "username" in settings.AUTHENTICATION_TYPES:
             user.username = self.cleaned_data['login']
         user.set_password(self.cleaned_data['password'])
         user.save()
         if self.is_valid():
             login = self.cleaned_data['login']
             password = self.cleaned_data['password']
-            if 'username' in openauth.settings.AUTHENTICATION_TYPES:
+            if 'username' in settings.AUTHENTICATION_TYPES:
                 user = get_object_or_None(User, username=login)
-            elif 'email' in openauth.settings.AUTHENTICATION_TYPES:
+            elif 'email' in settings.AUTHENTICATION_TYPES:
                 user = get_object_or_None(User, email=login.lower())
             if user and  user.check_password(password):
-                if openauth.settings.ACTIVATION_REQUIRED and not user.is_active:
+                if 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_user(self.request, user)
 
 class OpenIDRegistrationForm(forms.Form):
     def __init__(self, *args, **kwargs):
-        for key, value in openauth.settings.OPENID_PROFILE_MAPPING.items():
+        for key, value in settings.OPENID_PROFILE_MAPPING.items():
             self.base_fields[value] = forms.CharField()
             if value == 'email':
                 self.base_fields[value] = forms.EmailField()
 
     def clean_login(self):
         login = self.cleaned_data['login']
-        if openauth.settings.UNIQUE_USERNAME and get_object_or_None(User, username=login):
+        if settings.UNIQUE_USERNAME and get_object_or_None(User, username=login):
             raise forms.ValidationError("This username already taken");
         return login
 
     def save(self, openid_url):
         user = User.objects.create(username=self.cleaned_data['login'])
-        if openauth.settings.OPENID_ACTIVATION_REQUIRED:
+        if settings.OPENID_ACTIVATION_REQUIRED:
             user.is_active = False
         user.save()
         OpenID(user=user, url=openid_url).save()

File openauth/models.py

 from django.db import models
 from django.contrib.auth.models import User
 
-import openauth
+from openauth import settings
 
 
-User.username = models.CharField(max_length=30, unique=openauth.settings.UNIQUE_USERNAME)
+User.username = models.CharField(max_length=30, unique=settings.UNIQUE_USERNAME)
 
 class OpenID(models.Model):
     user = models.ForeignKey(User)

File openauth/signals.py

 from confirmation.models import Confirmation
 from confirmation.signals import successfull_confirmation
 
-import openauth
-
+from openauth import settings
 
 
 @signals(successfull_confirmation, sender=Confirmation)
 def sighandler(request, instance, confirmation_type, **kwargs):
-    if confirmation_type == openauth.settings.ACTIVATION_TYPE:
+    if confirmation_type == settings.ACTIVATION_TYPE:
         user = instance
         user.is_active = True
         user.save()
-        if openauth.settings.ACTIVATION_AUTO_LOGIN:
+        if settings.ACTIVATION_AUTO_LOGIN:
             user.backend = 'django.contrib.auth.backends.ModelBackend'
             auth.login(request, user)
             
-    elif confirmation_type == openauth.settings.PASSWORD_RESET_TYPE:
+    elif confirmation_type == settings.PASSWORD_RESET_TYPE:
         user = instance
         user.backend = 'django.contrib.auth.backends.ModelBackend'
         auth.login(request, user)    

File openauth/utils.py

 import re
+import time
 import pickle
+
 from functools import wraps
 
 from openid.extensions.sreg import SRegRequest, SRegResponse
 from django.shortcuts import redirect
 from django.utils.translation import ugettext as _
 from django.core.urlresolvers import reverse
-from django.conf import settings
+from django.conf import settings as django_settings
 
 from notify import notify_user
 
-import openauth
+from openauth import settings
+
 
 def unicode_urlencode(params):
     """A unicode aware version of urllib.urlencode"""
 
 
 def generate_hash(string=None):
-    import time
     try:
         from hashlib import md5
     except ImportError:
         md5 = md5.new
 
     if not string:
-        string = str(time.time()) + settings.SECRET_KEY
+        string = str(time.time()) + django_settings.SECRET_KEY
     hash = md5(string).hexdigest()
     return hash
 
 
     **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,
+    count = send_mail(subject, content, django_settings.DEFAULT_FROM_EMAIL,
                       [rcpt], fail_silently=True)
     return bool(count)
 
             if opposite and request.user.is_authenticated():
                 return notify_user.notice(request, '/', openauth.lang.PLEASE_LOGOUT)
             if request.user.is_authenticated():
-                if openauth.settings.ACTIVATION_REQUIRED and not request.user.is_active:
+                if settings.ACTIVATION_REQUIRED and not request.user.is_active:
                     return notify_user.notice(request, "/", openauth.lang.MUST_ACTIVATE_FIRST)
             elif not opposite:
                 next_data = {'next': request.path}
 
 
 def have_profile_name(field):
-    return field in openauth.settings.OPENID_PROFILE_MAPPING
+    return field in settings.OPENID_PROFILE_MAPPING
 
 
 def get_profile_field_name(field):
-    profile_field = openauth.settings.OPENID_PROFILE_MAPPING[field]
+    profile_field = settings.OPENID_PROFILE_MAPPING[field]
     return profile_field
 
 
 def attach_openid_data(openid_request):
-    sreg = SRegRequest(required=openauth.settings.OPENID_EXTRA_FIELDS)
+    sreg = SRegRequest(required=settings.OPENID_EXTRA_FIELDS)
     openid_request.addExtension(sreg)
     ax_msg = FetchRequest()
-    for detail in openauth.settings.OPENID_EXTRA_FIELDS:
-        ax_msg.add(AttrInfo(openauth.settings.AX_URIS[detail], required=True))
+    for detail in settings.OPENID_EXTRA_FIELDS:
+        ax_msg.add(AttrInfo(settings.AX_URIS[detail], required=True))
     openid_request.addExtension(ax_msg)
 
 
     initial = {}
     sreg_response = pickle.loads(request.session['sreg_response'])
     ax_response = pickle.loads(request.session['ax_response'])
-    for field in openauth.settings.OPENID_EXTRA_FIELDS:
+    for field in settings.OPENID_EXTRA_FIELDS:
         if have_profile_name(field):
             profile_field = get_profile_field_name(field)
             if sreg_response:
                 initial.update({profile_field: sreg_response.get(field, '')})
             if ax_response:
-                initial.update({profile_field: ax_response.getSingle(openauth.settings.AX_URIS[field], '')})
+                initial.update({profile_field: ax_response.getSingle(settings.AX_URIS[field], '')})
     return initial
 

File openauth/views.py

 from annoying.decorators import render_to
 from notify import notify_user
 
-import openauth
+from openauth import settings
 from openauth.forms import ResetPasswordForm, NewPasswordForm, LoginForm, \
      OpenIDLoginForm, OpenIDRegistrationForm
 from openauth.utils import email_template, build_redirect_url, str_to_class, \
     Only anonymous users can view this page
     Registration should be allowed in REGISTRATION_ALLOWED setting
     """
-    if not openauth.settings.REGISTRATION_ALLOWED:
+    if not settings.REGISTRATION_ALLOWED:
         return notify_user.notice(request, '/', openauth.lang.REGISTRATION_DISABLED)
     if request.method == "POST":
-        form = str_to_class(openauth.settings.REGISTRATION_FORM)(request.POST)
+        form = str_to_class(settings.REGISTRATION_FORM)(request.POST)
         if form.is_valid():
             user = form.save()
-            if openauth.settings.ACTIVATION_REQUIRED:
+            if settings.ACTIVATION_REQUIRED:
                 user.is_active = False
             user.save()
 
-            if openauth.settings.ACTIVATION_REQUIRED:
-                confirmation = Confirmation.objects.create(user, openauth.settings.ACTIVATION_TYPE)
+            if settings.ACTIVATION_REQUIRED:
+                confirmation = Confirmation.objects.create(user, settings.ACTIVATION_TYPE)
                 params = {'domain': request.get_host(), 'email': user.email, 'url': confirmation.get_url(request)}
                 if email_template(user.email, 'openauth/mail/registration.txt', **params):
                     return notify_user.success(request, "/", openauth.lang.PLEASE_ACTIVATE)
                     user.delete()
                     return notify_user.error(request, "/", openauth.lang.ERROR_SENDING_MAIL)
             else:
-                if openauth.settings.AUTO_LOGIN:
+                if settings.AUTO_LOGIN:
                     user.backend = 'django.contrib.auth.backends.ModelBackend'
                     login_user(request, user)
-                    return notify_user.success(request, openauth.settings.LOGIN_REDIRECT_URL, 
+                    return notify_user.success(request, settings.LOGIN_REDIRECT_URL, 
                                                 openauth.lang.SUCCESSFULL_LOGIN)
                 return notify_user.success(request, "openauth-login", openauth.lang.LOGIN_NOW)
     else:
-        form = str_to_class(openauth.settings.REGISTRATION_FORM)()
+        form = str_to_class(settings.REGISTRATION_FORM)()
     return {'form': form}
 
 
     if request.method == "POST":
         form = LoginForm(request, request.POST)
         if form.is_valid():
-            redirect_url = request.GET.get("next") or openauth.settings.LOGIN_REDIRECT_URL
+            redirect_url = request.GET.get("next") or settings.LOGIN_REDIRECT_URL
             return notify_user.success(request, redirect_url, openauth.lang.SUCCESSFULL_LOGIN)
     else:
         form = LoginForm(request=request)
         form = ResetPasswordForm(request.POST)
         if form.is_valid():
             user = User.objects.get(email=form.cleaned_data['email'].lower())
-            confirmation = Confirmation.objects.create(user, openauth.settings.PASSWORD_RESET_TYPE, redirect_url=reverse("openauth-change-password"))
+            confirmation = Confirmation.objects.create(user, settings.PASSWORD_RESET_TYPE, redirect_url=reverse("openauth-change-password"))
             args = {'domain': request.get_host(), 'url': confirmation.get_url(request)}
             if email_template(user.email, 'openauth/mail/reset_password.txt', **args):
                 return notify_user.notice(request, "/",  _('Check your email please'))
     if request.method == "POST":
         form = OpenIDLoginForm(request.POST, request=request)
         if form.is_valid():
-            next_url = request.GET.get("next") or openauth.settings.LOGIN_REDIRECT_URL
+            next_url = request.GET.get("next") or settings.LOGIN_REDIRECT_URL
             request.session['next_url'] = next_url
             return redirect(form.redirect_url)
     else:
         else:
             user = auth.authenticate(openid_url=resp.identity_url)
             if user:
-                if openauth.settings.OPENID_ACTIVATION_REQUIRED and not user.is_active:
+                if settings.OPENID_ACTIVATION_REQUIRED and not user.is_active:
                     return notify_user.success(request, "/", _("Your account is not activated. Please activate it first."))
                 else:
                     auth.login(request, user)
                     del request.session['next_url']
                     return notify_user.success(request, redirect_url, _("You have successfully authorized via OpenID"))
             else:
-                if not openauth.settings.REGISTRATION_ALLOWED:
+                if not settings.REGISTRATION_ALLOWED:
                     return notify_user.notice(request, '/', openauth.lang.REGISTRATION_DISABLED)
                 # if user must fill addition fields to complete registration
                 # we ease this process by trying to fetch extra information
                 # from openid provider.
-                if not openauth.settings.OPENID_PROFILE_MAPPING:
+                if not settings.OPENID_PROFILE_MAPPING:
                     OpenID(user=request.user, url=resp.identity_url).save()
-                    if not openauth.settings.OPENID_ACTIVATION_REQUIRED:
+                    if not settings.OPENID_ACTIVATION_REQUIRED:
                         user = auth.authenticate(openid_url=resp.identity_url)
                         if user:
                             auth.login(request, user)
         raise Http404
 
     if request.method == "POST":
-        form = str_to_class(openauth.settings.OPENID_REGISTRATION_FORM)(request.POST)
+        form = str_to_class(settings.OPENID_REGISTRATION_FORM)(request.POST)
         if form.is_valid():
             user = form.save(openid_url)
             del request.session['authenticated_openid_url']
-            if openauth.settings.OPENID_ACTIVATION_REQUIRED:
-                confirmation = Confirmation.objects.create(user, openauth.settings.ACTIVATION_TYPE)
+            if settings.OPENID_ACTIVATION_REQUIRED:
+                confirmation = Confirmation.objects.create(user, settings.ACTIVATION_TYPE)
                 params = {'domain': request.get_host(), 'email': user.email, 'url': confirmation.get_url(request)}
                 email_template(user.email, 'openauth/mail/registration.txt', **params)
                 return notify_user.success(request, "openauth-show-user", openauth.lang.PLEASE_ACTIVATE)
                 return notify_user.success(request, redirect_url, _("You have been successfully registred"))
     else:                                        
         initial = {}
-        if openauth.settings.OPENID_PROFILE_MAPPING:
+        if settings.OPENID_PROFILE_MAPPING:
             initial = extract_openid_data(request)
-        form = str_to_class(openauth.settings.OPENID_REGISTRATION_FORM)(initial=initial)
+        form = str_to_class(settings.OPENID_REGISTRATION_FORM)(initial=initial)
 
     return {'form': form, 'openid_url': openid_url}
 
     if not request.user.is_authenticated() or user != request.user and not request.user.is_staff:
         return redirect("/")
     if request.POST:
-        form = str_to_class(openauth.settings.EDIT_USER_FORM)(user, request.POST, request.FILES)
+        form = str_to_class(settings.EDIT_USER_FORM)(user, request.POST, request.FILES)
         if form.is_valid():
             form.save()
             url = reverse('openauth-show-user', args=[request.user.id])
             return notify_user.success(request, url, _('User details successfully changed'))
     else:
-        form = str_to_class(openauth.settings.EDIT_USER_FORM)(user)
+        form = str_to_class(settings.EDIT_USER_FORM)(user)
 
     return {'form': form, 'user': user}