Flask 中的登陸校驗

請求的登陸校驗是個常見的需求,如果使用 Flask 框架,一般會使用 flask-login 這個庫,說說使用遇到幾點問題

  • 怎麼全局禁用login檢查呢?

flask-login 提供了一個配置項 LOGIN_DISABLED, 開發和mock的時候有時候有這個需求。

app = Flask(__name__)
app.secret_key = "session secret key. TODO: store it securely"
app.config['LOGIN_DISABLED'] = True
  • how to handle view and blueprint login check ?

flask-login 提供了一個 view 級別的 decorator,login_required, 基本和 django 提供的類似

def login_required(func):
    @wraps(func)
    def decorated_view(*args, **kwargs):
        if request.method in EXEMPT_METHODS:
            return func(*args, **kwargs)
        elif current_app.login_manager._login_disabled:
            return func(*args, **kwargs)
        elif not current_user.is_authenticated:
            return current_app.login_manager.unauthorized()
        return func(*args, **kwargs)
    return decorated_view

那麼要對 blueprint 做 loing check呢? blueprint 中提供了一個 before_request 的 hook,這裏可以利用上

def bp_login_required():
    """
    usage:

    apibp = Blueprint('api', 'api_bp')
    apibp.before_request(bp_login_required)
    """
    if current_app.login_manager._login_disabled:
        pass
    # ajax not 302
    elif not current_user.is_authenticated:
        if request.is_xhr:
            abort(401)
        else:
            return current_app.login_manager.unauthorized()
發佈了489 篇原創文章 · 獲贊 350 · 訪問量 290萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章