Dynamic user based authorization in Pyramid

妖精的绣舞 提交于 2019-12-04 05:24:50

You might be making this too complicated. First, only show a link to the edit_post view if the visitor is the post's author. That will handle 99% of the problem by making that view invisible to people who shouldn't see it. For the other 1% - clever users hand-editing the URL to directly access the editing view - add something like this:

def edit_post(request):
    ...
    if authenticated_userid(request) != author:
        raise pyramid.httpexceptions.HTTPForbidden("You are not this post's author.")

You already have a "Resource Tree" by creating the Root resource in your project. You just need to add a node on it for posts that will return a Post object with a particular __acl__ that contains only the authorized user id. You can then have your edit_posts route use traverse='/posts/{post_id}' to traverse your resource tree to the Post object with the __acl__ on it.

This isn't difficult, and is the way to have Pyramid do this stuff for you.

If you don't want to use the permission argument you can do the authorization inside of the view itself, like Kirk suggested.

Also, if you don't like this method of adding __acl__ properties and traversal for authorization, you can implement your own AuthorizationPolicy to do what you'd like it to do with a given list of principals and a permission.

The point of Pyramid's auth system is that it's there, which is great. Pyramid by no means requires you to use it and for views that don't use it, there is no performance impact of dealing with it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!