235b38fac2ebd68f41e145865df479112cb95786
[django-cas-provider.git] / cas_provider / views.py
1 import logging
2 import urllib
3
4 from django.http import HttpResponse, HttpResponseRedirect
5 from django.shortcuts import render_to_response
6 from django.template import RequestContext
7 from django.contrib.auth import authenticate
8 from django.contrib.auth import login as auth_login, logout as auth_logout
9 from django.core.urlresolvers import reverse
10
11 from forms import LoginForm, MergeLoginForm
12 from models import ServiceTicket
13 from utils import create_service_ticket
14 from exceptions import SameEmailMismatchedPasswords
15
16 __all__ = ['login', 'validate', 'logout']
17
18
19 def login(request, template_name='cas/login.html', success_redirect='/account/', merge=False):
20     logging.debug('CAS Provider Login view. Method is %s, merge is %s, template is %s.',
21                   request.method, merge, template_name)
22     service = request.GET.get('service', None)
23     if service is not None:
24         request.session['service'] = service
25     if request.user.is_authenticated():
26         if service is not None:
27             ticket = create_service_ticket(request.user, service)
28             if service.find('?') == -1:
29                 url = service + '?ticket=' + ticket.ticket
30                 logging.debug('Redirecting to %s', url)
31                 return HttpResponseRedirect(url)
32             else:
33                 url = service + '&ticket=' + ticket.ticket
34                 logging.debug('Redirecting to %s', url)
35                 return HttpResponseRedirect()
36         else:
37             logging.debug('Redirecting to %s', success_redirect)
38             return HttpResponseRedirect(success_redirect)
39     errors = []
40     if request.method == 'POST':
41         if merge:
42             form = MergeLoginForm(request.POST, request=request)
43         else:
44             form = LoginForm(request.POST, request=request)
45
46         if form.is_valid():
47             try:
48                 auth_args = dict(username=form.cleaned_data['email'],
49                                  password=form.cleaned_data['password'])
50                 if merge:
51                     # We only want to send the merge argument if it's
52                     # True. If it it's False, we want it to propagate
53                     # through the auth backends properly.
54                     auth_args['merge'] = merge
55                 user = authenticate(**auth_args)
56             except SameEmailMismatchedPasswords:
57                 # Need to merge the accounts?
58                 if merge:
59                     # We shouldn't get here...
60                     raise
61                 else:
62                     base_url = reverse('cas_provider_merge')
63                     args = dict(
64                         success_redirect=success_redirect,
65                         email=form.cleaned_data['email'],
66                         )
67                     if service is not None:
68                         args['service'] = service
69                     args = urllib.urlencode(args)
70
71                     url = '%s?%s' % (base_url, args)
72                     logging.debug('Redirecting to %s', url)
73                     return HttpResponseRedirect(url)
74             
75             if user is not None:
76                 if user.is_active:
77                     auth_login(request, user)
78                     if service is not None:
79                         ticket = create_service_ticket(user, service)
80                         url = service + '?ticket=' + ticket.ticket
81                         logging.debug('Redirecting to %s', url)
82                         return HttpResponseRedirect(url)
83                     else:
84                         logging.debug('Redirecting to %s', success_redirect)
85                         return HttpResponseRedirect(success_redirect)
86                 else:
87                     errors.append('This account is disabled.')
88             else:
89                     errors.append('Incorrect username and/or password.')
90     else:
91         if merge:
92             form = MergeLoginForm(initial={'service': service, 'email': request.GET.get('email')})
93         else:
94             form = LoginForm(initial={'service': service})
95     logging.debug('Rendering response on %s, merge is %s', template_name, merge)
96     return render_to_response(template_name, {'form': form, 'errors': errors}, context_instance=RequestContext(request))
97
98
99 def socialauth_login(request, template_name='cas/login.html', success_redirect='/account/'):
100     """ Similiar to login but user has been authenticated already through social auth.
101         This step authenticates the login and generates a service ticket.
102     """
103     user = request.user
104     user.backend = 'django.contrib.auth.backends.ModelBackend'
105     if request.session.has_key('service'):
106         service = request.session['service']
107         del request.session['service']
108     else:
109         service = '/'
110     errors = []
111     if user is not None:
112         if user.is_active:
113             auth_login(request, user)
114             if service is not None:
115                 ticket = create_service_ticket(user, service)
116                 return HttpResponseRedirect(service + '?ticket=' + ticket.ticket)
117             else:
118                 return HttpResponseRedirect(success_redirect)
119         else:
120             errors.append('This account is disabled.')
121     else:
122             errors.append('Incorrect username and/or password.')
123     return render_to_response(template_name, {'errors': errors}, context_instance=RequestContext(request))
124
125
126 def validate(request):
127     service = request.GET.get('service', None)
128     ticket_string = request.GET.get('ticket', None)
129     if service is not None and ticket_string is not None:
130         try:
131             ticket = ServiceTicket.objects.get(ticket=ticket_string)
132             username = ticket.user.username
133             ticket.delete()
134             return HttpResponse("yes\n%s\n" % username)
135         except:
136             pass
137     return HttpResponse("no\n\n")
138     
139
140 def logout(request, template_name='cas/logout.html'):
141     url = request.GET.get('url', None)
142     auth_logout(request)
143     return render_to_response(template_name, {'url': url}, context_instance=RequestContext(request))