Commits

offline committed c409cb0

backends doesnt inherit forms.Form anymore

Comments (0)

Files changed (7)

openauth/backends/__init__.py

 from django.contrib.auth.models import User
 from django.contrib import auth
 from django.conf import settings as global_settings
-from django import forms
 
 from annoying.exceptions import Redirect
 
 from openauth import settings
 
 
-class BaseBackend(forms.Form):
+class BaseBackend(object):
 
     PROFILE_MAPPING = property(lambda self: getattr(global_settings, "%s_PROFILE_MAPPING" % self.provider.upper(), {}))
 
-    def __init__(self, *args, **kwargs):
+    def __init__(self, provider):
+        self.provider = provider
         self._identity = None
-        self.request = kwargs.pop('request', {})
-        self.provider = kwargs.pop('provider', None)
-        super(BaseBackend, self).__init__(*args, **kwargs)
+        self.errors = []
 
     def set_identity(self, identity):
         self._identity = identity
     def get_identity(self):
         return self._identity
 
+    def begin(self, request, data):
+        pass
+
     def complete(self, request):
         """
         Login user if its identity already exists,
             user = auth.authenticate(identity=self.get_identity(), provider=self.provider)
             if user:
                 auth.login(request, user)
-                redirect_url = request.session['next_url']
-                del request.session['next_url']
+                try:
+                    redirect_url = request.session['next_url']
+                    del request.session['next_url']
+                except KeyError:
+                    redirect_url = settings.LOGIN_REDIRECT_URL
                 raise Redirect(redirect_url)
         else:
             return data

openauth/backends/facebook.py

             self.set_identity(int(request.COOKIES.get('%s_user' % uid)))
 
     def complete(self, request, response):
-        extra = request.facebook.users.getInfo([self.get_identity()], settings.FACEBOOK_EXTRA_FIELDS)[0]
+        extra_fields = [i for i in self.PROFILE_MAPPING]
+        extra = request.facebook.users.getInfo([self.get_identity()], extra_fields)[0]
         self.set_profile_fields(request, extra)
 
         request.session['identity'] = self.get_identity()

openauth/backends/openid.py

 
 class OpenIDBackend(BaseBackend):
 
-    openid_url = forms.CharField(u'OpenID URL', widget=forms.TextInput())
-
-    def clean_openid_url(self):
-        """
-        Url is stripped and http:// is added in case url doesnt begin with it.
-
-        Validate openid url, try to login user or show form error if 
-        OpenID server returned reject response or doesnt respond at all.
-        """
-        openid_url = self.cleaned_data['openid_url'].strip()
+    def begin(self, request, data):
+        openid_url = data['openid_url'].strip()
         if not openid_url.startswith("http"):
             openid_url = "http://%s" % openid_url
-        return_url = self.request.build_absolute_uri(reverse('openauth-social-complete', args=[self.provider]))
-        self.request.session['openid_return_to'] = return_url
-        client = consumer.Consumer(self.request.session, None)
+        return_url = request.build_absolute_uri(reverse('openauth-social-complete', args=[self.provider]))
+        request.session['openid_return_to'] = return_url
+        client = consumer.Consumer(request.session, None)
 
         try:
             openid_request = client.begin(openid_url)
                 ax_msg.add(AttrInfo(settings.AX_URIS[detail], required=True))
             openid_request.addExtension(ax_msg)
 
-            redirect_url = openid_request.redirectURL(realm='http://' + self.request.get_host(), return_to=return_url)
+            redirect_url = openid_request.redirectURL(realm='http://' + request.get_host(), return_to=return_url)
             raise Redirect(redirect_url)
 
         except discover.DiscoveryFailure:
-            raise forms.ValidationError(_('Could not find OpenID server'))
+            self.errors.append(_('Could not find OpenID server'))
+            return self.errors
 
-        return openid_url
 
 
     def validate_response(self, request):
             raise Redirect('openauth-social-login')
         elif resp.status == consumer.SUCCESS:
             self.set_identity(resp.identity_url)
-            del self.request.session['openid_return_to']
+            del request.session['openid_return_to']
             return resp
 
     def complete(self, request, response):
         extra = self.get_extra_data(response)
         data = self.set_profile_fields(request, extra)
         request.session['extra'] = data
-        self.request.session['identity'] = self.get_identity()
+        request.session['identity'] = self.get_identity()
         raise Redirect('openauth-social-extra', self.provider)
 
     def get_extra_data(self, resp):

openauth/backends/twitter.py

     ACCESS_TOKEN_URL = property(lambda self: getattr(global_settings, "%s_ACCESS_TOKEN_URL" % self.provider.upper()))
     AUTHORIZE_URL = property(lambda self: getattr(global_settings, "%s_AUTHORIZE_URL" % self.provider.upper()))
 
-    def clean(self):
+    def begin(self, request, data):
         consumer = OAuthConsumer(self.CONSUMER_KEY, self.CONSUMER_SECRET)
         signature_method = OAuthSignatureMethod_HMAC_SHA1()
-        callback = self.request.build_absolute_uri(reverse('openauth-social-complete', args=[self.provider]))
+        callback = request.build_absolute_uri(reverse('openauth-social-complete', args=[self.provider]))
         oauth_req = OAuthRequest.from_consumer_and_token(consumer, callback=callback, http_url=self.REQUEST_TOKEN_URL)
         oauth_req.sign_request(signature_method, consumer, None)
         response = urllib.urlopen(oauth_req.to_url()).read()
         extra = self.get_extra_data(response)
         data = self.set_profile_fields(request, extra)
         request.session['extra'] = data
-        self.request.session['identity'] = self.get_identity()
+        request.session['identity'] = self.get_identity()
         raise Redirect('openauth-social-extra', self.provider)
 
     def get_extra_data(self, response):

openauth/templates/openauth/social_login.html

 
 {% block content %}
 <form action="{% url openauth-social-login 'openid' %}" method="post" id="openid_login">
-    {{ form.as_table }}
+    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>
 
 from django.core.exceptions import ImproperlyConfigured
 from django.utils.importlib import import_module
-from django.conf import settings
+from django.conf import global_settings
 from django.template.loader import get_template
 from django.template import Context
 from django.core.mail import send_mail
 
+from openauth import settings
+
 
 def parse_template(template_path, **kwargs):
     """
     """
 
     subject, content = parse_template(template_path, **kwargs)
-    count = send_mail(subject, content, settings.DEFAULT_FROM_EMAIL,
+    count = send_mail(subject, content, global_settings.DEFAULT_FROM_EMAIL,
                       [rcpt], fail_silently=True)
     return bool(count)
 
         raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr))
 
     return backend_class(*args, **kwargs)
+
+def get_backend(name):
+    return get_instance_from_path(settings.BACKEND_MAPPING[name], name)
 from annoying.decorators import render_to
 from confirmation.models import Confirmation
 
-from openauth.utils import email_template, str_to_class, get_instance_from_path
+from openauth.utils import email_template, str_to_class, get_backend
 from openauth.forms import SocialIDExtraForm
 from openauth import settings
 
     function below.
     """
     if provider:
-        path = settings.BACKEND_MAPPING[provider]
+        # merge data from POST and GET methods
         data = request.GET.copy()
         data.update(request.POST)
-        form = get_instance_from_path(path, data, request=request, provider=provider)
-        next_url = request.GET.get("next") or settings.LOGIN_REDIRECT_URL
-        request.session['next_url'] = next_url
-        if form.is_valid():
-            form.save()
-    else:
-        form = get_instance_from_path(settings.DEFAULT_LOGIN_FORM)
 
-    return {'form': form}
+        request.session['next_url'] = request.GET.get("next") or settings.LOGIN_REDIRECT_URL
+        
+        # start the authentication process 
+        backend = get_backend(provider)
+        backend.begin(request, data)
+
+    return {}
 
 
 def social_complete(request, provider):
      * if no user with such ID exists and user must fill extra fields, 
        redirect him to registration form.
     """
-    path = settings.BACKEND_MAPPING[provider]
-    backend = get_instance_from_path(path, request=request, provider=provider)
+    backend = get_backend(provider)
     response = backend.validate_response(request)
     if request.user.is_authenticated():
         backend.login_user(request)
     backend.complete(request, response)
 
 
-
 @render_to('openauth/social_extra.html')
 def social_extra(request, provider):
     """                                                
     Handle registration of new user with extra data for profile
     """                                                          
-    path = settings.BACKEND_MAPPING[provider]
-    backend = get_instance_from_path(path, request=request, provider=provider)
+    backend = get_backend(provider)
 
     try:
         identity = request.session['identity']