|
| 1 | +""" |
| 2 | +© Ocado Group |
| 3 | +Created on 05/08/2024 at 08:39:57(+01:00). |
| 4 | +""" |
| 5 | + |
| 6 | +from django import forms |
| 7 | +from django.contrib.auth import authenticate |
| 8 | +from django.core.exceptions import ValidationError |
| 9 | +from django.core.handlers.wsgi import WSGIRequest |
| 10 | + |
| 11 | +from ..user.models import User |
| 12 | + |
| 13 | + |
| 14 | +class BaseLoginForm(forms.Form): |
| 15 | + """ |
| 16 | + Base login form that all other login forms must inherit. |
| 17 | + """ |
| 18 | + |
| 19 | + user: User |
| 20 | + |
| 21 | + def __init__(self, request: WSGIRequest, *args, **kwargs): |
| 22 | + self.request = request |
| 23 | + super().__init__(*args, **kwargs) |
| 24 | + |
| 25 | + def clean(self): |
| 26 | + """Authenticates a user. |
| 27 | +
|
| 28 | + Raises: |
| 29 | + ValidationError: If there are form errors. |
| 30 | + ValidationError: If the user's credentials were incorrect. |
| 31 | + ValidationError: If the user's account is deactivated. |
| 32 | +
|
| 33 | + Returns: |
| 34 | + The cleaned form data. |
| 35 | + """ |
| 36 | + |
| 37 | + if self.errors: |
| 38 | + raise ValidationError( |
| 39 | + "Found form errors. Skipping authentication.", |
| 40 | + code="form_errors", |
| 41 | + ) |
| 42 | + |
| 43 | + user = authenticate( |
| 44 | + self.request, |
| 45 | + **{key: self.cleaned_data[key] for key in self.fields.keys()} |
| 46 | + ) |
| 47 | + if user is None: |
| 48 | + raise ValidationError( |
| 49 | + self.get_invalid_login_error_message(), |
| 50 | + code="invalid_login", |
| 51 | + ) |
| 52 | + if not isinstance(user, User): |
| 53 | + raise ValidationError( |
| 54 | + "Incorrect user class.", |
| 55 | + code="incorrect_user_class", |
| 56 | + ) |
| 57 | + self.user = user |
| 58 | + |
| 59 | + if not user.is_active: |
| 60 | + raise ValidationError( |
| 61 | + "User is not active", |
| 62 | + code="user_not_active", |
| 63 | + ) |
| 64 | + |
| 65 | + return self.cleaned_data |
| 66 | + |
| 67 | + def get_invalid_login_error_message(self) -> str: |
| 68 | + """Returns the error message if the user failed to login. |
| 69 | +
|
| 70 | + Raises: |
| 71 | + NotImplementedError: If message is not set. |
| 72 | + """ |
| 73 | + raise NotImplementedError() |
0 commit comments