Commits

offline committed 808914f

all code from basic authentication is removed

  • Participants
  • Parent commits 88f420a

Comments (0)

Files changed (16)

openauth/backends/email.py

-from __future__ import absolute_import
-
-from django import forms
-from openauth.backends import BaseBackend
-from django.utils.translation import ugettext as _
-
-from annoying.exceptions import Redirect
-
-from openauth import settings
-from openauth.fields import PasswordField
-
-
-class EmailBackend(BaseBackend):
-
-    email = forms.EmailField()
-    password = PasswordField()
-
-    def clean(self):
-        """
-        Validate cridentials and login the user in case of success.
-        If user is not activated and ACTIVATION_REQUIRED set to True
-        form will not validate.
-        """
-        super(EmailBackend, 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 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)
-                raise Redirect(settings.LOGIN_REDIRECT_URL)
-            else:
-                raise forms.ValidationError(_(u'Incorrect authentication data'))
-
-
-

openauth/backends/openid.py

 
         try:
             openid_request = client.begin(openid_url)
-            sreg = SRegRequest(required=settings.OPENID_EXTRA_FIELDS)
+            sreg_extra = [i for i in self.PROFILE_MAPPING]
+            sreg = SRegRequest(required=sreg_extra)
             openid_request.addExtension(sreg)
             ax_msg = FetchRequest()
-            for detail in settings.GOOGLE_EXTRA_FIELDS:
+            for detail in self.PROFILE_MAPPING:
                 ax_msg.add(AttrInfo(settings.AX_URIS[detail], required=True))
             openid_request.addExtension(ax_msg)
 

openauth/fields.py

-from django.utils.translation import ugettext as _
-from django.contrib.auth.models import User
-from django.contrib.auth import login
-from django import forms
-
-from annoying.functions import get_object_or_None
-
-from openauth import settings
-
-
-class LoginField(forms.CharField):
-    """
-    Form field for login handling.
-    Please set LOGIN_LABEL attribute in your settings file
-    """
-
-    def __init__(self, *args, **kwargs):
-        """
-        Set label according to authentication type or set it
-        to custom label defined in project settings file.
-        """
-        super(LoginField, self).__init__(*args, **kwargs)
-        if not settings.LOGIN_LABEL:
-            if "username" in settings.AUTHENTICATION_TYPES:
-                self.label = _("Login")
-            if "email" in settings.AUTHENTICATION_TYPES:
-                self.label = _("Email")
-        else:
-            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) < 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
-
-
-class PasswordField(forms.CharField):
-    """
-    Form field for password handling.
-    """
-
-    def __init__(self, *args, **kwargs):
-        """
-        Set field widget to PasswordInput to hide characters
-        when user type.
-        """
-        super(PasswordField, self).__init__(*args, **kwargs)
-        self.widget = forms.PasswordInput()
-        self.help_text = ''
-
-    def clean(self, value):
-        """
-        Validate the field with min/max length restrictions and regex.
-        """
-        super(PasswordField, self).clean(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 django.utils.translation import ugettext as _
+from django.contrib.auth.models import User
 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 annoying.functions import get_object_or_None
 from annoying.decorators import autostrip
 
-from openauth.utils import uri_to_username
-from openauth.fields import LoginField, PasswordField
 from openauth.models import SocialID
 from openauth import settings
 
 
-class RegistrationForm(forms.Form):
-    """
-    Basic registration form. 
-    To provide custom registration form, please refer to settings 
-    file for instractions.
-    """
-    def __init__(self, *args, **kwargs):
-        if settings.DISPLAYNAME_REQUIRED:
-            self.base_fields['username'] = forms.CharField()
-        super(RegistrationForm, self).__init__(*args, **kwargs)
-
-    login = LoginField()
-    password = PasswordField(label=_('Password'))
-    password_dup = PasswordField(label=_('Password (confirmation)'))
-
-
-    def clean_login(self):
-        """
-        Validate login field according to AUTHENTIFICATION types 
-        specified in settings. The login field must be unique.
-        """
-        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 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']
-
-
-    def clean_username(self):
-        """
-        Validate uniqeness of username in case DISPLAYNAME_REQUIRED 
-        is set to True.
-        """
-        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']
-
-
-    def clean(self):
-        """
-        Validates that password and confirmation password are the same.
-        """
-        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):
-        """
-        Fill free to override this method in your custom registration
-        form. The method should return User instance.
-        """
-        user = User()
-        if "email" in settings.AUTHENTICATION_TYPES:
-            user.email = self.cleaned_data['login'].lower()
-            if settings.DISPLAYNAME_REQUIRED:
-                user.username = self.cleaned_data['username']
-            else:
-                user.username = user.email
-        if "username" in settings.AUTHENTICATION_TYPES:
-            user.username = self.cleaned_data['login']
-        user.set_password(self.cleaned_data['password'])
-        user.save()
-        return user
-
-RegistrationForm = autostrip(RegistrationForm)
-
-
-class LoginForm(forms.Form):
-    """
-    Login form for username or email base authentication types.
-    """
-    login = LoginField()
-    password = PasswordField()
-
-    def __init__(self, request, *args, **kwargs):
-        self.request = request
-        super(LoginForm, self).__init__(*args, **kwargs)
-
-    def clean(self):
-        """
-        Validate cridentials and login the user in case of success.
-        If user is not activated and ACTIVATION_REQUIRED set to True
-        form will not validate.
-        """
-        super(LoginForm, self).clean()
-        if self.is_valid():
-            login = self.cleaned_data['login']
-            password = self.cleaned_data['password']
-            if 'username' in settings.AUTHENTICATION_TYPES:
-                user = get_object_or_None(User, username=login)
-            elif 'email' in settings.AUTHENTICATION_TYPES:
-                user = get_object_or_None(User, email=login.lower())
-            if user and  user.check_password(password):
-                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)
-                return self.cleaned_data
-            else:
-                raise forms.ValidationError(_(u'Incorrect authentication data'))
-
-LoginForm = autostrip(LoginForm)
-
-
-class ResetPasswordForm(forms.Form):
-    """
-    This form will send confirmation link to user asocciated with this email. 
-    Please note that users without email can't reset their passwords. 
-    """
-    email = forms.EmailField(label=_('Email'))
-
-    def clean_email(self):
-        """
-        Check that user with such email exists in database.
-        """
-        email = self.cleaned_data['email'].lower()
-        if get_object_or_None(User, email=email):
-            return email
-        else:
-            raise forms.ValidationError(_(u'This email is not registered'))
-
-ResetPasswordForm = autostrip(ResetPasswordForm)
-
-
-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 SocialIDExtraForm(forms.Form):
     def __init__(self, *args, **kwargs):
         """
             self.base_fields[key] = value
         super(SocialIDExtraForm, self).__init__(*args, **kwargs)
 
+    def clean_username(self):
+        if get_object_or_None(User, username=self.cleaned_data['username']):
+            raise forms.ValidationError(_(u'This username name is already taken'))
+        return self.cleaned_data['username']
+
+
     def save(self, identity, provider):
         user = User.objects.create(username=self.cleaned_data['username'])
         if settings.SOCIALID_ACTIVATION_REQUIRED:
         SocialID.objects.create(user=user, identity=identity, provider=provider)
         return user
 
+SocialIDExtraForm = autostrip(SocialIDExtraForm)
+

openauth/models.py

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

openauth/settings.py

 REGISTRATION_ALLOWED = get_config("REGISTRATION_ALLOWED", True)                                    #
 ####################################################################################################
 
-### AUTHENTIFICATION_TYPES #########################################################################
-# Please provide list or tuple with authentification types that you 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    #
-#            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"])                  #
-####################################################################################################
-
 ### ACTIVATION_REQUIRED ############################################################################
 # Activation is provided by seperate application, django-confirmation                              #
 # http://bitbucket.org/offline/django-confirmation/                                                #
 ACTIVATION_REQUIRED = get_config("ACTIVATION_REQUIRED", False)                                     #
 ####################################################################################################
 
-### REGISTRATION_FORM ##############################################################################
-# If you want to define your own registration form, please provide a string representing the       #
-# application name, module and a class. To cut developing time, subclass the original              #
-# RegistrationForm class, add your fields and override the save() method.                          #
-REGISTRATION_FORM = get_config("REGISTRATION_FORM", "openauth.forms.RegistrationForm")             #
-####################################################################################################
-
-### LOGIN_REGEX ####################################################################################
-# The default login regex is to allow anything as login                                            #
-LOGIN_REGEX = get_config("LOGIN_REGEX", re.compile(r"^.*$"))                                       #
-####################################################################################################
-
-### LOGIN_LENGTH ###################################################################################
-# You can set default login length, Only usefull in case of username authentication type           #
-LOGIN_MIN_LENGTH = get_config("LOGIN_MIN_LENGTH", 1)                                               #
-LOGIN_MAX_LENGTH = get_config("LOGIN_MAX_LENGTH", 50)                                              #
-####################################################################################################
-
-### LOGIN_LABEL ####################################################################################
-# Please 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)                                                      #
-####################################################################################################
-
-### DISPLAYNAME_REQUIRED ###########################################################################
-# In any type of authentication you may decide that user need another name besides login, email    #
-# or open url name. If it set to True, user will be required to provide this name at registration  #
-# time                                                                                             #
-DISPLAYNAME_REQUIRED = get_config("DISPLAYNAME_REQUIRED", False)                                   #
-####################################################################################################
-
-### UNIQUE_USERNAME ################################################################################
-# In case of django username field used as display name and email or OpenID as login, you can      #
-# set it to false to allow duplicate usernames                                                     #
-UNIQUE_USERNAME = get_config("UNIQUE_USERNAME", True)                                              #
-####################################################################################################
-
-### PASSWORD_REGEX #################################################################################
-# The default login regex is anything at all                                                       #
-PASSWORD_REGEX = get_config("PASSWORD_REGEX", re.compile(r"^.*$"))                                 #
-####################################################################################################
-
-### PASSWORD_LENGTH ################################################################################
-# You can set default password length                                                              #
-PASSWORD_MIN_LENGTH = get_config("PASSWORD_MIN_LENGTH", 1)                                         #
-PASSWORD_MAX_LENGTH = get_config("PASSWORD_MAX_LENGTH", 50)                                        #
-####################################################################################################
-
 ### LOGIN_URL ######################################################################################
 # When anonymous user try to access page that wrapped by login_required decorator, it will         #
 # redirect him to this url.                                                                        #
 # django-confirmation use confirmation types to distinct confirmations. Please don't change this   #
 # settings                                                                                         #
 ACTIVATION_TYPE = get_config("ACTIVATION_TYPE", 1)                                                 #
-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 #######################################################################
+### SOCIALID_REGISTRATION_FORM #####################################################################
 # See REGISTRATION_FORM description above                                                          #
 SOCIALID_EXTRA_FORM = get_config("SOCIALID_EXTRA_FORM", "openauth.forms.SocialIDExtraForm")        #
 ####################################################################################################
 
-OPENID_ACTIVATION_REQUIRED = get_config("OPENID_ACTIVATION_REQUIRED", False)                       #
-
 ### SOCIAL_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                      #
-SOCIALID_ACTIVATION_REQUIRED = get_config("OPENID_ACTIVATION_REQUIRED", ACTIVATION_REQUIRED)       #
+SOCIALID_ACTIVATION_REQUIRED = get_config("SOCIALID_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'})               #
-####################################################################################################
-
-SOCIALID_EXTRA_FIELDS_MAPPING = get_config("SOCIALID_EXTRA_FIELDS_MAPPING", {'nickname': 'login', 'emai': 'email'}) #
-
 ### 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/                                                                   #
 }                                                                                                  #
 ####################################################################################################
 
-
 ### BACKEND_MAPPING ################################################################################
 BACKEND_MAPPING = get_config("BACKEND_MAPPING", {                                                  #
     'openid': 'openauth.backends.openid.OpenIDBackend',                                            #
     'google': 'openauth.backends.google.GoogleBackend',                                            #
     'twitter': 'openauth.backends.twitter.TwitterBackend',                                         #
     'facebook': 'openauth.backends.facebook.FacebookBackend',                                      #
-    'email': 'openauth.backends.email.EmailBackend',
-    #'oauth': 'openauth.backends.oauth.OAuthBackend',                                               #
+    #'oauth': 'openauth.backends.oauth.OAuthBackend',                                              #
     }                                                                                              #
 )                                                                                                  #
 ####################################################################################################
                                                                                                    #
 ####################################################################################################
 
-GOOGLE_OPENID_URL = "https://www.google.com/accounts/o8/id"
-
-
 REGISTRATION_DISABLED_REDIRECT = get_config("REGISTRATION_DISABLED_REDIRECT", "/")
 
-FACEBOOK_EXTRA_FIELDS = ['name']
-FACEBOOK_PROFILE_MAPPING = get_config("FACEBOOK_PROFILE_MAPPING", {'name': 'login'})        
-
-GOOGLE_EXTRA_FIELDS = ['nickname', 'email', 'fullname', 'dob', 'gender']
-GOOGLE_PROFILE_MAPPING = get_config("GOOGLE_PROFILE_MAPPING", {'nickname': 'login', 'email': 'email'})        
-
-TWITTER_EXTRA_FIELDS = ['screen_name']
-TWITTER_PROFILE_MAPPING = get_config("TWITTER_PROFILE_MAPPING", {'screen_name': 'login', 'email': 'email'})        

openauth/signals.py

         if settings.ACTIVATION_AUTO_LOGIN:
             user.backend = 'django.contrib.auth.backends.ModelBackend'
             auth.login(request, user)
-            
-    elif confirmation_type == settings.PASSWORD_RESET_TYPE:
-        user = instance
-        user.backend = 'django.contrib.auth.backends.ModelBackend'
-        auth.login(request, user)    
-

openauth/templates/openauth/change_password.html

-{% extends 'base.html' %}
-{% load i18n %}
-
-{% block content %}
-<h1>{% trans "New password" %}</h1>
-<form method="post" action=".">
-    <div class="wide">{{ form.as_p }}</div>
-    <p><input type="submit" value="{% trans "Save" %}" /></p>
-</form>
-
-{% endblock %}

openauth/templates/openauth/login.html

-{% extends 'base.html' %}
-{% block content %}
-<h1>Вход</h1>
-<div class="error">{{ error }}</div>
-<form method='post' action='?next={{ request.GET.next }}' id="loginform">
-    <table>
-    {{ form.as_table }}
-    </table>
-    <input type='submit' value='Войти' />
-</form>
-
-<div>
-  <p>Есть OpenID или учетная запись Google? <a href="../openid-login/">Войти с помощью OpenID</a>.</p>
-</div>
-<div>
-	<h3>Забыли пароль?</h3>
-	<p>Если вы забыли пароль, то сервер <span><a href="../reset_password/">может отправить вам новый</a></span>.</p>
-</div>
-<div>
-	<h3>Новый пользователь?</h3>
-	<p>Чтобы стать новым пользователем перейдите на <span><a href="../registation/">страницу регистрации</a></span>.</p>
-</div>
-{% endblock content %}

openauth/templates/openauth/profile.html

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

openauth/templates/openauth/registration.html

-{% extends 'base.html' %}
-{% block content %}
-<form action='.' method='post'>
-    <table>
-        {{ form.as_table }}
-    </table>
-<input type='submit' value='submit' />
-</form>
-{% endblock %}

openauth/templates/openauth/reset_password.html

-{% extends 'base.html' %}
-
-{% block content %}
-<form action="." method="post">
-    <table>
-    {{ form.as_table }}
-    </table>
-    <input type="submit" name="submit" value="submit" />
-</form>
-{% endblock content %}

openauth/templates/openauth/users.html

-{% extends 'base.html' %}
-{% block content %}
-{% for user in users %}
-    {{ user }} <br/>
-{% endfor %}
-{% endblock %}
 
 
 urlpatterns = patterns('',
-    url(r'^registration/$', views.registration, name='openauth-registration'),
-    url(r'^login/$', views.login, name='openauth-login'),
     url(r'^social-login/$', views.social_login, name='openauth-social-login'),
     url(r'^social-login/(\w+)/$', views.social_login, name='openauth-social-login'),
     url(r'^social-complete/(\w+)/$', views.social_complete, name='openauth-social-complete'),
     url(r'^social-extra/(\w+)/$', views.social_extra, name='openauth-social-extra'),
     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'^xdreceiver/$', direct_to_template, {'template': 'openauth/xdreceiver.html'}, name='openauth-facebook-xdreceiver'),
 )

openauth/utils.py

 import re
-import time
-import pickle
-
-try:
-    from hashlib import md5
-except ImportError:
-    import md5
-    md5 = md5.new
 
 from functools import wraps
-from urllib import urlencode
-
-from openid.extensions.sreg import SRegRequest, SRegResponse
-from openid.extensions.ax import FetchRequest, AttrInfo, FetchResponse
 
 from django.core.exceptions import ImproperlyConfigured
 from django.utils.importlib import import_module
-from django.conf import settings as django_settings
-from django.utils.translation import ugettext as _
-from django.core.urlresolvers import reverse
+from django.conf import settings
 from django.template.loader import get_template
 from django.template import Context
-from django.shortcuts import redirect
 from django.core.mail import send_mail
 
-from notify import notify_user
-
-import openauth
-from openauth import settings
-
-
-def unicode_urlencode(params):
-    """A unicode aware version of urllib.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):
-    """Generate random or md5 version of string"""
-
-    if not string:
-        string = str(time.time()) + django_settings.SECRET_KEY
-    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):
     """
     """
 
     subject, content = parse_template(template_path, **kwargs)
-    count = send_mail(subject, content, django_settings.DEFAULT_FROM_EMAIL,
+    count = send_mail(subject, content, settings.DEFAULT_FROM_EMAIL,
                       [rcpt], fail_silently=True)
     return bool(count)
 
     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 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)
 

openauth/views.py

-import pickle
+from django.utils.translation import ugettext as _
+from django.shortcuts import redirect
+from django.http import Http404
+from django.contrib import auth 
 
-from openid.consumer import consumer, discover
-from openid.extensions import sreg, ax
+from annoying.decorators import render_to
+from confirmation.models import Confirmation
 
-from django.shortcuts import get_object_or_404, redirect
-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.contrib import auth 
-from django.http import Http404
+from openauth.utils import email_template, str_to_class, get_instance_from_path
+from openauth.forms import SocialIDExtraForm
+from openauth import settings
 
-from confirmation.models import Confirmation
-from annoying.decorators import render_to
-from annoying.exceptions import Redirect
-from notify import notify_user
 
-from openauth import settings
-from openauth.forms import ResetPasswordForm, NewPasswordForm, LoginForm, SocialIDExtraForm
-from openauth.utils import email_template, build_redirect_url, str_to_class, login_required, get_instance_from_path
-
-
-@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 settings.REGISTRATION_ALLOWED:
-        return notify_user.notice(request, '/', openauth.lang.REGISTRATION_DISABLED)
-    if request.method == "POST":
-        form = str_to_class(settings.REGISTRATION_FORM)(request.POST)
-        if form.is_valid():
-            user = form.save()
-            if settings.ACTIVATION_REQUIRED:
-                user.is_active = False
-            user.save()
-
-            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)
-                else:
-                    user.delete()
-                    request.flash['error'] = openauth.lang.ERROR_SENDING_MAIL
-                    return redirect("/")
-            else:
-                if settings.AUTO_LOGIN:
-                    user.backend = 'django.contrib.auth.backends.ModelBackend'
-                    login_user(request, user)
-                    request.flash['success'] = openauth.lang.SUCCESSFULL_LOGIN
-                    return redirect(settings.LOGIN_REDIRECT_URL)
-
-                request.flash['success'] = openauth.lang.LOGIN_NOW
-                return redirect("openauth-login")
-    else:
-        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.
-    """
-    if request.method == "POST":
-        form = LoginForm(request, request.POST)
-        if form.is_valid():
-            redirect_url = request.GET.get("next") or settings.LOGIN_REDIRECT_URL
-            request.flash['success'] = openauth.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, 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):
-                request.flash['notice'] =  _('Check your email please')
-                return redirect("/")
-            else:
-                request.flash['notice'] = openauth.lang.ERROR_SENDING_MAIL
-                return redirect("/")
-    else:
-        form = ResetPasswordForm()
-    return {'form': form}
-
-
-@login_required
-@render_to('openauth/change_password.html')
-def change_password(request):
-    if request.POST:
-        form = NewPasswordForm(request.POST)
-    else:
-        form = NewPasswordForm()
-
-    if form.is_valid():
-        form.save(request.user)
-        request.flash['success'] =  _('Password was changed')
-        return redirect("/")
-    return {'form': form}
-
-
-@login_required
 def logout(request):
     auth.logout(request)
     request.flash['success'] = _('You have been logged out')