Django tool with login and password that hides all pages of a website

I wrote the following middleware that displays the form and asks the user for a username and password. Middleware should apply to the entire website:

class InviteLoginForWebsiteMiddleware(object):

    def process_request(self, request):
        if request.session.get('has_invite') == True:
            return None

        form = WebsiteLoginForm()
        extra_context = dict()
        extra_context['form'] = form
        template_name = 'websiteLogin.html'

        if request.method == "POST":
            form = WebsiteLoginForm(request.POST)
            if form.is_valid():
                login = form.cleaned_data['login']
                password = form.cleaned_data['password']

                if login == "mylogin" and password == "mypassword":
                    request.session['has_inv'] = True
                    return None

        return ExtraContextTemplateView.as_view(template_name=template_name, extra_context=extra_context)(request)

The problem with this solution is that when creating the form inside process_request, the csrf token is not on the displayed page. I searched the answer and found that the developers recommend creating the form and processing it inside process_view

After moving all the code to process_view, for example:

def process_view(self, request, view_func, view_args, view_kwargs):
    if request.session.get('has_inv') == True:
        return None

    form = WebsiteLoginForm()
    extra_context = dict()
    extra_context['form'] = form
    template_name = 'websiteLogin.html'

    if request.method == "POST":
        form = WebsiteLoginForm(request.POST)
        if form.is_valid():
            login = form.cleaned_data['login']
            password = form.cleaned_data['password']

            if login == "mylogin" and password == "mypassword":
                request.session['has_inv'] = True
                return None

    return ExtraContextTemplateView.as_view(template_name=template_name, extra_context=extra_context)(request)

the code started working, the csrf token was opened, and I was able to submit the form with login and password.

, , , www.mysite.com/notworkingurl/. process_view , 404 , , -. , , , .

:

  • process_request, -, csrf . csrf .
  •    process_view    . ,   404 URL- . , .

- ?

:

@knbk csrf_protect. , :

class ExtraContextTemplateViewCsrfProtect(TemplateView):
  extra_context = None

  @method_decorator(csrf_protect)
  def dispatch(self, request, *args, **kwargs):
    return super(ExtraContextTemplateViewCsrfProtect, self).dispatch(request, *args, **kwargs)

  def get_context_data(self, *args, **kwargs):
    context = super(ExtraContextTemplateViewCsrfProtect, self).get_context_data(*args, **kwargs)
    if self.extra_context:
      context.update(self.extra_context)
    return context

  post = TemplateView.get
+4
2

csrf, CSRF.

, , . csrf_protect CSRF, :

class InviteLoginForWebsiteMiddleware(object):

    def process_request(self, request):
        if request.session.get('has_invite') == True:
            return None

        return csrf_protect(CustomLoginView.as_view())(request)

, matox.

0

, , :

Django Login Required Middleware

settings.py:

LOGIN_URL = '/login/'

LOGIN_EXEMPT_URLS = (
 r'^about\.html$',
 r'^legal/', # allow any URL under /legal/*
) 

MIDDLEWARE_CLASSES = (
    # ...
    'python.path.to.LoginRequiredMiddleware',
)                    

LoginRequiredMiddleware:

from django.http import HttpResponseRedirect
from django.conf import settings
from re import compile

EXEMPT_URLS = [compile(settings.LOGIN_URL.lstrip('/'))]
if hasattr(settings, 'LOGIN_EXEMPT_URLS'):
    EXEMPT_URLS += [compile(expr) for expr in settings.LOGIN_EXEMPT_URLS]

class LoginRequiredMiddleware:
    """
    Middleware that requires a user to be authenticated to view any page other
    than LOGIN_URL. Exemptions to this requirement can optionally be specified
    in settings via a list of regular expressions in LOGIN_EXEMPT_URLS (which
    you can copy from your urls.py).

    Requires authentication middleware and template context processors to be
    loaded. You'll get an error if they aren't.
    """
    def process_request(self, request):
        assert hasattr(request, 'user'), "The Login Required middleware\
 requires authentication middleware to be installed. Edit your\
 MIDDLEWARE_CLASSES setting to insert\
 'django.contrib.auth.middlware.AuthenticationMiddleware'. If that doesn't\
 work, ensure your TEMPLATE_CONTEXT_PROCESSORS setting includes\
 'django.core.context_processors.auth'."
        if not request.user.is_authenticated():
            path = request.path_info.lstrip('/')
            if not any(m.match(path) for m in EXEMPT_URLS):
                return HttpResponseRedirect(settings.LOGIN_URL)
0

Source: https://habr.com/ru/post/1661710/


All Articles