1- from typing import Any , Dict
1+ from typing import Any , Optional
22
33from django import forms
4+ from django .contrib .auth .password_validation import get_password_validators , validate_password
45from django .utils .translation import gettext_lazy as _
56
67from shiftings .accounts .models import User
8+ from shiftings .settings import AUTH_PASSWORD_VALIDATORS
79
810
911class UserCreateForm (forms .ModelForm ):
@@ -26,11 +28,16 @@ def clean(self) -> Dict[str, Any]:
2628 password = cleaned_data ['password' ]
2729 confirm_password = cleaned_data ['confirm_password' ]
2830 if password != confirm_password :
29- raise forms .ValidationError (
30- _ ('Please enter matching passwords' )
31- )
32- return cleaned_data
31+ self .add_error ('password' , _ ('Please enter matching passwords' ))
32+ self .add_error ('confirm_password' , _ ('Please enter matching passwords' ))
33+
34+ # validate password using Django's built-in validators
35+ try :
36+ validate_password (password , user = None , password_validators = get_password_validators (AUTH_PASSWORD_VALIDATORS ))
37+ except forms .ValidationError as e :
38+ self .add_error ('password' , e )
3339
40+ return cleaned_data
3441
3542class UserUpdateForm (forms .ModelForm ):
3643 class Meta :
@@ -47,3 +54,13 @@ def __init__(self, *args: Any, **kwargs: Any) -> None:
4754 self .fields ['first_name' ].disabled = True
4855 self .fields ['last_name' ].disabled = True
4956 self .fields ['email' ].disabled = True
57+
58+ def clean (self ) -> Optional [dict [str , Any ]]:
59+ cleaned_data = super ().clean ()
60+ if hasattr (self .instance , 'ldap_user' ):
61+ # if this is an ldap user, ensure that the fields are not changed
62+ if (cleaned_data .get ('first_name' ) != self .instance .first_name or
63+ cleaned_data .get ('last_name' ) != self .instance .last_name or
64+ cleaned_data .get ('email' ) != self .instance .email ):
65+ raise forms .ValidationError (_ ('Cannot change first name, last name or email for LDAP users.' ))
66+ return cleaned_data
0 commit comments