Search code examples
pythonauthorizationpyramid

Restrict Pyramid to require login by default


How can I use pyramid so, that it requires a User to be logged in, unless I explicitly say it does not for a certain view?

Currently I need to add some required permission to each and every view_config I'm creating. If I forget one, I'll have a possible security risk. I'd like it the other way around, adding some free access tag on login etc. If I forget one of those, I'll have an inaccessible page, which will be discovered much more likely than the missing protection.

Right now I'll need some permission argument and some check against that in my AuthPolicy

@view_config(route_name='my_route', renderer='my_templ.html', permission='view')
def view_foo(request):
    # ...

I'd want something like having to add permission=None or maybe a second decorator like @public_access or whatever.

I'm currently actually only interested in making all my views accessible for logged in users only (and not to ask for a more specific permission). But using permissions seemed like the right approach. Any suggestions achieving a "logged in only unless explicitly specified" situation would be appreciated.


Solution

  • Use config.set_default_permission to set a permission for views for which none is set explicitly.

    Thus you could do

    config.set_default_permission('private_view')
    

    and restrict the 'private_view' permission to authenticated users; and then explicitly allow the some views, like login, for unauthenticated users.

    Do also note that:

    If a default permission is in effect, view configurations meant to create a truly anonymously accessible view (even exception view views) must use the value of the permission importable as pyramid.security.NO_PERMISSION_REQUIRED. When this string is used as the permission for a view configuration, the default permission is ignored, and the view is registered, making it available to all callers regardless of their credentials.

    Otherwise access to your 404, 403 views will be denied...