Python http.HTTPStatus.FORBIDDEN Examples

The following are 30 code examples of http.HTTPStatus.FORBIDDEN(). 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 http.HTTPStatus , or try the search function .
Example #1
Source File: decorators.py    From flask-react-spa with MIT License 6 votes vote down vote up
def anonymous_user_required(*args, **kwargs):
    """Decorator requiring no user be logged in

    Aborts with HTTP 403: Forbidden if there is an authenticated user
    """
    def wrapper(fn):
        @wraps(fn)
        def decorated(*args, **kwargs):
            if current_user.is_authenticated:
                abort(HTTPStatus.FORBIDDEN)
            return fn(*args, **kwargs)
        return decorated

    if was_decorated_without_parenthesis(args):
        return wrapper(args[0])

    return wrapper 
Example #2
Source File: test_machines.py    From python-libmaas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test__enter_rescue_mode_operation_not_allowed(self):
        machine = make_machines_origin().Machine(
            {
                "system_id": make_name_without_spaces("system-id"),
                "hostname": make_name_without_spaces("hostname"),
            }
        )
        # Mock the call to content.decode in the CallError constructor
        content = Mock()
        content.decode = Mock(return_value="")
        machine._handler.rescue_mode.side_effect = CallError(
            request={"method": "GET", "uri": "www.example.com"},
            response=Mock(status=HTTPStatus.FORBIDDEN),
            content=content,
            call="",
        )
        self.assertRaises(OperationNotAllowed, machine.enter_rescue_mode) 
Example #3
Source File: anonymous_user_required.py    From flask-unchained with MIT License 6 votes vote down vote up
def anonymous_user_required(*decorator_args, msg=None, category=None, redirect_url=None):
    """
    Decorator requiring that there is no user currently logged in.

    Aborts with ``HTTP 403: Forbidden`` if there is an authenticated user.
    """
    def wrapper(fn):
        @wraps(fn)
        def decorated(*args, **kwargs):
            if current_user.is_authenticated:
                if request.is_json:
                    abort(HTTPStatus.FORBIDDEN)
                else:
                    if msg:
                        flash(msg, category)
                    return redirect('SECURITY_POST_LOGIN_REDIRECT_ENDPOINT',
                                    override=redirect_url)
            return fn(*args, **kwargs)
        return decorated

    if decorator_args and callable(decorator_args[0]):
        return wrapper(decorator_args[0])
    return wrapper 
Example #4
Source File: test_drivers_minio.py    From cloudstorage with MIT License 6 votes vote down vote up
def test_container_generate_upload_url_expiration(container, text_stream):
    form_post = container.generate_upload_url(settings.TEXT_FORM_FILENAME, expires=1)
    assert "url" in form_post and "fields" in form_post
    assert uri_validator(form_post["url"])

    sleep(1.1)  # cannot generate a policy with -1 value

    url = form_post["url"]
    fields = form_post["fields"]
    multipart_form_data = {"file": text_stream}
    response = requests.post(url, data=fields, files=multipart_form_data)

    if "s3" in container.driver.client._endpoint_url:
        http_code = HTTPStatus.FORBIDDEN
    else:  # minio server
        http_code = HTTPStatus.BAD_REQUEST

    assert response.status_code == http_code, response.text 
Example #5
Source File: decorators.py    From flask-react-spa with MIT License 5 votes vote down vote up
def roles_accepted(*roles):
    """Decorator which specifies that a user must have at least one of the
    specified roles.

    Aborts with HTTP: 403 if the user doesn't have at least one of the roles

    Example::

        @app.route('/create_post')
        @roles_accepted('ROLE_ADMIN', 'ROLE_EDITOR')
        def create_post():
            return 'Create Post'

    The current user must have either the `ROLE_ADMIN` role or `ROLE_EDITOR`
    role in order to view the page.

    :param args: The possible roles.
    """
    def wrapper(fn):
        @wraps(fn)
        def decorated_view(*args, **kwargs):
            perm = Permission(*[RoleNeed(role) for role in roles])
            if not perm.can():
                abort(HTTPStatus.FORBIDDEN)
            return fn(*args, **kwargs)
        return decorated_view
    return wrapper 
Example #6
Source File: decorators.py    From flask-react-spa with MIT License 5 votes vote down vote up
def roles_required(*roles):
    """Decorator which specifies that a user must have all the specified roles.

    Aborts with HTTP 403: Forbidden if the user doesn't have the required roles

    Example::

        @app.route('/dashboard')
        @roles_required('ROLE_ADMIN', 'ROLE_EDITOR')
        def dashboard():
            return 'Dashboard'

    The current user must have both the `ROLE_ADMIN` and `ROLE_EDITOR` roles
    in order to view the page.

    :param args: The required roles.
    """
    def wrapper(fn):
        @wraps(fn)
        def decorated_view(*args, **kwargs):
            perms = [Permission(RoleNeed(role)) for role in roles]
            for perm in perms:
                if not perm.can():
                    abort(HTTPStatus.FORBIDDEN)
            return fn(*args, **kwargs)
        return decorated_view
    return wrapper 
Example #7
Source File: security.py    From flask-react-spa with MIT License 5 votes vote down vote up
def _handle_view(self, name, **kwargs):
        if not self.is_accessible():
            if not user.is_authenticated:
                return redirect(url_for('security.login', next=request.url))
            abort(HTTPStatus.FORBIDDEN) 
Example #8
Source File: machines.py    From python-libmaas with GNU Affero General Public License v3.0 5 votes vote down vote up
def enter_rescue_mode(self, wait: bool = False, wait_interval: int = 5):
        """
        Send this machine into 'rescue mode'.

        :param wait: If specified, wait until the deploy is complete.
        :param wait_interval: How often to poll, defaults to 5 seconds
        """
        try:
            self._reset(await self._handler.rescue_mode(system_id=self.system_id))
        except CallError as error:
            if error.status == HTTPStatus.FORBIDDEN:
                message = "Not allowed to enter rescue mode"
                raise OperationNotAllowed(message) from error
            else:
                raise

        if not wait:
            return self
        else:
            # Wait for machine to finish entering rescue mode
            while self.status == NodeStatus.ENTERING_RESCUE_MODE:
                await asyncio.sleep(wait)
                self._reset(await self._handler.read(system_id=self.system_id))
            if self.status == NodeStatus.FAILED_ENTERING_RESCUE_MODE:
                msg = "{hostname} failed to enter rescue mode.".format(
                    hostname=self.hostname
                )
                raise RescueModeFailure(msg, self)
            return self 
Example #9
Source File: machines.py    From python-libmaas with GNU Affero General Public License v3.0 5 votes vote down vote up
def exit_rescue_mode(self, wait: bool = False, wait_interval: int = 5):
        """
        Exit rescue mode.

        :param wait: If specified, wait until the deploy is complete.
        :param wait_interval: How often to poll, defaults to 5 seconds
        """
        try:
            self._reset(await self._handler.exit_rescue_mode(system_id=self.system_id))
        except CallError as error:
            if error.status == HTTPStatus.FORBIDDEN:
                message = "Not allowed to exit rescue mode."
                raise OperationNotAllowed(message) from error
            else:
                raise
        if not wait:
            return self
        else:
            # Wait for machine to finish exiting rescue mode
            while self.status == NodeStatus.EXITING_RESCUE_MODE:
                await asyncio.sleep(wait_interval)
                self._reset(await self._handler.read(system_id=self.system_id))
            if self.status == NodeStatus.FAILED_EXITING_RESCUE_MODE:
                msg = "{hostname} failed to exit rescue mode.".format(
                    hostname=self.hostname
                )
                raise RescueModeFailure(msg, self)
            return self 
Example #10
Source File: machines.py    From python-libmaas with GNU Affero General Public License v3.0 5 votes vote down vote up
def power_on(
        self, comment: str = None, wait: bool = False, wait_interval: int = 5
    ):
        """
        Power on.

        :param comment: Reason machine was powered on.
        :type comment: `str`
        :param wait: If specified, wait until the machine is powered on.
        :type wait: `bool`
        :param wait_interval: How often to poll, defaults to 5 seconds.
        :type wait_interval: `int`
        """
        params = {"system_id": self.system_id}
        if comment is not None:
            params["comment"] = comment
        try:
            self._reset(await self._handler.power_on(**params))
        except CallError as error:
            if error.status == HTTPStatus.FORBIDDEN:
                message = "Not allowed to power on machine."
                raise OperationNotAllowed(message) from error
            else:
                raise
        if not wait or self.power_state == PowerState.UNKNOWN:
            # Don't wait for a machine that always shows power state as
            # unknown as the driver cannot query the power state.
            return self
        else:
            # Wait for machine to be powered on.
            while self.power_state == PowerState.OFF:
                await asyncio.sleep(wait_interval)
                self._reset(await self._handler.read(system_id=self.system_id))
            if self.power_state == PowerState.ERROR:
                msg = "{hostname} failed to power on.".format(hostname=self.hostname)
                raise PowerError(msg, self)
            return self 
Example #11
Source File: test_github.py    From Kiwi with GNU General Public License v2.0 5 votes vote down vote up
def test_missing_signature_header(self):
        request = self.factory.post(self.url)
        result = github.verify_signature(request, b'')

        self.assertIsInstance(result, HttpResponseForbidden)
        self.assertEqual(HTTPStatus.FORBIDDEN, result.status_code) 
Example #12
Source File: test_github.py    From Kiwi with GNU General Public License v2.0 5 votes vote down vote up
def test_invalid_signature_header(self):
        request = self.factory.post(self.url)
        request.META['HTTP_X_HUB_SIGNATURE'] = 'invalid-ssh1'
        result = github.verify_signature(request, b'')

        self.assertIsInstance(result, HttpResponseForbidden)
        self.assertEqual(HTTPStatus.FORBIDDEN, result.status_code) 
Example #13
Source File: test_admin.py    From Kiwi with GNU General Public License v2.0 5 votes vote down vote up
def test_non_admin_cant_see_list_of_all_users(self):
        response = self.client.get('/admin/auth/user/')
        self.assertEqual(HTTPStatus.FORBIDDEN, response.status_code) 
Example #14
Source File: test_admin.py    From Kiwi with GNU General Public License v2.0 5 votes vote down vote up
def test_non_admin_cant_delete_others(self):
        response = self.client.get('/admin/auth/user/%d/delete/' % self.admin.pk)
        self.assertEqual(HTTPStatus.FORBIDDEN, response.status_code) 
Example #15
Source File: test_admin.py    From Kiwi with GNU General Public License v2.0 5 votes vote down vote up
def test_regular_user_should_not_delete_another_user(self):
        self.client.login(  # nosec:B106:hardcoded_password_funcarg
            username=self.regular_user.username,
            password='password')
        response = self.client.get(reverse('admin:auth_user_delete', args=[self.superuser.pk]))

        # it is not possible to delete other user accounts
        self.assertEqual(HTTPStatus.FORBIDDEN, response.status_code) 
Example #16
Source File: wsgi.py    From pywebview with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def do_403(environ, start_response):
    """
    Generic app to produce a 403
    """
    urlpath = environ['SCRIPT_NAME'] + environ['PATH_INFO']

    return send_simple_text(
        environ, start_response, HTTPStatus.FORBIDDEN, "Path {} is not allowed.".format(urlpath),
    ) 
Example #17
Source File: test_drivers_minio.py    From cloudstorage with MIT License 5 votes vote down vote up
def test_blob_generate_download_url_expiration(binary_blob):
    download_url = binary_blob.generate_download_url(expires=1)
    assert uri_validator(download_url)

    sleep(1.1)  # cannot generate a policy with -1 value

    response = requests.get(download_url)
    assert response.status_code == HTTPStatus.FORBIDDEN, response.text 
Example #18
Source File: test_drivers_amazon.py    From cloudstorage with MIT License 5 votes vote down vote up
def test_container_generate_upload_url_expiration(container, text_stream):
    form_post = container.generate_upload_url(settings.TEXT_FORM_FILENAME, expires=-10)
    assert "url" in form_post and "fields" in form_post
    assert uri_validator(form_post["url"])

    url = form_post["url"]
    fields = form_post["fields"]
    multipart_form_data = {"file": text_stream}
    response = requests.post(url, data=fields, files=multipart_form_data)
    assert response.status_code == HTTPStatus.FORBIDDEN, response.text 
Example #19
Source File: test_drivers_amazon.py    From cloudstorage with MIT License 5 votes vote down vote up
def test_blob_generate_download_url_expiration(binary_blob):
    download_url = binary_blob.generate_download_url(expires=-10)
    assert uri_validator(download_url)

    response = requests.get(download_url)
    assert response.status_code == HTTPStatus.FORBIDDEN, response.text 
Example #20
Source File: test_drivers_microsoft.py    From cloudstorage with MIT License 5 votes vote down vote up
def test_blob_generate_download_url_expiration(binary_blob):
    download_url = binary_blob.generate_download_url(expires=-10)
    assert uri_validator(download_url)

    response = requests.get(download_url)
    assert response.status_code == HTTPStatus.FORBIDDEN, response.text 
Example #21
Source File: test_account.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_rejects_unknown_username(self):
        username = factory.make_name("username")
        password = factory.make_name("password")
        response = self.client.post(
            reverse("authenticate"),
            data={"username": username, "password": password},
        )
        self.assertThat(response, HasStatusCode(HTTPStatus.FORBIDDEN)) 
Example #22
Source File: test_account.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_rejects_incorrect_password(self):
        username = factory.make_name("username")
        password = factory.make_name("password")
        factory.make_User(username, password)
        response = self.client.post(
            reverse("authenticate"),
            data={"username": username, "password": password + "-garbage"},
        )
        self.assertThat(response, HasStatusCode(HTTPStatus.FORBIDDEN)) 
Example #23
Source File: test_account.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_rejects_inactive_user(self):
        username = factory.make_name("username")
        password = factory.make_name("password")
        user = factory.make_User(username, password)
        user.is_active = False
        user.save()
        response = self.client.post(
            reverse("authenticate"),
            data={"username": username, "password": password},
        )
        self.assertThat(response, HasStatusCode(HTTPStatus.FORBIDDEN)) 
Example #24
Source File: test_account.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_forbidden_when_not_authenticated(self):
        response = self.client.post(reverse("csrf"))
        self.assertThat(response, HasStatusCode(HTTPStatus.FORBIDDEN)) 
Example #25
Source File: http.py    From galaxy-integrations-python-api with MIT License 5 votes vote down vote up
def handle_exception():
    """
    Context manager translating network related exceptions
    to custom :mod:`~galaxy.api.errors`.
    """
    try:
        yield
    except asyncio.TimeoutError:
        raise BackendTimeout()
    except aiohttp.ServerDisconnectedError:
        raise BackendNotAvailable()
    except aiohttp.ClientConnectionError:
        raise NetworkError()
    except aiohttp.ContentTypeError as error:
        raise UnknownBackendResponse(error.message)
    except aiohttp.ClientResponseError as error:
        if error.status == HTTPStatus.UNAUTHORIZED:
            raise AuthenticationRequired(error.message)
        if error.status == HTTPStatus.FORBIDDEN:
            raise AccessDenied(error.message)
        if error.status == HTTPStatus.SERVICE_UNAVAILABLE:
            raise BackendNotAvailable(error.message)
        if error.status == HTTPStatus.TOO_MANY_REQUESTS:
            raise TooManyRequests(error.message)
        if error.status >= 500:
            raise BackendError(error.message)
        if error.status >= 400:
            logger.warning(
                "Got status %d while performing %s request for %s",
                error.status, error.request_info.method, str(error.request_info.url)
            )
            raise UnknownError(error.message)
    except aiohttp.ClientError as e:
        logger.exception("Caught exception while performing request")
        raise UnknownError(repr(e)) 
Example #26
Source File: client.py    From acm-sdk-python with Apache License 2.0 5 votes vote down vote up
def remove(self, data_id, group, timeout=None):
        """ Remove one data item from ACM.

        :param data_id: dataId.
        :param group: group, use "DEFAULT_GROUP" if no group specified.
        :param timeout: timeout for requesting server in seconds.
        :return: True if success or an exception will be raised.
        """
        data_id, group = process_common_params(data_id, group)
        logger.info(
            "[remove] data_id:%s, group:%s, namespace:%s, timeout:%s" % (data_id, group, self.namespace, timeout))

        params = {
            "dataId": data_id,
            "group": group,
        }
        if self.namespace:
            params["tenant"] = self.namespace

        try:
            resp = self._do_sync_req("/diamond-server/datum.do?method=deleteAllDatums", None, None, params,
                                     timeout or self.default_timeout)
            logger.info("[remove] success to remove group:%s, data_id:%s, server response:%s" % (
                group, data_id, resp.read()))
            return True
        except HTTPError as e:
            if e.code == HTTPStatus.FORBIDDEN:
                logger.error(
                    "[remove] no right for namespace:%s, group:%s, data_id:%s" % (self.namespace, group, data_id))
                raise ACMException("Insufficient privilege.")
            else:
                logger.error("[remove] error code [:%s] for namespace:%s, group:%s, data_id:%s" % (
                    e.code, self.namespace, group, data_id))
                raise ACMException("Request Error, code is %s" % e.code)
        except Exception as e:
            logger.exception("[remove] exception %s occur" % str(e))
            raise 
Example #27
Source File: client.py    From acm-sdk-python with Apache License 2.0 5 votes vote down vote up
def list(self, page=1, size=200):
        """ Get config items of current namespace with content included.

        Data is directly from acm server.

        :param page: which page to query, starts from 1.
        :param size: page size.
        :return:
        """
        logger.info("[list] try to list namespace:%s" % self.namespace)

        params = {
            "pageNo": page,
            "pageSize": size,
            "method": "getAllConfigByTenant",
        }

        if self.namespace:
            params["tenant"] = self.namespace

        try:
            resp = self._do_sync_req("/diamond-server/basestone.do", None, params, None, self.default_timeout)
            d = resp.read()
            if isinstance(d, bytes):
                d = d.decode("utf8")
            return json.loads(d)
        except HTTPError as e:
            if e.code == HTTPStatus.FORBIDDEN:
                logger.error("[list] no right for namespace:%s" % self.namespace)
                raise ACMException("Insufficient privilege.")
            else:
                logger.error("[list] error code [%s] for namespace:%s" % (e.code, self.namespace))
                raise ACMException("Request Error, code is %s" % e.code)
        except Exception as e:
            logger.exception("[list] exception %s occur" % str(e))
            raise 
Example #28
Source File: decorators.py    From flask-react-spa with MIT License 5 votes vote down vote up
def auth_required_same_user(*args, **kwargs):
    """Decorator for requiring an authenticated user to be the same as the
    user in the URL parameters. By default the user url parameter name to
    lookup is 'id', but this can be customized by passing an argument:

    @auth_require_same_user('user_id')
    @bp.route('/users/<int:user_id>/foo/<int:id>')
    def get(user_id, id):
        # do stuff

    Any keyword arguments are passed along to the @auth_required decorator,
    so roles can also be specified in the same was as it, eg:
    @auth_required_same_user('user_id', role='ROLE_ADMIN')

    Aborts with HTTP 403: Forbidden if the user-check fails
    """
    auth_kwargs = {}
    user_id_parameter_name = 'id'
    if not was_decorated_without_parenthesis(args):
        auth_kwargs = kwargs
        if args and isinstance(args[0], str):
            user_id_parameter_name = args[0]

    def wrapper(fn):
        @wraps(fn)
        @auth_required(**auth_kwargs)
        def decorated(*args, **kwargs):
            try:
                user_id = request.view_args[user_id_parameter_name]
            except KeyError:
                raise KeyError('Unable to find the user lookup parameter '
                               f'{user_id_parameter_name} in the url args')
            if not Permission(UserNeed(user_id)).can():
                abort(HTTPStatus.FORBIDDEN)
            return fn(*args, **kwargs)
        return decorated

    if was_decorated_without_parenthesis(args):
        return wrapper(args[0])
    return wrapper 
Example #29
Source File: login_required_example.py    From aiohttp-session with Apache License 2.0 5 votes vote down vote up
def login(request):
    router = request.app.router
    form = await request.post()
    user_signature = (form['name'], form['password'])

    # actually implement business logic to check user credentials
    try:
        user_id = DATABASE.index(user_signature)
        # Always use `new_session` during login to guard against
        # Session Fixation. See aiohttp-session#281
        session = await new_session(request)
        session['user_id'] = user_id
        return web.HTTPFound(router['restricted'].url_for())
    except ValueError:
        return web.Response(text='No such user', status=HTTPStatus.FORBIDDEN) 
Example #30
Source File: unittest.py    From hutils with MIT License 5 votes vote down vote up
def forbidden(self, response, **kwargs):
        """ shortcuts to response 403 """
        self.assertEqual(HTTPStatus.FORBIDDEN, response.status_code, "status code should be 403")
        if kwargs:
            self.assert_same(response.data, **kwargs)
        return self