2 logger = logging.getLogger('cas_provider.views')
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
12 from forms import LoginForm, MergeLoginForm
13 from models import ServiceTicket
14 from utils import create_service_ticket
15 from exceptions import SameEmailMismatchedPasswords
17 #FIXME: Remove this dependency
18 from accounts.models import IdentifierHistory
19 from django.contrib.auth.models import User
21 __all__ = ['login', 'validate', 'logout']
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)
38 url = service + '&ticket=' + ticket.ticket
39 logging.debug('Redirecting to %s', url)
40 return HttpResponseRedirect()
42 logging.debug('Redirecting to %s', success_redirect)
43 return HttpResponseRedirect(success_redirect)
45 if request.method == 'POST':
47 form = MergeLoginForm(request.POST, request=request)
49 form = LoginForm(request.POST, request=request)
53 auth_args = dict(username=form.cleaned_data['email'],
54 password=form.cleaned_data['password'])
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?
64 # We shouldn't get here...
67 base_url = reverse('cas_provider_merge')
69 success_redirect=success_redirect,
70 email=form.cleaned_data['email'],
72 if service is not None:
73 args['service'] = service
74 args = urllib.urlencode(args)
76 url = '%s?%s' % (base_url, args)
77 logging.debug('Redirecting to %s', url)
78 return HttpResponseRedirect(url)
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)
89 logging.debug('Redirecting to %s', success_redirect)
90 return HttpResponseRedirect(success_redirect)
92 errors.append('This account is disabled.')
94 errors.append('Incorrect username and/or password.')
97 form = MergeLoginForm(initial={'service': service, 'email': request.GET.get('email')})
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))
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.
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']
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)
123 return HttpResponseRedirect(success_redirect)
125 errors.append('This account is disabled.')
127 errors.append('Incorrect username and/or password.')
128 return render_to_response(template_name, {'errors': errors}, context_instance=RequestContext(request))
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:
138 ticket = ServiceTicket.objects.get(ticket=ticket_string)
139 username = ticket.user.username
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 ''
146 return HttpResponse("yes\n%s\n%s" % (username, histories))
148 except Exception as e:
149 logger.exception("Got an exception!: %s"% e)
151 return HttpResponse("no\n\n")
154 def logout(request, template_name='cas/logout.html'):
155 url = request.GET.get('url', None)
157 return render_to_response(template_name, {'url': url}, context_instance=RequestContext(request))