Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mark all endpoints as @login_required

I am using flask-login plugin for my application, which is already developed to a good extent.

I want to mark all the url endpoints as "@login_required".

Is there any way I can do this in one place with a single line of code rather than marking every view function with @login_required.

like image 724
Vivek Jha Avatar asked Oct 30 '25 10:10

Vivek Jha


1 Answers

You can define your own decorator. Matt Wright's overholt template provides an example that does exactly what you want.

from functools import wraps

from flask_security import login_required

def route(bp, *args, **kwargs):
    def decorator(f):
        @bp.route(*args, **kwargs)
        @login_required
        @wraps(f)
        def wrapper(*args, **kwargs):
            return f(*args, **kwargs)
        return f

    return decorator

You can use this decorator to add routes to any endpoints used by the blueprint instead of using the blueprint's route decorator directly.

bp = Blueprint('name', __name__)

@route(bp, '/')
def route1():
    return 'Hello, world!'
like image 144
dirn Avatar answered Nov 03 '25 21:11

dirn