How to check if the cookie exist or not and allow the authority to the particular page on the basis of it?

I am creating an authorisation with custom middleware in Django where I save the token in cookie, now I want to check if the cookie is valid or not if it’s valid then allow the user to access the page or else should redirect to login page.

this is my login method in views.py where I get the token and set it to cookie

def loginPage(request):

    form = AuthenticationForm()

    if request.method == 'POST':

        print("login........")
        username = request.POST.get('username')
        password = request.POST.get('password')

        bearerTokenResponse = requests.post(
            'http://localhost:8000/auth/login', json={"email": username, "password": password})
        print(bearerTokenResponse)
        code = bearerTokenResponse.json()['code']

        # Check if the code is 200 it's successfully get the token
        if code == 200:
            token = bearerTokenResponse.json()['token']
            print(token)

            response = HttpResponse("Cookie Set")  

            # Render the home page(patients)
            response = render(request, 'dashboard.html')

            # Set the cookie with key name 'core-api'
            response.set_cookie('core-api', token, max_age=3600) # expire in 1 hour
            return response

    return render(request, 'login.html', {'form': form})

# Get the cookie with the key name 'core-api'
def getcookie(request):  
    s  = request.COOKIES['core-api']  
    return HttpResponse(s)

and the middleware

from django.conf import settings


class LoginMiddleware:
    def __init__(self, get_response):
        #print(get_response)
        pass

    def __call__(self, request):
        
        #response = self.get_response(request)
        pass
        #return response

    def process_view(self, request, view_func, *view_args, **view_kargs):
        email = request.COOKIES['core-api']
        print('this is the cookie from views.py:')
        print(email)

    def process_exception(self, request, exception):
        pass

    def process_template_response(self, request, response):
        pass

I think I don’t need to use the middleware in the login view, so I can use login without have a token yet. Any recommendations how to achieve this?

This is almost exactly what django-login-required-middleware · PyPI does. If this package doesn’t do what you want it to do, you can at least look at the source to see how it handles your situation.