喜欢这个问题:最好的方法是让Django的login_required成为默认值
我现在正在使用Flask-Login的是login_required装饰器.反正有没有把它作为默认行为Flask?
Mal*_*ats 37
我在我的乐器项目中这样做了.我用before_request装饰器:
@app.before_request
def check_valid_login():
login_valid = 'user' in session # or whatever you use to check valid login
if (request.endpoint and
'static' not in request.endpoint and
not login_valid and
not getattr(app.view_functions[request.endpoint], 'is_public', False) ) :
return render_template('login.html', next=request.endpoint)
Run Code Online (Sandbox Code Playgroud)
然后我is_public()为少数几个无需登录就可以访问的地方创建了一个装饰器:
def public_endpoint(function):
function.is_public = True
return function
Run Code Online (Sandbox Code Playgroud)
如果您正在使用蓝图并且需要使用登录来保护整个蓝图,则可以使整个before_request需要登录.
这就是我用于CMS蓝图的内容:
@cms.before_request
@login_required
def before_request():
if g.user.role != ROLE_ADMIN:
abort(401)
Run Code Online (Sandbox Code Playgroud)
如果您只需要检查用户是否已登录(而不是用户是否具有权限),您可以只使用pass该功能
小智 5
这是对@MalphasWats已经很好的答案的跟进(更多的 pythonic,但值得商de)。
还包括@nonagon建议的重要安全修复程序。
使用以下命令解释漏洞'static' in request.endpoint:
想象一下,存在可以由用户以某种方式定义的路线,例如,配置文件链接。
如果用户设置了他的名字,请说“静态乔”,然后:
"Static Joe" --slugifys--> /usr/profiles/static_joe。
这样可以公开此路线。这只是自找麻烦。
这是在每次请求处理之前都会应用的路由保护功能:
@app.before_request
def check_route_access():
if any([request.endpoint.startswith('static/'),
current_user.is_authenticated(), # From Flask-Login
getattr(app.view_functions[request.endpoint],'is_public',False)]):
return # Access granted
else:
return redirect(url_for('users.login_page'))
Run Code Online (Sandbox Code Playgroud)
(Flask-Login是一个很好的模块,使会话处理变得轻而易举)
这是装饰器(@public_route),您可以使用它来允许访问默认情况下需要公共访问的特殊页面。(注册页面,登录页面):
def public_route(decorated_function):
decorated_function.is_public = True
return decorated_function
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9458 次 |
| 最近记录: |