offline avatar offline committed 312a180

templates renamed

Comments (0)

Files changed (19)

publicauth/backends/__init__.py

+from django.shortcuts import render_to_response, redirect
+from django.conf import settings as global_settings
 from django.utils.translation import ugettext as _
 from django.contrib.auth.models import User
+from django.template import RequestContext
+from django.contrib import messages
 from django.contrib import auth
-from django.conf import settings as global_settings
+from django.http import Http404
 
 from annoying.exceptions import Redirect
 
 from publicauth.models import PublicID
 from publicauth.utils import str_to_class
 from publicauth import settings
+from publicauth import lang
 
 
 class BaseBackend(object):
 
     PROFILE_MAPPING = property(lambda self: getattr(global_settings, "%s_PROFILE_MAPPING" % self.provider.upper(), {}))
+    EXTRA_FORM = property(lambda self: getattr(global_settings, "%s_EXTRA_FORM" % self.provider.upper(), 'publicauth.forms.ExtraForm'))
 
     def __init__(self, provider):
         self.provider = provider
         return self._identity
 
     def begin(self, request, data):
-        pass
+        raise NotImplementedError
 
     def complete(self, request):
         """
         and user with such identity doesnt exists.
         Merge accounts if user already logged in and identity is new.
         """
-        pass
+        raise NotImplementedError
     
     def attach_account(self, request, user):
         """
         account and then login user.
         """
         PublicID.objects.create(user=user, identity=self.get_identity(), provider=self.provider)
-        request.flash['success'] =  _('OpenId record was added to your account')
+        messages.add_message(request, messages.SUCCESS, lang.ACCOUNTS_MERGED)
         auth.authenticate(identity=self.get_identity(), provider=self.provider)
         auth.login(request, user)
         raise Redirect(global_settings.LOGIN_REDIRECT_URL)
 
     def login_user(self, request):
         if settings.PUBLICID_ACTIVATION_REQUIRED and not request.user.is_active:
-            request.flash['error'] =  _('Your account is not activated. Please activate it first.')
+            messages.add_message(request, messages.ERROR, lang.NOT_ACTIVATED)
             raise Redirect("/")
+
         user = auth.authenticate(identity=self.get_identity(), provider=self.provider)
         if user:
-            request.flash['success'] =  _('You have successfully authenticated')
+            messages.add_message(request, messages.SUCCESS, lang.SUCCESSFULLY_AUTHENTICATED)
             auth.login(request, user)
             raise Redirect(global_settings.LOGIN_REDIRECT_URL)
 
         for field in self.PROFILE_MAPPING:
             data.update(self.extract_data(extra, field))
 
-        form = str_to_class(settings.PUBLICID_EXTRA_FORM)(data, fields=self.PROFILE_MAPPING)
+        form = str_to_class(self.EXTRA_FORM)(data, fields=self.PROFILE_MAPPING)
         if form.is_valid():
             form.save(self.get_identity(), self.provider)
             user = auth.authenticate(identity=self.get_identity(), provider=self.provider)
 
     def validate_response(self, request):
         pass
+
+
+    def extra(self, request):
+        """
+        Handle registration of new user with extra data for profile
+        """
+        try:
+            identity = request.session['identity']
+        except KeyError:
+            raise Http404
+
+        if request.method == "POST":
+            form = str_to_class(self.EXTRA_FORM)(request.POST)
+            if form.is_valid():
+                user = form.save(identity, self.provider)
+                del request.session['identity']
+                user = auth.authenticate(identity=identity, provider=self.provider)
+                if user:
+                    auth.login(request, user)
+                    next_url = request.session['next_url']
+                    del request.session['next_url']
+                    return redirect(next_url)
+        else:
+            initial = request.session['extra']
+            form = str_to_class(self.EXTRA_FORM)(initial=initial)
+
+        return render_to_response(     
+                                    "publicauth/extra.html", 
+                                    {'form': form}, 
+                                    context_instance=RequestContext(request)
+                                )
+

publicauth/backends/facebook.py

 from __future__ import absolute_import 
 
 from django.utils.translation import ugettext as _
+from django.contrib import messages
 from django.contrib import auth
 
 from annoying.exceptions import Redirect
 
 from publicauth.backends import BaseBackend
 from publicauth import settings
+from publicauth import lang
 
 
 class FacebookBackend(BaseBackend):
     
     def validate_response(self, request):
         if not request.facebook.validate_cookie_signature(request.COOKIES):
-            request.flash['error'] = _('Invalid response received from facebook server, please start the authentication process again')
-            raise Redirect('publicauth-social-login')
+            messages.add_message(request, messages.SUCCESS, lang.FACEBOOK_INVALID_RESPONSE)
+            raise Redirect('publicauth-login')
         else:
             uid = request.facebook.api_key
             self.set_identity(int(request.COOKIES.get('%s_user' % uid)))

publicauth/backends/openid.py

 
 from django.utils.translation import ugettext as _
 from django.core.urlresolvers import reverse
+from django.shortcuts import redirect
+from django.contrib import messages
 from django.contrib import auth
 from django import forms
 
 from publicauth.backends import BaseBackend
 from publicauth.utils import str_to_class
 from publicauth import settings
+from publicauth import lang
 
 
 class OpenIDBackend(BaseBackend):
 
     def begin(self, request, data):
-        openid_url = data['openid_url'].strip()
+        try:
+            openid_url = data['openid_url'].strip()
+        except KeyError:
+            messages.add_message(request, messages.ERROR, "Please fill openid url field")
+
+        # allow user to type openid provider without http:// prefix
         if not openid_url.startswith("http"):
             openid_url = "http://%s" % openid_url
-        return_url = request.build_absolute_uri(reverse('publicauth-social-complete', args=[self.provider]))
+
+        return_url = request.build_absolute_uri(reverse('publicauth-complete', args=[self.provider]))
         request.session['openid_return_to'] = return_url
         client = consumer.Consumer(request.session, None)
 
             raise Redirect(redirect_url)
 
         except discover.DiscoveryFailure:
-            request.flash['error'] = _('Could not find OpenID server')
-            raise Redirect('publicauth-social-login')
-
+            messages.add_message(request, messages.ERROR, _('Could not find OpenID server'))
+            raise Redirect('publicauth-login')
 
     def validate_response(self, request):
         """
         try:
             resp = client.complete(data, request.session['openid_return_to'])
         except KeyError:
-            request.flash['error'] = _('Invalid response received from OpenID server, please start the authentication process again')
-            raise Redirect('publicauth-social-login')
+            messages.add_message(request, messages.ERROR, lang.INVALID_RESPONSE_FROM_OPENID)
+            raise Redirect('publicauth-begin')
         if resp.status == consumer.CANCEL:
-            request.flash['warn'] = _('You have cancelled OpenID authentication')
-            raise Redirect('publicauth-social-login')
+            messages.add_message(request, messages.WARNING, lang.OPENID_CANCELED)
+            raise Redirect('publicauth-begin')
         elif resp.status == consumer.FAILURE:
-            request.flash['error'] =  _('OpenID authentication failed. Reason: %s') % resp.message
-            raise Redirect('publicauth-social-login')
+            messages.add_message(request, messages.ERROR, lang.OPENID_FAILED % resp.message)
+            raise Redirect('publicauth-begin')
         elif resp.status == consumer.SUCCESS:
             self.set_identity(resp.identity_url)
             del request.session['openid_return_to']
             return resp
 
-    def complete(self, request, response):
+    def complete(self, request):
+        response = self.validate_response(request)
         extra = self.get_extra_data(response)
         data = self.set_profile_fields(request, extra)
         request.session['extra'] = data
         request.session['identity'] = self.get_identity()
-        raise Redirect('publicauth-social-extra', self.provider)
+        return redirect('publicauth-extra', self.provider)
 
     def get_extra_data(self, resp):
         return SRegResponse.fromSuccessResponse(resp)

publicauth/forms.py

 from publicauth import settings
 
 
-class PublicIDExtraForm(forms.Form):
+class ExtraForm(forms.Form):
     def __init__(self, *args, **kwargs):
         """
         Form with fields from backend PROFILE_MAPPINGS setting.
         fields = kwargs.pop("fields", {})
         for key, value in fields.values():
             self.base_fields[key] = value
-        super(PublicIDExtraForm, self).__init__(*args, **kwargs)
+        super(ExtraForm, self).__init__(*args, **kwargs)
 
     def clean_username(self):
         if get_object_or_None(User, username=self.cleaned_data['username']):
         PublicID.objects.create(user=user, identity=identity, provider=provider)
         return user
 
-PublicIDExtraForm = autostrip(PublicIDExtraForm)
+ExtraForm = autostrip(ExtraForm)
 

publicauth/lang.py

 from django.utils.translation import ugettext as _
+from django.conf import settings
 
-LOGOUT_BEFORE_REGISTRATION = _('You have to logout before new account registration')
-REGISTRATION_DISABLED = _('We are sorry, but registration is disabled. Come back later')
-PLEASE_ACTIVATE = _("You have successfully registered. Check your inbox for email with activation link.")
-ERROR_SENDING_MAIL = _('Unfortunately we could not send you email in current time. Please, try later')
-LOGIN_NOW = _("You have successfully registered. You can login now")
-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')
+REGISTRATION_DISABLED = getattr(settings, "PUBLICAUTH_REGISTRATION_DISABLED", _('We are sorry, but registration is disabled. Come back later'))
+OPENID_CANCELED = getattr(settings, "PUBLICAUTH_OPENID_CANCELED", _('You have cancelled OpenID authentication'))
+OPENID_FAILED = getattr(settings, "PUBLICAUTH_OPENID_FAILED", _('OpenID authentication failed. Reason: %s'))
+SUCCESS_LOGOUT = getattr(settings, "PUBLICAUTH_SUCCESS_LOGOUT", _('You have successfully logged out'))
+ACCOUNTS_MERGED = getattr(settings, "PUBLICAUTH_ACCOUNTS_MERGED", _('Your existing account was merged with new authentication account'))
+NOT_ACTIVATED = getattr(settings, "PUBLICAUTH_NOT_ACTIVATED",  _('Your account is not activated. Please activate it first.'))
+SUCCESSFULLY_AUTHENTICATED = getattr(settings, "PUBLICAUTH_SUCCESSFULLY_AUTHENTICATED", _('You have successfully authenticated'))
+FACEBOOK_INVALID_RESPONSE = getattr(settings, 
+                                    "PUBLICAUTH_FACEBOOK_INVALID_RESPONSE", 
+                                    _('Invalid response received from facebook server, please start the authentication process again')
+                                    )
+INVALID_RESPONSE_FROM_OPENID = getattr(settings, 
+                                        "PUBLICAUTH_INVALID_RESPONSE_FROM_OPENID",
+                                        ('Invalid response received from OpenID server, please start the authentication process again'))

publicauth/settings.py

 import re
 
 from django import forms
-
-from annoying.functions import get_config
+from django.conf import settings
 
 
 ### REGISTRATION_ALLOWED ###########################################################################
 # To disable registration, set it to False                                                         #
-REGISTRATION_ALLOWED = get_config("REGISTRATION_ALLOWED", True)                                    #
-####################################################################################################
-
-### PUBLICID_REGISTRATION_FORM #####################################################################
-# See REGISTRATION_FORM description above                                                          #
-PUBLICID_EXTRA_FORM = get_config("PUBLICID_EXTRA_FORM", "publicauth.forms.PublicIDExtraForm")      #
+REGISTRATION_ALLOWED = getattr(settings, "REGISTRATION_ALLOWED", True)                             #
 ####################################################################################################
 
 ### 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 = {                                                                                        #
+AX_URIS = getattr(settings, "AX_URIS", {                                                           #
     'nickname': 'http://axschema.org/namePerson/friendly',                                         #
     'email': 'http://axschema.org/contact/email',                                                  #
     'fullname': 'http://axschema.org/namePerson',                                                  #
     'country': 'http://axschema.org/contact/country/home',                                         #
     'language': 'http://axschema.org/pref/language',                                               #
     'timezone': 'http://axschema.org/pref/timezone',                                               #
-}                                                                                                  #
+})                                                                                                 #
 ####################################################################################################
 
 ### BACKEND_MAPPING ################################################################################
-BACKEND_MAPPING = get_config("BACKEND_MAPPING", {                                                  #
+PUBLICAUTH_BACKEND_MAPPING = getattr(settings, "PUBLICAUTH_BACKEND_MAPPING", {                     #
     'openid': 'publicauth.backends.openid.OpenIDBackend',                                          #
     'google': 'publicauth.backends.google.GoogleBackend',                                          #
     'twitter': 'publicauth.backends.twitter.TwitterBackend',                                       #
 )                                                                                                  #
 ####################################################################################################
 
-REGISTRATION_DISABLED_REDIRECT = get_config("REGISTRATION_DISABLED_REDIRECT", "/")
+REGISTRATION_DISABLED_REDIRECT = getattr(settings, "REGISTRATION_DISABLED_REDIRECT", "/")
 
-PUBLICID_ACTIVATION_REQUIRED = get_config("PUBLICID_ACTIVATION_REQUIRED", False)
+PUBLICID_ACTIVATION_REQUIRED = getattr(settings, "PUBLICID_ACTIVATION_REQUIRED", False)

publicauth/templates/openauth/mail/registration.txt

-{% load i18n %}{% blocktrans %}Registration on {{ domain }}{% endblocktrans %}
-{% blocktrans %}Thanks for registration on {{ domain }}{% endblocktrans %}.
-{% blocktrans %}Please use following link to activate your account: {{ url }}{% endblocktrans %}

publicauth/templates/openauth/mail/reset_password.txt

-Password restore on {{ domain }}
-
-Someone, hopefully you, requested password reset on {{ domain }}. 
-To approve request, please use following link: {{ url }}
-
-If you have not requested password reset or are not registered user of {{ domain }}, just ignore this email.

publicauth/templates/openauth/social_extra.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>Регистрация через OpenID</legend>
-        <div class="wide">{{ form.as_p }}</div>
-        <p><input type="submit" value="{% trans "Submit" %}"/></p>
-    </formfield>
-</form>
-{% endblock %}

publicauth/templates/openauth/social_login.html

-{% extends 'base.html' %}
-
-{% block content %}
-<form action="{% url openauth-social-login 'openid' %}" method="post" id="openid_login">
-    Openid URL
-    <input type="text" name="openid_url" />
-    <p><input type="submit" value="Continue"/></p>
-</form>
-
-<a href="{% url openauth-social-login 'google' %}?openid_url=https://www.google.com/accounts/o8/id">Google</a>
-<a href="{% url openauth-social-login 'twitter' %}">Twitter</a>
-
-
-<a href="#" onclick="return fb_login();" id="facebook">Login with facebook</a>
-
-<script type="text/javascript" src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php"></script>
-<script type="text/javascript">
-    FB.init("{{ request.facebook.api_key }}", "{% url openauth-facebook-xdreceiver %}");
-
-    function fb_login() {
-        FB.Connect.requireSession(function(test) {
-            window.location = "{% url openauth-social-complete 'facebook' %}";
-        });
-        return false;
-    }
-</script>
-
-{% endblock %}
-
-

publicauth/templates/openauth/xdreceiver.html

-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml">
-    <body>
-        <script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/XdCommReceiver.js" type="text/javascript"></script>
-    </body>
-</html>

publicauth/templates/publicauth/extra.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>Регистрация через OpenID</legend>
+        <div class="wide">{{ form.as_p }}</div>
+        <p><input type="submit" value="{% trans "Submit" %}"/></p>
+    </formfield>
+</form>
+{% endblock %}

publicauth/templates/publicauth/login.html

+{% extends 'base.html' %}
+
+{% block content %}
+<form action="{% url publicauth-begin 'openid' %}?next=request.GET.next" method="post" id="openid_login">
+    Openid URL
+    <input type="text" name="openid_url" />
+    <p><input type="submit" value="Continue"/></p>
+</form>
+
+<a href="{% url publicauth-begin 'google' %}?openid_url=https://www.google.com/accounts/o8/id&next=request.GET.next">Google</a>
+<a href="{% url publicauth-begin 'twitter' %}?next=request.GET.next">Twitter</a>
+
+
+<a href="#" onclick="return fb_login();" id="facebook">Login with facebook</a>
+
+<script type="text/javascript" src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php"></script>
+<script type="text/javascript">
+    FB.init("{{ request.facebook.api_key }}", "{% url publicauth-facebook-xdreceiver %}");
+
+    function fb_login() {
+        FB.Connect.requireSession(function(test) {
+            window.location = "{% url publicauth-complete 'facebook' %}?next=request.GET.next";
+        });
+        return false;
+    }
+</script>
+
+{% endblock %}
+
+

publicauth/templates/publicauth/mail/registration.txt

+{% load i18n %}{% blocktrans %}Registration on {{ domain }}{% endblocktrans %}
+{% blocktrans %}Thanks for registration on {{ domain }}{% endblocktrans %}.
+{% blocktrans %}Please use following link to activate your account: {{ url }}{% endblocktrans %}

publicauth/templates/publicauth/mail/reset_password.txt

+Password restore on {{ domain }}
+
+Someone, hopefully you, requested password reset on {{ domain }}. 
+To approve request, please use following link: {{ url }}
+
+If you have not requested password reset or are not registered user of {{ domain }}, just ignore this email.

publicauth/templates/publicauth/xdreceiver.html

+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml">
+    <body>
+        <script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/XdCommReceiver.js" type="text/javascript"></script>
+    </body>
+</html>

publicauth/urls.py

 
 
 urlpatterns = patterns('',
-    url(r'^begin/$', views.begin, name='publicauth-begin'),
     url(r'^begin/(\w+)/$', views.begin, name='publicauth-begin'),
     url(r'^complete/(\w+)/$', views.complete, name='publicauth-complete'),
     url(r'^extra/(\w+)/$', views.extra, name='publicauth-extra'),
+    url(r'^login/$', direct_to_template, {'template': 'publicauth/login.html'}, name='publicauth-login'),
+    url(r'^xdreceiver/$', direct_to_template, {'template': 'publicauth/xdreceiver.html'}, name='publicauth-facebook-xdreceiver'),
     url(r'^logout/$', views.logout, name='publicauth-logout'),
-    url(r'^xdreceiver/$', direct_to_template, {'template': 'publicauth/xdreceiver.html'}, name='publicauth-facebook-xdreceiver'),
+    #url(r'^begin/(\w+)/$', views.begin, name='publicauth-begin'),
 )

publicauth/utils.py

     return backend_class(*args, **kwargs)
 
 def get_backend(name):
-    return get_instance_from_path(settings.BACKEND_MAPPING[name], name)
+    return get_instance_from_path(settings.PUBLICAUTH_BACKEND_MAPPING[name], name)

publicauth/views.py

+from django.conf import settings as global_settings
 from django.utils.translation import ugettext as _
 from django.shortcuts import redirect
+from django.contrib import messages
 from django.http import Http404
 from django.contrib import auth 
-from django.conf import settings as global_settings
 
 from annoying.decorators import render_to
 
 
 def logout(request):
     auth.logout(request)
-    request.flash['success'] = _('You have been logged out')
+    messages.add_message(request, messages.SUCCESS, publicauth.lang.SUCCESS_LOGOUT)
     return redirect("/")
 
 
-@render_to('publicauth/begin.html')
-def begin(request, provider=None):
+def begin(request, provider):
     """
     Display authentication form. This is also the first step
     in registration. The actual login is in social_complete 
     function below.
     """
-    if provider:
-        # merge data from POST and GET methods
-        data = request.GET.copy()
-        data.update(request.POST)
+    # merge data from POST and GET methods
+    data = request.GET.copy()
+    data.update(request.POST)
 
-        request.session['next_url'] = request.GET.get("next") or global_settings.LOGIN_REDIRECT_URL
+    request.session['next_url'] = request.GET.get("next") or global_settings.LOGIN_REDIRECT_URL
         
-        # start the authentication process 
-        backend = get_backend(provider)
-        backend.begin(request, data)
+    # start the authentication process 
+    backend = get_backend(provider)
+    backend.begin(request, data)
 
     return {}
 
     else:
         backend.login_user(request)
         if not settings.REGISTRATION_ALLOWED:
-            request.flash['warning'] =  publicauth.lang.REGISTRATION_DISABLED
+            messages.add_message(request, messages.WARNING, lang.REGISTRATION_DISABLED)
             return redirect(settings.REGISTRATION_DISABLED_REDIRECT)
     backend.complete(request, response)
 
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.