python – 基于记录属性的金字塔安全性

我在DB中有相同的界面用于查看和使用Pyramid应用程序编辑它们.例如:

报告表查看记录的路径示例:/ birdreport / report / 871;

报告表编辑记录的路径示例:/ birdreport / report / 871 / edit;

报告表的每个记录都包含user_id的字段 – 该值与authenticated_userid函数返回的值相同.我很清楚如何通过添加查看权限来禁用编辑访问权限.但是,我如何只为那些用户ID在相应记录中显示的用户启用访问编辑视图?

最佳答案 您可以通过在报表模型中定义__acl __()来使用
Pyramid authorization policy.例如:

from sqlalchemy.orm import relationship, backref
from pyramid.security import Everyone, Allow

class Report(Base):
    # ...
    user_id = Column(Integer, ForeignKey('user.id'))
    # ...


    @property
    def __acl__(self):
        return [
            (Allow, Everyone, 'view'),
            (Allow, self.user_id, 'edit'),
        ]

    # this also works:
    #__acl__ = [
    #    (Allow, Everyone, 'view'),
    #    (Allow, self.user_id, 'edit'),
    #]

class User(Base):
    # ...
    reports = relationship('Report', backref='user')

上面的__acl __()允许每个人调用您的视图视图,但只允许与Report相关的用户进行编辑.

您可能没有启用身份验证策略或授权策略,引用documentation

Use the set_authorization_policy() method of the Configurator to enable an authorization policy.

You must also enable an authentication policy in order to enable the authorization policy. This is because authorization, in general, depends upon authentication. Use the set_authentication_policy() and method during application setup to specify the authentication policy.

from pyramid.config import Configurator
from pyramid.authentication import AuthTktAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy
authentication_policy = AuthTktAuthenticationPolicy('seekrit')
authorization_policy = ACLAuthorizationPolicy()
config = Configurator()
config.set_authentication_policy(authentication_policy)
config.set_authorization_policy(authorization_policy)

The above configuration enables a policy which compares the value of an “auth ticket” cookie passed in the request’s environment which contains a reference to a single principal against the principals present in any ACL found in the resource tree when attempting to call some view.

While it is possible to mix and match different authentication and authorization policies, it is an error to configure a Pyramid application with an authentication policy but without the authorization policy or vice versa. If you do this, you’ll receive an error at application startup time.

点赞