Beispiel #1
0
def test_ActiveUserRolePermission_authenticated_user(authenticated_user_instance):
    authenticated_user_instance.is_active = True
    with permissions.ActiveUserRolePermission():
        pass
    authenticated_user_instance.is_active = False
    with pytest.raises(HTTPException):
        with permissions.ActiveUserRolePermission():
            pass
Beispiel #2
0
        def decorator(func_or_class):
            """
            A helper wrapper.
            """
            if isinstance(func_or_class, type):
                # Handle Resource classes decoration
                # pylint: disable=protected-access
                func_or_class._apply_decorator_to_methods(decorator)
                return func_or_class
            else:
                func = func_or_class

            # Avoid circilar dependency
            from app.extensions import oauth2
            from app.modules.users import permissions

            # Automatically apply `permissions.ActiveUserRolePermisson`
            # guard if none is yet applied.
            if getattr(func, '_role_permission_applied', False):
                protected_func = func
            else:
                protected_func = self.permission_required(
                    permissions.ActiveUserRolePermission()
                )(func)

            # Ignore the current OAuth2 scopes if another @login_required
            # decorator was applied and just copy the already applied scopes.
            if hasattr(protected_func, '__apidoc__') \
                    and 'security' in protected_func.__apidoc__ \
                    and '__oauth__' in protected_func.__apidoc__['security']:
                _oauth_scopes = protected_func.__apidoc__['security']['__oauth__']['scopes']
            else:
                _oauth_scopes = oauth_scopes

            oauth_protection_decorator = oauth2.require_oauth(*_oauth_scopes)
            self._register_access_restriction_decorator(protected_func, oauth_protection_decorator)
            oauth_protected_func = oauth_protection_decorator(protected_func)

            return self.doc(
                security={
                    # This is a temporary configuration which is overriden in
                    # `Api.add_namespace`.
                    '__oauth__': {
                        'type': 'oauth',
                        'scopes': _oauth_scopes,
                    }
                }
            )(
                self.response(
                    code=HTTPStatus.UNAUTHORIZED.value,
                    description=(
                        "Authentication is required"
                        if not oauth_scopes else
                        "Authentication with %s OAuth scope(s) is required" % (
                            ', '.join(oauth_scopes)
                        )
                    ),
                )(oauth_protected_func)
            )
        def decorator(func_or_class):
            """
            A helper wrapper.
            """
            if isinstance(func_or_class, type):
                # Handle Resource classes decoration
                # pylint: disable=protected-access
                func_or_class._apply_decorator_to_methods(decorator)
                return func_or_class
            else:
                func = func_or_class

            # Avoid circilar dependency
            from app.extensions import oauth2
            from app.modules.users import permissions

            # This way we will avoid unnecessary checks if the decorator is
            # applied several times, e.g. when Resource class is decorated.
            func.__dict__['__latest_oauth_decorator_id__'] = id(decorator)

            # Automatically apply `permissions.ActiveUserRolePermisson`
            # guard if none is yet applied.
            if getattr(func, '_role_permission_applied', False):
                protected_func = func
            else:
                protected_func = self.permission_required(
                    permissions.ActiveUserRolePermission())(func)

            # Accumulate OAuth2 scopes if @login_required decorator is applied
            # several times
            if hasattr(protected_func, '__apidoc__') \
                    and 'security' in protected_func.__apidoc__ \
                    and '__oauth__' in protected_func.__apidoc__['security']:
                _oauth_scopes = (oauth_scopes +
                                 protected_func.__apidoc__['security']
                                 ['__oauth__']['scopes'])
            else:
                _oauth_scopes = oauth_scopes

            def oauth_protection_decorator(func):
                """
                This helper decorator is necessary to be able to skip redundant
                checks when Resource class is also decorated.
                """
                oauth_protected_func = oauth2.require_oauth(
                    *_oauth_scopes)(func)

                @wraps(oauth_protected_func)
                def wrapper(self, *args, **kwargs):
                    """
                    This wrapper decides whether OAuth2.require_oauth should be
                    executed to avoid unnecessary calls when ``login_required``
                    decorator is applied several times.
                    """
                    latest_oauth_decorator_id = getattr(
                        getattr(self, func.__name__),
                        '__latest_oauth_decorator_id__', None)
                    if id(decorator) == latest_oauth_decorator_id:
                        _func = oauth_protected_func
                    else:
                        _func = func
                    return _func(self, *args, **kwargs)

                return wrapper

            self._register_access_restriction_decorator(
                protected_func, oauth_protection_decorator)
            oauth_protected_func = oauth_protection_decorator(protected_func)

            return self.doc(
                security={
                    # This is a temporary configuration which is overriden in
                    # `Api.add_namespace`.
                    '__oauth__': {
                        'type': 'oauth',
                        'scopes': _oauth_scopes,
                    }
                })(self.response(
                    code=http_exceptions.Unauthorized.code,
                    description=(
                        "Authentication is required" if not _oauth_scopes else
                        "Authentication with %s OAuth scope(s) is required" %
                        (', '.join(_oauth_scopes))),
                )(oauth_protected_func))
Beispiel #4
0
def test_ActiveUserRolePermission_anonymous_user(anonymous_user_instance):
    # pylint: disable=unused-argument
    with pytest.raises(HTTPException):
        with permissions.ActiveUserRolePermission():
            pass
Beispiel #5
0
        def decorator(func_or_class):
            """
            A helper wrapper.
            """
            if isinstance(func_or_class, type):
                # Handle Resource classes decoration
                # pylint: disable=protected-access
                func_or_class._apply_decorator_to_methods(decorator)
                return func_or_class
            func = func_or_class

            # Avoid circular dependency
            from app.extensions import oauth2
            from app.modules.users import permissions

            # Automatically apply `permissions.ActiveUserRolePermisson`
            # guard if none is yet applied.
            if getattr(func, '_role_permission_applied', False):
                protected_func = func
            else:
                protected_func = self.permission_required(
                    permissions.ActiveUserRolePermission())(func)

            # Ignore the current OAuth2 scopes if another @login_required
            # decorator was applied and just copy the already applied scopes.
            if (hasattr(protected_func, '__apidoc__')
                    and 'security' in protected_func.__apidoc__
                    and '__oauth__' in protected_func.__apidoc__['security']):
                _oauth_scopes = protected_func.__apidoc__['security'][
                    '__oauth__']['scopes']
            else:
                _oauth_scopes = oauth_scopes

            oauth_protection_decorator = oauth2.require_oauth(
                *_oauth_scopes, locations=locations)
            self._register_access_restriction_decorator(
                protected_func, oauth_protection_decorator)
            oauth_protected_func = oauth_protection_decorator(protected_func)

            if 'form' in locations:
                oauth_protected_func = self.param(
                    name='access_token',
                    description=
                    ('This is an alternative way of passing the access_token, useful for '
                     'making authenticated requests from the browser native forms.'
                     ),
                    _in='formData',
                    type='string',
                    required=False,
                )(oauth_protected_func)

            return self.doc(
                security={
                    # This is a temporary (namespace) configuration which gets
                    # overriden on a namespace registration (in `Api.add_namespace`).
                    '__oauth__': {
                        'type': 'oauth',
                        'scopes': _oauth_scopes
                    }
                })(self.response(
                    code=HTTPStatus.UNAUTHORIZED.value,
                    description=(
                        'Authentication is required' if not oauth_scopes else
                        'Authentication with %s OAuth scope(s) is required' %
                        (', '.join(oauth_scopes))),
                )(oauth_protected_func))