Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inform a user that he is not active in Django login view

I'm creating a custom authentication app to Django, everything is fine, the user needs to verify email to set is_active True, this works like a charm, but once the user send the e-mail and the token expires, the user try to login and receive a message of user or pass incorrect, and I want to show the user has to activate the account and give a link to resend the activation token to his email.

I'm using the default Login View:

url(r'^login/$', auth_views.LoginView.as_view(template_name='accounts/login.html'), name='account_login')

How can i modify this view or other thing to show the user is not active?

Looking in the AuthenticationForm from Django auth I can see that there is an error of inactive user, but only the error invalid_login is being raised in login form.

class AuthenticationForm(forms.Form):
    """
    Base class for authenticating users. Extend this to get a form that accepts
    username/password logins.
    """
    username = UsernameField(
        max_length=254,
        widget=forms.TextInput(attrs={'autofocus': True}),
    )
    password = forms.CharField(
        label=_("Password"),
        strip=False,
        widget=forms.PasswordInput,
    )

    error_messages = {
        'invalid_login': _(
            "Please enter a correct %(username)s and password. Note that both "
            "fields may be case-sensitive."
        ),
        'inactive': _("This account is inactive."),
    }

    def __init__(self, request=None, *args, **kwargs):
        """
        The 'request' parameter is set for custom auth use by subclasses.
        The form data comes in via the standard 'data' kwarg.
        """
        self.request = request
        self.user_cache = None
        super(AuthenticationForm, self).__init__(*args, **kwargs)

        # Set the label for the "username" field.
        self.username_field = UserModel._meta.get_field(UserModel.USERNAME_FIELD)
        if self.fields['username'].label is None:
            self.fields['username'].label = capfirst(self.username_field.verbose_name)

    def clean(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')

        if username is not None and password:
            self.user_cache = authenticate(self.request, username=username, password=password)
            if self.user_cache is None:
                raise forms.ValidationError(
                    self.error_messages['invalid_login'],
                    code='invalid_login',
                    params={'username': self.username_field.verbose_name},
                )
            else:
                self.confirm_login_allowed(self.user_cache)

        return self.cleaned_data

    def confirm_login_allowed(self, user):
        """
        Controls whether the given User may log in. This is a policy setting,
        independent of end-user authentication. This default behavior is to
        allow login by active users, and reject login by inactive users.

        If the given user cannot log in, this method should raise a
        ``forms.ValidationError``.

        If the given user may log in, this method should return None.
        """
        if not user.is_active:
            raise forms.ValidationError(
                self.error_messages['inactive'],
                code='inactive',
            )

    def get_user_id(self):
        if self.user_cache:
            return self.user_cache.id
        return None

    def get_user(self):
        return self.user_cache
like image 796
Gui Avatar asked Nov 20 '25 09:11

Gui


2 Answers

I'm able to correct this overrinding clean method from AuthenticationForm class.

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:
            self.user_cache = authenticate(self.request, username=username, password=password)
            if self.user_cache is None:
                try:
                    user_temp = User.objects.get(username=username)
                except:
                    user_temp = None

                if user_temp is not None:
                        self.confirm_login_allowed(user_temp)
                else:
                    raise forms.ValidationError(
                        self.error_messages['invalid_login'],
                        code='invalid_login',
                        params={'username': self.username_field.verbose_name},
                    )

        return self.cleaned_data

The inactive user never is raised, this happens because after Django 1.10 all users that is not active cannot authenticate, so self.user_chache is always be None for inactive users, even if has a correct user and pass.

like image 52
Gui Avatar answered Nov 23 '25 00:11

Gui


This introduces the issue of information disclosure fixed in Django 2.0.2 (see also https://code.djangoproject.com/ticket/28645).

In addition you should check, if the user supplied the correct password:

def clean(self):
    username = self.cleaned_data.get('username')
    password = self.cleaned_data.get('password')

    if username is not None and password:
        self.user_cache = authenticate(self.request, username=username, password=password)
        if self.user_cache is None:
            try:
                user_temp = User.objects.get(username=username)
            except:
                user_temp = None

            if user_temp is not None and user_temp.check_password(password):
                self.confirm_login_allowed(user_temp)
            else:
                raise forms.ValidationError(
                    self.error_messages['invalid_login'],
                    code='invalid_login',
                    params={'username': self.username_field.verbose_name},
                )

    return self.cleaned_data
like image 24
Christoph Avatar answered Nov 22 '25 22:11

Christoph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!