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