diff --git a/authens/forms.py b/authens/forms.py new file mode 100644 index 0000000..d69d460 --- /dev/null +++ b/authens/forms.py @@ -0,0 +1,61 @@ +from django import forms +from django.contrib.auth import forms as auth_forms, authenticate +from django.utils.translation import ugettext_lazy as _ +from django.utils import timezone + + +def promo_choices(): + return [(r, r) for r in range(2000, timezone.now().year + 1)] + + +class OldCASAuthForm(forms.Form): + """ Adapts Django's AuthenticationForm to allow for OldCAS login. + """ + + cas_login = auth_forms.UsernameField( + label=_("Ancien login clipper"), max_length=1023 + ) + password = forms.CharField( + label=_("Mot de passe"), + strip=False, + widget=forms.PasswordInput(attrs={"autocomplete": "current-password"}), + ) + entrance_year = forms.TypedChoiceField( + label=_("Promotion"), choices=promo_choices, coerce=int + ) + + def __init__(self, request=None, *args, **kwargs): + self.request = request + self.user_cache = None + super().__init__(*args, **kwargs) + + def clean(self): + cas_login = self.cleaned_data.get("cas_login") + password = self.cleaned_data.get("password") + entrance_year = self.cleaned_data.get("entrance_year") + + if cas_login is not None and password: + self.user_cache = authenticate( + self.request, + cas_login=cas_login, + password=password, + entrance_year=entrance_year, + ) + if self.user_cache is None: + raise self.get_invalid_login_error() + + return self.cleaned_data + + def get_user(self): + # Necessary API for LoginView + return self.user_cache + + def get_invalid_login_error(self): + return forms.ValidationError( + _( + "Aucun utilisateur n'existe avec ce clipper, cette promo et/ou ce mot" + "de passe. Veuillez vérifier votre saisie. Attention, tous les champs " + "sont sensibles à la casse !" + ), + code="invalid_login", + ) diff --git a/authens/urls.py b/authens/urls.py index 7b13310..1fe4eb9 100644 --- a/authens/urls.py +++ b/authens/urls.py @@ -7,5 +7,6 @@ urlpatterns = [ path("login/choose", views.LoginSwitchView.as_view(), name="login"), path("login/cas", views.CASLoginView.as_view(), name="login.cas"), path("login/pwd", views.PasswordLoginView.as_view(), name="login.pwd"), + path("login/oldcas", views.OldCASLoginView.as_view(), name="login.oldcas"), path("logout", views.LogoutView.as_view(), name="logout"), ] diff --git a/authens/views.py b/authens/views.py index 14ead4e..d5641a5 100644 --- a/authens/views.py +++ b/authens/views.py @@ -9,6 +9,7 @@ from django.shortcuts import redirect from django.utils.translation import gettext_lazy as _ from authens.utils import get_cas_client +from authens.forms import OldCASAuthForm class NextPageMixin: @@ -79,6 +80,11 @@ class PasswordLoginView(auth_views.LoginView): template_name = "authens/pwd_login.html" +class OldCASLoginView(auth_views.LoginView): + template_name = "authens/old_cas_login.html" + authentication_form = OldCASAuthForm + + class LogoutView(auth_views.LogoutView): """Logout view of AuthENS.