CPI Ordering System (the old version)
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.
 
 
 
 
 

70 lines
2.2 KiB

''' User Authentication and Authorization '''
from pyramid.authentication import AuthTktAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy
from pyramid.security import Authenticated, Everyone
from ordr2.models.account import User, passlib_context
class AuthenticationPolicy(AuthTktAuthenticationPolicy):
''' How to authenticate users '''
def authenticated_userid(self, request):
''' returns the id of an authenticated user
heavy lifting done in get_user() attached to request
'''
user = request.user
if user is not None:
return user.id
def effective_principals(self, request):
''' returns a list of principals for the user '''
principals = [Everyone]
user = request.user
if user is not None:
principals.append(Authenticated)
principals.append(user.principal)
principals.extend(user.role_principals)
return principals
def get_user(request):
''' retrieves the user object by the unauthenticated user id
:param request:
the current request object
:type request:
pyramid.request.Request
:rtype:
:class:`ordr2.models.account.User` or None
'''
user_id = request.unauthenticated_userid
if user_id is not None:
user = request.dbsession.query(User).filter_by(id=user_id).first()
if user and user.is_active:
return user
return None
def includeme(config):
''' initializing authentication, authorization and password hash settings
Activate this setup using ``config.include('ordr2.security')``.
'''
settings = config.get_settings()
# configure the passlib context manager for hashing user passwords
passlib_context.load_path(settings['passlib.config'])
# config for authentication and authorization
authn_policy = AuthenticationPolicy(
settings['auth.secret'],
hashalg='sha512',
)
config.set_authentication_policy(authn_policy)
config.set_authorization_policy(ACLAuthorizationPolicy())
# attach the get_user function returned by get_user_closure()
config.add_request_method(get_user, 'user', reify=True)