金字塔中的身份验证/授权工具

Pau*_*Yin 1 python security pyramid

我按照文档组级安全性
写了这些:

def groupfinder(userid, request):
    print '#'*80
    print userid
    role = DBSession.query(Role)....

    if role.name == "Admin":
        return ['g:admin']


class RootFactory(object):
        __acl__ = [
            (Allow, Everyone, 'view'),
            (Allow, Authenticated, 'edit'),
            (Allow, 'g:admin', 'admin')
        ]

        def __init__(self, request):
            pass


authn_policy = AuthTktAuthenticationPolicy(
    settings['auth.secret'],
    callback=groupfinder,
)
Run Code Online (Sandbox Code Playgroud)

它工作,但每个页面加载它反复查询数据库
只是在用户登录时第一次返回权限?
或者我做错了...

以及我如何知道像mako这样的模板中的权限"g:admin"

Mic*_*kel 6

groupfinder现在有一个微妙的错误.如果用户有效,它应该总是返回一个列表.只有没有用户才能返回None.现在,如果用户是管理员,您只返回一个列表,因此永远不会识别普通用户.

def groupfinder(userid, request):
    print '#'*80
    print userid
    role = DBSession.query(Role)....

    if role is not None:
        principals = []
        if role.name == "Admin":
            principals.append('g:admin')
        return principals
Run Code Online (Sandbox Code Playgroud)

注意我们总是返回一个列表,除非roleNone.

接下来,您询问了性能.金字塔不会尝试缓存任何内容.但是,您可以自己轻松处理此问题.执行此操作的典型方法是在request包含roleor的对象上添加缓存(reified)属性user.这样每次groupfinder调用时,您都将使用缓存role而不是再次查询它.这种模式在这里展示.

我怎么知道像mako这样的模板中的权限"g:admin"

嗯'g:admin'实际上是Pyramid的身份验证术语中的主体.'admin'(访问控制条目的第三个元素)是权限.Principal被视为实现细节,只是帮助我们将事物映射到权限.最后,我们在处理访问/授权时非常关心权限.

要查看用户是否在您的模板中拥有该权限,您可以使用pyramid.security.has_permission('admin', request.context, request).您可以替换request.context任何具有__acl__on的对象,但request.context您将RootFactory在此场景中(这是您想要的).