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