675150bdf3543ed80985d906c0b85d6c4c934ab4
[django-cas-provider.git] / cas_provider / views.py
1 import logging
2 logger = logging.getLogger('cas_provider.views')
3 import urllib
4
5 from django.http import HttpResponse, HttpResponseRedirect
6 from django.shortcuts import render_to_response
7 from django.template import RequestContext
8 from django.contrib.auth import authenticate
9 from django.contrib.auth import login as auth_login, logout as auth_logout
10 from django.core.urlresolvers import reverse
11
12 from forms import LoginForm, MergeLoginForm
13 from models import ServiceTicket
14 from utils import create_service_ticket
15 from exceptions import SameEmailMismatchedPasswords
16
17 from . import signals
18
19 __all__ = ['login', 'validate', 'logout']
20
21
22 def _build_service_url(service, ticket):
23     if service.find('?') == -1:
24         return service + '?ticket=' + ticket
25     else:
26         return service + '&ticket=' + ticket
27
28
29 def login(request, template_name='cas/login.html', success_redirect='/account/', **kwargs):
30     merge = kwargs.get('merge', False)
31     logging.debug('CAS Provider Login view. Method is %s, merge is %s, template is %s.',
32                   request.method, merge, template_name)
33
34     service = request.GET.get('service', None)
35     if service is not None:
36         # Save the service on the session, for later use if we end up
37         # in one of the more complicated workflows.
38         request.session['service'] = service
39
40     user = request.user
41
42     errors = []
43
44     if request.method == 'POST':
45         if merge:
46             form = MergeLoginForm(request.POST, request=request)
47         else:
48             form = LoginForm(request.POST, request=request)
49
50         if form.is_valid():
51             service = form.cleaned_data.get('service', None)
52             try:
53                 auth_args = dict(username=form.cleaned_data['email'],
54                                  password=form.cleaned_data['password'])
55                 if merge:
56                     # We only want to send the merge argument if it's
57                     # True. If it it's False, we want it to propagate
58                     # through the auth backends properly.
59                     auth_args['merge'] = merge
60                 user = authenticate(**auth_args)
61             except SameEmailMismatchedPasswords:
62                 # Need to merge the accounts?
63                 if merge:
64                     # We shouldn't get here...
65                     raise
66                 else:
67                     base_url = reverse('cas_provider_merge')
68                     args = dict(
69                         success_redirect=success_redirect,
70                         email=form.cleaned_data['email'],
71                         )
72                     if service is not None:
73                         args['service'] = service
74                     args = urllib.urlencode(args)
75
76                     url = '%s?%s' % (base_url, args)
77                     logging.debug('Redirecting to %s', url)
78                     return HttpResponseRedirect(url)
79             
80             if user is None:
81                 errors.append('Incorrect username and/or password.')
82             else:
83                 if user.is_active:
84                     auth_login(request, user)
85
86     else:  # Not a POST...
87         if merge:
88             form = MergeLoginForm(initial={'service': service, 'email': request.GET.get('email')})
89         else:
90             form = LoginForm(initial={'service': service})
91
92     if user is not None and user.is_authenticated():
93         # We have an authenticated user.
94         if not user.is_active:
95             errors.append('This account is disabled.')
96         else:
97             if service is None:
98                 # Try and pull the service off the session
99                 service = request.session.pop('service', service)
100             
101             if service is None:
102                 # Normal internal success redirection.
103                 logging.debug('Redirecting to %s', success_redirect)
104                 return HttpResponseRedirect(success_redirect)
105             else:
106                 # Create a service ticket and redirect to the service.
107                 ticket = create_service_ticket(request.user, service)
108                 if 'service' in request.session:
109                     # Don't need this any more.
110                     del request.session['service']
111
112                 url = _build_service_url(service, ticket.ticket)
113                 logging.debug('Redirecting to %s', url)
114                 return HttpResponseRedirect(url)
115
116     logging.debug('Rendering response on %s, merge is %s', template_name, merge)
117     return render_to_response(template_name, {'form': form, 'errors': errors}, context_instance=RequestContext(request))
118
119
120 def validate(request):
121     service = request.GET.get('service', None)
122     ticket_string = request.GET.get('ticket', None)
123     logger.info('Validating ticket %s for %s', ticket_string, service)
124     if service is not None and ticket_string is not None:
125         try:
126             ticket = ServiceTicket.objects.get(ticket=ticket_string)
127         except ServiceTicket.DoesNotExist:
128             logger.exception("Tried to validate with an invalid ticket %s for %s", ticket_string, service)
129         except Exception as e:
130             logger.exception('Got an exception: %s', e)
131         else:
132             username = ticket.user.username
133             ticket.delete()
134
135             results = signals.on_cas_collect_histories.send(sender=validate, for_email=ticket.user.email)
136             histories = '\n'.join('\n'.join(rs) for rc, rs in results)
137             logger.info('Validated %s %s', username, "(also %s)" % histories if histories else '')
138             return HttpResponse("yes\n%s\n%s" % (username, histories))
139
140     logger.info('Validation failed.')
141     return HttpResponse("no\n\n")
142     
143
144 def logout(request, template_name='cas/logout.html'):
145     url = request.GET.get('url', None)
146     auth_logout(request)
147     return render_to_response(template_name, {'url': url}, context_instance=RequestContext(request))