예제 #1
0
 def test_only_unauthenticated_userid_with_groupfinder(self):
     policies = [TestAuthnPolicyUnauthOnly()]
     policy = MultiAuthenticationPolicy(policies, testgroupfinder)
     request = DummyRequest()
     self.assertEquals(policy.unauthenticated_userid(request), "test3")
     self.assertEquals(policy.authenticated_userid(request), None)
     self.assertEquals(policy.effective_principals(request), [Everyone])
예제 #2
0
 def test_stacking_of_authenticated_userid_with_groupdfinder(self):
     policies = [TestAuthnPolicy2(), TestAuthnPolicy3()]
     policy = MultiAuthenticationPolicy(policies, testgroupfinder)
     request = DummyRequest()
     self.assertEquals(policy.authenticated_userid(request), "test3")
     policies.reverse()
     self.assertEquals(policy.unauthenticated_userid(request), "test3")
예제 #3
0
 def test_authenticated_userid_unauthenticated_with_groupfinder(self):
     policies = [TestAuthnPolicy2()]
     policy = MultiAuthenticationPolicy(policies, testgroupfinder)
     request = DummyRequest()
     self.assertEquals(policy.authenticated_userid(request), None)
     self.assertEquals(sorted(policy.effective_principals(request)),
                       [Everyone, 'test2'])
예제 #4
0
 def test_stacking_of_authenticated_userid(self):
     policies = [TestAuthnPolicy2(), TestAuthnPolicy3()]
     policy = MultiAuthenticationPolicy(policies)
     request = DummyRequest()
     self.assertEquals(policy.authenticated_userid(request), "test2")
     policies.reverse()
     self.assertEquals(policy.authenticated_userid(request), "test3")
예제 #5
0
 def test_stacking_of_authenticated_userid_with_groupdfinder(self):
     policies = [TestAuthnPolicy2(), TestAuthnPolicy3()]
     policy = MultiAuthenticationPolicy(policies, testgroupfinder)
     request = DummyRequest()
     self.assertEquals(policy.authenticated_userid(request), "test3")
     policies.reverse()
     self.assertEquals(policy.unauthenticated_userid(request), "test3")
예제 #6
0
 def test_basic_stacking(self):
     policies = [TestAuthnPolicy1(), TestAuthnPolicy2()]
     policy = MultiAuthenticationPolicy(policies)
     request = DummyRequest()
     self.assertEquals(policy.authenticated_userid(request), "test2")
     self.assertEquals(sorted(policy.effective_principals(request)),
                       [Authenticated, Everyone, "test1", "test2"])
예제 #7
0
    def test_policy_selected_event(self):
        from pyramid.testing import testConfig
        from pyramid_multiauth import MultiAuthPolicySelected

        policies = [TestAuthnPolicy2(), TestAuthnPolicy3()]
        policy = MultiAuthenticationPolicy(policies)
        # Simulate loading from config:
        policies[0]._pyramid_multiauth_name = "name"

        with testConfig() as config:
            request = DummyRequest()

            selected_policy = []

            def track_policy(event):
                selected_policy.append(event)

            config.add_subscriber(track_policy, MultiAuthPolicySelected)

            self.assertEquals(policy.authenticated_userid(request), "test2")

            self.assertEquals(selected_policy[0].policy, policies[0])
            self.assertEquals(selected_policy[0].policy_name, "name")
            self.assertEquals(selected_policy[0].userid, "test2")
            self.assertEquals(selected_policy[0].request, request)
            self.assertEquals(len(selected_policy), 1)

            # Effective principals also triggers an event when groupfinder
            # is provided.
            policy_with_group = MultiAuthenticationPolicy(policies,
                                                          lambda u, r: ['foo'])
            policy_with_group.effective_principals(request)
            self.assertEquals(len(selected_policy), 2)
예제 #8
0
 def test_only_unauthenticated_userid_with_groupfinder(self):
     policies = [TestAuthnPolicyUnauthOnly()]
     policy = MultiAuthenticationPolicy(policies, testgroupfinder)
     request = DummyRequest()
     self.assertEquals(policy.unauthenticated_userid(request), "test3")
     self.assertEquals(policy.authenticated_userid(request), None)
     self.assertEquals(policy.effective_principals(request), [Everyone])
예제 #9
0
 def test_authenticated_userid_unauthenticated_with_groupfinder(self):
     policies = [TestAuthnPolicy2()]
     policy = MultiAuthenticationPolicy(policies, testgroupfinder)
     request = DummyRequest()
     self.assertEquals(policy.authenticated_userid(request), None)
     self.assertEquals(sorted(policy.effective_principals(request)),
                       [Everyone, 'test2'])
예제 #10
0
 def test_stacking_of_authenticated_userid(self):
     policies = [TestAuthnPolicy2(), TestAuthnPolicy3()]
     policy = MultiAuthenticationPolicy(policies)
     request = DummyRequest()
     self.assertEquals(policy.authenticated_userid(request), "test2")
     policies.reverse()
     self.assertEquals(policy.authenticated_userid(request), "test3")
예제 #11
0
 def test_basic_stacking(self):
     policies = [TestAuthnPolicy1(), TestAuthnPolicy2()]
     policy = MultiAuthenticationPolicy(policies)
     request = DummyRequest()
     self.assertEquals(policy.authenticated_userid(request),
                       "test2")
     self.assertEquals(sorted(policy.effective_principals(request)),
                       [Authenticated, Everyone, "test1", "test2"])
예제 #12
0
 def test_stacking_of_effective_principals(self):
     policies = [TestAuthnPolicy2(), TestAuthnPolicy3()]
     policy = MultiAuthenticationPolicy(policies)
     request = DummyRequest()
     self.assertEquals(sorted(policy.effective_principals(request)),
                       [Authenticated, Everyone, "test2", "test3", "test4"])
     policies.reverse()
     self.assertEquals(sorted(policy.effective_principals(request)),
                       [Authenticated, Everyone, "test2", "test3", "test4"])
     policies.append(TestAuthnPolicy1())
     self.assertEquals(
         sorted(policy.effective_principals(request)),
         [Authenticated, Everyone, "test1", "test2", "test3", "test4"])
예제 #13
0
 def test_stacking_of_effective_principals(self):
     policies = [TestAuthnPolicy2(), TestAuthnPolicy3()]
     policy = MultiAuthenticationPolicy(policies)
     request = DummyRequest()
     self.assertEquals(sorted(policy.effective_principals(request)),
                       [Authenticated, Everyone, "test2", "test3", "test4"])
     policies.reverse()
     self.assertEquals(sorted(policy.effective_principals(request)),
                       [Authenticated, Everyone, "test2", "test3", "test4"])
     policies.append(TestAuthnPolicy1())
     self.assertEquals(sorted(policy.effective_principals(request)),
                       [Authenticated, Everyone, "test1", "test2",
                        "test3", "test4"])
예제 #14
0
 def test_stacking_of_remember_and_forget(self):
     policies = [TestAuthnPolicy1(), TestAuthnPolicy2(), TestAuthnPolicy3()]
     policy = MultiAuthenticationPolicy(policies)
     request = DummyRequest()
     self.assertEquals(policy.remember(request, "ha"),
                      [("X-Remember", "ha"), ("X-Remember-2", "ha")])
     self.assertEquals(policy.forget(request),
                      [("X-Forget", "foo"), ("X-Forget", "bar")])
     policies.reverse()
     self.assertEquals(policy.remember(request, "ha"),
                      [("X-Remember-2", "ha"), ("X-Remember", "ha")])
     self.assertEquals(policy.forget(request),
                      [("X-Forget", "bar"), ("X-Forget", "foo")])
예제 #15
0
def includeme(config):
    # Register our login service
    config.register_service_factory(database_login_factory, IUserService)

    # Register our token services
    config.register_service_factory(TokenServiceFactory(name="password"),
                                    ITokenService,
                                    name="password")
    config.register_service_factory(TokenServiceFactory(name="email"),
                                    ITokenService,
                                    name="email")

    # Register our password breach detection service.
    config.register_service_factory(hibp_password_breach_factory,
                                    IPasswordBreachedService)

    # Register our authentication and authorization policies
    config.set_authentication_policy(
        MultiAuthenticationPolicy([
            SessionAuthenticationPolicy(callback=_authenticate),
            BasicAuthAuthenticationPolicy(check=_login_via_basic_auth),
        ]))
    config.set_authorization_policy(ACLAuthorizationPolicy())

    # Add a request method which will allow people to access the user object.
    config.add_request_method(_user, name="user", reify=True)

    # Register the rate limits that we're going to be using for our login
    # attempts
    config.register_service_factory(RateLimit("10 per 5 minutes"),
                                    IRateLimiter,
                                    name="user.login")
    config.register_service_factory(RateLimit("1000 per 5 minutes"),
                                    IRateLimiter,
                                    name="global.login")
예제 #16
0
def create_authentication(settings):
    timeout = settings.get("authtkt_timeout")
    timeout = None if timeout is None else int(timeout)
    reissue_time = settings.get("reissue_time")
    reissue_time = None if reissue_time is None else int(reissue_time)
    http_only = settings.get("authtkt_http_only", "True")
    http_only = http_only.lower() in ("true", "yes", "1")
    secure = settings.get("authtkt_secure", "True")
    secure = secure.lower() in ("true", "yes", "1")
    samesite = settings.get("authtkt_samesite", "Lax")
    secret = settings["authtkt_secret"]
    if len(secret) < 64:
        raise Exception(
            '"authtkt_secret should be at least 64 characters.'
            'See https://docs.pylonsproject.org/projects/pyramid/en/latest/api/session.html'
        )

    cookie_authentication_policy = AuthTktAuthenticationPolicy(
        secret,
        callback=defaultgroupsfinder,
        cookie_name=settings["authtkt_cookie_name"],
        samesite=None if samesite == '' else samesite,
        timeout=timeout,
        max_age=timeout,
        reissue_time=reissue_time,
        hashalg="sha512",
        http_only=http_only,
        secure=secure,
    )
    basic_authentication_policy = BasicAuthAuthenticationPolicy(
        c2cgeoportal_check)
    policies = [cookie_authentication_policy, basic_authentication_policy]
    return MultiAuthenticationPolicy(policies)
예제 #17
0
파일: test_views.py 프로젝트: wangjs/MAGMa
    def test_access_token(self, time):
        time.return_value = 1355000000.000000
        request = testing.DummyRequest()
        request.user = User('bob', 'Bob Example', '*****@*****.**')

        # mock auth
        from pyramid.authorization import ACLAuthorizationPolicy
        from pyramid_macauth import MACAuthenticationPolicy
        from pyramid_multiauth import MultiAuthenticationPolicy
        self.config.set_authorization_policy(ACLAuthorizationPolicy())
        policy = Mock(MACAuthenticationPolicy)
        policy.encode_mac_id.return_value = 'id', 'key'
        mpolicy = MultiAuthenticationPolicy([policy])
        self.config.set_authentication_policy(mpolicy)

        views = Views(request)

        response = views.access_token()

        expected_response = {
            "acesss_token": 'id',
            "mac_key": 'key',
            "expires_in": 360,
            "token_type": "mac",
            "mac_algorithm": "hmac-sha-1"
        }
        self.assertDictEqual(response, expected_response)
        self.assertEqual(request.response.headers['Cache-Control'], "no-store")
        policy.encode_mac_id.assert_called_with(request,
                                                'bob',
                                                expires=1355000360)
예제 #18
0
def create_app(global_config, **settings):
    config = configure(settings=settings)

    config.add_request_method(features.Client, name='feature', reify=True)

    config.set_authorization_policy(ACLAuthorizationPolicy())

    policy = MultiAuthenticationPolicy([
        TokenAuthenticationPolicy(callback=groupfinder),
        SessionAuthenticationPolicy(callback=groupfinder),
    ])
    config.set_authentication_policy(policy)

    config.include('h.auth')
    config.include('h.sentry')
    config.include('h.stats')

    # We have to include models and db to set up sqlalchemy metadata.
    config.include('h.models')
    config.include('h.db')
    config.include('h.api.db')

    # We have to include search to set up the `request.es` property.
    config.include('h.api.search')

    config.include('h.streamer')

    return config.make_wsgi_app()
예제 #19
0
def includeme(config):
    # Register our login service
    config.register_service_factory(database_login_factory, IUserService)
    config.register_service_factory(user_token_factory, IUserTokenService)

    # Register our authentication and authorization policies
    config.set_authentication_policy(
        MultiAuthenticationPolicy([
            SessionAuthenticationPolicy(callback=_authenticate),
            BasicAuthAuthenticationPolicy(check=_login),
        ]),
    )
    config.set_authorization_policy(ACLAuthorizationPolicy())

    # Add a request method which will allow people to access the user object.
    config.add_request_method(_user, name="user", reify=True)

    # Register the rate limits that we're going to be using for our login
    # attempts
    config.register_service_factory(
        RateLimit("10 per 5 minutes"),
        IRateLimiter,
        name="user.login",
    )
    config.register_service_factory(
        RateLimit("1000 per 5 minutes"),
        IRateLimiter,
        name="global.login",
    )
예제 #20
0
파일: __init__.py 프로젝트: ssin122/test-h
def includeme(config):
    global DEFAULT_POLICY
    global WEBSOCKET_POLICY

    # Set up authsanity
    settings = config.registry.settings
    settings['authsanity.source'] = 'cookie'
    settings['authsanity.cookie.max_age'] = 2592000
    settings['authsanity.cookie.httponly'] = True
    settings['authsanity.secret'] = derive_key(settings['secret_key'],
                                               b'h.auth.cookie_secret')
    config.include('pyramid_authsanity')

    if config.registry.settings.get('h.proxy_auth'):
        log.warn('Enabling proxy authentication mode: you MUST ensure that '
                 'the X-Forwarded-User request header can ONLY be set by '
                 'trusted downstream reverse proxies! Failure to heed this '
                 'warning will result in ALL DATA stored by this service '
                 'being available to ANYONE!')

        DEFAULT_POLICY = AuthenticationPolicy(api_policy=TOKEN_POLICY,
                                              fallback_policy=PROXY_POLICY)
        WEBSOCKET_POLICY = MultiAuthenticationPolicy([TOKEN_POLICY,
                                                      PROXY_POLICY])

    # Set the default authentication policy. This can be overridden by modules
    # that include this one.
    config.set_authentication_policy(DEFAULT_POLICY)

    # Allow retrieval of the auth_domain from the request object.
    config.add_request_method(auth_domain, name='auth_domain', reify=True)

    # Allow retrieval of the auth token (if present) from the request object.
    config.add_request_method('.tokens.auth_token', reify=True)
예제 #21
0
파일: __init__.py 프로젝트: zermelozf/h
def includeme(config):
    global DEFAULT_POLICY
    global WEBSOCKET_POLICY

    if config.registry.settings.get('h.proxy_auth'):
        log.warn('Enabling proxy authentication mode: you MUST ensure that '
                 'the X-Forwarded-User request header can ONLY be set by '
                 'trusted downstream reverse proxies! Failure to heed this '
                 'warning will result in ALL DATA stored by this service '
                 'being available to ANYONE!')

        DEFAULT_POLICY = AuthenticationPolicy(api_policy=TOKEN_POLICY,
                                              fallback_policy=PROXY_POLICY)
        WEBSOCKET_POLICY = MultiAuthenticationPolicy(
            [TOKEN_POLICY, PROXY_POLICY])

    # Set the default authentication policy. This can be overridden by modules
    # that include this one.
    config.set_authentication_policy(DEFAULT_POLICY)

    # Allow retrieval of the auth_domain from the request object.
    config.add_request_method(auth_domain, name='auth_domain', reify=True)

    # Allow retrieval of the auth token (if present) from the request object.
    config.add_request_method(auth_token, reify=True)
예제 #22
0
def main(global_config, **settings):
    """Application factory"""
    config = Configurator(settings=settings, root_factory=RootFactory)
    declare_routes(config)

    session_factory = SignedCookieSessionFactory(
        settings.get('session_key', 'itsaseekreet'))
    config.set_session_factory(session_factory)

    global cache
    cache = CacheManager(**parse_cache_config_options(settings))

    from .authnz import APIKeyAuthenticationPolicy
    api_key_authn_policy = APIKeyAuthenticationPolicy()
    config.include('openstax_accounts')
    openstax_authn_policy = config.registry.getUtility(
        IOpenstaxAccountsAuthenticationPolicy)
    policies = [api_key_authn_policy, openstax_authn_policy]
    authn_policy = MultiAuthenticationPolicy(policies)
    config.set_authentication_policy(authn_policy)
    authz_policy = ACLAuthorizationPolicy()
    config.set_authorization_policy(authz_policy)

    config.scan(ignore='cnxpublishing.tests')
    return config.make_wsgi_app()
예제 #23
0
    def test_policy_selected_event(self):
        from pyramid.testing import testConfig
        from pyramid_multiauth import MultiAuthPolicySelected

        policies = [TestAuthnPolicy2(), TestAuthnPolicy3()]
        policy = MultiAuthenticationPolicy(policies)
        # Simulate loading from config:
        policies[0]._pyramid_multiauth_name = "name"

        with testConfig() as config:
            request = DummyRequest()

            selected_policy = []

            def track_policy(event):
                selected_policy.append(event)

            config.add_subscriber(track_policy, MultiAuthPolicySelected)

            self.assertEquals(policy.authenticated_userid(request), "test2")

            self.assertEquals(selected_policy[0].policy, policies[0])
            self.assertEquals(selected_policy[0].policy_name, "name")
            self.assertEquals(selected_policy[0].userid, "test2")
            self.assertEquals(selected_policy[0].request, request)
            self.assertEquals(len(selected_policy), 1)

            # Effective principals also triggers an event when groupfinder
            # is provided.
            policy_with_group = MultiAuthenticationPolicy(
                policies, lambda u, r: ['foo'])
            policy_with_group.effective_principals(request)
            self.assertEquals(len(selected_policy), 2)
예제 #24
0
    def configure_authentication(self):
        """Set up authentication and authorization policies.
        """
        import pyramid.tweens
        from pyramid.authorization import ACLAuthorizationPolicy
        from pyramid.authentication import SessionAuthenticationPolicy
        from pyramid_jwt import create_jwt_authentication_policy
        from pyramid_multiauth import MultiAuthenticationPolicy
        from elixr2.web.auth.principals import (
            resolve_principals as get_principals,
            get_request_user
            )
        from .api.security import jwt_principals_finder

        authz_policy = ACLAuthorizationPolicy()
        ses_authn_policy = SessionAuthenticationPolicy(callback=get_principals)
        jwt_authn_policy = create_jwt_authentication_policy(self.config,
            callback=jwt_principals_finder)

        multi_auth_args = [jwt_authn_policy, ses_authn_policy]
        authn_policy = MultiAuthenticationPolicy(multi_auth_args)

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

        # We need to carefully be above TM view, but below exc view so that
        # internal server error page doesn't trigger session authentication
        # that accesses the database
        self.config.add_tween(
            "elixr2.web.auth.tweens.SessionInvalidationTweenFactory",
            under="pyramid_tm.tm_tween_factory")

        # # TODO: Grab incoming auth details changed events
        # from websauna.system.auth import subscribers
        # self.config.scan(subscribers)

        # Experimental support for transaction aware properties
        try:
            from pyramid_tm.reify import transaction_aware_reify
            self.config.add_request_method(
                callable=transaction_aware_reify(self.config, get_request_user),
                name="user", property=True, reify=False)
        except ImportError:
            self.config.add_request_method(get_request_user, 'user', reify=True)

        ## request method for jwt
        def create_jwt_token(request, principal, expiration=None, **claims):
            return jwt_authn_policy.create_token(principal, expiration, **claims)

        def jwt_claims(request):
            return jwt_authn_policy.get_claims(request)

        self.config.add_request_method(create_jwt_token, 'create_jwt_token')
        self.config.add_request_method(jwt_claims, 'jwt_claims', reify=True)
예제 #25
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    config = Configurator(settings=settings, root_factory=root_factory)
    config.include('substanced')
    config.include('.catalog')
    config.include('.evolution')
    config.add_workflow(workflow, ('Document',))

    config.scan()
    # paster serve entry point
    settings['debug_templates'] = 'true'
    config.add_route('deformdemo', '/deformdemo*traverse')
    config.add_route('ubikdbsocket', 'socket.io/*remaining')
    config.add_static_view('static_demo', 'deformdemo:static')
    config.add_static_view('static_ubikdb', 'ubikdb:static')
    config.add_static_view('static_sdi_ubikdb_demo', 'sdi_ubikdb_demo:static')
    config.add_translation_dirs(
        'colander:locale',
        'deform:locale',
        'deformdemo:locale'
        )
    def onerror(*arg):
        pass
    config.scan('deformdemo', onerror=onerror)
    # override login page to show login info
    config.add_mgmt_view(
        login,
        name='login',
        renderer='sdi_ubikdb_demo:templates/login.pt',
        tab_condition=False,
        permission=NO_PERMISSION_REQUIRED)
    config.add_mgmt_view(
        login,
        context=HTTPForbidden,
        renderer='sdi_ubikdb_demo:templates/login.pt',
        tab_condition=False,
        permission=NO_PERMISSION_REQUIRED
        )
    try:
        from sddav.authentication import SDIBasicAuthPolicy
        # set up the basic auth policy if we have sddav
        secret = settings['substanced.secret']
        authn_policy = MultiAuthenticationPolicy([
            AuthTktAuthenticationPolicy(secret, callback=groupfinder),
            SDIBasicAuthPolicy(),
            ])
        config.set_authentication_policy(authn_policy)
    except ImportError:
        pass
    else:
        config.include('sddav')
    return config.make_wsgi_app()
예제 #26
0
def create_authentication(
        settings: Dict[str, Any]) -> MultiAuthenticationPolicy:
    timeout = settings.get("authtkt_timeout")
    timeout = None if timeout is None or timeout.lower() == "none" else int(
        timeout)
    reissue_time = settings.get("authtkt_reissue_time")
    reissue_time = None if reissue_time is None or reissue_time.lower(
    ) == "none" else int(reissue_time)
    max_age = settings.get("authtkt_max_age")
    max_age = None if max_age is None or max_age.lower() == "none" else int(
        max_age)
    http_only = settings.get("authtkt_http_only", "True")
    http_only = http_only.lower() in ("true", "yes", "1")
    secure = settings.get("authtkt_secure", "True")
    secure = secure.lower() in ("true", "yes", "1")
    samesite = settings.get("authtkt_samesite", "Lax")
    secret = settings["authtkt_secret"]
    basicauth = settings.get("basicauth",
                             "False").lower() in ("true", "yes", "1")
    if len(secret) < 64:
        raise Exception(
            '"authtkt_secret should be at least 64 characters.'
            "See https://docs.pylonsproject.org/projects/pyramid/en/latest/api/session.html"
        )

    policies = []

    url_authentication_policy = UrlAuthenticationPolicy(
        settings.get("urllogin", {}).get("aes_key"),
        defaultgroupsfinder,
    )
    policies.append(url_authentication_policy)

    cookie_authentication_policy = AuthTktAuthenticationPolicy(
        secret,
        callback=defaultgroupsfinder,
        cookie_name=settings["authtkt_cookie_name"],
        samesite=None if samesite == "" else samesite,
        timeout=timeout,
        max_age=max_age,
        reissue_time=reissue_time,
        hashalg="sha512",
        http_only=http_only,
        secure=secure,
    )
    policies.append(cookie_authentication_policy)

    if basicauth:
        basic_authentication_policy = BasicAuthAuthenticationPolicy(
            c2cgeoportal_check)
        policies.append(basic_authentication_policy)

    return MultiAuthenticationPolicy(policies)
예제 #27
0
def create_authentication(settings):
    timeout = settings.get("authtkt_timeout", None)
    timeout = None if timeout is None else int(timeout)
    cookie_authentication_policy = AuthTktAuthenticationPolicy(
        settings["authtkt_secret"],
        callback=defaultgroupsfinder,
        cookie_name=settings["authtkt_cookie_name"],
        timeout=timeout, max_age=timeout,
        hashalg="sha512", http_only=True,
    )
    basic_authentication_policy = BasicAuthAuthenticationPolicy(c2cgeoportal_check)
    policies = [cookie_authentication_policy, basic_authentication_policy]
    return MultiAuthenticationPolicy(policies)
예제 #28
0
    def test_policy_selected_event(self):
        from pyramid.testing import testConfig
        from pyramid_multiauth import MultiAuthPolicySelected

        policies = [TestAuthnPolicy2(), TestAuthnPolicy3()]
        policy = MultiAuthenticationPolicy(policies)

        with testConfig() as config:
            request = DummyRequest()

            selected_policy = []

            def track_policy(event):
                selected_policy.append((event.policy, event.request))

            config.add_subscriber(track_policy, MultiAuthPolicySelected)


            self.assertEquals(policy.authenticated_userid(request), "test2")

            self.assertEquals(selected_policy[0][0], policies[0])
            self.assertEquals(selected_policy[0][1], request)
            self.assertEquals(len(selected_policy), 1)
예제 #29
0
def includeme(config):
    # Register our login service
    config.register_service_factory(database_login_factory, IUserService)

    # Register our token services
    config.register_service_factory(
        TokenServiceFactory(name="password"), ITokenService, name="password"
    )
    config.register_service_factory(
        TokenServiceFactory(name="email"), ITokenService, name="email"
    )
    config.register_service_factory(
        TokenServiceFactory(name="two_factor"), ITokenService, name="two_factor"
    )

    # Register our password breach detection service.
    breached_pw_class = config.maybe_dotted(
        config.registry.settings.get(
            "breached_passwords.backend", HaveIBeenPwnedPasswordBreachedService
        )
    )
    config.register_service_factory(
        breached_pw_class.create_service, IPasswordBreachedService
    )

    # Register our authentication and authorization policies
    config.set_authentication_policy(
        MultiAuthenticationPolicy(
            [
                SessionAuthenticationPolicy(callback=_authenticate),
                BasicAuthAuthenticationPolicy(check=_basic_auth_login),
                MacaroonAuthenticationPolicy(callback=_authenticate),
            ]
        )
    )
    config.set_authorization_policy(
        MacaroonAuthorizationPolicy(policy=ACLAuthorizationPolicy())
    )

    # Add a request method which will allow people to access the user object.
    config.add_request_method(_user, name="user", reify=True)

    # Register the rate limits that we're going to be using for our login
    # attempts
    config.register_service_factory(
        RateLimit("10 per 5 minutes"), IRateLimiter, name="user.login"
    )
    config.register_service_factory(
        RateLimit("1000 per 5 minutes"), IRateLimiter, name="global.login"
    )
예제 #30
0
def includeme(config):
    # Register our login service
    config.register_service_factory(database_login_factory, IUserService)

    # Register our authentication and authorization policies
    config.set_authentication_policy(
        MultiAuthenticationPolicy([
            SessionAuthenticationPolicy(callback=_authenticate),
            BasicAuthAuthenticationPolicy(check=_login),
        ]), )
    config.set_authorization_policy(ACLAuthorizationPolicy())

    # Add a request method which will allow people to access the user object.
    config.add_request_method(_user, name="user", reify=True)
예제 #31
0
def includeme(config):
    """Configuration include fuction for this module"""
    api_key_authn_policy = APIKeyAuthenticationPolicy()
    config.include('openstax_accounts')
    openstax_authn_policy = config.registry.getUtility(
        IOpenstaxAccountsAuthenticationPolicy)

    # Set up api & user authentication policies.
    policies = [api_key_authn_policy, openstax_authn_policy]
    authn_policy = MultiAuthenticationPolicy(policies)
    config.set_authentication_policy(authn_policy)

    # Set up the authorization policy.
    authz_policy = ACLAuthorizationPolicy()
    config.set_authorization_policy(authz_policy)
예제 #32
0
파일: webapp.py 프로젝트: hkmshb/gridix.web
def set_multi_authentication_policy(config, settings):
    policy_tkt = AuthTktAuthenticationPolicy(settings['auth.secret_key'],
                                             callback=role_finder)
    policy_jwt = create_jwt_authentication_policy(config,
                                                  callback=api_role_finder)
    policy = MultiAuthenticationPolicy([policy_jwt, policy_tkt])

    ## extraced from pyramid_jwt
    def request_create_token(request, principal, expiration=None, **claims):
        return policy_jwt.create_token(principal, expiration, **claims)

    def request_claims(request):
        return policy_jwt.get_claims(request)

    config.set_authentication_policy(policy)
    config.add_request_method(request_create_token, 'create_jwt_token')
    config.add_request_method(request_claims, 'jwt_claims', reify=True)
예제 #33
0
 def test_stacking_of_remember_and_forget(self):
     policies = [TestAuthnPolicy1(), TestAuthnPolicy2(), TestAuthnPolicy3()]
     policy = MultiAuthenticationPolicy(policies)
     request = DummyRequest()
     self.assertEquals(policy.remember(request, "ha"),
                       [("X-Remember", "ha"), ("X-Remember-2", "ha")])
     self.assertEquals(policy.forget(request), [("X-Forget", "foo"),
                                                ("X-Forget", "bar")])
     policies.reverse()
     self.assertEquals(policy.remember(request, "ha"),
                       [("X-Remember-2", "ha"), ("X-Remember", "ha")])
     self.assertEquals(policy.forget(request), [("X-Forget", "bar"),
                                                ("X-Forget", "foo")])
예제 #34
0
def create_authentication(settings):
    timeout = settings.get("authtkt_timeout")
    timeout = None if timeout is None else int(timeout)
    reissue_time = settings.get("reissue_time")
    reissue_time = None if reissue_time is None else int(reissue_time)
    http_only = settings.get("authtk_http_only")
    http_only = True if http_only is None else http_only != "False"
    secure = settings.get("authtk_secure")
    secure = True if secure is None else secure != "False"
    cookie_authentication_policy = AuthTktAuthenticationPolicy(
        settings["authtkt_secret"],
        callback=defaultgroupsfinder,
        cookie_name=settings["authtkt_cookie_name"],
        timeout=timeout,
        max_age=timeout,
        reissue_time=reissue_time,
        hashalg="sha512",
        http_only=http_only,
        secure=secure,
    )
    basic_authentication_policy = BasicAuthAuthenticationPolicy(
        c2cgeoportal_check)
    policies = [cookie_authentication_policy, basic_authentication_policy]
    return MultiAuthenticationPolicy(policies)
예제 #35
0
def create_authentication(settings):
    timeout = settings.get("authtkt_timeout")
    timeout = None if timeout is None else int(timeout)
    reissue_time = settings.get("reissue_time")
    reissue_time = None if reissue_time is None else int(reissue_time)
    http_only = settings.get("authtkt_http_only", "True")
    http_only = http_only.lower() in ("true", "yes", "1")
    secure = settings.get("authtkt_secure", "True")
    secure = secure.lower() in ("true", "yes", "1")
    cookie_authentication_policy = AppAwareAuthTktAuthenticationPolicy(
        settings["authtkt_secret"],
        callback=defaultgroupsfinder,
        cookie_name=settings["authtkt_cookie_name"],
        timeout=timeout,
        max_age=timeout,
        reissue_time=reissue_time,
        hashalg="sha512",
        http_only=http_only,
        secure=secure,
        parent_domain=True)
    basic_authentication_policy = BasicAuthAuthenticationPolicy(
        c2cgeoportal_check)
    policies = [cookie_authentication_policy, basic_authentication_policy]
    return MultiAuthenticationPolicy(policies)
예제 #36
0
def configure_karl(config, load_zcml=True):
    # Authorization/Authentication policies
    settings = config.registry.settings
    authentication_policy = MultiAuthenticationPolicy([
        AuthTktAuthenticationPolicy(settings['who_secret'],
                                    callback=group_finder,
                                    cookie_name=settings['who_cookie']),
        # for b/w compat with bootstrapper
        RepozeWho1AuthenticationPolicy(callback=group_finder),
        BasicAuthenticationPolicy()
    ])
    config.set_authorization_policy(ACLAuthorizationPolicy())
    config.set_authentication_policy(authentication_policy)

    # Static tree revisions routing
    static_rev = settings.get('static_rev')
    if not static_rev:
        static_rev = _guess_static_rev()
        settings['static_rev'] = static_rev
    config.add_static_view('/static/%s' % static_rev,
                           'karl.views:static',
                           cache_max_age=60 * 60 * 24 * 365)

    # Add a redirecting static view to all _other_ revisions.
    def _expired_static_predicate(info, request):
        # We add a redirecting route to all static/*,
        # _except_ if it starts with the active revision segment.
        path = info['match']['path']
        return path and path[0] != static_rev

    config.add_route('expired-static',
                     '/static/*path',
                     custom_predicates=(_expired_static_predicate, ))

    # Need a session if using Velruse
    config.set_session_factory(Session(settings['who_secret']))

    # Configure bottlecap layouts
    config.include('bottlecap')
    config.add_renderer('.pt', ux2_metarenderer_factory)
    config.registry.registerUtility(FormishZPTMetaRenderer(), IFormishRenderer)
    config.include('karl.security.sso')

    if load_zcml:
        config.hook_zca()
        config.include('pyramid_zcml')
        config.load_zcml('standalone.zcml')

    # chatter uses this to display user chatter pages, because
    # there is no container for chatter to hang a view from.
    config.add_view('karl.views.chatter.finder',
                    context=NotFound,
                    renderer="karl.views:templates/errorpage.pt")

    debug = asbool(settings.get('debug', 'false'))
    if not debug:
        config.add_view('karl.errorpage.errorpage',
                        context=Exception,
                        renderer="karl.views:templates/errorpage.pt")

    debugtoolbar = asbool(settings.get('debugtoolbar', 'false'))
    if debugtoolbar and pyramid_debugtoolbar:
        config.include(pyramid_debugtoolbar)

    config.add_subscriber(block_webdav, NewRequest)

    if slowlog is not None:
        config.include(slowlog)

    if perfmetrics is not None:
        config.include(perfmetrics)
예제 #37
0
파일: config.py 프로젝트: cmaceves/MAGMa
def configure(config):
    """Configures the MAGMa web app.

    `config` is a instance of :class:Configurator.
    """
    settings = config.get_settings()
    config.include('pyramid_mako')
    config.include('pyramid_tm')

    # for human users
    authn_policy1 = AuthTktAuthenticationPolicy(
        secret=settings['cookie.secret'],
        path=settings['cookie.path'],
        hashalg='sha512',
        callback=groupfinder,
        cookie_name=settings.get('cookie.name', 'auth_tkt'),
        wild_domain=False,
        http_only=True,
    )

    # for service consumers
    # See http://www.rfk.id.au/blog/entry/securing-pyramid-persona-macauth/
    authn_policy2 = MACAuthenticationPolicy.from_settings(settings)
    authn_policy2.find_groups = groupfinder

    auth_policies = [
        authn_policy1,
        authn_policy2,
    ]
    authn_policy = MultiAuthenticationPolicy(auth_policies)
    config.set_authentication_policy(authn_policy)
    config.set_authorization_policy(ACLAuthorizationPolicy())
    config.set_root_factory(RootFactory)

    config.add_renderer('jsonhtml', jsonhtml_renderer_factory)

    config.add_static_view('static', 'magmaweb:static', cache_max_age=3600)

    # for everyone
    config.add_route('home', '/')
    config.add_route('help', '/help')
    config.add_route('login', '/login')

    # for authenticated users
    config.add_route('defaults.json', '/defaults.json')
    config.add_route('startjob', '/start')
    config.add_route('jobfromscratch', '/results/')
    config.add_route('uploaddb', '/uploaddb')
    config.add_route('workspace', '/workspace')
    config.add_route('access_token', '/access_token.json')
    config.add_route('logout', '/logout')

    # JobFactory + traverse
    def add_job_route(name, pattern):
        """"Add route with :class:Job as context"""
        config.add_route(name,
                         pattern,
                         traverse='/{jobid}',
                         factory=JobIdFactory)

    # for job owner
    add_job_route('status.json', '/status/{jobid}.json')
    add_job_route('status', '/status/{jobid}')

    # for authenticated users
    add_job_route('results', '/results/{jobid}')
    add_job_route('molecules.json', '/results/{jobid}/molecules.json')
    add_job_route('molecules.csv', '/results/{jobid}/molecules.csv')
    add_job_route('molecules.sdf', '/results/{jobid}/molecules.sdf')
    add_job_route('fragments.json',
                  '/results/{jobid}/fragments/{scanid}/{molid}.json')
    add_job_route('chromatogram.json', '/results/{jobid}/chromatogram.json')
    add_job_route('mspectra.json', '/results/{jobid}/mspectra/{scanid}.json')
    add_job_route('extractedionchromatogram.json',
                  '/results/{jobid}/extractedionchromatogram/{molid}.json')
    add_job_route('stderr.txt', '/results/{jobid}/stderr.txt')
    add_job_route('stdout.txt', '/results/{jobid}/stdout.txt')
    add_job_route('runinfo.json', '/results/{jobid}/runinfo.json')

    # for job owner
    add_job_route('rpc.add_structures', '/rpc/{jobid}/add_structures')
    add_job_route('rpc.add_ms_data', '/rpc/{jobid}/add_ms_data')
    add_job_route('rpc.metabolize', '/rpc/{jobid}/metabolize')
    add_job_route('rpc.metabolize_one', '/rpc/{jobid}/metabolize_one')
    add_job_route('rpc.annotate', '/rpc/{jobid}/annotate')
    add_job_route('rpc.assign', '/rpc/{jobid}/assign')
    add_job_route('rpc.unassign', '/rpc/{jobid}/unassign')

    # find view_config decorations
    config.scan('magmaweb', ignore='magmaweb.tests')

    # add config defaults and
    # cast config parameter to boolean
    auto_register = asbool(settings.get('auto_register', False))
    config.add_settings(auto_register=auto_register)
    restricted = asbool(settings.get('restricted', False))
    config.add_settings(restricted=restricted)
    ncpus = settings.get('ncpus', 1)
    config.add_settings(ncpus=ncpus)

    # Setup connection to user database
    engine = engine_from_config(settings)
    init_user_db(engine)
예제 #38
0
__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)

DEFAULT_POLICY = AuthenticationPolicy(api_policy=TOKEN_POLICY,
                                      fallback_policy=TICKET_POLICY)
WEBSOCKET_POLICY = MultiAuthenticationPolicy([TOKEN_POLICY, TICKET_POLICY])


def includeme(config):
    global DEFAULT_POLICY
    global WEBSOCKET_POLICY

    # Set up authsanity
    config.register_service_factory(
        '.services.auth_ticket_service_factory',
        iface='pyramid_authsanity.interfaces.IAuthService')
    settings = config.registry.settings
    settings['authsanity.source'] = 'cookie'
    settings['authsanity.cookie.max_age'] = 2592000
    settings['authsanity.cookie.httponly'] = True
    settings['authsanity.secret'] = derive_key(settings['secret_key'],
예제 #39
0
파일: auth.py 프로젝트: zogzog/cubicweb
def includeme(config):
    """ Activate the CubicWeb AuthTkt authentication policy.

    Usually called via ``config.include('cubicweb.pyramid.auth')``.

    See also :ref:`defaults_module`
    """
    settings = config.registry.settings

    policies = []

    if asbool(settings.get('cubicweb.auth.update_login_time', True)):
        policies.append(UpdateLoginTimeAuthenticationPolicy())

    if asbool(settings.get('cubicweb.auth.authtkt', True)):
        session_prefix = 'cubicweb.auth.authtkt.session.'
        persistent_prefix = 'cubicweb.auth.authtkt.persistent.'

        session_secret = settings.get(session_prefix + 'secret', 'notsosecret')
        persistent_secret = settings.get(persistent_prefix + 'secret',
                                         'notsosecret')
        if ('notsosecret' in (session_secret, persistent_secret)
                and config.registry['cubicweb.config'].mode != 'test'):
            warnings.warn('''

                !! SECURITY WARNING !!

                The authentication cookies are signed with a static secret key.

                Configure the following options in your pyramid.ini file:

                - cubicweb.auth.authtkt.session.secret
                - cubicweb.auth.authtkt.persistent.secret

                YOU SHOULD STOP THIS INSTANCE unless your really know what you
                are doing !!

                Please refer to to cubicweb-pyramid documentation on how to
                write this pyramid.ini file:
                https://cubicweb.readthedocs.io/en/latest/book/pyramid/settings/#pyramid-settings-file
                Without it authentication WON'T work.

            ''')

        policies.append(
            CWAuthTktAuthenticationPolicy(session_secret,
                                          False,
                                          defaults={
                                              'hashalg': 'sha512',
                                              'cookie_name': 'auth_tkt',
                                              'timeout': 1200,
                                              'reissue_time': 120,
                                              'http_only': True,
                                              'secure': True
                                          },
                                          prefix=session_prefix,
                                          **settings))

        policies.append(
            CWAuthTktAuthenticationPolicy(persistent_secret,
                                          True,
                                          defaults={
                                              'hashalg': 'sha512',
                                              'cookie_name': 'pauth_tkt',
                                              'max_age': 3600 * 24 * 30,
                                              'reissue_time': 3600 * 24,
                                              'http_only': True,
                                              'secure': True
                                          },
                                          prefix=persistent_prefix,
                                          **settings))

    kw = {}
    if asbool(settings.get('cubicweb.auth.groups_principals', True)):
        kw['callback'] = get_principals

    authpolicy = MultiAuthenticationPolicy(policies, **kw)
    config.registry['cubicweb.authpolicy'] = authpolicy

    config.set_authentication_policy(authpolicy)
    config.set_authorization_policy(ACLAuthorizationPolicy())