gpt4 book ai didi

python - Flask-Admin & Authentication : "/admin" is protected but "/admin/anything-else" is not

转载 作者:太空狗 更新时间:2023-10-29 20:31:33 29 4
gpt4 key购买 nike

我正在尝试使用 Flask 和 Flask-SuperAdmin 自定义我的 Admin View ,但是,索引 View 和 subview 显然没有使用相同的 is_accessible 方法:

编辑:我设法找出我做错了什么。我需要在每个 View 类中定义 is_accessible。这是通过混合类很好地完成的,如固定代码所示:

app/frontend/admin.py(固定和工作代码)

from flask.ext.security import current_user, login_required
from flask.ext.superadmin import expose, AdminIndexView
from flask.ext.superadmin.model.base import ModelAdmin
from ..core import db

# all admin views should subclass AuthMixin
class AuthMixin(object):
def is_accessible(self):
if current_user.is_authenticated() and current_user.has_role('Admin'):
return True
return False

# the view that gets used for the admin home page
class AdminIndex(AuthMixin, AdminIndexView):
# use a custom template for the admin home page
@expose('/')
def index(self):
return self.render('admin/index.jade')

# base view for all other admin pages
class AdminBase(AuthMixin, ModelAdmin): # AuthMixin must come before ModelAdmin!
"""A base class for customizing admin views using our DB connection."""
session = db.session

# customize the form displays for User and Role models

class UserAdmin(AdminBase):
list_display = ('email',)
search_fields = ('email',)
exclude = ['password',]
#fields_order = ['email', 'active', 'last_login_at',]

class RoleAdmin(AdminBase):
field_args = {'name': {'label': 'Role Name'},
'description': {'description': "Duties & Responsibilities"}}
list_display = ('name', 'description')

然后使用我们的管理 View 设置 Flask 应用程序:
应用程序/工厂.py

app = Flask(package_name, instance_relative_config=True)
# other app setup stuff like db, mail, ...

from .frontend.admin import AdminIndex, UserAdmin, RoleAdmin
admin = Admin(app, name='PyCBM Admin',
index_view=AdminIndex(url='/admin', name='Admin Home'))
admin.register(User, UserAdmin)
admin.register(Role, RoleAdmin)

所以,正如标题所说,这就是问题所在:

/admin throws a 403 when an 'Admin' user isn't logged in, like it should, but
/admin/user lets anybody right on in.

我翻遍了源代码,试图找到另一个“全局所有管理员蓝图”安全功能——也许我是瞎子——但我找不到。

最佳答案

如果您转到 flask_superadmin/base.py,在第 193 行有以下代码片段:

def _handle_view(self, name, *args, **kwargs):
if not self.is_accessible():
return abort(403)

所以也许这个方法必须被 AdminIndex 覆盖以避免返回 abort(403) 而是重定向到 /login

关于python - Flask-Admin & Authentication : "/admin" is protected but "/admin/anything-else" is not,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17583247/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com