问题
I am getting my feet wet working with the Pyramid framework (great framework), and I've come to the point of user authorization. I want to take advantage of the ACL to block users who are already logged in from visiting the registration page. Obviously, I could do this other ways, but I was wondering if there was any way to do this using tools in pyramid.
I know that by adding permissions to a view, users who do not meet the criteria are shown a forbidden view. In my case, I simply want to re route users who are already members away from views that don't apply to them (registration, login, etc.).
I've tried __acl__ = [(Deny, Authenticated, 'guest')]
to no avail, as it blocks the login page for all users.
Also, somewhat on another note, is there any way to dynamically change a route. I want the home page to be different for users who are logged in than it is for guests.
回答1:
You'll want to investigate the principals that are being returned by your authentication policy to understand what's going on. It's easy to tell if you turn on pyramid.debug_authorization
in your INI file. The authorization policy will compare the ACL found against the principals returned via pyramid.security.effective_principals(request)
. If these do not match up, it should be clear what is going on.
The way to implement a form-based login would be (assuming Pyramid 1.3a9+):
from pyramid.httpexceptions import HTTPSeeOther
from pyramid.security import authenticated_userid
from pyramid.view import forbidden_view_config
@forbidden_view_config()
def forbidden_view(request):
if authenticated_userid(request):
# user is already logged in, they are really forbidden
return request.context # the forbidden 403 response
url = request.route_url('login', _query={'came_from': request.path})
return HTTPSeeOther(url)
That will add the came_from
parameter to the URL as request.GET['came_from']
in your login view. Of course if that isn't there you can just redirect them to the home screen after logging in.
来源:https://stackoverflow.com/questions/9448228/how-flexible-is-pyramids-auth-system