1 from django.http import HttpResponse, HttpResponseForbidden, HttpResponseRedirect
2 from django.shortcuts import get_object_or_404, render_to_response, get_list_or_404
3 from django.core.urlresolvers import reverse
4 from django.core.exceptions import SuspiciousOperation
5 from django.template import RequestContext
6 from django.contrib.auth.models import User
7 from django.contrib.auth import authenticate
8 from django.contrib.auth import login as auth_login, logout as auth_logout
10 from forms import LoginForm
11 from models import ServiceTicket, LoginTicket
12 from utils import create_service_ticket
14 __all__ = ['login', 'validate', 'logout']
16 def login(request, template_name='cas/login.html', success_redirect='/accounts/'):
17 service = request.GET.get('service', None)
18 if request.user.is_authenticated():
19 if service is not None:
20 ticket = create_service_ticket(request.user, service)
21 if service.find('?') == -1:
22 return HttpResponseRedirect(service + '?ticket=' + ticket.ticket)
24 return HttpResponseRedirect(service + '&ticket=' + ticket.ticket)
26 return HttpResponseRedirect(success_redirect)
28 if request.method == 'POST':
29 username = request.POST.get('username', None)
30 password = request.POST.get('password', None)
31 service = request.POST.get('service', None)
32 lt = request.POST.get('lt', None)
35 login_ticket = LoginTicket.objects.get(ticket=lt)
37 errors.append('Login ticket expired. Please try again.')
40 user = authenticate(username=username, password=password)
43 auth_login(request, user)
44 if service is not None:
45 ticket = create_service_ticket(user, service)
46 return HttpResponseRedirect(service + '?ticket=' + ticket.ticket)
48 return HttpResponseRedirect(success_redirect)
50 errors.append('This account is disabled.')
52 errors.append('Incorrect username and/or password.')
53 form = LoginForm(service)
54 return render_to_response(template_name, {'form': form, 'errors': errors}, context_instance=RequestContext(request))
56 def validate(request):
57 service = request.GET.get('service', None)
58 ticket_string = request.GET.get('ticket', None)
59 if service is not None and ticket_string is not None:
61 ticket = ServiceTicket.objects.get(ticket=ticket_string)
62 username = ticket.user.username
64 return HttpResponse("yes\n\r%s\n\r" % username)
67 return HttpResponse("no\n\r\n\r")
69 def logout(request, template_name='cas/logout.html'):
70 url = request.GET.get('url', None)
72 return render_to_response(template_name, {'url': url}, context_instance=RequestContext(request))