0
我看到过很多这样的解决方案的网络,但是所有的人都解决更复杂的应用程序,允许外部用户创建账户。在我的情况下,唯一的用户将是管理员。如何以有效的方式保护由Flask-Admin创建的管理路线?如果我的唯一用户将成为管理员,如何保护Flask-Admin?
我看到过很多这样的解决方案的网络,但是所有的人都解决更复杂的应用程序,允许外部用户创建账户。在我的情况下,唯一的用户将是管理员。如何以有效的方式保护由Flask-Admin创建的管理路线?如果我的唯一用户将成为管理员,如何保护Flask-Admin?
您可以使用Flask-Login了点。如果用户尚未登录,我通常会向AdminIndexView类添加路由,以处理登录。否则,将显示默认管理页面。
from flask import Flask
from flask_login import LoginManager
from flask_admin import Admin
app = Flask(__name__)
login_manager = LoginManager(app)
login_manager.session_protection = 'strong'
login_manager.login_view = 'admin.login'
admin = Admin(app, index_view=MyIndexView())
MyAdminView的定义可以是这样的:
from flask_admin import AdminIndexView, expose, helpers
class FlaskyAdminIndexView(AdminIndexView):
@expose('/')
def index(self):
if not login.current_user.is_authenticated:
return redirect(url_for('.login'))
return super(MyAdminIndexView, self).index()
@expose('/login', methods=['GET', 'POST'])
def login(self):
form = LoginForm(request.form)
if helpers.validate_form_on_submit(form):
user = form.get_user()
if user is not None and user.verify_password(form.password.data):
login.login_user(user)
else:
flash('Invalid username or password.')
if login.current_user.is_authenticated:
return redirect(url_for('.index'))
self._template_args['form'] = form
return super(MyAdminIndexView, self).index()
@expose('/logout')
@login_required
def logout(self):
login.logout_user()
return redirect(url_for('.login'))
这在瓶 - 管理界面集成悄悄烧瓶登录。您仍然需要执行用户和密码验证,如Flask-Login documentation中所述。
编辑
为了防止您的管理途径未经授权的访问创造ModelView类为每个视图并添加功能is_accessible()
用下面的代码:
def is_accessible(self):
if (not login.current_user.is_active or not
login.current_user.is_authenticated):
return False
return True