Created
November 18, 2013 23:54
-
-
Save scott2b/7537563 to your computer and use it in GitHub Desktop.
public and private User views in Pyramid
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pyramid.security import ALL_PERMISSIONS | |
from pyramid.security import Allow | |
from pyramid.security import Everyone | |
ADMINS = [ __some__list__of__admins__ ] | |
def groupfinder(userid, request): | |
"""groupfinder should be the callback to your authentication policy. | |
""" | |
if userid in ADMINS: | |
return ['g:admins'] | |
else: | |
return [] | |
class UserFactory(object): | |
"""Specify this factory for the user route. e.g.: | |
config.add_route('user', '/users/{username}', factory=UserFactory, | |
traverse='/{username}') | |
""" | |
def __init__(self, request): | |
self.request = request | |
def __getitem__(self, key): | |
user = User.get_by_username(key) | |
user.__parent__ = self | |
user.__name__ = key | |
return user | |
class User(object): | |
@property | |
def __acl__(self): | |
return [ | |
(Allow, self.email, 'edit'), | |
(Allow, 'g:admins', ALL_PERMISSIONS), | |
(Allow, Everyone, 'view'), | |
] | |
@classmethod | |
def get_by_username(cls, username): | |
### return a user object | |
pass |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<body> | |
{% if can_edit %} | |
Editable content goes here | |
{% endif %} | |
<h1>{{ user.username }}</h1> | |
<h3>{{ user.email }}</h3> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pyramid.security import has_permission | |
from pyramid.view import view_config | |
from .models import User | |
@view_config(route_name='user', renderer='templates/user.jinja2', | |
request_method='GET', permission='view') | |
def user_view_GET(request): | |
username = request.matchdict['username'] | |
user = User.get_by_username(username) | |
return { | |
'user': user, | |
'can_edit': has_permission('edit', user, request) # users both with and without edit perms will get this view | |
} | |
@view_config(route_name='user', renderer='templates/user.jinja2', | |
request_method='POST', permission='edit') | |
def user_view_POST(request): | |
username = request.matchdict['username'] | |
user = User.get_by_username(username) | |
return { | |
'user': user, | |
'can_edit': True | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment