def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ engine = engine_from_config(settings, 'sqlalchemy.') initialize_sql(engine) # configure the security stuff config = Configurator( settings=settings, authentication_policy=RemoteUserAuthenticationPolicy(), authorization_policy=ACLAuthorizationPolicy()) config.add_static_view('static', 'pyramidapp:static') config.add_route('home', '/') config.add_view('pyramidapp.views.my_view', route_name='home', renderer='templates/mytemplate.pt') # pyramid_formalchemy's configuration config.include('pyramid_formalchemy') config.formalchemy_admin('admin', package='pyramidapp', factory=ModelsWithACL) # use the secure factory return config.make_wsgi_app()
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ engine = engine_from_config(settings, 'sqlalchemy.') DBSession.configure(bind=engine) Base.metadata.bind = engine config = Configurator(settings=settings, root_factory='.models.RootFactory') config.include('pyramid_chameleon') # This mess is used to bypass authentication during testing. # Some day this will be cleaned up. if 'RemoteUserAuthenticationPolicy' in settings: authn_policy = RemoteUserAuthenticationPolicy(callback=groupfinder) authz_policy = ACLAuthorizationPolicy() config.set_authorization_policy(authz_policy) else: config.include("pyramid_persona") authn_policy = AuthTktAuthenticationPolicy( settings['persona.secret'], callback=groupfinder, hashalg='sha512') config.set_authentication_policy(authn_policy) if 'disable_caching' in settings and settings['disable_caching'] == 'true': config.add_static_view('static', 'static', cache_max_age=0) else: config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('add_article', '/add') config.add_route('edit_article', '/edit/{id}') config.add_route('atom_feed', '/feed.atom') config.add_route('view_article', '/{year}/{month}/{day}/{slug}') config.add_route('view_page', '/{slug}') config.add_route('view_all', '/') config.scan() return config.make_wsgi_app()
def remoteuserauthenticationpolicy(_context, environ_key='REMOTE_USER', callback=None): policy = RemoteUserAuthenticationPolicy(environ_key=environ_key, callback=callback) # authentication policies must be registered eagerly so they can # be found by the view registration machinery config = with_context(_context) set_authentication_policy(config, policy)
def includeme(config): config.set_authentication_policy(RemoteUserAuthenticationPolicy()) config.set_authorization_policy(AuthorizationPolicy()) config.add_route('public', '/public') config.add_view(public, route_name='public') config.add_route('private', '/private') config.add_view(private, route_name='private', permission='foo') config.add_route('inaccessible', '/inaccessible') config.add_view(inaccessible, route_name='inaccessible', permission='bar')
def includeme(config): from pyramid.authentication import RemoteUserAuthenticationPolicy from pyramid.authorization import ACLAuthorizationPolicy authn_policy = RemoteUserAuthenticationPolicy() authz_policy = ACLAuthorizationPolicy() config._set_authentication_policy(authn_policy) config._set_authorization_policy(authz_policy) config.add_static_view('allowed', 'pyramid.tests:fixtures/static/') config.add_static_view('protected', 'pyramid.tests:fixtures/static/', permission='view') config.add_static_view('factory_protected', 'pyramid.tests:fixtures/static/', permission='view', factory=LocalRootFactory)
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ config = Configurator(settings=settings) config.add_request_method(get_user, 'user', reify=True) authen = RemoteUserAuthenticationPolicy('HTTP_X_PROXY_REMOTE_USER') config.set_authentication_policy(authen) config.set_default_permission('view') config.set_authorization_policy(ACLAuthorizationPolicy()) config.set_root_factory(RootFactory) # The default json renderer is pure python try other implementations # Benchmarks with 760/2013-05-31T00:00:00Z/2013-08-09T00:00:00Z # json = 41s # simplejson = 26s # omnijson = ~ incorrect response no adaptor support # ujson = ~ incorrect response no adaptor support # yajl = ~ incorrect response no adaptor support # jsonlib2 = 58s # jsonlib = 61s # anyjson = ~ incorrect response no adaptor support # Conclusion use simplejson json_renderer = JSON(serializer=simplejson.dumps) json_renderer.add_adapter(datetime.datetime, datetime_adaptor) json_renderer.add_adapter(datetime.timedelta, timedelta_adaptor) json_renderer.add_adapter(decimal.Decimal, decimal_adaptor) json_renderer.add_adapter(RealDictCursor, cursor_adaptor) config.add_renderer('json', json_renderer) config.add_static_view('/static', 'annotation:static') config.add_route('home', '/') config.add_route('trackers', '/trackers') config.add_route('tracker', '/tracker/{id}/{start}/{end}') config.add_route('uploads.html', '/uploads.html') config.add_route('annotations.html', '/uploads/{table}/annotations.html') config.add_route('annotations.csv', '/uploads/{table}/annotations.csv') config.scan() return config.make_wsgi_app()
from h.auth.policy import AuthenticationPolicy from h.auth.policy import APIAuthenticationPolicy from h.auth.policy import AuthClientPolicy from h.auth.policy import TokenAuthenticationPolicy from h.auth.util import default_authority, groupfinder from h.security import derive_key __all__ = ( 'DEFAULT_POLICY', 'WEBSOCKET_POLICY', ) log = logging.getLogger(__name__) PROXY_POLICY = RemoteUserAuthenticationPolicy( environ_key='HTTP_X_FORWARDED_USER', callback=groupfinder) TICKET_POLICY = pyramid_authsanity.AuthServicePolicy() TOKEN_POLICY = TokenAuthenticationPolicy(callback=groupfinder) AUTH_CLIENT_POLICY = AuthClientPolicy() API_POLICY = APIAuthenticationPolicy(user_policy=TOKEN_POLICY, client_policy=AUTH_CLIENT_POLICY) DEFAULT_POLICY = AuthenticationPolicy(api_policy=API_POLICY, fallback_policy=TICKET_POLICY) WEBSOCKET_POLICY = TOKEN_POLICY def includeme(config): global DEFAULT_POLICY
def getRemoteUserAuthenticationPolicy(): """Define the authentication policy for remote user server""" return RemoteUserAuthenticationPolicy( environ_key=Configuration.get('pyramid_remoteuser_environ_key'), callback=Configuration.get('pyramid_authentication_callback'), debug=Configuration.get('pyramid_authentication_debug'))
# http://127.0.0.1:8080/entries/1 # # DELETE: # # curl -i -X DELETE http://127.0.0.1:8080/entries/1 import json from webob.exc import HTTPNoContent from groundhog import Groundhog from groundhog import request from pyramid.authentication import RemoteUserAuthenticationPolicy authn_policy = RemoteUserAuthenticationPolicy() class DummyRiakAuthorizationPolicy(object): def permits(self, context, principals, permission): print('checked security policy with principals %r and permission %s' % (principals, permission)) return True authz_policy = DummyRiakAuthorizationPolicy() class DummyRiakObject(object): def delete(self): pass
"""Override the :term:`client factory` in the current configuration. The ``factory`` argument must support the :class:`h.oauth.IClientFactory` interface or be a dotted Python name that points to a client factory. """ def register(): impl = config.maybe_dotted(factory) config.registry.registerUtility(impl, IClientFactory) intr = config.introspectable('client factory', None, config.object_description(factory), 'client factory') intr['factory'] = factory config.action(IClientFactory, register, introspectables=(intr,)) remote_authn = RemoteUserAuthenticationPolicy(callback=effective_principals) session_authn = SessionAuthenticationPolicy('', callback=effective_principals) acl_authz = ACLAuthorizationPolicy() validator = RequestValidator() def includeme(config): registry = config.registry settings = registry.settings config.include('pyramid_oauthlib') config.add_oauth_param('assertion') # Use session credentials as a client credentials authorization grant config.add_grant_type('oauthlib.oauth2.ClientCredentialsGrant', request_validator=validator)
def factory(global_config, **settings): """Call to return a WSGI application.""" # Bind the SQLAlchemy model classes to the database specified in the # ``settings`` provided. engine = engine_from_config(settings, 'sqlalchemy.') Session.configure(bind=engine) # Initialise the ``Configurator`` with authentication policy. auth_policy = RemoteUserAuthenticationPolicy() config = Configurator(settings=settings, authentication_policy=auth_policy) # Include external libraries. config.include('pyramid_assetgen') config.include('pyramid_weblayer') # Setup request and session factories. class CustomRequest(AssetGenRequestMixin, Request): pass config.set_request_factory(CustomRequest) config.set_session_factory(session_factory_from_settings(settings)) # Add ``is_authenticated`` and ``user`` properties to the request. config.set_request_property(get_is_authenticated, 'is_authenticated', reify=True) config.set_request_property(get_user, 'user', reify=True) # Tell the translation machinery where the message strings are. config.add_translation_dirs(settings['locale_dir']) # Expose `/static` and `/thumbs` directories, cached for two weeks, # specifying that ``settings['static_dir'] has an assetgen manifest # in it, and expose the panorama `/tour` files without caching. static_dir = settings['static_dir'] thumbs_dir = settings['thumbnails_dir'] tour_dir = settings['tour_dir'] config.add_assetgen_manifest(static_dir) config.add_static_view('static', static_dir, cache_max_age=1209600) config.add_static_view('thumbs', thumbs_dir, cache_max_age=1209600) config.add_static_view('tour', tour_dir) # Configure a custom 404 that first tries to append a slash to the URL. not_found = AppendSlashNotFoundViewFactory(not_found_view) config.add_view(not_found, context='pyramid.httpexceptions.HTTPNotFound') # Expose dynamic views. for name, pattern in route_mapping: config.add_route(name, pattern) # Run a venusian scan to pick up the declerative configuration from this # and any included packages. config.scan() # Fake authentication for now. class AuthenticationMiddleware: def __init__(self, app): self.app = app def __call__(self, environ, start_response): environ['REMOTE_USER'] = '******' return self.app(environ, start_response) # Return a configured WSGI application. return AuthenticationMiddleware(config.make_wsgi_app())
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ #Session factory (CSRF) my_session_factory = SignedCookieSessionFactory(settings['session.secret']) #SqlAlchemy: engine = engine_from_config(settings, 'sqlalchemy.default.') DBSession.configure(bind=engine) Base.metadata.bind = engine try: engine2 = engine_from_config(settings, 'sqlalchemy.ea.', pool_size=settings.get('sqla_ea_pool_size', 5), max_overflow=settings.get('sqla_ea_max_overflow', 20), pool_recycle=settings.get('sqla_ea_pool_recycle', 3600)) #For testing with SqlLite we need to have different engine setup except TypeError: engine2 = engine_from_config(settings, 'sqlalchemy.ea.') DBSession_EA.configure(bind=engine2) Base_EA.metadata.bind = engine2 #Security #authn_policy = RemoteUserAuthenticationPolicy(environ_key='REMOTE_USER', callback=groupfinder) #authn_policy = AuthTktAuthenticationPolicy('sosecret', callback=groupfinder, hashalg='sha512') authz_policy = ACLAuthorizationPolicy() #Pyramid_multiauth seperate module for REMOTE_USER fallback policies = [ RemoteUserAuthenticationPolicy(environ_key='HTTP_PROXY_AD_USER', callback=groupfinder), AuthTktAuthenticationPolicy(settings['auth.secret'], callback=groupfinder, hashalg='sha512') ] authn_policy = MultiAuthenticationPolicy(policies) config = Configurator(settings=settings, root_factory=RootFactory, session_factory = my_session_factory) config.set_authentication_policy(authn_policy) config.set_authorization_policy(authz_policy) #Jinja: #config.add_translation_dirs('locale/') config.include('pyramid_jinja2') # Cornice config.include('cornice') #Template locations config.add_jinja2_search_path('arhea:templates') #Supports updating objects in Jinja. Used in querysorter_m.jinja2 config.add_jinja2_extension('jinja2.ext.do') #Register custom filter in Jinja config.commit() config.get_jinja2_environment().filters['dateformat'] = dateformat config.get_jinja2_environment().filters['datetimeformat'] = datetimeformat #Static config.add_static_view(name='static', path='static', cache_max_age=3600) #Admin Gateway url config.add_route('admin_gtwy', settings['admin_gtwy']) #Routes config.add_route('home', '/') #Security package sec include config.include('.app_sec.include') #Applications package apps include config.include('.app_apps.include') #HR package apps include config.include('.app_hr.include') #SD package apps include config.include('.app_sd.include') config.scan() return config.make_wsgi_app()