2 logger = logging.getLogger('cas_provider.views')
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
12 from forms import LoginForm, MergeLoginForm
13 from models import ServiceTicket
14 from utils import create_service_ticket
15 from exceptions import SameEmailMismatchedPasswords
19 __all__ = ['login', 'validate', 'logout']
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 service = request.GET.get('service', None)
26 if service is not None:
27 request.session['service'] = service
28 if request.user.is_authenticated():
29 if service is not None:
30 ticket = create_service_ticket(request.user, service)
31 if service.find('?') == -1:
32 url = service + '?ticket=' + ticket.ticket
33 logging.debug('Redirecting to %s', url)
34 return HttpResponseRedirect(url)
36 url = service + '&ticket=' + ticket.ticket
37 logging.debug('Redirecting to %s', url)
38 return HttpResponseRedirect(url)
40 logging.debug('Redirecting to %s', success_redirect)
41 return HttpResponseRedirect(success_redirect)
43 if request.method == 'POST':
45 form = MergeLoginForm(request.POST, request=request)
47 form = LoginForm(request.POST, request=request)
50 service = form.cleaned_data.get('service', None)
52 auth_args = dict(username=form.cleaned_data['email'],
53 password=form.cleaned_data['password'])
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?
63 # We shouldn't get here...
66 base_url = reverse('cas_provider_merge')
68 success_redirect=success_redirect,
69 email=form.cleaned_data['email'],
71 if service is not None:
72 args['service'] = service
73 args = urllib.urlencode(args)
75 url = '%s?%s' % (base_url, args)
76 logging.debug('Redirecting to %s', url)
77 return HttpResponseRedirect(url)
81 auth_login(request, user)
82 if service is not None:
83 ticket = create_service_ticket(user, service)
84 url = service + '?ticket=' + ticket.ticket
85 logging.debug('Redirecting to %s', url)
86 return HttpResponseRedirect(url)
88 logging.debug('Redirecting to %s', success_redirect)
89 return HttpResponseRedirect(success_redirect)
91 errors.append('This account is disabled.')
93 errors.append('Incorrect username and/or password.')
96 form = MergeLoginForm(initial={'service': service, 'email': request.GET.get('email')})
98 form = LoginForm(initial={'service': service})
99 logging.debug('Rendering response on %s, merge is %s', template_name, merge)
100 return render_to_response(template_name, {'form': form, 'errors': errors}, context_instance=RequestContext(request))
103 def socialauth_login(request, template_name='cas/login.html', success_redirect='/account/'):
104 """ Similiar to login but user has been authenticated already through social auth.
105 This step authenticates the login and generates a service ticket.
108 user.backend = 'django.contrib.auth.backends.ModelBackend'
109 if request.session.has_key('service'):
110 service = request.session['service']
111 del request.session['service']
117 auth_login(request, user)
118 if service is not None:
119 ticket = create_service_ticket(user, service)
120 return HttpResponseRedirect(service + '?ticket=' + ticket.ticket)
122 return HttpResponseRedirect(success_redirect)
124 errors.append('This account is disabled.')
126 errors.append('Incorrect username and/or password.')
127 return render_to_response(template_name, {'errors': errors}, context_instance=RequestContext(request))
130 def validate(request):
131 service = request.GET.get('service', None)
132 ticket_string = request.GET.get('ticket', None)
133 logger.info('Validating ticket %s for %s', ticket_string, service)
134 if service is not None and ticket_string is not None:
136 ticket = ServiceTicket.objects.get(ticket=ticket_string)
137 except ServiceTicket.DoesNotExist:
138 logger.exception("Tried to validate with an invalid ticket %s for %s", ticket_string, service)
139 except Exception as e:
140 logger.exception('Got an exception: %s', e)
142 username = ticket.user.username
145 results = signals.on_cas_collect_histories.send(sender=validate, for_email=ticket.user.email)
146 histories = '\n'.join('\n'.join(rs) for rc, rs in results)
147 logger.info('Validated %s %s', username, "(also %s)" % histories if histories else '')
148 return HttpResponse("yes\n%s\n%s" % (username, histories))
150 logger.info('Validation failed.')
151 return HttpResponse("no\n\n")
154 def logout(request, template_name='cas/logout.html'):
155 url = request.GET.get('url', None)
157 return render_to_response(template_name, {'url': url}, context_instance=RequestContext(request))