From 3e51a8cda802e9cbd0054d09337d0d09170ad1a5 Mon Sep 17 00:00:00 2001 From: Holger Frey Date: Wed, 27 Sep 2017 10:12:36 +0200 Subject: [PATCH] configured app security --- development.ini | 2 +- ordr2/security.py | 50 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 ordr2/security.py diff --git a/development.ini b/development.ini index d00cbbd..406c35e 100644 --- a/development.ini +++ b/development.ini @@ -22,7 +22,7 @@ sqlalchemy.url = sqlite:///%(here)s/ordr2.sqlite # custom settings - +auth.secret = 'Change Me 1' session.secret = 'Change Me 2' session.auto_csrf = true diff --git a/ordr2/security.py b/ordr2/security.py new file mode 100644 index 0000000..88d0e97 --- /dev/null +++ b/ordr2/security.py @@ -0,0 +1,50 @@ +from pyramid.authentication import AuthTktAuthenticationPolicy +from pyramid.authorization import ACLAuthorizationPolicy +from pyramid.security import Authenticated, Everyone + +from .models import User + + +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 ''' + 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 and authorization for the Pyramid app ''' + settings = config.get_settings() + authn_policy = AuthenticationPolicy( + settings['auth.secret'], + hashalg='sha512', + ) + config.set_authentication_policy(authn_policy) + config.set_authorization_policy(ACLAuthorizationPolicy()) + config.add_request_method(get_user, 'user', reify=True)