47c2fdccc52cad916c0d718723270889d314bd4d
[django-cas-provider.git] / cas_provider / forms.py
1 from django import forms
2 from django.conf import settings
3 from django.contrib.auth import authenticate
4 from django.core.exceptions import ValidationError
5 from django.utils.translation import ugettext_lazy as _
6 from models import LoginTicket
7 import datetime
8
9
10 __all__ = ['LoginForm', ]
11
12
13 class LoginForm(forms.Form):
14     username = forms.CharField(max_length=30, label=_('username'))
15     password = forms.CharField(widget=forms.PasswordInput, label=_('password'))
16     lt = forms.CharField(widget=forms.HiddenInput)
17     service = forms.CharField(widget=forms.HiddenInput, required=False)
18
19     def __init__(self, *args, **kwargs):
20         super(LoginForm, self).__init__(*args, **kwargs)
21         self._user = None
22
23     def clean_lt(self):
24         ticket = self.cleaned_data['lt']
25         timeframe = datetime.datetime.now() - \
26                     datetime.timedelta(minutes=settings.CAS_TICKET_EXPIRATION)
27         try:
28             return LoginTicket.objects.get(ticket=ticket, created__gte=timeframe)
29         except LoginTicket.DoesNotExist:
30             raise ValidationError(_('Login ticket expired. Please try again.'))
31         return ticket
32
33     def clean(self):
34         username = self.cleaned_data.get('username')
35         password = self.cleaned_data.get('password')
36         user = authenticate(username=username, password=password)
37         if user is None:
38             raise ValidationError(_('Incorrect username and/or password.'))
39         if not user.is_active:
40             raise ValidationError(_('This account is disabled.'))
41         self._user = user
42         self.cleaned_data.get('lt').delete()
43         return self.cleaned_data
44
45     def get_user(self):
46         return self._user
47     
48     def get_errors(self):
49         errors = []
50         for k, error in self.errors.items():
51             errors += [e for e in error]
52         return errors