v0.166.0
  1from collections.abc import Callable, Generator
  2from typing import Any
  3
  4from app.users.models import User
  5from plain.exceptions import ValidationError
  6from plain.postgres.fields.base import ColumnField
  7from plain.postgres.forms import ModelForm
  8
  9from plain import forms
 10
 11from .core import check_user_password
 12from .hashers import check_password
 13from .utils import unicode_ci_compare
 14
 15
 16class PasswordResetForm(forms.Form):
 17    email = forms.EmailField(max_length=254)
 18
 19    def send_mail(
 20        self,
 21        *,
 22        template_name: str,
 23        context: dict[str, Any],
 24        from_email: str,
 25        to_email: str,
 26    ) -> None:
 27        from plain.email import TemplateEmail
 28
 29        email = TemplateEmail(
 30            template=template_name,
 31            context=context,
 32            from_email=from_email,
 33            to=[to_email],
 34            headers={
 35                "X-Auto-Response-Suppress": "All",
 36            },
 37        )
 38
 39        email.send()
 40
 41    def get_users(self, email: str) -> Generator[User]:
 42        """Given an email, return matching user(s) who should receive a reset.
 43
 44        This allows subclasses to more easily customize the default policies
 45        that prevent inactive users and users with unusable passwords from
 46        resetting their password.
 47        """
 48        active_users = User.query.where(User.email.iequals(email))
 49        return (u for u in active_users if unicode_ci_compare(email, u.email))
 50
 51    def save(
 52        self,
 53        *,
 54        generate_reset_url: Callable[[User], str],
 55        email_template_name: str = "password_reset",
 56        from_email: str = "",
 57        extra_email_context: dict[str, Any] | None = None,
 58    ) -> None:
 59        """
 60        Generate a one-use only link for resetting password and send it to the
 61        user.
 62        """
 63        email = self.cleaned_data["email"]
 64        for user in self.get_users(email):
 65            context = {
 66                "email": email,
 67                "user": user,
 68                "url": generate_reset_url(user),
 69                **(extra_email_context or {}),
 70            }
 71            self.send_mail(
 72                template_name=email_template_name,
 73                context=context,
 74                from_email=from_email,
 75                to_email=user.email,
 76            )
 77
 78
 79class PasswordSetForm(forms.Form):
 80    """
 81    A form that lets a user set their password without entering the old
 82    password
 83    """
 84
 85    new_password1 = forms.TextField(strip=False)
 86    new_password2 = forms.TextField(strip=False)
 87
 88    def __init__(self, user: User, *args: Any, **kwargs: Any) -> None:
 89        self.user = user
 90        super().__init__(*args, **kwargs)
 91
 92    def clean_new_password2(self) -> str:
 93        password1 = self.cleaned_data.get("new_password1")
 94        password2 = self.cleaned_data.get("new_password2")
 95        if password1 and password2 and password1 != password2:
 96            raise ValidationError(
 97                "The two password fields didn't match.",
 98                code="password_mismatch",
 99            )
100
101        # password2 must exist at this point (required field)
102        assert isinstance(password2, str), "new_password2 must be a string"
103
104        # Clean it as if it were being put into the model directly
105        password_field = self.user._model_meta.get_forward_field("password")
106        if not isinstance(password_field, ColumnField):
107            raise TypeError(
108                f"{type(self.user).__name__}.password must be a column field"
109            )
110        password_field.clean(password2, self.user)
111
112        return password2
113
114    def save(self, commit: bool = True) -> User:
115        self.user.password = self.cleaned_data["new_password1"]
116        if commit:
117            self.user.update()
118        return self.user
119
120
121class PasswordChangeForm(PasswordSetForm):
122    """
123    A form that lets a user change their password by entering their old
124    password.
125    """
126
127    current_password = forms.TextField(strip=False)
128
129    def clean_current_password(self) -> str:
130        """
131        Validate that the current_password field is correct.
132        """
133        current_password = self.cleaned_data["current_password"]
134        if not check_user_password(self.user, current_password):
135            raise ValidationError(
136                "Your old password was entered incorrectly. Please enter it again.",
137                code="password_incorrect",
138            )
139        return current_password
140
141
142class PasswordLoginForm(forms.Form):
143    email = forms.EmailField(max_length=150)
144    password = forms.TextField(strip=False)
145
146    def clean(self) -> dict[str, Any]:
147        email = self.cleaned_data.get("email")
148        password = self.cleaned_data.get("password")
149
150        if email and password:
151            try:
152                # The vast majority of users won't have a case-sensitive email, so we act that way
153                user = User.query.get(User.email.iequals(email))
154            except User.DoesNotExist:
155                # Run the default password hasher once to reduce the timing
156                # difference between an existing and a nonexistent user (django #20760).
157                check_password(password, "")
158
159                raise ValidationError(
160                    "Please enter a correct email and password. Note that both fields may be case-sensitive.",
161                    code="invalid_login",
162                )
163
164            if not check_user_password(user, password):
165                raise ValidationError(
166                    "Please enter a correct email and password. Note that both fields may be case-sensitive.",
167                    code="invalid_login",
168                )
169
170            self._user = user
171
172        return self.cleaned_data
173
174    def get_user(self) -> User:
175        return self._user
176
177
178class PasswordSignupForm(ModelForm):
179    confirm_password = forms.TextField(strip=False)
180
181    class Meta:
182        model = User
183        fields = ("email", "password")
184
185    def clean(self) -> dict[str, Any]:
186        cleaned_data = super().clean()
187        password = cleaned_data.get("password")
188        confirm_password = cleaned_data.get("confirm_password")
189        if password and confirm_password and password != confirm_password:
190            raise ValidationError(
191                "The two password fields didn't match.",
192                code="password_mismatch",
193            )
194        return cleaned_data