def test_authorization_identity_getter():
    class UserNameRequirement(Requirement):
        def __init__(self, expected_name: str):
            self.expected_name = expected_name

        def handle(self, context: AuthorizationContext):
            assert context.identity is not None

            if context.identity.has_claim_value('name', self.expected_name):
                context.succeed(self)

    auth = get_strategy([Policy('user', UserNameRequirement('Tybek'))],
                        request_identity_getter)

    @auth(policy='user')
    def some_method(request: Request):
        assert request is not None
        return True

    value = some_method(Request(None, User({'name': 'Tybek'})))

    assert value is True
Exemple #2
0
    def use_authorization(
        self,
        strategy: Optional[AuthorizationStrategy] = None
    ) -> AuthorizationStrategy:
        if self.running:
            raise RuntimeError(
                'The application is already running, configure authorization '
                'before starting the application')

        if not strategy:
            strategy = AuthorizationStrategy()

        if strategy.default_policy is None:
            # by default, a default policy is configured with no requirements,
            # meaning that request handlers allow anonymous users, unless specified otherwise
            # this can be modified, by adding a requirement to the default policy
            strategy.default_policy = Policy('default')

        self._authorization_strategy = strategy
        self.exceptions_handlers[
            AuthenticateChallenge] = handle_authentication_challenge
        self.exceptions_handlers[UnauthorizedError] = handle_unauthorized
        return strategy
def test_policy_repr():
    policy = Policy('Cats lover')

    assert repr(policy).startswith('<Policy "Cats lover"')
Exemple #4
0
def test_policy_iadd_syntax_raises_for_non_requirements():
    strategy = AuthorizationStrategy(default_policy=Policy('default'))

    with raises(ValueError,
                match='Only requirements can be added using __iadd__ syntax'):
        strategy.default_policy += object()