[英]protect admin area in Flask app fromNormal users accesss
你好,我的 flask 应用程序中的 /admin 路由有问题,当任何人都可以看到 mywesite/admin 页面时,他们无法访问管理方法,但他们可以看到页面,我尝试通过代码 blow 来做到这一点,但我仍然有问题:
from flask_admin import expose, BaseView
from flask_admin.contrib.sqla import ModelView
from flask_login import current_user
from flask import abort
class CustomView(BaseView):
@expose('/')
def index(self):
if current_user.is_authenticated and current_user.is_admin:
return self.render('admin/index.html')
else:
return abort(403)
def is_accessible(self):
return current_user.is_authenticated and current_user.is_admin
def is_visible(self):
return current_user.is_authenticated and current_user.is_admin
class CustomModelView(ModelView):
def is_accessible(self):
return current_user.is_authenticated and current_user.is_admin
class UserView(CustomModelView):
column_list = ('username', 'active', 'email')
def is_accessible(self):
return current_user.is_authenticated and current_user.is_admin
在我的主要应用程序文件中,我有这个:
from flask import Flask
from .extentions import db, ckeditor, mail, migrate, bootstrap, user_login_manager,
basic_auth
from flask_admin import Admin
def create_app():
application = Flask(__name__)
application.config.from_object(Config)
db.init_app(application)
bootstrap.init_app(application)
ckeditor.init_app(application)
mail.init_app(application)
migrate.init_app(application, db)
basic_auth.init_app(application)
return application
app = create_app()
admin = Admin(app)
admin.add_view(CustomView(name='My View', menu_icon_type='glyph',
menu_icon_value='glyphicon-home'))
admin.add_view(UserView(User, db.session))
@app.route('/admin')
@admin_only
@login_required
def admin_index():
return render_template('admin/index.html')
请告诉我我的问题在哪里,我该如何解决这个问题,非常感谢
我找到了我的答案并将其发布在这里也许可以帮助某人
我创建了一个 MyHomeView class 并继承自 AdminIndexView:
from flask_admin import expose, BaseView, AdminIndexView
class MyHomeView(AdminIndexView):
@expose('/')
def index(self):
new_cafe = db.session.query(NewCafe).all()
new_users = db.session.query(NewUser).all()
new_subs = db.session.query(NewSubscriber).all()
count = db.session.query(NewCount).first()
# check current user is admin and authenticated
if current_user.is_authenticated and current_user.is_admin:
return self.render('admin/index.html',
new_cafe=new_cafe,
new_users=new_users,
new_subs=new_subs,
count=count)
else:
return abort(403)
在主文件中,当我从 Admin 创建管理员时,我将 MyhomeView class 作为 index_view 传递,如下所示:
from flask_admin import Admin
from app.admin_views.admin_page import MyHomeView
admin = Admin(app, index_view=MyHomeView(), template_mode='bootstrap4')
当尝试访问我的 /admin 视图时使用此方法不是管理员用户得到 403 错误你可以用你想要的任何错误替换它
问题未解决?试试以下方法:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.