django - force first time login user to reset password change

Viewed 38

I want to be able to create a new user via admin panel or via my application for the user to use. When the user login for the first time, the user will be redirected to the password reset page to change their password. After successfully changing the password, they will be redirected to the home page.

To do this, I have a field in my User model called is_1st_login which takes a 'Y' (default) and 'N' value. So all I need to do is to write like below:

def login_view(request):
    form = LoginForm(request.POST or None)

    msg = None

    if request.method == "POST":

        if form.is_valid():
            username = form.cleaned_data.get("username")
            password = form.cleaned_data.get("password")
            user = authenticate(username=username, password=password)
            if user is not None and (user.has_perm('authentication.can_access_web') or user.is_superuser):
                login(request, user)
               
                # redirect 1st time user login to reset password
                if user.is_1st_login == 'Y':
                    return redirect('user_password_change')
                return redirect("/")
            else:
                msg = 'Invalid credentials'
        else:
            msg = 'Error validating the form'

    return render(request, "account/login2.html", {"form": form, "msg" : msg})`

And the after resetting the password, I'll update the field to 'N'. While all this is working as expected, how do I restrict the user from trying to bypass it via changing the url to a valid path without changing the password?

My application is big with many apps and I thought of using middleware or decorator but that would require me to apply it to many functions in the backend. Is there a way to prevent user from trying to tamper the URL to skip the reset password process like by setting a middleware that automatically applies to the entire system?

I have tried finding third party libraries or packages that suits my need but I did not find one. I tried using middleware but from my understanding, middlewares have to be individually applied.

1 Answers

A middleware applies itself to everything that comes through the server, so you only have to write it and add it to the middleware stack in settings.py for the site. Since you will be accesing request.user it will have to go after whatever middleware attaches user to request. That's probably django.contrib.auth.middleware.AuthenticationMiddleware

Related