Authentication form and view

This commit is contained in:
Ludovic Stephan 2020-06-13 19:46:31 +02:00
parent 1c9ecb5eb9
commit b656bc3b76
3 changed files with 68 additions and 0 deletions

61
authens/forms.py Normal file
View file

@ -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",
)

View file

@ -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"),
]

View file

@ -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.