1 from django.http import HttpResponse, HttpResponseRedirect
2 from django.shortcuts import render_to_response
3 from django.template import RequestContext
4 from django.contrib.auth import authenticate
5 from django.contrib.auth import login as auth_login, logout as auth_logout
6 from django.utils.translation import ugettext_lazy as _
8 from forms import LoginForm
9 from models import ServiceTicket, LoginTicket
10 from utils import create_service_ticket
12 __all__ = ['login', 'validate', 'logout']
14 def login(request, template_name='cas/login.html', success_redirect='/accounts/'):
15 service = request.GET.get('service', None)
16 if request.user.is_authenticated():
17 if service is not None:
18 ticket = create_service_ticket(request.user, service)
19 if service.find('?') == -1:
20 return HttpResponseRedirect(service + '?ticket=' + ticket.ticket)
22 return HttpResponseRedirect(service + '&ticket=' + ticket.ticket)
24 return HttpResponseRedirect(success_redirect)
26 if request.method == 'POST':
27 username = request.POST.get('username', None)
28 password = request.POST.get('password', None)
29 service = request.POST.get('service', None)
30 lt = request.POST.get('lt', None)
33 login_ticket = LoginTicket.objects.get(ticket=lt)
35 errors.append(_('Login ticket expired. Please try again.'))
38 user = authenticate(username=username, password=password)
41 auth_login(request, user)
42 if service is not None:
43 ticket = create_service_ticket(user, service)
44 return HttpResponseRedirect(service + '?ticket=' + ticket.ticket)
46 return HttpResponseRedirect(success_redirect)
48 errors.append(_('This account is disabled.'))
50 errors.append(_('Incorrect username and/or password.'))
51 form = LoginForm(service)
52 return render_to_response(template_name, {'form': form, 'errors': errors}, context_instance=RequestContext(request))
54 def validate(request):
55 service = request.GET.get('service', None)
56 ticket_string = request.GET.get('ticket', None)
57 if service is not None and ticket_string is not None:
59 ticket = ServiceTicket.objects.get(ticket=ticket_string)
60 username = ticket.user.username
62 return HttpResponse("yes\r\n%s\r\n" % username)
65 return HttpResponse("no\r\n\r\n")
67 def logout(request, template_name='cas/logout.html'):
68 url = request.GET.get('url', None)
70 return render_to_response(template_name, {'url': url}, context_instance=RequestContext(request))