60 lines
2.1 KiB
Python
60 lines
2.1 KiB
Python
import logging
|
|
|
|
from django.contrib.auth.forms import AuthenticationForm, PasswordChangeForm
|
|
from django.contrib.auth.models import Group, User
|
|
from django.core.exceptions import ValidationError
|
|
|
|
from .authentications import authentication, change_password, get_finance_perm
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class LoginForm(AuthenticationForm):
|
|
def clean(self):
|
|
username = self.cleaned_data.get("username").lower()
|
|
password = self.cleaned_data.get("password")
|
|
|
|
if username is not None and password:
|
|
if (auth_user := authentication(username, password)) is None:
|
|
raise ValidationError(
|
|
"Bitte Benutzername und Passwort korrekt eingeben.",
|
|
code="invalid_login",
|
|
)
|
|
|
|
try:
|
|
self.user_cache = User.objects.get(username=auth_user.lower())
|
|
except User.DoesNotExist:
|
|
self.user_cache = User.objects.create_user(auth_user.lower())
|
|
finally:
|
|
self.confirm_login_allowed(self.user_cache)
|
|
|
|
# add user to all groups
|
|
for elem in Group.objects.all():
|
|
elem.user_set.add(self.user_cache)
|
|
|
|
# delete finance group if no permission
|
|
if not get_finance_perm(username, password):
|
|
finance_group = Group.objects.get(name="finance")
|
|
finance_group.user_set.remove(self.user_cache)
|
|
|
|
return self.cleaned_data
|
|
|
|
|
|
class LdapPasswordChangeForm(PasswordChangeForm):
|
|
def clean_old_password(self):
|
|
old_password = self.cleaned_data.get("old_password")
|
|
if not authentication(self.user, old_password):
|
|
raise ValidationError(
|
|
self.error_messages["password_incorrect"],
|
|
code="password_incorrect",
|
|
)
|
|
|
|
return old_password
|
|
|
|
def save(self):
|
|
old_password = self.cleaned_data.get("old_password")
|
|
new_password = self.cleaned_data.get("new_password1")
|
|
change_password(self.user, old_password, new_password)
|
|
|
|
return self.user
|