Now tracking login success.
[django-cas-provider.git] / cas_provider / views.py
1 import logging
2 logger = logging.getLogger('cas_provider.views')
3 import urllib
4
5 import logging
6 from urllib import urlencode
7 import urllib2
8 import urlparse
9
10 from django.http import HttpResponse, HttpResponseRedirect
11 from django.conf import settings
12 from django.contrib.auth import login as auth_login, logout as auth_logout
13 from django.core.urlresolvers import get_callable
14 from django.shortcuts import render_to_response
15 from django.template import RequestContext
16 from django.contrib.auth import authenticate
17 from django.core.urlresolvers import reverse
18
19 from lxml import etree
20 from cas_provider.attribute_formatters import NSMAP, CAS
21 from cas_provider.models import ProxyGrantingTicket, ProxyTicket
22 from cas_provider.models import ServiceTicket
23
24 from cas_provider.exceptions import SameEmailMismatchedPasswords
25 from cas_provider.forms import LoginForm, MergeLoginForm
26
27 from . import signals
28
29 __all__ = ['login', 'validate', 'logout', 'service_validate']
30
31 INVALID_TICKET = 'INVALID_TICKET'
32 INVALID_SERVICE = 'INVALID_SERVICE'
33 INVALID_REQUEST = 'INVALID_REQUEST'
34 INTERNAL_ERROR = 'INTERNAL_ERROR'
35
36 ERROR_MESSAGES = (
37     (INVALID_TICKET, u'The provided ticket is invalid.'),
38     (INVALID_SERVICE, u'Service is invalid'),
39     (INVALID_REQUEST, u'Not all required parameters were sent.'),
40     (INTERNAL_ERROR, u'An internal error occurred during ticket validation'),
41     )
42
43
44 logger = logging.getLogger(__name__)
45
46
47 def login(request, template_name='cas/login.html',
48           success_redirect=settings.LOGIN_REDIRECT_URL,
49           warn_template_name='cas/warn.html', **kwargs):
50     merge = kwargs.get('merge', False)
51     logging.debug('CAS Provider Login view. Method is %s, merge is %s, template is %s.',
52                   request.method, merge, template_name)
53
54     service = request.GET.get('service', None)
55     if service is not None:
56         # Save the service on the session, for later use if we end up
57         # in one of the more complicated workflows.
58         request.session['service'] = service
59
60     user = request.user
61
62     errors = []
63
64     if request.method == 'POST':
65         if merge:
66             form = MergeLoginForm(request.POST, request=request)
67         else:
68             form = LoginForm(request.POST, request=request)
69
70         if form.is_valid():
71             service = form.cleaned_data.get('service', None)
72             try:
73                 auth_args = dict(username=form.cleaned_data['email'],
74                                  password=form.cleaned_data['password'])
75                 if merge:
76                     # We only want to send the merge argument if it's
77                     # True. If it it's False, we want it to propagate
78                     # through the auth backends properly.
79                     auth_args['merge'] = merge
80                 user = authenticate(**auth_args)
81             except SameEmailMismatchedPasswords:
82                 # Need to merge the accounts?
83                 if merge:
84                     # We shouldn't get here...
85                     raise
86                 else:
87                     base_url = reverse('cas_provider_merge')
88                     args = dict(
89                         success_redirect=success_redirect,
90                         email=form.cleaned_data['email'],
91                         )
92                     if service is not None:
93                         args['service'] = service
94                     args = urllib.urlencode(args)
95
96                     url = '%s?%s' % (base_url, args)
97                     logging.debug('Redirecting to %s', url)
98                     return HttpResponseRedirect(url)
99             
100             if user is None:
101                 errors.append('Incorrect username and/or password.')
102             else:
103                 if user.is_active:
104                     auth_login(request, user)
105
106     else:  # Not a POST...
107         if merge:
108             form = MergeLoginForm(initial={'service': service, 'email': request.GET.get('email')})
109         else:
110             form = LoginForm(initial={'service': service})
111
112     if user is not None and user.is_authenticated():
113         # We have an authenticated user.
114         if not user.is_active:
115             errors.append('This account is disabled.')
116         else:
117             # Send the on_cas_login signal. If we get an HttpResponse, return that.
118             for receiver, response in signals.on_cas_login.send(sender=login, request=request, **kwargs):
119                 if isinstance(response, HttpResponse):
120                     return response
121             
122             if service is None:
123                 # Try and pull the service off the session
124                 service = request.session.pop('service', service)
125             
126             signals.on_cas_login_success.send(sender=login, request=request,
127                                               service=service, **kwargs)
128
129             if service is None:
130                 # Normal internal success redirection.
131                 logging.debug('Redirecting to %s', success_redirect)
132                 return HttpResponseRedirect(success_redirect)
133             else:
134                 if request.GET.get('warn', False):
135                     return render_to_response(warn_template_name, {
136                         'service': service,
137                         'warn': False
138                     }, context_instance=RequestContext(request))
139                 
140                 # Create a service ticket and redirect to the service.
141                 ticket = ServiceTicket.objects.create(service=service, user=user)
142                 if 'service' in request.session:
143                     # Don't need this any more.
144                     del request.session['service']
145
146                 url = ticket.get_redirect_url()
147                 logging.debug('Redirecting to %s', url)
148                 return HttpResponseRedirect(url)
149
150     logging.debug('Rendering response on %s, merge is %s', template_name, merge)
151     return render_to_response(template_name, {'form': form, 'errors': errors}, context_instance=RequestContext(request))
152
153
154 def validate(request):
155     """Validate ticket via CAS v.1 protocol
156     """
157     service = request.GET.get('service', None)
158     ticket_string = request.GET.get('ticket', None)
159     logger.info('Validating ticket %s for %s', ticket_string, service)
160     if service is not None and ticket_string is not None:
161         #renew = request.GET.get('renew', True)
162         #if not renew:
163         # TODO: check user SSO session
164         try:
165             ticket = ServiceTicket.objects.get(ticket=ticket_string)
166             assert ticket.service == service
167         except ServiceTicket.DoesNotExist:
168             logger.exception("Tried to validate with an invalid ticket %s for %s", ticket_string, service)
169         except Exception as e:
170             logger.exception('Got an exception: %s', e)
171         else:
172             username = ticket.user.username
173             ticket.delete()
174
175             results = signals.on_cas_collect_histories.send(sender=validate, for_user=ticket.user)
176             histories = '\n'.join('\n'.join(rs) for rc, rs in results)
177             logger.info('Validated %s %s', username, "(also %s)" % histories if histories else '')
178             return HttpResponse("yes\n%s\n%s" % (username, histories))
179
180     logger.info('Validation failed.')
181     return HttpResponse("no\n\n")
182     
183
184 def logout(request, template_name='cas/logout.html',
185            auto_redirect=settings.CAS_AUTO_REDIRECT_AFTER_LOGOUT):
186     url = request.GET.get('url', None)
187     if request.user.is_authenticated():
188         for ticket in ServiceTicket.objects.filter(user=request.user):
189             ticket.delete()
190         auth_logout(request)
191         if url and auto_redirect:
192             return HttpResponseRedirect(url)
193     return render_to_response(template_name, {'url': url},
194         context_instance=RequestContext(request))
195
196
197 def proxy(request):
198     targetService = request.GET['targetService']
199     pgt_id = request.GET['pgt']
200
201     try:
202         proxyGrantingTicket = ProxyGrantingTicket.objects.get(ticket=pgt_id)
203     except ProxyGrantingTicket.DoesNotExist:
204         return _cas2_error_response(INVALID_TICKET)
205
206     pt = ProxyTicket.objects.create(proxyGrantingTicket=proxyGrantingTicket,
207         user=proxyGrantingTicket.serviceTicket.user,
208         service=targetService)
209     return _cas2_proxy_success(pt.ticket)
210
211
212 def ticket_validate(service, ticket_string, pgtUrl):
213     if service is None or ticket_string is None:
214         return _cas2_error_response(INVALID_REQUEST)
215
216     try:
217         if ticket_string.startswith('ST'):
218             ticket = ServiceTicket.objects.get(ticket=ticket_string)
219         elif ticket_string.startswith('PT'):
220             ticket = ProxyTicket.objects.get(ticket=ticket_string)
221         else:
222             return _cas2_error_response(INVALID_TICKET,
223                 '%(ticket)s is neither Service (ST-...) nor Proxy Ticket (PT-...)' % {
224                     'ticket': ticket_string})
225     except ServiceTicket.DoesNotExist:
226         return _cas2_error_response(INVALID_TICKET)
227
228     ticketUrl = urlparse.urlparse(ticket.service)
229     serviceUrl = urlparse.urlparse(service)
230
231     if not(ticketUrl.hostname == serviceUrl.hostname and ticketUrl.path == serviceUrl.path and ticketUrl.port == serviceUrl.port):
232         return _cas2_error_response(INVALID_SERVICE)
233
234     pgtIouId = None
235     proxies = ()
236     if pgtUrl is not None:
237         pgt = generate_proxy_granting_ticket(pgtUrl, ticket)
238         if pgt:
239             pgtIouId = pgt.pgtiou
240
241     if hasattr(ticket, 'proxyticket'):
242         pgt = ticket.proxyticket.proxyGrantingTicket
243         # I am issued by this proxy granting ticket
244         if hasattr(pgt.serviceTicket, 'proxyticket'):
245             while pgt:
246                 if hasattr(pgt.serviceTicket, 'proxyticket'):
247                     proxies += (pgt.serviceTicket.service,)
248                     pgt = pgt.serviceTicket.proxyticket.proxyGrantingTicket
249                 else:
250                     pgt = None
251
252     user = ticket.user
253     ticket.delete()
254     return _cas2_sucess_response(user, pgtIouId, proxies)
255
256
257 def service_validate(request):
258     """Validate ticket via CAS v.2 protocol"""
259     service = request.GET.get('service', None)
260     ticket_string = request.GET.get('ticket', None)
261     pgtUrl = request.GET.get('pgtUrl', None)
262     if ticket_string.startswith('PT-'):
263         return _cas2_error_response(INVALID_TICKET, "serviceValidate cannot verify proxy tickets")
264     else:
265         return ticket_validate(service, ticket_string, pgtUrl)
266
267
268 def proxy_validate(request):
269     """Validate ticket via CAS v.2 protocol"""
270     service = request.GET.get('service', None)
271     ticket_string = request.GET.get('ticket', None)
272     pgtUrl = request.GET.get('pgtUrl', None)
273     return ticket_validate(service, ticket_string, pgtUrl)
274
275
276 def generate_proxy_granting_ticket(pgt_url, ticket):
277     proxy_callback_good_status = (200, 202, 301, 302, 304)
278     uri = list(urlparse.urlsplit(pgt_url))
279
280     pgt = ProxyGrantingTicket()
281     pgt.serviceTicket = ticket
282     pgt.targetService = pgt_url
283
284     if hasattr(ticket, 'proxyGrantingTicket'):
285         # here we got a proxy ticket! tata!
286         pgt.pgt = ticket.proxyGrantingTicket
287
288     params = {'pgtId': pgt.ticket, 'pgtIou': pgt.pgtiou}
289
290     query = dict(urlparse.parse_qsl(uri[4]))
291     query.update(params)
292
293     uri[3] = urlencode(query)
294
295     try:
296         response = urllib2.urlopen(urlparse.urlunsplit(uri))
297     except urllib2.HTTPError as e:
298         if not e.code in proxy_callback_good_status:
299             logger.debug('Checking Proxy Callback URL {} returned {}. Not issuing PGT.'.format(uri, e.code))
300             return
301     except urllib2.URLError as e:
302         logger.debug('Checking Proxy Callback URL {} raised URLError. Not issuing PGT.'.format(uri))
303         return
304
305     pgt.save()
306     return pgt
307
308
309 def _cas2_proxy_success(pt):
310     return HttpResponse(proxy_success(pt))
311
312
313 def _cas2_sucess_response(user, pgt=None, proxies=None):
314     return HttpResponse(auth_success_response(user, pgt, proxies), mimetype='text/xml')
315
316
317 def _cas2_error_response(code, message=None):
318     return HttpResponse(u'''<cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">
319             <cas:authenticationFailure code="%(code)s">
320                 %(message)s
321             </cas:authenticationFailure>
322         </cas:serviceResponse>''' % {
323         'code': code,
324         'message': message if message else dict(ERROR_MESSAGES).get(code)
325     }, mimetype='text/xml')
326
327
328 def proxy_success(pt):
329     response = etree.Element(CAS + 'serviceResponse', nsmap=NSMAP)
330     proxySuccess = etree.SubElement(response, CAS + 'proxySuccess')
331     proxyTicket = etree.SubElement(proxySuccess, CAS + 'proxyTicket')
332     proxyTicket.text = pt
333     return unicode(etree.tostring(response, encoding='utf-8'), 'utf-8')
334
335
336 def auth_success_response(user, pgt, proxies):
337     response = etree.Element(CAS + 'serviceResponse', nsmap=NSMAP)
338     auth_success = etree.SubElement(response, CAS + 'authenticationSuccess')
339     username = etree.SubElement(auth_success, CAS + 'user')
340     username.text = user.username
341
342     attrs = {}
343     for receiver, custom in signals.cas_collect_custom_attributes.send(sender=auth_success_response, user=user):
344         if custom:
345             attrs.update(custom)
346
347     identifiers = [i for sr, rr in signals.on_cas_collect_histories.send(sender=validate, for_user=user)
348                    for i in rr]
349
350     if identifiers:
351         attrs['identifiers'] = identifiers
352
353     if attrs:
354         formatter = get_callable(settings.CAS_CUSTOM_ATTRIBUTES_FORMATER)
355         formatter(auth_success, attrs)
356
357     if pgt:
358         pgtElement = etree.SubElement(auth_success, CAS + 'proxyGrantingTicket')
359         pgtElement.text = pgt
360
361     if proxies:
362         proxiesElement = etree.SubElement(auth_success, CAS + "proxies")
363         for proxy in proxies:
364             proxyElement = etree.SubElement(proxiesElement, CAS + "proxy")
365             proxyElement.text = proxy
366
367     return unicode(etree.tostring(response, encoding='utf-8'), 'utf-8')