[英]Pyramid authorization for stored items
我正在嘗試創建一個將“項目”所有權考慮在內的授權策略。 例如,一些用戶X“擁有”項目A,B,C。這些是通過/item/{item}/some_options
等URL訪問的。
如何獲取有關{item}
的信息到授權策略對象(permit()調用)? 將附加信息放入上下文中是一個好主意(我只做基於路由的路由)。 我該怎么辦?
您可以使用ACLAuthorizationPolicy
與URL Dispatch結合使用為此目的設計的自定義資源樹來執行此操作。
例如,您擁有Foo
對象的權限和Bar
對象的權限。 可以使用url遍歷資源樹來找到這些ACL:
/foos/{obj}
/bars/{obj}
然后,您的資源樹將成為權限層次結構,您可以在樹中的任何位置在資源對象上放置__acl__
:
root (Root)
|- foos (FooContainer)
| `- {obj} (Foo)
`- bars (BarContainer)
`- {obj} (Bar)
您可以在資源樹中表示此層次結構:
class Root(dict):
# this is the root factory, you can set an __acl__ here for all resources
__acl__ = [
(Allow, 'admin', ALL_PERMISSIONS),
]
def __init__(self, request):
self.request = request
self['foos'] = FooContainer(self, 'foos')
self['bars'] = BarContainer(self, 'bars')
class FooContainer(object):
# set ACL here for *all* objects of type Foo
__acl__ = [
]
def __init__(self, parent, name):
self.__parent__ = parent
self.__name__ = name
def __getitem__(self, key):
# get a database connection
s = DBSession()
obj = s.query(Foo).filter_by(id=key).scalar()
if obj is None:
raise KeyError
obj.__parent__ = self
obj.__name__ = key
return obj
class Foo(object):
# this __acl__ is computed dynamically based on the specific object
@property
def __acl__(self):
acls = [(Allow, 'u:%d' % o.id, 'view') for o in self.owners]
return acls
owners = relation('FooOwner')
class Bar(object):
# allow any authenticated user to view Bar objects
__acl__ = [
(Allow, Authenticated, 'view')
]
使用這樣的設置,您可以將路由模式映射到資源樹:
config = Configurator()
config.add_route('item_options', '/item/{item}/some_options',
# tell pyramid where in the resource tree to go for this url
traverse='/foos/{item}')
您還需要將路線映射到特定視圖:
config.add_view(route_name='item_options', view='.views.options_view',
permission='view', renderer='item_options.mako')
太好了,現在我們可以定義我們的視圖並使用加載的上下文對象,知道如果執行了視圖,則用戶具有相應的權限!
def options_view(request):
foo = request.context
return {
'foo': foo,
}
使用此設置,您使用的是默認的ACLAuthorizationPolicy
,並且您使用URL Dispatch為對象提供行級權限。 另請注意,由於對象在子項上設置了__parent__
屬性,因此該策略將使__parent__
冒泡,繼承父項的權限。 只需在ACL中放置DENY_ALL
ACE,或者編寫不使用上下文沿襲的自定義策略,就可以避免這種情況。
*更新*我已將此帖子轉換為Github上的實際演示。 希望它可以幫助某人。 https://github.com/mmerickel/pyramid_auth_demo
*更新*我在這里寫了一個關於金字塔認證和授權系統的完整教程: http : //michael.merickel.org/projects/pyramid_auth_demo/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.