Changed the signature of the login hijack signal.
[django-cas-provider.git] / cas_provider / views.py
index ea72805..5ba62e6 100644 (file)
@@ -19,27 +19,28 @@ from . import signals
 __all__ = ['login', 'validate', 'logout']
 
 
-def login(request, template_name='cas/login.html', success_redirect='/account/', merge=False):
+def _build_service_url(service, ticket):
+    if service.find('?') == -1:
+        return service + '?ticket=' + ticket
+    else:
+        return service + '&ticket=' + ticket
+
+
+def login(request, template_name='cas/login.html', success_redirect='/account/', **kwargs):
+    merge = kwargs.get('merge', False)
     logging.debug('CAS Provider Login view. Method is %s, merge is %s, template is %s.',
                   request.method, merge, template_name)
+
     service = request.GET.get('service', None)
     if service is not None:
+        # Save the service on the session, for later use if we end up
+        # in one of the more complicated workflows.
         request.session['service'] = service
-    if request.user.is_authenticated():
-        if service is not None:
-            ticket = create_service_ticket(request.user, service)
-            if service.find('?') == -1:
-                url = service + '?ticket=' + ticket.ticket
-                logging.debug('Redirecting to %s', url)
-                return HttpResponseRedirect(url)
-            else:
-                url = service + '&ticket=' + ticket.ticket
-                logging.debug('Redirecting to %s', url)
-                return HttpResponseRedirect()
-        else:
-            logging.debug('Redirecting to %s', success_redirect)
-            return HttpResponseRedirect(success_redirect)
+
+    user = request.user
+
     errors = []
+
     if request.method == 'POST':
         if merge:
             form = MergeLoginForm(request.POST, request=request)
@@ -76,55 +77,49 @@ def login(request, template_name='cas/login.html', success_redirect='/account/',
                     logging.debug('Redirecting to %s', url)
                     return HttpResponseRedirect(url)
             
-            if user is not None:
+            if user is None:
+                errors.append('Incorrect username and/or password.')
+            else:
                 if user.is_active:
                     auth_login(request, user)
-                    if service is not None:
-                        ticket = create_service_ticket(user, service)
-                        url = service + '?ticket=' + ticket.ticket
-                        logging.debug('Redirecting to %s', url)
-                        return HttpResponseRedirect(url)
-                    else:
-                        logging.debug('Redirecting to %s', success_redirect)
-                        return HttpResponseRedirect(success_redirect)
-                else:
-                    errors.append('This account is disabled.')
-            else:
-                    errors.append('Incorrect username and/or password.')
-    else:
+
+    else:  # Not a POST...
         if merge:
             form = MergeLoginForm(initial={'service': service, 'email': request.GET.get('email')})
         else:
             form = LoginForm(initial={'service': service})
-    logging.debug('Rendering response on %s, merge is %s', template_name, merge)
-    return render_to_response(template_name, {'form': form, 'errors': errors}, context_instance=RequestContext(request))
-
 
-def socialauth_login(request, template_name='cas/login.html', success_redirect='/account/'):
-    """ Similiar to login but user has been authenticated already through social auth.
-        This step authenticates the login and generates a service ticket.
-    """
-    user = request.user
-    user.backend = 'django.contrib.auth.backends.ModelBackend'
-    if request.session.has_key('service'):
-        service = request.session['service']
-        del request.session['service']
-    else:
-        service = '/'
-    errors = []
-    if user is not None:
-        if user.is_active:
-            auth_login(request, user)
-            if service is not None:
-                ticket = create_service_ticket(user, service)
-                return HttpResponseRedirect(service + '?ticket=' + ticket.ticket)
-            else:
-                return HttpResponseRedirect(success_redirect)
-        else:
+    if user is not None and user.is_authenticated():
+        # We have an authenticated user.
+        if not user.is_active:
             errors.append('This account is disabled.')
-    else:
-            errors.append('Incorrect username and/or password.')
-    return render_to_response(template_name, {'errors': errors}, context_instance=RequestContext(request))
+        else:
+            # Send the on_cas_login signal. If we get an HttpResponse, return that.
+            for receiver, response in signals.on_cas_login.send(sender=login, request=request, **kwargs):
+                if isinstance(response, HttpResponse):
+                    return response
+            
+            if service is None:
+                # Try and pull the service off the session
+                service = request.session.pop('service', service)
+            
+            if service is None:
+                # Normal internal success redirection.
+                logging.debug('Redirecting to %s', success_redirect)
+                return HttpResponseRedirect(success_redirect)
+            else:
+                # Create a service ticket and redirect to the service.
+                ticket = create_service_ticket(request.user, service)
+                if 'service' in request.session:
+                    # Don't need this any more.
+                    del request.session['service']
+
+                url = _build_service_url(service, ticket.ticket)
+                logging.debug('Redirecting to %s', url)
+                return HttpResponseRedirect(url)
+
+    logging.debug('Rendering response on %s, merge is %s', template_name, merge)
+    return render_to_response(template_name, {'form': form, 'errors': errors}, context_instance=RequestContext(request))
 
 
 def validate(request):
@@ -136,6 +131,8 @@ def validate(request):
             ticket = ServiceTicket.objects.get(ticket=ticket_string)
         except ServiceTicket.DoesNotExist:
             logger.exception("Tried to validate with an invalid ticket %s for %s", ticket_string, service)
+        except Exception as e:
+            logger.exception('Got an exception: %s', e)
         else:
             username = ticket.user.username
             ticket.delete()
@@ -145,6 +142,7 @@ def validate(request):
             logger.info('Validated %s %s', username, "(also %s)" % histories if histories else '')
             return HttpResponse("yes\n%s\n%s" % (username, histories))
 
+    logger.info('Validation failed.')
     return HttpResponse("no\n\n")