Python pyramid.authorization.ACLAuthorizationPolicy() Examples

The following are 10 code examples of pyramid.authorization.ACLAuthorizationPolicy(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pyramid.authorization , or try the search function .
Example #1
Source File: test_integration.py    From pyramid_jwt with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def base_config() -> Configurator:
    config = Configurator()
    config.set_authorization_policy(ACLAuthorizationPolicy())

    config.include("pyramid_jwt")
    config.set_root_factory(Root)
    config.add_route("secure", "/secure")
    config.add_view(
        secure_view, route_name="secure", renderer="string", permission="read"
    )
    config.add_route("extra_claims", "/extra_claims")
    config.add_view(extra_claims, route_name="extra_claims", renderer="json")
    config.add_route("dump_claims", "/dump_claims")
    config.add_view(
        dump_claims, route_name="dump_claims", renderer="json", permission="read"
    )
    return config 
Example #2
Source File: test_pyramid.py    From sentry-python with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_error_in_authenticated_userid(
    sentry_init, pyramid_config, capture_events, route, get_client
):
    from sentry_sdk.integrations.logging import LoggingIntegration

    sentry_init(
        send_default_pii=True,
        integrations=[
            PyramidIntegration(),
            LoggingIntegration(event_level=logging.ERROR),
        ],
    )
    logger = logging.getLogger("test_pyramid")

    class AuthenticationPolicy(object):
        def authenticated_userid(self, request):
            logger.error("failed to identify user")

    pyramid_config.set_authorization_policy(ACLAuthorizationPolicy())
    pyramid_config.set_authentication_policy(AuthenticationPolicy())

    events = capture_events()

    client = get_client()
    client.get("/message")

    assert len(events) == 1 
Example #3
Source File: __init__.py    From learning-python with MIT License 5 votes vote down vote up
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

    authn_policy = AuthTktAuthenticationPolicy(
        'secret', callback=groupfinder, hashalg='sha512'
    )
    authz_policy = ACLAuthorizationPolicy()

    config = Configurator(settings=settings, root_factory='myshop.RootFactory')
    config.set_authentication_policy(authn_policy)
    config.set_authorization_policy(authz_policy)

    config.set_request_property(get_user, 'user', reify=True)
    config.set_request_property(lambda request: DBSession, 'db', reify=True)

    config.include('pyramid_chameleon')

    config.add_static_view('static', 'static', cache_max_age=3600)
    config.add_route('home', '/')
    config.add_route('category', '/category/{id}')
    config.add_route('item', '/item/{id}')
    config.add_route('search', '/search')
    config.add_route('annoncement', '/annoncement/{id}')

    config.add_route('login', '/login')
    config.add_route('logout', '/logout')
    config.add_route('register', '/register')

    config.add_route('order', '/order')
    config.add_route('cart', '/cart')
    config.add_route('comment', '/comment')

    config.add_route('add_item', '/category/{id}/add')

    config.scan()
    return config.make_wsgi_app() 
Example #4
Source File: __init__.py    From n6 with GNU Affero General Public License v3.0 5 votes vote down vote up
def main(global_config, **settings):
    return N6ConfigHelper(
        settings=settings,
        data_backend_api_class=N6DataBackendAPI,
        component_module_name='n6portal',
        auth_api_class=AuthAPI,                 # <- XXX: legacy stuff, to be removed in the future
        auth_query_api=AuthQueryAPI(settings),  # <- XXX: dummy stuff yet; to be used in the future
        auth_manage_api=AuthManageAPI(settings),
        authentication_policy=LoginOrSSLUserAuthenticationPolicy(settings),
        resources=RESOURCES,
        authorization_policy=ACLAuthorizationPolicy(),
        root_factory=N6PortalRootFactory,
    ).make_wsgi_app() 
Example #5
Source File: wsgi_app.py    From channelstream with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def make_app(server_config):
    config = Configurator(
        settings=server_config, root_factory=APIFactory, default_permission="access"
    )
    config.include("pyramid_jinja2")
    module_, class_ = server_config["signature_checker"].rsplit(".", maxsplit=1)
    signature_checker_cls = getattr(importlib.import_module(module_), class_)
    config.registry.signature_checker = signature_checker_cls(server_config["secret"])
    authn_policy = AuthTktAuthenticationPolicy(
        server_config["cookie_secret"], max_age=2592000
    )
    authz_policy = ACLAuthorizationPolicy()

    config.set_authentication_policy(authn_policy)
    config.set_authorization_policy(authz_policy)

    json_renderer = JSON(serializer=json.dumps, indent=4)
    json_renderer.add_adapter(datetime.datetime, datetime_adapter)
    json_renderer.add_adapter(uuid.UUID, uuid_adapter)
    config.add_renderer("json", json_renderer)

    config.add_subscriber(
        "channelstream.subscribers.handle_new_request", "pyramid.events.NewRequest"
    )
    config.add_request_method("channelstream.utils.handle_cors", "handle_cors")
    config.include("channelstream.wsgi_views")
    config.scan("channelstream.wsgi_views.server")
    config.scan("channelstream.wsgi_views.error_handlers")
    config.scan("channelstream.events")

    config.include("pyramid_apispec.views")
    config.pyramid_apispec_add_explorer(
        spec_route_name="openapi_spec",
        script_generator="channelstream.utils:swagger_ui_script_template",
        permission="admin",
        route_args={
            "factory": "channelstream.wsgi_views.wsgi_security:AdminAuthFactory"
        },
    )
    app = config.make_wsgi_app()
    return app 
Example #6
Source File: test_resource.py    From rest_toolkit with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_secured_default_view_not_allowed():
    config = Configurator()
    config.set_authentication_policy(AuthTktAuthenticationPolicy('seekrit'))
    config.set_authorization_policy(ACLAuthorizationPolicy())
    config.scan('resource_abc')
    app = make_app(config)
    app.get('/secure', status=403) 
Example #7
Source File: auth.py    From ramses with Apache License 2.0 5 votes vote down vote up
def setup_auth_policies(config, raml_root):
    """ Setup authentication, authorization policies.

    Performs basic validation to check all the required values are present
    and performs authentication, authorization policies generation using
    generator functions from `AUTHENTICATION_POLICIES`.

    :param config: Pyramid Configurator instance.
    :param raml_root: Instance of ramlfications.raml.RootNode.
    """
    log.info('Configuring auth policies')
    secured_by_all = raml_root.secured_by or []
    secured_by = [item for item in secured_by_all if item]
    if not secured_by:
        log.info('API is not secured. `secured_by` attribute '
                 'value missing.')
        return
    secured_by = secured_by[0]

    schemes = {scheme.name: scheme
               for scheme in raml_root.security_schemes}
    if secured_by not in schemes:
        raise ValueError(
            'Undefined security scheme used in `secured_by`: {}'.format(
                secured_by))

    scheme = schemes[secured_by]
    if scheme.type not in AUTHENTICATION_POLICIES:
        raise ValueError('Unsupported security scheme type: {}'.format(
            scheme.type))

    # Setup Authentication policy
    policy_generator = AUTHENTICATION_POLICIES[scheme.type]
    params = dictset(scheme.settings or {})
    authn_policy = policy_generator(config, params)
    config.set_authentication_policy(authn_policy)

    # Setup Authorization policy
    authz_policy = ACLAuthorizationPolicy()
    config.set_authorization_policy(authz_policy) 
Example #8
Source File: __init__.py    From shavar with Mozilla Public License 2.0 5 votes vote down vote up
def includeme(config):
    """Include mozsvc user-handling into a pyramid config.

    This function will set up user-handling via the mozsvc.user system.
    Things configured include:

        * use RequestWithUser as the request object factory
        * use TokenServerAuthenticationPolicy as the default authn policy

    """
    # Use RequestWithUser as the request object factory.
    config.set_request_factory(RequestWithUser)

    # Hook up a default AuthorizationPolicy.
    # ACLAuthorizationPolicy is usually what you want.
    # If the app configures one explicitly then this will get overridden.
    # In auto-commit mode this needs to be set before adding an authn policy.
    authz_policy = ACLAuthorizationPolicy()
    config.set_authorization_policy(authz_policy)

    # Build a TokenServerAuthenticationPolicy from the deployment settings.
    settings = config.get_settings()
    authn_policy = TokenServerAuthenticationPolicy.from_settings(settings)
    config.set_authentication_policy(authn_policy)

    # Set the forbidden view to use the challenge() method from the policy.
    config.add_forbidden_view(authn_policy.challenge) 
Example #9
Source File: __init__.py    From pyvac with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def main(global_config, **settings):
    settings = dict(settings)

    # Scoping sessions for Pyramid ensure session are commit/rollback
    # after the template has been rendered
    create_engine(settings, scoped=True)

    session_factory = UnencryptedCookieSessionFactoryConfig(
        settings['pyvac.cookie_key']
    )

    authn_policy = RouteSwithchAuthPolicy(secret=settings['pyvac.cookie_key'],
                                          callback=groupfinder)
    authz_policy = ACLPolicy()

    config = Configurator(settings=settings,
                          root_factory=RootFactory,
                          locale_negotiator=locale_negotiator,
                          authentication_policy=authn_policy,
                          authorization_policy=authz_policy,
                          session_factory=session_factory)

    config.add_subscriber('pyvac.helpers.i18n.add_renderer_globals',
                          IBeforeRender)
    config.add_subscriber('pyvac.helpers.i18n.add_localizer', NewRequest)

    config.end()

    return config.make_wsgi_app() 
Example #10
Source File: __init__.py    From travelcrm with GNU General Public License v3.0 4 votes vote down vote up
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
    session_factory = session_factory_from_settings(settings)
    authentication = AuthTktAuthenticationPolicy(
        settings.get('session.secret'),
    )
    authorization = ACLAuthorizationPolicy()

    config = Configurator(
        settings=settings,
        root_factory=root_factory,
        authentication_policy=authentication,
        authorization_policy=authorization,
        session_factory=session_factory,
    )
    config.add_translation_dirs(
        'colander:locale/',
        'travelcrm:locale/',
    )
    config.add_subscriber(
        '.lib.subscribers.company_schema',
        'pyramid.events.NewRequest'
    )
    config.add_subscriber(
        '.lib.subscribers.company_settings',
        'pyramid.events.NewRequest'
    )
    config.add_subscriber(
        '.lib.subscribers.helpers',
        'pyramid.events.BeforeRender'
    )
    config.add_subscriber(
        '.lib.subscribers.scheduler',
        'pyramid.events.ApplicationCreated'
    )

    config.add_renderer('sse', SSERendererFactory)
    config.add_renderer('str', STRRendererFactory)
    config.add_static_view('css', 'static/css', cache_max_age=3600)
    config.add_static_view('js', 'static/js', cache_max_age=3600)
    config.add_thumb_view('thumbs')

    config.scan()
    return config.make_wsgi_app()