a692ba5a846e419a7c380478db44b96736d014dd
[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 login(request, template_name='cas/login.html', success_redirect='/account/', merge=False):
23     logging.debug('CAS Provider Login view. Method is %s, merge is %s, template is %s.',
24                   request.method, merge, template_name)
25
26     service = request.GET.get('service', None)
27     if service is not None:
28         # Save the service on the session, for later use if we end up
29         # in one of the more complicated workflows.
30         request.session['service'] = service
31
32     user = request.user
33
34     errors = []
35
36     if request.method == 'POST':
37         if merge:
38             form = MergeLoginForm(request.POST, request=request)
39         else:
40             form = LoginForm(request.POST, request=request)
41
42         if form.is_valid():
43             service = form.cleaned_data.get('service', None)
44             try:
45                 auth_args = dict(username=form.cleaned_data['email'],
46                                  password=form.cleaned_data['password'])
47                 if merge:
48                     # We only want to send the merge argument if it's
49                     # True. If it it's False, we want it to propagate
50                     # through the auth backends properly.
51                     auth_args['merge'] = merge
52                 user = authenticate(**auth_args)
53             except SameEmailMismatchedPasswords:
54                 # Need to merge the accounts?
55                 if merge:
56                     # We shouldn't get here...
57                     raise
58                 else:
59                     base_url = reverse('cas_provider_merge')
60                     args = dict(
61                         success_redirect=success_redirect,
62                         email=form.cleaned_data['email'],
63                         )
64                     if service is not None:
65                         args['service'] = service
66                     args = urllib.urlencode(args)
67
68                     url = '%s?%s' % (base_url, args)
69                     logging.debug('Redirecting to %s', url)
70                     return HttpResponseRedirect(url)
71             
72             if user is None:
73                 errors.append('Incorrect username and/or password.')
74             else:
75                 if user.is_active:
76                     auth_login(request, user)
77
78     else:  # Not a POST...
79         if merge:
80             form = MergeLoginForm(initial={'service': service, 'email': request.GET.get('email')})
81         else:
82             form = LoginForm(initial={'service': service})
83
84     if user is not None and user.is_authenticated():
85         if not user.is_active:
86             errors.append('This account is disabled.')
87         else:
88             if service is None:
89                 # Normal internal success redirection.
90                 logging.debug('Redirecting to %s', success_redirect)
91                 return HttpResponseRedirect(success_redirect)
92             else:
93                 # Create a service ticket and redirect.
94                 ticket = create_service_ticket(request.user, service)
95                 if service.find('?') == -1:
96                     url = service + '?ticket=' + ticket.ticket
97                     logging.debug('Redirecting to %s', url)
98                     return HttpResponseRedirect(url)
99                 else:
100                     url = service + '&ticket=' + ticket.ticket
101                     logging.debug('Redirecting to %s', url)
102                     return HttpResponseRedirect(url)
103
104     logging.debug('Rendering response on %s, merge is %s', template_name, merge)
105     return render_to_response(template_name, {'form': form, 'errors': errors}, context_instance=RequestContext(request))
106
107
108 def socialauth_login(request, template_name='cas/login.html', success_redirect='/account/'):
109     """ Similiar to login but user has been authenticated already through social auth.
110         This step authenticates the login and generates a service ticket.
111     """
112     user = request.user
113     user.backend = 'django.contrib.auth.backends.ModelBackend'
114     if request.session.has_key('service'):
115         service = request.session['service']
116         del request.session['service']
117     else:
118         service = '/'
119     errors = []
120     if user is not None:
121         if user.is_active:
122             auth_login(request, user)
123             if service is not None:
124                 ticket = create_service_ticket(user, service)
125                 return HttpResponseRedirect(service + '?ticket=' + ticket.ticket)
126             else:
127                 return HttpResponseRedirect(success_redirect)
128         else:
129             errors.append('This account is disabled.')
130     else:
131         errors.append('Incorrect username and/or password.')
132     return render_to_response(template_name, {'errors': errors}, context_instance=RequestContext(request))
133
134
135 def validate(request):
136     service = request.GET.get('service', None)
137     ticket_string = request.GET.get('ticket', None)
138     logger.info('Validating ticket %s for %s', ticket_string, service)
139     if service is not None and ticket_string is not None:
140         try:
141             ticket = ServiceTicket.objects.get(ticket=ticket_string)
142         except ServiceTicket.DoesNotExist:
143             logger.exception("Tried to validate with an invalid ticket %s for %s", ticket_string, service)
144         except Exception as e:
145             logger.exception('Got an exception: %s', e)
146         else:
147             username = ticket.user.username
148             ticket.delete()
149
150             results = signals.on_cas_collect_histories.send(sender=validate, for_email=ticket.user.email)
151             histories = '\n'.join('\n'.join(rs) for rc, rs in results)
152             logger.info('Validated %s %s', username, "(also %s)" % histories if histories else '')
153             return HttpResponse("yes\n%s\n%s" % (username, histories))
154
155     logger.info('Validation failed.')
156     return HttpResponse("no\n\n")
157     
158
159 def logout(request, template_name='cas/logout.html'):
160     url = request.GET.get('url', None)
161     auth_logout(request)
162     return render_to_response(template_name, {'url': url}, context_instance=RequestContext(request))