[Django]-Restrict access to reset_password form of Django in PasswordResetView in case the user is already logged in

1๐Ÿ‘

โœ…

If you really want to modify the default views, one option would be to subclass them and use them in your urls.

In your views (using UserPassesTestMixin class):

from django.contrib.auth.mixins import UserPassesTestMixin
from django.contrib.auth.views import PasswordResetView

class MyPasswordResetView(UserPassesTestMixin, PasswordResetView):
    template_name = 'users/password_reset.html'

    # https://docs.djangoproject.com/en/2.2/ref/contrib/auth/#django.contrib.auth.models.User.is_anonymous
    def test_func(self):
        return self.request.user.is_anonymous

In your urls:

from .views import MyPasswordResetView

...
    path(
        'password_reset/', 
        MyPasswordResetView.as_view(),
        name="password_reset"),
...

You should learn to read the linked docs to find your answers. It says here:

[โ€ฆ] you can set any of the parameters of AccessMixin to customize the handling of unauthorized users [โ€ฆ]

And under AccessMixin you can find the attributes and methods to redirect unauthorized users.

๐Ÿ‘คRalf

3๐Ÿ‘

Multiple ways to do this; However, I think that the quickest solution would be to write a decorator:

def login_forbidden(function=None):
    actual_decorator = user_passes_test(
        lambda u: u.is_anonymous,
    )
    if function:
        return actual_decorator(function)
    return actual_decorator

and use it to decorate the password reset views where you want to restrict access only to unauthenticated users:

path('password_reset/', login_forbidden(auth_views.PasswordResetView.as_view(template_name='users/password_reset.html')), name="password_reset")

Alternatively, you can override the actual views.

๐Ÿ‘คAlex

2๐Ÿ‘

You can use {% if user.is_authenticated %} or {% if user.is_anonymous %} and put that directly in your template no need to modify the view:

{% if user.is_anonymous %}
# user is not logged in
...
{% else %}
# user is logged in
...
{% endif %}
๐Ÿ‘คCeDeROM

Leave a comment