Files
fet2020/fet2020/authentications/forms.py

50 lines
1.7 KiB
Python

from django.contrib.auth.forms import AuthenticationForm, PasswordChangeForm
from django.contrib.auth.models import User
from django.core.validators import ValidationError
from .authentications import authentication, change_password
class LoginForm(AuthenticationForm):
def clean(self):
username = self.cleaned_data.get("username")
password = self.cleaned_data.get("password")
if username is not None and password:
auth_user = authentication(username, password)
if auth_user:
try:
self.user_cache = User.objects.get(username=auth_user.lower())
except User.DoesNotExist:
self.user_cache = User.objects.create_user(auth_user.lower())
else:
raise self.get_invalid_login_error()
if self.user_cache is None:
raise self.get_invalid_login_error()
else:
self.confirm_login_allowed(self.user_cache)
return self.cleaned_data
class LdapPasswordChangeForm(PasswordChangeForm):
def clean_old_password(self):
old_password = self.cleaned_data["old_password"]
if not authentication(self.user.username, old_password):
raise ValidationError(
self.error_messages["password_incorrect"],
code="password_incorrect",
)
return old_password
def clean(self):
old_password = self.cleaned_data["old_password"]
new_password = self.cleaned_data["new_password1"]
if not change_password(self.user, old_password, new_password):
raise ValidationError("Passwort im LDAP ändern funktioniert nicht.")
def save(self):
return self.user