How can I redirect the user to the login page until they complete the authorization?

461 Views Asked by At

I found such a piece of code, but I don't understand how it works. And if you set the path to another page without performing authorization - this page opens.

@login_required
def my_view(login_url='/'):
    return HttpResponseRedirect('/config')

I need your help.

(how authorization is performed)

class LoginView(View):

    def get(self, request, *args, **kwargs):
        form = LoginForm(request.POST or None)
        context = {
            'form': form
        }
        return render(request, 'manager/login.html', context)

    def post(self, request, *args, **kwargs):
        form = LoginForm(request.POST or None)
        context = {
            'form': form
        }
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = authenticate(username=username, password=password)
            if user:
                login(request, user)
                return HttpResponseRedirect('/config')
        return render(request, 'manager/login.html', context)
1

There are 1 best solutions below

0
On

You want to redirect all unauthenticated users to your login page until they login ?
I think using MiddleWares is best way to handle this because you want to do it on all of your views.

from django.http import HttpResponseRedirect
from django.urls import reverse


class AuthRequiredMiddleware(object):
    def process_request(self, request):
        if not request.user.is_authenticated():
            return HttpResponseRedirect(reverse('login')) # Your login page url
        return None   

And in your settings.py you need to add your MiddleWare:

MIDDLEWARE_CLASSES = (
    ...
    'path.to.your.AuthRequiredMiddleware',
)