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