Commits

offline committed 0a2ff10

openid support removed

  • Participants
  • Parent commits 5e92f0c

Comments (0)

Files changed (16)

README.ru

-Персональная страница проекта:
-
-http://bitbucket.org/offline/django-openauth/
-
-Проект имеет зависимости от следующих продуктов:
-
-hg+https://bitbucket.org/offline/django-annoying/#egg=django-annoying
-hg+https://bitbucket.org/offline/django-confirmation/#egg=django-confirmation
-hg+https://bitbucket.org/offline/django-flashcookie/#egg=django-flashcookie
-hg+https://bitbucket.org/offline/django-notify/#egg=django-notify
-python-openid
-

openauth/admin.py

-from django.contrib import admin
-
-from openauth.models import OpenID
-
-
-class OpenIDAdmin(admin.ModelAdmin):
-    list_display = ['user', 'url']
-
-admin.site.register(OpenID, OpenIDAdmin)
-

openauth/backends.py

-from django.contrib.auth.models import User
-
-from openauth.models import OpenID
-
-
-class OpenIDBackend(object):
-    """
-    Don't forget to add this backend to the 
-    AUTHENTICATION_BACKENDS settins of your project
-    if you need OpenID authentication.
-    """
-    def authenticate(self, openid_url=None):
-        """
-        Authenticate user by OpenId url or email in case of gmail or yahoo.
-        """
-        if openid_url:
-            try:
-                user = OpenID.objects.get(url=openid_url).user
-                return user
-            except OpenID.DoesNotExist:
-                return None
-        else:
-            return None
-
-    def get_user(self, user_id):
-        try:
-            return User.objects.get(pk=user_id)
-        except User.DoesNotExist:
-            return None
-

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 settings.AUTHENTICATION_TYPE == settings.USERNAME:
                 self.label = _("Login")
-            if "email" in openauth.settings.AUTHENTICATION_TYPES:
+            if settings.AUTHENTICATION_TYPE == settings.EMAIL:
                 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
 

openauth/forms.py

-from openid.consumer import consumer, discover
-from openid.extensions import sreg, ax
-
-from django import forms
-from django.contrib.auth.models import User
 from django.contrib.auth import login as login_user
 from django.utils.translation import ugettext as _
-from django.core.urlresolvers import reverse
+from django.contrib.auth.models import User
+from django import forms
 
 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.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 settings.AUTHENTICATION_TYPE == settings.EMAIL:
             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 settings.AUTHENTICATION_TYPE == settings.USERNAME:
             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 settings.AUTHENTICATION_TYPE == settings.EMAIL:
             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 settings.AUTHENTICATION_TYPE == settings.USERNAME:
             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 settings.AUTHENTICATION_TYPE == settings.USERNAME:
                 user = get_object_or_None(User, username=login)
-            elif 'email' in openauth.settings.AUTHENTICATION_TYPES:
+            elif settings.AUTHENTICATION_TYPE == settings.EMAIL:
                 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)
 ResetPasswordForm = autostrip(ResetPasswordForm)
 
 
-class OpenIDLoginForm(forms.Form):
-    openid_url = forms.CharField(u'OpenID URL', widget=forms.TextInput())
-
-    def __init__(self, *args, **kwargs):
-        self.request = kwargs.pop('request', {})
-        super(OpenIDLoginForm, self).__init__(*args, **kwargs)
-
-    def clean(self):
-        """
-        Validate the data, try to login user or show form error if 
-        OpenID server returned reject response
-        """
-        request = self.request
-        super(OpenIDLoginForm, self).clean()
-        if self.is_valid():
-            openid_url = self.cleaned_data['openid_url']
-            return_url = request.build_absolute_uri(reverse('openauth-openid-complete'))
-            request.session['openid_return_to'] = return_url
-            client = consumer.Consumer(request.session, None)
-            try:
-                auth_request = client.begin(openid_url)
-                attach_openid_data(auth_request)
-                redirect_url = auth_request.redirectURL(realm='http://' + request.get_host(), return_to=return_url)
-                self.redirect_url = redirect_url
-
-            except discover.DiscoveryFailure:
-                raise forms.ValidationError(_('Could not find OpenID server'))
-        return self.cleaned_data
-
-
-class OpenIDRegistrationForm(forms.Form):
-    def __init__(self, *args, **kwargs):
-        for key, value in openauth.settings.OPENID_PROFILE_MAPPING.items():
-            self.base_fields[value] = forms.CharField()
-            if value == 'email':
-                self.base_fields[value] = forms.EmailField()
-        super(OpenIDRegistrationForm, self).__init__(*args, **kwargs)
-
-    def clean_login(self):
-        login = self.cleaned_data['login']
-        if openauth.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:
-            user.is_active = False
-        user.save()
-        OpenID(user=user, url=openid_url).save()
-        return user
-
-
 class NewPasswordForm(forms.Form):
     """
     Form for changing user's password.
 
 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):
-        self.user = user
-        self.base_fields['username'] = forms.CharField(max_length=254, initial=user.username)
-        super(EditUserForm, self).__init__(*args, **kwargs)
-
-    def save(self):
-        self.user.username = self.cleaned_data['username']
-        self.user.save()
-        return self.user
-
-EditUserForm = autostrip(EditUserForm)
 MUST_ACTIVATE_FIRST = _("You must activate your account first. Please check you email for activation link")
 SUCCESSFULL_LOGIN = _('You have successfully logged-in')
 PLEASE_LOGOUT = _('Please logout before proceeding to this page')
+CHECK_YOUR_EMAIL = _('Check your email please')
+PASSWORD_CHANGED = _('Password changed')
+LOGGED_OUT = _('You have been logged out')

openauth/models.py

-from django.db import models
-from django.contrib.auth.models import User
-
-import openauth
-
-
-User.username = models.CharField(max_length=30, unique=openauth.settings.UNIQUE_USERNAME)
-
-class OpenID(models.Model):
-    user = models.ForeignKey(User)
-    url = models.CharField(u'OpenID URL', max_length=255, unique=True)
-
-    def __unicode__(self):
-        return self.url
-

openauth/settings.py

 
 from annoying.functions import get_config
 
+USERNAME = 1
+EMAIL = 2
 
 ### REGISTRATION_ALLOWED ###########################################################################
 # To disable registration, set it to False                                                         #
 ####################################################################################################
 
 ### AUTHENTIFICATION_TYPES #########################################################################
-# Please provide list or tuple with authentification types that you site want to support.          #
+# Please provide which authentification type your site want to support.                            #
 # The choices are:                                                                                 #
-# 1. username - username will be as login name. Also user will be asked for password               #
-# 2. email - email will be used as login name. Please not that you can't use username and email    #
+# 1. USERNAME - username will be as login name. Also user will be asked for password               #
+# 2. EMAIL - email will be used as login name. Please not that you can't use username and email    #
 #            both in authentication types.                                                         #
-# 3. openid - OpenId type of authentication. Can be used along with username or email              #
-#             authentication.                                                                      #
-AUTHENTICATION_TYPES = get_config("AUTHENTICATION_TYPES", ["username", "openid"])                  #
+AUTHENTICATION_TYPE = get_config("AUTHENTICATION_TYPE", USERNAME)                                  #
 ####################################################################################################
 
 ### ACTIVATION_REQUIRED ############################################################################
 ####################################################################################################
 
 ### LOGIN_LABEL ####################################################################################
-# Please provide an appropriate label for you login field. The default for username type           #
+# Provide an appropriate label for you login field. The default for username type                  #
 # of authentication is 'Login', for email authentication is 'Email'                                #
 LOGIN_LABEL = get_config("LOGIN_LABEL", None)                                                      #
 ####################################################################################################
 
 ### PASSWORD_REGEX #################################################################################
 # The default login regex is anything at all                                                       #
-PASSWORD_REGEX = get_config("PASSWORD_REGEX", re.compile(r"^.*$"))                                 #
+PASSWORD_REGEX = get_config("PASSWORD_REGEX", re.compile(r"^.+$"))                                 #
 ####################################################################################################
 
 ### PASSWORD_LENGTH ################################################################################
 ### LOGIN_URL ######################################################################################
 # When anonymous user try to access page that wrapped by login_required decorator, it will         #
 # redirect him to this url.                                                                        #
-LOGIN_URL = get_config("LOGIN_URL", "/auth/login/")                                                #
+LOGIN_URL = get_config("LOGIN_URL", None)                                                          #
 ####################################################################################################
 
 ### LOGIN_REDIRECT_URL #############################################################################
 # URL that user is redirected after successfull login attempt                                      #
-LOGIN_REDIRECT_URL = get_config("LOGIN_REDIRECT_URL", "/auth/user/")                               #
+LOGIN_REDIRECT_URL = get_config("LOGIN_REDIRECT_URL", None)                                        #
 ####################################################################################################
 
 ### LOGOUT_REDIRECT_URL ############################################################################
 PASSWORD_RESET_TYPE = get_config("PASSWORD_RESET_TYPE", 2)                                         #
 ####################################################################################################
 
-### EDIT_USER_FORM #################################################################################
-# Read the REGISTRATION_FORM description above. One thing to note here is that you shoud not add   #
-# fields in normal way, please look at the original form, you should add form fields from the      #
-# __init__ method, that recive user as one of parameters. This is to allow initial data in fields  #
-EDIT_USER_FORM = get_config("EDIT_USER_FORM", "openauth.forms.EditUserForm")                       #
-####################################################################################################
-
-
-
-### OpenID Settings ###
-
-### OPENID_REGISTRATION_FORM #######################################################################
-# See REGISTRATION_FORM description above                                                          #
-OPENID_REGISTRATION_FORM = get_config("OPENID_REGISTRATION_FORM",                                  #
-                                        "openauth.forms.OpenIDRegistrationForm")                   #
-####################################################################################################
-
-### OPENID_ACTIVATION_REQUIRED #####################################################################
-# If activation is not required, user will be signed in immidiatly after OpenID registration       #
-# process. By default this activation is depend on regular activation setting                      #
-OPENID_ACTIVATION_REQUIRED = get_config("OPENID_ACTIVATION_REQUIRED", ACTIVATION_REQUIRED)         #
-####################################################################################################
-
-### OPENID_EXTRA_FIELDS  ###########################################################################
-# Simple registration fields allows to reterive addition information about user from OpenID        #
-# server. Please list every field that you might ask user when registering with OpenID. The name   #
-# are available on http://www.axschema.org/types/#sreg                                             #
-OPENID_EXTRA_FIELDS = get_config("OPENID_EXTRA_FIELDS", ['nickname'])                              #
-####################################################################################################
-
-### OPENID_PROFILE_MAPPING #########################################################################
-# Please provide a mapping from OPENID_EXTRA_FIELDS to your profile fields.                        #
-OPENID_PROFILE_MAPPING = get_config("OPENID_PROFILE_MAPPING", {'nickname': 'login'})               #
-####################################################################################################
-
-### AX_URIS ########################################################################################
-# This dict contains mapping of SREG fields to AX uris, you probably don't need to change it       #
-# http://www.axschema.org/types/                                                                   #
-AX_URIS = {                                                                                        #
-    'nickname': 'http://axschema.org/namePerson/friendly',                                         #
-    'email': 'http://axschema.org/contact/email',                                                  #
-    'fullname': 'http://axschema.org/namePerson',                                                  #
-    'dob': 'http://axschema.org/birthDate',                                                        #
-    'gender': 'http://axschema.org/person/gender',                                                 #
-    'postcode': 'http://axschema.org/contact/postalCode/home',                                     #
-    'country': 'http://axschema.org/contact/country/home',                                         #
-    'language': 'http://axschema.org/pref/language',                                               #
-    'timezone': 'http://axschema.org/pref/timezone',                                               #
-}                                                                                                  #
-####################################################################################################
-
+REGISTRATION_DISABLED_URL = get_config("REGISTRATION_DISABLED_URL", "/")
+PRE_ACTIVATION_URL = get_config("PRE_ACTIVATION_URL", "/")
+ERROR_SENDING_MAIL_URL = get_config("ERROR_SENDING_MAIL_URL", "/")
+LOGIN_NOW_URL = get_config("LOGIN_NOW_URL", "openauth-login")
+RESET_PASSWORD_URL = get_config("RESET_PASSWORD_URL", "openauth-login")
+PASSWORD_CHANGED_URL = get_config("PASSWORD_CHANGED_URL", "/")

openauth/templates/openauth/openid_login.html

-{% extends 'base.html' %}
-
-{% block content %}
-<script type="text/javascript">
-function chooseProvider(provider) {
-    var form = document.getElementById('openid_login');
-    var url = document.getElementById('id_openid_url');
-    if (provider == 'google') {
-        url.value = 'https://www.google.com/accounts/o8/id';
-        form.submit();
-    } else if(provider == 'yahoo') {
-        url.value =  'http://yahoo.com';
-        form.submit();
-    } else {
-        alert('unknown provider');
-    }
-}
-</script>
-<h2>OpenID Authorization and Registration</h2>
-
-<form action="." method="post" id="openid_login">
-    {{ form.as_table }}
-    <p>Or with <input type="button" name="auth_google" onclick="chooseProvider('google')" value="Google"/></p>
-    <p>Or with <input type="button" name="auth_yahoo" onclick="chooseProvider('yahoo')" value="Yahoo"/></p>
-    <p><input type="submit" value="Continue"/></p>
-</form>
-{% endblock %}

openauth/templates/openauth/openid_registration.html

-{% extends 'base.html' %}
-{% load i18n %}
-
-{% block content %}
-<h2>{% trans "Registration with OpenID: last step" %}</h2>
-<p><label>{% trans "OpenID URL" %}:</label> {{ openid_url }}</p>
-<form method="post">
-    <formfield>
-        <legend>{% trans "Registration with OpenID" %}</legend>
-        <div class="wide">{{ form.as_p }}</div>
-        <p><input type="submit" value="{% trans "Submit" %}"/></p>
-    </formfield>
-</form>
-{% endblock %}

openauth/templates/openauth/profile.html

-{% extends "base.html" %}
-{% block content %}
-{{ user.username }}
-{% endblock content %}

openauth/templates/openauth/users.html

-{% extends 'base.html' %}
-{% block content %}
-{% for user in users %}
-    {{ user }} <br/>
-{% endfor %}
-{% endblock %}

openauth/tests/tests.py

 from django.test import Client, TestCase
 from django.conf import settings
 
-import notify
-import openauth
+from openauth import settings
 from openauth import views
 from openauth import forms
 
 class RegistrationTest(TestCase):
 
     def setUp(self):
-        openauth.settings.REGISTRATION_ALLOWED = True
-        openauth.settings.DISPLAYNAME_REQUIRED = True
-        openauth.settings.LOGIN_REGEX = EMAIL_REGEX
-        openauth.settings.AUTHENTICATION_TYPES = ['email']
-        openauth.settings.REGISTRATION_FORM = "openauth.forms.RegistrationForm"
+        settings.REGISTRATION_ALLOWED = True
+        settings.DISPLAYNAME_REQUIRED = True
+        settings.LOGIN_REGEX = EMAIL_REGEX
+        settings.AUTHENTICATION_TYPE = settings.EMAIL
+        settings.REGISTRATION_FORM = "openauth.forms.RegistrationForm"
         self.client = Client()
         self.registration_url = reverse('openauth-registration')
 
         self.failUnlessEqual(user.username, 'petya')
 
     def test_disabled_registration(self):
-        openauth.settings.REGISTRATION_ALLOWED = False
+        settings.REGISTRATION_ALLOWED = False
         response = self.client.post(self.registration_url, {'username': 'petya', 'email': 'admin@example.com', 'password': 'test', 'password_dup': 'test'}) 
         self.failUnlessRaises(User.DoesNotExist, User.objects.get, username='petya')
 
 class LoginTest(TestCase):
 
     def setUp(self):
-        notify.settings.NOTIFY_TYPE = 'flashcookie'
-        openauth.settings.REGISTRATION_ALLOWED = True
-        openauth.settings.ACTIVATION_REQUIRED = True
-        openauth.settings.LOGIN_REDIRECT_URL = "/auth/user/"
-        openauth.settings.LOGIN_REGEX = USER_REGEX
-        openauth.settings.AUTHENTICATION_TYPES = ['username']
+        settings.REGISTRATION_ALLOWED = True
+        settings.ACTIVATION_REQUIRED = True
+        settings.LOGIN_REDIRECT_URL = "/auth/user/"
+        settings.LOGIN_REGEX = USER_REGEX
+        settings.AUTHENTICATION_TYPE = settings.USERNAME
         self.client = Client()
         self.login_url = reverse('openauth-login')
         self.active_user = User.objects.create_user('ivan', 'ivan@example.com', password='test')
 
     def test_valid_active_user_activation_enabled(self):
         response = self.client.post(self.login_url, {'login': self.active_user.username, 'password': 'test'})
-        self.assertRedirects(response, openauth.settings.LOGIN_REDIRECT_URL)
+        self.assertRedirects(response, settings.LOGIN_REDIRECT_URL)
 
     def test_invalid_active_user_activation_enabled(self):
         response = self.client.post(self.login_url, {'login': self.active_user.username, 'password': 'INCORRECT'})
         self.assertEqual(response.status_code, 200)
 
     def test_inactive_user_activation_disabled(self):
-        openauth.settings.ACTIVATION_REQUIRED = False
+        settings.ACTIVATION_REQUIRED = False
         response = self.client.post(self.login_url, {'login': self.inactive_user.username, 'password': 'test'})
-        self.assertRedirects(response, openauth.settings.LOGIN_REDIRECT_URL)
+        self.assertRedirects(response, settings.LOGIN_REDIRECT_URL)
 from openauth import views
 
 urlpatterns = patterns('',
+    url(r'^login/$', views.login, name='openauth-login'),
+    url(r'^logout/$', views.logout, name='openauth-logout'),
     url(r'^registration/$', views.registration, name='openauth-registration'),
-    url(r'^login/$', views.login, name='openauth-login'),
-    url(r'^openid-login/$', views.openid_login, name='openauth-openid-login'),
-    url(r'^openid-complete/$', views.openid_complete, name='openauth-openid-complete'),
-    url(r'^openid-registration/$', views.openid_registration, name='openauth-openid-registration'),
-    url(r'^logout/$', views.logout, name='openauth-logout'),
     url(r'^reset-password/$', views.reset_password, name='openauth-reset-password'),
     url(r'^change-password/$', views.change_password, name='openauth-change-password'),
-    url(r'^user/$', views.show_user, name='openauth-show-user'),
-    url(r'^user/(\d+)/$', views.show_user, name='openauth-show-user'),
-    url(r'^users/$', views.users, name='openauth-show-users'),
-    url(r'^edit/(\d+)/$', views.edit_user, name='openauth-edit-user'),
-    #url(r'^email_changed/$', views.email_changed, name='auth_email_changed'),
 )

openauth/utils.py

 import re
-import pickle
-from functools import wraps
+import time
 
-from openid.extensions.sreg import SRegRequest, SRegResponse
-from openid.extensions.ax import FetchRequest, AttrInfo, FetchResponse
+from urllib import urlencode
 
+from django.template.loader import get_template
+from django.core.urlresolvers import reverse
+from django.utils.encoding import smart_str
 from django.shortcuts import redirect
-from django.utils.translation import ugettext as _
-from django.core.urlresolvers import reverse
+from django.core.mail import send_mail
+from django.template import Context
 from django.conf import settings
 
-from notify import notify_user
-
-import openauth
 
 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 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.
+    """
+    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.
+    """
+    subject, content = parse_template(template_path, **kwargs)
+    count = send_mail(subject, content, settings.DEFAULT_FROM_EMAIL,
+                      [rcpt], fail_silently=True)
+    return bool(count)
+
+
+def str_to_class(str):
+    mod_str, cls_str = str.rsplit('.', 1)
+    mod = __import__(mod_str, globals(), locals(), ['foobar'])
+    cls = getattr(mod, cls_str)
+    return cls
+
+
 def generate_hash(string=None):
-    import time
     try:
         from hashlib import md5
     except ImportError:
 
     if not string:
         string = str(time.time()) + settings.SECRET_KEY
-    hash = md5(string).hexdigest()
-    return hash
+    return md5(smart_str(string)).hexdigest()
 
-
-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)
-
-
-def str_to_class(str):
-    mod_str, cls_str = str.rsplit('.', 1)
-    mod = __import__(mod_str, globals(), locals(), ['foobar'])
-    cls = getattr(mod, cls_str)
-    return cls
-
-
-
-def login_required(*args, **kwargs):
-    """
-    Decorator for views that checks if user activated and authenticated
-    if opposite is True, allow only anonymouses users to enter this view.
-    can be used as:
-    @login_required
-    def my_view(request, ..)
-    
-    or
-
-    @login_required(opposite=True)
-    def my_view_for_anonymous_users(request, ..)
-    """
-    _kwargs = kwargs
-    def decorator(function):
-        def wrapper(request, *args, **kwargs):
-            opposite = _kwargs.get('opposite', False)
-            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:
-                    return notify_user.notice(request, "/", openauth.lang.MUST_ACTIVATE_FIRST)
-            elif not opposite:
-                next_data = {'next': request.path}
-                next = reverse('openauth-login')
-                joiner = ('?' in next) and '&' or '?'
-                next += joiner + unicode_urlencode(next_data) 
-                return redirect(next)
-            return function(request, *args, **kwargs)
-        return wrapper
-    if kwargs:
-        return decorator
-    else:
-        return decorator(args[0])
-
-
-def uri_to_username(uri):
-    return re.sub('r[^0-9a-z]', '_', uri)
-
-
-def have_profile_name(field):
-    return field in openauth.settings.OPENID_PROFILE_MAPPING
-
-
-def get_profile_field_name(field):
-    profile_field = openauth.settings.OPENID_PROFILE_MAPPING[field]
-    return profile_field
-
-
-def attach_openid_data(openid_request):
-    sreg = SRegRequest(required=openauth.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))
-    openid_request.addExtension(ax_msg)
-
-
-def dump_openid_data(request, response):
-    request.session['authenticated_openid_url'] = response.identity_url
-    sreg_response = SRegResponse.fromSuccessResponse(response)
-    ax_response = FetchResponse.fromSuccessResponse(response)
-    request.session['sreg_response'] = pickle.dumps(sreg_response)
-    request.session['ax_response'] = pickle.dumps(ax_response)
-
-
-def extract_openid_data(request):
-    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:
-        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], '')})
-    return initial
-

openauth/views.py

-import pickle
-
-from openid.consumer import consumer, discover
-from openid.extensions import sreg, ax
-
-from django.shortcuts import get_object_or_404, redirect
+from django.contrib.auth.decorators import login_required
 from django.contrib.auth import login as login_user
-from django.utils.translation import ugettext as _
 from django.core.urlresolvers import reverse
 from django.contrib.auth.models import User
+from django.shortcuts import redirect
+from django.contrib import messages
 from django.contrib import auth 
-from django.http import Http404
 
 from confirmation.models import Confirmation
 from annoying.decorators import render_to
-from notify import notify_user
 
-import openauth
-from openauth.forms import ResetPasswordForm, NewPasswordForm, LoginForm, \
-     OpenIDLoginForm, OpenIDRegistrationForm
-from openauth.utils import email_template, build_redirect_url, str_to_class, \
-    login_required, dump_openid_data, extract_openid_data
-from openauth.models import OpenID
+from openauth.forms import ResetPasswordForm, NewPasswordForm, LoginForm
+from openauth.utils import email_template, str_to_class 
+from openauth import settings
+from openauth import lang
 
 
-@login_required(opposite=True)
 @render_to('openauth/registration.html')
 def registration(request):
     """
     Only anonymous users can view this page
     Registration should be allowed in REGISTRATION_ALLOWED setting
     """
-    if not openauth.settings.REGISTRATION_ALLOWED:
-        return notify_user.notice(request, '/', openauth.lang.REGISTRATION_DISABLED)
+    if not settings.REGISTRATION_ALLOWED:
+        messages.notice(request, lang.REGISTRATION_DISABLED)
+        return redirect(settings.REGISTRATION_DISABLED_URL)
     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)
+                    messages.success(request, lang.PLEASE_ACTIVATE)
+                    return redirect(settings.PRE_ACTIVATION_URL)
                 else:
                     user.delete()
-                    return notify_user.error(request, "/", openauth.lang.ERROR_SENDING_MAIL)
+                    messages.error(request, lang.ERROR_SENDING_MAIL)
+                    return redirect(settings.ERROR_SENDING_MAIL_URL)
             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, 
-                                                openauth.lang.SUCCESSFULL_LOGIN)
-                return notify_user.success(request, "openauth-login", openauth.lang.LOGIN_NOW)
+                    messages.success(request, lang.SUCCESSFULL_LOGIN)
+                    return redirect(settings.LOGIN_REDIRECT_URL)
+                else:
+                    messages.success(request, lang.LOGIN_NOW)
+                    return redirect(settings.LOGIN_NOW)
     else:
-        form = str_to_class(openauth.settings.REGISTRATION_FORM)()
+        form = str_to_class(settings.REGISTRATION_FORM)()
     return {'form': form}
 
 
-@login_required(opposite=True)
 @render_to('openauth/login.html')
 def login(request):
     """
-    Login function for username of email based authentication.
-    Two allow also openid authentication on the same page, 
-    please adjust action url in form with javascipt.
+    Login function for username or email based authentication.
+    After successfull authentication, user will be redirected to 
+    LOGIN_REDIRECT_URL or to 'next' get parameter if exists.
     """
     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
-            return notify_user.success(request, redirect_url, openauth.lang.SUCCESSFULL_LOGIN)
+            redirect_url = request.GET.get("next") or settings.LOGIN_REDIRECT_URL
+            messages.success(request, lang.SUCCESSFULL_LOGIN)
+            return redirect(redirect_url)
     else:
         form = LoginForm(request=request)
     return {'form': form}
 
 
-@login_required(opposite=True)
 @render_to('openauth/reset_password.html')
 def reset_password(request):
     if request.POST:
         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'))
-            else:
-                return notify_user.notice(request, "/", openauth.lang.ERROR_SENDING_MAIL)
+            email_template(user.email, 'openauth/mail/reset_password.txt', **args)
+            messages.notice(request, lang.CHECK_YOUR_EMAIL)
+            return redirect(settings.RESET_PASSWORD_URL)
     else:
         form = ResetPasswordForm()
     return {'form': form}
 
 
-@render_to('openauth/openid_login.html')
-def openid_login(request):
-    """
-    Display OpenID authentication form. This is also the first step
-    in OpenID registration. The actual login is in openid_complete 
-    function below.
-    """
-    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
-            request.session['next_url'] = next_url
-            return redirect(form.redirect_url)
-    else:
-        form = OpenIDLoginForm()
-
-    return {'form': form}
-
-
-def openid_complete(request):
-    """
-    Complete OpenID authorization process.
-    If OpenID URL was successfuly authenticated:
-     * if no user with such URL exists and current user is authenticated then
-       assign OpenID url to this user
-     * if user with such URL exists then login as this user
-     * if no user with such URL exists then redirect to registration form
-    """
-    client = consumer.Consumer(request.session, None)
-    data = dict(request.GET.items())
-
-    # In case OpenID server responded with POST method
-    if request.method == "POST":
-        data.update(request.POST)
-    try:
-        resp = client.complete(data, request.session['openid_return_to'])
-        del request.session['openid_return_to']
-    except KeyError:
-        return notify_user.error(request, 
-                reverse("openauth-openid-login"),
-                _("Invalid response received from OpenID server, please start start the authentication process again")
-                )
-    if resp.status == consumer.CANCEL:
-        return notify_user.error(request, "/", _('You have cancelled OpenID authorization'))
-    elif resp.status == consumer.FAILURE:
-        return notify_user.error(request, "/", _('OpenID authorization failed. Reason: %s') % resp.message)
-    elif resp.status == consumer.SUCCESS:
-        redirect_url = request.session['next_url']
-        if request.user.is_authenticated():
-            try:
-                user = OpenID.objects.get(url=resp.identity_url).user
-            except OpenID.DoesNotExist:
-                OpenID(user=request.user, url=resp.identity_url).save()
-            del request.session['next_url']
-            return notify_user.success(request, redirect_url, _("Your OpenID account is saved"))
-        else:
-            user = auth.authenticate(openid_url=resp.identity_url)
-            if user:
-                if openauth.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:
-                    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:
-                    OpenID(user=request.user, url=resp.identity_url).save()
-                    if not openauth.settings.OPENID_ACTIVATION_REQUIRED:
-                        user = auth.authenticate(openid_url=resp.identity_url)
-                        if user:
-                            auth.login(request, user)
-                            del request.session['next_url']
-                            return notify_user.success(request, redirect_url, _("You have successfully authorized via OpenID"))
-                else:
-                    dump_openid_data(request, resp)
-                    return redirect(reverse('openauth-openid-registration'))
-
-    return notify_user.error(request, reverse("openauth-openid-login"), _("Invalid response received from OpenID server, please start start the authentication process again"))
-
-
-@render_to('openauth/openid_registration.html')
-def openid_registration(request):
-    """                                                
-    Handle registration new user with given authenticated_openid_url in session
-    """                                                          
-    try:
-        openid_url = request.session['authenticated_openid_url']
-    except KeyError:
-        raise Http404
-
-    if request.method == "POST":
-        form = str_to_class(openauth.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)
-                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)
-            user = auth.authenticate(openid_url=openid_url)
-            if user:
-                auth.login(request, user)
-                redirect_url = request.session['next_url']
-                del request.session['next_url']
-                return notify_user.success(request, redirect_url, _("You have been successfully registred"))
-    else:                                        
-        initial = {}
-        if openauth.settings.OPENID_PROFILE_MAPPING:
-            initial = extract_openid_data(request)
-        form = str_to_class(openauth.settings.OPENID_REGISTRATION_FORM)(initial=initial)
-
-    return {'form': form, 'openid_url': openid_url}
-
-
-
 @login_required
 @render_to('openauth/change_password.html')
 def change_password(request):
     if form.is_valid():
         form.save(request.user)
         url = reverse('openauth-show-user', args=[request.user.id])
-        return notify_user.success(request, url, _('Password was changed'))
+        messages.success(request, lang.PASSWORD_CHANGED)
+        return redirect(settings.PASSWORD_CHANGED_URL)
     return {'form': form}
 
 
 @login_required
 def logout(request):
     auth.logout(request)
-    return notify_user.success(request, openauth.settings.LOGOUT_REDIRECT_URL, _('You have been logged out'))
+    messages.success(request, lang.PASSWORD_CHANGED)
+    return redirect(settings.LOGOUT_REDIRECT_URL)
 
-
-
-@login_required
-@render_to('openauth/edit_user.html')
-def edit_user(request, user_id):
-    user = get_object_or_404(User, pk=user_id)
-    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)
-        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)
-
-    return {'form': form, 'user': user}
-
-
-
-@render_to('openauth/profile.html')
-def show_user(request, user_id=None):
-    """
-    Show user profile 
-    """
-    user_id = user_id or request.user.id
-    user = get_object_or_404(User, pk=user_id)
-    return {'user': user}
-
-
-@render_to('openauth/users.html')
-def users(request):
-    users = User.objects.filter(is_active=True).all()
-    return {'users': users}
-