'Is it possible to redirect inside a middleware class?

class Middleware:
    def __init__(self, app):
        self.app = app


    def __call__(self, environ, start_response):
        request = Request(environ)
        cookies = request.cookies
        path = request.path
        

        if not isAuthenticated(cookies):
            #Redirect to /login

        return self.app(environ, start_response)

So I have a Middleware class that is supposed to get the cookies from the request and then send it to a function isAuthenticated which returns either True or False now if the function returns False I need to redirect to /login page is that possible to do? even though I don't have the request object I only have the environ?



Solution 1:[1]

Not sure. Because WSGI middleware is at a layer outside the app itself.

You can use other hooks to work inside app / request context. In this case you can use flask.request, flask.redirect() etc. By the way, you don't need to initialize the request (request = Request (Environment)).

Solution 2:[2]

Its possible using HTTP 301 redirection:

class PrefixMiddleware(object):

    def __init__(self, app, prefix=''):
        self.app = app
        self.prefix = prefix

    def __call__(self, environ, start_response):
        if environ['PATH_INFO'].startswith(self.prefix):
            environ['PATH_INFO'] = environ['PATH_INFO'][len(self.prefix):]
            environ['SCRIPT_NAME'] = self.prefix
            return self.app(environ, start_response)
        else:
            start_response('301', [('Location', self.prefix)])
            return ["Redirecting to application...".encode()]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Danila Ganchar
Solution 2 Reishin