ff7dcd71b2a633081f52e1b7b89cbab2f3e54cc9
[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     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)
35             else:
36                 url = service + '&ticket=' + ticket.ticket
37                 logging.debug('Redirecting to %s', url)
38                 return HttpResponseRedirect()
39         else:
40             logging.debug('Redirecting to %s', success_redirect)
41             return HttpResponseRedirect(success_redirect)
42     errors = []
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             try:
51                 auth_args = dict(username=form.cleaned_data['email'],
52                                  password=form.cleaned_data['password'])
53                 if merge:
54                     # We only want to send the merge argument if it's
55                     # True. If it it's False, we want it to propagate
56                     # through the auth backends properly.
57                     auth_args['merge'] = merge
58                 user = authenticate(**auth_args)
59             except SameEmailMismatchedPasswords:
60                 # Need to merge the accounts?
61                 if merge:
62                     # We shouldn't get here...
63                     raise
64                 else:
65                     base_url = reverse('cas_provider_merge')
66                     args = dict(
67                         success_redirect=success_redirect,
68                         email=form.cleaned_data['email'],
69                         )
70                     if service is not None:
71                         args['service'] = service
72                     args = urllib.urlencode(args)
73
74                     url = '%s?%s' % (base_url, args)
75                     logging.debug('Redirecting to %s', url)
76                     return HttpResponseRedirect(url)
77             
78             if user is not None:
79                 if user.is_active:
80                     auth_login(request, user)
81                     if service is not None:
82                         ticket = create_service_ticket(user, service)
83                         url = service + '?ticket=' + ticket.ticket
84                         logging.debug('Redirecting to %s', url)
85                         return HttpResponseRedirect(url)
86                     else:
87                         logging.debug('Redirecting to %s', success_redirect)
88                         return HttpResponseRedirect(success_redirect)
89                 else:
90                     errors.append('This account is disabled.')
91             else:
92                     errors.append('Incorrect username and/or password.')
93     else:
94         if merge:
95             form = MergeLoginForm(initial={'service': service, 'email': request.GET.get('email')})
96         else:
97             form = LoginForm(initial={'service': service})
98     logging.debug('Rendering response on %s, merge is %s', template_name, merge)
99     return render_to_response(template_name, {'form': form, 'errors': errors}, context_instance=RequestContext(request))
100
101
102 def socialauth_login(request, template_name='cas/login.html', success_redirect='/account/'):
103     """ Similiar to login but user has been authenticated already through social auth.
104         This step authenticates the login and generates a service ticket.
105     """
106     user = request.user
107     user.backend = 'django.contrib.auth.backends.ModelBackend'
108     if request.session.has_key('service'):
109         service = request.session['service']
110         del request.session['service']
111     else:
112         service = '/'
113     errors = []
114     if user is not None:
115         if user.is_active:
116             auth_login(request, user)
117             if service is not None:
118                 ticket = create_service_ticket(user, service)
119                 return HttpResponseRedirect(service + '?ticket=' + ticket.ticket)
120             else:
121                 return HttpResponseRedirect(success_redirect)
122         else:
123             errors.append('This account is disabled.')
124     else:
125             errors.append('Incorrect username and/or password.')
126     return render_to_response(template_name, {'errors': errors}, context_instance=RequestContext(request))
127
128
129 def validate(request):
130     service = request.GET.get('service', None)
131     ticket_string = request.GET.get('ticket', None)
132     logger.debug("service: %s"% service)
133     logger.debug("ticket_string: %s"% ticket_string)
134     if service is not None and ticket_string is not None:
135         try:
136             ticket = ServiceTicket.objects.get(ticket=ticket_string)
137             username = ticket.user.username
138             ticket.delete()
139
140             results = signals.on_cas_collect_histories.send(sender=validate, for_email=ticket.user.email)
141             histories = '\n'.join('\n'.join(rs) for rc, rs in results)
142
143             return HttpResponse("yes\n%s\n%s" % (username, histories))
144
145         except Exception as e:
146             logger.exception("Got an exception!: %s"% e)
147
148     return HttpResponse("no\n\n")
149     
150
151 def logout(request, template_name='cas/logout.html'):
152     url = request.GET.get('url', None)
153     auth_logout(request)
154     return render_to_response(template_name, {'url': url}, context_instance=RequestContext(request))