【问题标题】:Pyramid security based on attribute of record基于记录属性的金字塔安全性
【发布时间】:2012-10-08 17:39:46
【问题描述】:

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

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

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

report 表的每条记录都有包含user_id 的字段 - 该值与authenticated_userid 函数返回的值相同。我很清楚如何通过添加查看权限来禁用对edit 的访问。但是我如何才能只为相应记录中显示用户 ID 的用户启用对edit 视图的访问权限?

【问题讨论】:

  • 可能需要在问题中添加路由配置,因为这种情况下的行为取决于您使用的是url dispatch还是traversal

标签: python pyramid


【解决方案1】:

您可以通过在Report 模型中定义__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__()将允许所有人调用你的视图view,但只有与Report相关的用户才能调用edit它。


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

使用配置器的 set_authorization_policy() 方法启用授权策略。

您还必须启用身份验证策略才能启用授权策略。这是因为授权通常取决于身份验证。在应用程序设置期间使用 set_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)

上述配置启用了一个策略,该策略将在请求环境中传递的“auth ticket”cookie 的值进行比较,该 cookie 包含对单个主体的引用,与在尝试调用某些资源时在资源树中找到的任何 ACL 中存在的主体查看。

虽然可以混合和匹配不同的身份验证和授权策略,但使用身份验证策略但没有授权策略配置 Pyramid 应用程序是错误的,反之亦然。如果这样做,您将在应用程序启动时收到错误消息。

【讨论】:

猜你喜欢
  • 2011-09-07
  • 1970-01-01
  • 1970-01-01
  • 2013-06-10
  • 2021-03-21
  • 1970-01-01
  • 1970-01-01
  • 2015-02-26
  • 2012-09-16
相关资源
最近更新 更多