updated link on profile page
[cas.git] / provider / cas_provider / views.py
1 from django.http import HttpResponse, HttpResponseForbidden, HttpResponseRedirect
2 from django.shortcuts import render_to_response
3 from django.template import RequestContext
4 from django.contrib.auth.models import User
5 from django.contrib.auth import authenticate
6 from django.contrib.auth import login as auth_login, logout as auth_logout
7 from django.utils.translation import ugettext_lazy as _
8
9 from cas_provider.forms import LoginForm
10 from cas_provider.models import ServiceTicket, LoginTicket, auth_success_response
11 from cas_provider.utils import create_service_ticket
12
13 import urlparse, urllib
14
15 try:
16     from urlparse import parse_qs as url_parse_qs
17 except ImportError:
18     from cgi import parse_qs as url_parse_qs
19
20 import logging
21 logger = logging.getLogger("cas.provider")
22
23 __all__ = ['login', 'validate', 'service_validate', 'logout']
24
25 def _add_query_param(url, param, value):
26     parsed = urlparse.urlparse(url)
27     query = url_parse_qs(parsed.query)
28     query[param] = [unicode(value, 'utf-8')]
29     query = [ ((k, v) if len(v) != 1 else (k, v[0])) for k, v in query.iteritems() ]
30     parsed = urlparse.ParseResult(parsed.scheme, parsed.netloc,
31                                   parsed.path, parsed.params,
32                                   urllib.urlencode(query), parsed.fragment)
33     return parsed.geturl()
34
35
36 def login(request, template_name='cas/login.html', success_redirect='/accounts/'):
37     service = request.GET.get('service', None)
38
39     if request.user.is_authenticated():
40         if service is not None:
41             ticket = create_service_ticket(request.user, service)
42             target = _add_query_param(service, 'ticket', ticket.ticket)
43             logger.info("Redirecting to %s", target)
44             return HttpResponseRedirect(target)
45         else:
46             logger.info("Redirecting to default: %s", success_redirect)
47             return HttpResponseRedirect(success_redirect)
48
49     errors = []
50     if request.method == 'POST':
51         username = request.POST.get('username', None)
52         password = request.POST.get('password', None)
53         service = request.POST.get('service', None)
54         lt = request.POST.get('lt', None)
55
56         logger.debug("User %s logging in", username)
57
58         try:
59             login_ticket = LoginTicket.objects.get(ticket=lt)
60         except:
61             errors.append(_(u'Login ticket expired. Please try again.'))
62         else:
63             login_ticket.delete()
64             user = authenticate(username=username, password=password)
65             if user is not None:
66                 if user.is_active:
67                     auth_login(request, user)
68                     if service is not None:
69                         ticket = create_service_ticket(user, service)
70                         target = _add_query_param(service, 'ticket', ticket.ticket)
71                         return HttpResponseRedirect(target)
72                     else:
73                         return HttpResponseRedirect(success_redirect)
74                 else:
75                     errors.append(_(u'This account is disabled.'))
76             else:
77                     errors.append(_(u'Incorrect username and/or password.'))
78
79     form = LoginForm(service)
80     return render_to_response(template_name, {'form': form, 'errors': errors}, context_instance=RequestContext(request))
81
82 def validate(request):
83     service = request.GET.get('service', None)
84     ticket_string = request.GET.get('ticket', None)
85     if service is not None and ticket_string is not None:
86         try:
87             ticket = ServiceTicket.objects.get(ticket=ticket_string)
88             username = ticket.user.username
89             ticket.delete()
90             return HttpResponse("yes\n%s\n" % username)
91         except:
92             pass
93     return HttpResponse("no\n\n")
94
95 def service_validate(request):
96     service = request.GET.get('service', None)
97     ticket_string = request.GET.get('ticket', None)
98     if service is None or ticket_string is None:
99         return HttpResponse(r'''<cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">
100             <cas:authenticationFailure code="INVALID_REQUEST">
101                 Not all required parameters were sent.
102             </cas:authenticationFailure>
103         </cas:serviceResponse>''', mimetype='application/xml')
104
105     try:
106         ticket = ServiceTicket.objects.get(ticket=ticket_string)
107         ticket.delete()
108         return HttpResponse(auth_success_response(ticket.user), mimetype='text/xml')
109     except ServiceTicket.DoesNotExist:
110         return HttpResponse(r'''<cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">
111             <cas:authenticationFailure code="INVALID_TICKET">
112                 The provided ticket is invalid.
113             </cas:authenticationFailure>
114         </cas:serviceResponse>''', mimetype='application/xml')
115
116 def logout(request, template_name='cas/logout.html'):
117     url = request.GET.get('url', None)
118     auth_logout(request)
119     return render_to_response(template_name, {'url': url}, context_instance=RequestContext(request))