I'm using Cornice and Pyramid with ACL Auth. This is a duplicate of an older question which I'm re-asking as Pyramid has changed.
Current docs say that pyramid.security.has_permission
has ben replaced with request.has_permission
which has an optional context
arg. I'm trying to use has_permission
in a loop through all the services to see which services the current user (request
) has access to.
The end goal is to dynamically scan all Cornice services (ie view files with Cornice's @resource
decorator) to see which ones are authorized for a given permission (ie 'view'
) for the current user. I'm open to using another way of doing this besides has_permission
.
The use case of this knowledge is to provide a Swagger Spec JSON document which only documents API endpoints available to the current user.
I'm expecting code to look something like this:
from cornice import service
# Get our list of services
services = service.get_services()
# Assume we have an authenticated user logged in, thus attaching auth info to request
for svc in services:
context = magic_context_function(svc)
if request.has_permission('view', context) == False:
# Code will go here to hide endpoint documentation for this endpoint
It seems the answer should be to use view_execution_permitted(context, request, name=''), but I can't get it to work with an arbitrary view name, as the
name
arg does not match to acornice.service.name
value.However, here's a semi-solution from a Pyramid issue on Github . You'll need a few imports to make the linked solution work (better). Here's the full code
One can use the above function to determine if the current user (determined from
request
object) is able to access a service (by name) like so:I found that the above solution has two deficiencies:
svc
loop opens a new connection to the API for some reason.Perhaps someone can see a way to improve the answer above. In the meantime, here's a solution using the ACL's attached to each service and then determining if the current
request.effective_principals
match.The weaknesses here are:
@resource
-decorated service classes, and not the@view
-decorated methods which may have permissions or acls of their own.This can be remedied with something like: