我在DB中有相同的界面用于查看和使用Pyramid应用程序编辑它们.例如:
为视图的记录路由的一个例子report的表:/birdreport/report/871;
report表编辑记录的路由示例:/birdreport/report/871/edit;
report表的每个记录都包含字段user_id- 该值与authenticated_userid函数返回的值相同.我很清楚如何edit通过添加查看权限来禁用访问权限.但是我如何才能启用访问权限edit只查看用户ID在相应记录中显示的用户?
您可以通过在模型内部定义来使用金字塔授权策略.例如:__acl__()Report
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')
Run Code Online (Sandbox Code Playgroud)
在__acl__()上面可以让大家打电话给你的观点view,但只有用户相关Report,以edit它.
您可能没有启用身份验证策略或授权策略,引用文档:
使用Configurator的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)
Run Code Online (Sandbox Code Playgroud)
上述配置启用了一个策略,该策略将在请求环境中传递的"auth ticket"cookie的值与尝试调用某个视图时在资源树中找到的任何ACL中存在的主体进行比较.
虽然可以混合和匹配不同的身份验证和授权策略,但使用身份验证策略配置Pyramid应用程序但没有授权策略是错误的,反之亦然.如果这样做,您将在应用程序启动时收到错误.