tsunami

log in
history

Understanding Pyramid's authentication and authorization scheme

Luke Breuer
2013-12-18 18:51 UTC

links
authentication
Pyramid offers no intrinsic user management; once you verify that a given login has been verified (using password or OpenID or something else), you'll have code (adapted from Michael's code) like:
def login_view(request):
    next = request.params.get('next') or request.route_url('home')
    # ...
    headers = remember(request, login)
    return HTTPFound(location=next, headers=headers)

For logging out:
def logout_view(request):
    headers = forget(request)
    loc = request.route_url('home')
    return HTTPFound(location=loc, headers=headers)

Here's how you get the login:
def page_with_permissions(request):
    login = authenticated_userid(request)
    if owner is None:
        raise HTTPForbidden()

For sample code which would implement remember, forget, and authenticated_userid, see the cookbook. If you'd like to be able to get a full user as part of the request object, see Making A “User Object” Available as a Request Attribute.
authorization
Authorization is generally done based on group, not individual user. For example (from Michael's code):
@view_config(
    route_name='edit_page',
    permission='edit',
    renderer='edit_page.mako',
)
def edit_page_view(request):

Groups are defined by a root_factory object:
class Root(object):
    __acl__ = [
        (Allow, Authenticated, 'create'),
        (Allow, 'g:editor', 'edit'),
        (Allow, 'g:admin', ALL_PERMISSIONS),
    ]

    def __init__(self, request):
        self.request = request

Users are mapped to groups via the groupfinder:
def groupfinder(userid, request):
    user = USERS.get(userid) # obviously this will be custom
    if user:
        return ['g:%s' % g for g in user.groups]