295c3f30659656887004a8277bd48b38b2590b4e
[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             logging.debug('Using mergeloginform, email is %' % request.GET.get('email'))
43             form = MergeLoginForm(request.POST, request=request)
44         else:
45             form = LoginForm(request.POST, request=request)
46
47         if form.is_valid():
48             try:
49                 auth_args = dict(username=form.cleaned_data['email'],
50                                  password=form.cleaned_data['password'])
51                 if merge:
52                     # We only want to send the merge argument if it's
53                     # True. If it it's False, we want it to propagate
54                     # through the auth backends properly.
55                     auth_args['merge'] = merge
56                 user = authenticate(**auth_args)
57             except SameEmailMismatchedPasswords:
58                 # Need to merge the accounts?
59                 if merge:
60                     # We shouldn't get here...
61                     raise
62                 else:
63                     base_url = reverse('cas_provider_merge')
64                     args = dict(
65                         success_redirect=success_redirect,
66                         email=form.cleaned_data['email'],
67                         )
68                     if service is not None:
69                         args['service'] = service
70                     args = urllib.urlencode(args)
71
72                     url = '%s?%s' % (base_url, args)
73                     logging.debug('Redirecting to %s', url)
74                     return HttpResponseRedirect(url)
75             
76             if user is not None:
77                 if user.is_active:
78                     auth_login(request, user)
79                     if service is not None:
80                         ticket = create_service_ticket(user, service)
81                         url = service + '?ticket=' + ticket.ticket
82                         logging.debug('Redirecting to %s', url)
83                         return HttpResponseRedirect(url)
84                     else:
85                         logging.debug('Redirecting to %s', success_redirect)
86                         return HttpResponseRedirect(success_redirect)
87                 else:
88                     errors.append('This account is disabled.')
89             else:
90                     errors.append('Incorrect username and/or password.')
91     else:
92         if merge:
93             logging.debug('Using mergeloginform, email is %' % request.GET.get('email'))
94             form = MergeLoginForm(initial={'service': service, 'email': request.GET.get('email')})
95         else:
96             logging.debug('Using normal login form.')
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     if service is not None and ticket_string is not None:
133         try:
134             ticket = ServiceTicket.objects.get(ticket=ticket_string)
135             username = ticket.user.username
136             ticket.delete()
137             return HttpResponse("yes\n%s\n" % username)
138         except:
139             pass
140     return HttpResponse("no\n\n")
141     
142
143 def logout(request, template_name='cas/logout.html'):
144     url = request.GET.get('url', None)
145     auth_logout(request)
146     return render_to_response(template_name, {'url': url}, context_instance=RequestContext(request))