Python aiohttp.web.HTTPForbidden() Examples

The following are 30 code examples of aiohttp.web.HTTPForbidden(). 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 aiohttp.web , or try the search function .
Example #1
Source File: jwt.py    From dvhb-hybrid with MIT License 49224 votes vote down vote up
def user_login(request, email, password, connection=None):
    models = request.app.models
    user = await models.user.get_user_by_email(email, connection=connection)
    if user:
        if not user.is_active:
            raise web.HTTPForbidden(reason="User disabled")
        elif check_password(password, user.password):
            await models.user_action_log_entry.create_login(
                request, user_id=user.pk, connection=connection)
            token = request.app.context.jwt.generate(uid=user.id)
            return web.json_response(
                {
                    'uid': user.id,
                    'profile': await user.get_profile(connection=connection),
                    'token': token,
                }, headers={'Authorization': 'Bearer %s' % token},
            )
    raise web.HTTPUnauthorized(reason="Login incorrect") 
Example #2
Source File: routes.py    From aries-cloudagent-python with Apache License 2.0 6 votes vote down vote up
def actionmenu_request(request: web.BaseRequest):
    """
    Request handler for requesting a menu from the connection target.

    Args:
        request: aiohttp request object

    """
    context = request.app["request_context"]
    connection_id = request.match_info["conn_id"]
    outbound_handler = request.app["outbound_message_router"]

    try:
        connection = await ConnectionRecord.retrieve_by_id(context, connection_id)
    except StorageNotFoundError as err:
        LOGGER.debug("Connection not found for action menu request: %s", connection_id)
        raise web.HTTPNotFound(reason=err.roll_up) from err

    if connection.is_ready:
        msg = MenuRequest()
        await outbound_handler(msg, connection_id=connection_id)
        return web.json_response({})

    raise web.HTTPForbidden(reason=f"Connection {connection_id} not ready") 
Example #3
Source File: test_routes.py    From aries-cloudagent-python with Apache License 2.0 6 votes vote down vote up
def test_missing_wallet(self):
        request = async_mock.MagicMock()
        request.app = self.app
        self.context.injector.clear_binding(BaseWallet)

        with self.assertRaises(HTTPForbidden):
            await test_module.wallet_create_did(request)

        with self.assertRaises(HTTPForbidden):
            await test_module.wallet_did_list(request)

        with self.assertRaises(HTTPForbidden):
            await test_module.wallet_get_public_did(request)

        with self.assertRaises(HTTPForbidden):
            await test_module.wallet_set_public_did(request)

        with self.assertRaises(HTTPForbidden):
            await test_module.wallet_set_did_endpoint(request)

        with self.assertRaises(HTTPForbidden):
            await test_module.wallet_get_did_endpoint(request) 
Example #4
Source File: test_routes.py    From aries-cloudagent-python with Apache License 2.0 6 votes vote down vote up
def test_set_did_endpoint_public_did_no_ledger(self):
        request = async_mock.MagicMock()
        request.app = self.app
        request.json = async_mock.CoroutineMock(
            return_value={
                "did": self.test_did,
                "endpoint": "https://my-endpoint.ca:8020",
            }
        )

        self.wallet.get_local_did.return_value = DIDInfo(
            self.test_did,
            self.test_verkey,
            {"public": False, "endpoint": "http://old-endpoint.ca"},
        )
        self.wallet.get_public_did.return_value = DIDInfo(
            self.test_did, self.test_verkey, {}
        )

        with self.assertRaises(test_module.web.HTTPForbidden):
            await test_module.wallet_set_did_endpoint(request) 
Example #5
Source File: routes.py    From aries-cloudagent-python with Apache License 2.0 6 votes vote down vote up
def wallet_create_did(request: web.BaseRequest):
    """
    Request handler for creating a new local DID in the wallet.

    Args:
        request: aiohttp request object

    Returns:
        The DID info

    """
    context = request.app["request_context"]
    wallet: BaseWallet = await context.inject(BaseWallet, required=False)
    if not wallet:
        raise web.HTTPForbidden(reason="No wallet available")
    try:
        info = await wallet.create_local_did()
    except WalletError as err:
        raise web.HTTPBadRequest(reason=err.roll_up) from err

    return web.json_response({"result": format_did_info(info)}) 
Example #6
Source File: public.py    From mautrix-facebook with GNU Affero General Public License v3.0 6 votes vote down vote up
def check_token(self, request: web.Request) -> Optional['u.User']:
        try:
            token = request.headers["Authorization"]
            token = token[len("Bearer "):]
        except KeyError:
            raise web.HTTPBadRequest(body='{"error": "Missing Authorization header"}',
                                     headers=self._headers)
        except IndexError:
            raise web.HTTPBadRequest(body='{"error": "Malformed Authorization header"}',
                                     headers=self._headers)
        if self.shared_secret and token == self.shared_secret:
            try:
                user_id = request.query["user_id"]
            except KeyError:
                raise web.HTTPBadRequest(body='{"error": "Missing user_id query param"}',
                                         headers=self._headers)
        else:
            user_id = self.verify_token(token)
            if not user_id:
                raise web.HTTPForbidden(body='{"error": "Invalid token"}', headers=self._headers)

        user = u.User.get_by_mxid(user_id)
        return user 
Example #7
Source File: security.py    From lbry-sdk with MIT License 6 votes vote down vote up
def ensure_request_allowed(request, conf):
    if is_request_allowed(request, conf):
        return
    if conf.allowed_origin:
        log.warning(
            "API requests with Origin '%s' are not allowed, "
            "configuration 'allowed_origin' limits requests to: '%s'",
            request.headers.get('Origin'), conf.allowed_origin
        )
    else:
        log.warning(
            "API requests with Origin '%s' are not allowed, "
            "update configuration 'allowed_origin' to enable this origin.",
            request.headers.get('Origin')
        )
    raise web.HTTPForbidden() 
Example #8
Source File: preflight_handler.py    From aiohttp-cors with Apache License 2.0 6 votes vote down vote up
def _parse_request_headers(request: web.Request):
        """Parse Access-Control-Request-Headers header or the preflight request

        Returns set of headers in upper case.
        """
        headers = request.headers.get(hdrs.ACCESS_CONTROL_REQUEST_HEADERS)
        if headers is None:
            return frozenset()

        # FIXME: validate each header string, if parsing fails, raise
        # HTTPForbidden.
        # FIXME: check, that headers split and stripped correctly (according
        # to ABNF).
        headers = (h.strip(" \t").upper() for h in headers.split(","))
        # pylint: disable=bad-builtin
        return frozenset(filter(None, headers)) 
Example #9
Source File: routes.py    From aries-cloudagent-python with Apache License 2.0 6 votes vote down vote up
def actionmenu_perform(request: web.BaseRequest):
    """
    Request handler for performing a menu action.

    Args:
        request: aiohttp request object

    """
    context = request.app["request_context"]
    connection_id = request.match_info["conn_id"]
    outbound_handler = request.app["outbound_message_router"]
    params = await request.json()

    try:
        connection = await ConnectionRecord.retrieve_by_id(context, connection_id)
    except StorageNotFoundError as err:
        raise web.HTTPNotFound(reason=err.roll_up) from err

    if connection.is_ready:
        msg = Perform(name=params["name"], params=params.get("params"))
        await outbound_handler(msg, connection_id=connection_id)
        return web.json_response({})

    raise web.HTTPForbidden(reason=f"Connection {connection_id} not ready") 
Example #10
Source File: routes.py    From dask-gateway with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def adapt_cluster(request):
    user = request["user"]
    cluster_name = request.match_info["cluster_name"]
    backend = request.app["backend"]
    cluster = await backend.get_cluster(cluster_name)
    if cluster is None:
        raise web.HTTPNotFound(reason=f"Cluster {cluster_name} not found")
    if not user.has_permissions(cluster):
        raise web.HTTPForbidden(
            reason=f"User {user.name} lacks permissions to view cluster {cluster_name}"
        )

    msg = await request.json()
    minimum = msg.get("minimum", None)
    maximum = msg.get("maximum", None)
    active = msg.get("active", True)

    try:
        await backend.forward_message_to_scheduler(
            cluster,
            {"op": "adapt", "minimum": minimum, "maximum": maximum, "active": active},
        )
    except PublicException as exc:
        raise web.HTTPConflict(reason=str(exc))
    return web.Response() 
Example #11
Source File: server.py    From RPGBot with GNU General Public License v3.0 6 votes vote down vote up
def getguild(self, request: web.Request):
        guild = int(request.match_info['guild'])
        req = f"""SELECT info FROM guilddata WHERE UUID = $1"""
        async with self.bot.db._conn.acquire() as connection:
            response = await connection.fetchval(req, guild)
        if response:
            data = json.loads(response)

            fdata = data
            if request.match_info['tail']:
                for item in request.match_info['tail'].split("/"):
                    if not item:
                        continue
                    try:
                        key = unquote(item)
                        if isinstance(fdata, list):
                            key = int(key)
                        fdata = fdata[key]
                    except:
                        raise web.HTTPNotFound()

            return web.json_response(fdata)
        raise web.HTTPForbidden()

    # @server.route("/", methods=["GET"]) 
Example #12
Source File: routes.py    From aries-cloudagent-python with Apache License 2.0 6 votes vote down vote up
def rotate_public_did_keypair(request: web.BaseRequest):
    """
    Request handler for rotating key pair associated with public DID.

    Args:
        request: aiohttp request object
    """
    context = request.app["request_context"]
    ledger = await context.inject(BaseLedger, required=False)
    if not ledger:
        reason = "No ledger available"
        if not context.settings.get_value("wallet.type"):
            reason += ": missing wallet-type?"
        raise web.HTTPForbidden(reason=reason)
    async with ledger:
        try:
            await ledger.rotate_public_did_keypair()  # do not take seed over the wire
        except (WalletError, BadLedgerRequestError) as err:
            raise web.HTTPBadRequest(reason=err.roll_up) from err

    return web.json_response({}) 
Example #13
Source File: test_aiohttp.py    From sentry-python with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_403_not_captured(sentry_init, aiohttp_client, loop, capture_events):
    sentry_init(integrations=[AioHttpIntegration()])

    async def hello(request):
        raise web.HTTPForbidden()

    app = web.Application()
    app.router.add_get("/", hello)

    events = capture_events()

    client = await aiohttp_client(app)
    resp = await client.get("/")
    assert resp.status == 403

    assert not events 
Example #14
Source File: views.py    From bioconda-utils with MIT License 6 votes vote down vote up
def check_permission(request, permission, context=None):
    """Checks permissions

    Custom implementation replacing aiohttp-security one. This one
    adds the requested permissions to the request so they can
    be presented in the error handler.

    Raises:
      HTTPForbidden
    """

    await check_authorized(request)
    allowed = await permits(request, permission, context)
    if not allowed:
        request['permission_required'] = permission
        raise web.HTTPForbidden() 
Example #15
Source File: test_mixin.py    From aiohttp-cors with Apache License 2.0 5 votes vote down vote up
def test_raises_forbidden_when_config_not_found(app):
    app[APP_CONFIG_KEY].defaults = {}
    request = mock.Mock()
    request.app = app
    request.headers = {
        'Origin': '*',
        'Access-Control-Request-Method': 'GET'
    }
    view = SimpleView(request)

    with pytest.raises(web.HTTPForbidden):
        await view.options() 
Example #16
Source File: jwt.py    From dvhb-hybrid with MIT License 5 votes vote down vote up
def user_change_password_by_request(request, new_password, connection=None):
    session = request.session
    email = session.get('email')
    if not email or not session.get('log_id'):
        raise web.HTTPForbidden()
    m = request.app.m
    user = await m.user.get_user_by_email(email, silent=False, connection=connection)
    log = await m.user_action_log_entry.get_one(session.get('log_id'), connection=connection)
    if log.status == UserActionLogStatus.done.value:
        raise web.HTTPForbidden()
    user['password'] = make_password(new_password)
    await user.save(fields=['password'], connection=connection)
    log['status'] = UserActionLogStatus.done.value
    await log.save(fields=['status'], connection=connection) 
Example #17
Source File: test_routes.py    From aries-cloudagent-python with Apache License 2.0 5 votes vote down vote up
def test_rotate_did_keypair_missing_wallet(self):
        request = async_mock.MagicMock()
        request.app = self.app
        request.query = {"did": "did"}
        self.context.injector.clear_binding(BaseWallet)

        with self.assertRaises(HTTPForbidden):
            await test_module.wallet_rotate_did_keypair(request) 
Example #18
Source File: web.py    From kube-web-view with GNU General Public License v3.0 5 votes vote down vote up
def validate_namespace(namespace: str, request):
    if namespace and namespace != ALL and not filter_namespaces([namespace], request):
        raise web.HTTPForbidden(
            text="Access to this Namespace was denied by configuration"
        ) 
Example #19
Source File: decorators.py    From aiohttp-login with ISC License 5 votes vote down vote up
def admin_required(handler):
    @wraps(handler)
    async def decorator(*args):
        request = _get_request(args)
        response = await login_required(handler)(request)
        if request['user']['email'] not in cfg.ADMIN_EMAILS:
            raise HTTPForbidden(reason='You are not admin')
        return response
    return decorator 
Example #20
Source File: test_allowed_origin.py    From lbry-sdk with MIT License 5 votes vote down vote up
def test_ensure_default(self):
        conf = Config()
        ensure(request('GET', '/'), conf)
        with self.assertLogs() as log:
            with self.assertRaises(HTTPForbidden):
                ensure(request('GET', '/', headers={'Origin': 'localhost'}), conf)
            self.assertIn("'localhost' are not allowed", log.output[0]) 
Example #21
Source File: test_allowed_origin.py    From lbry-sdk with MIT License 5 votes vote down vote up
def test_ensure_specific(self):
        conf = Config(allowed_origin='localhost')
        ensure(request('GET', '/', headers={'Origin': 'localhost'}), conf)
        with self.assertLogs() as log:
            with self.assertRaises(HTTPForbidden):
                ensure(request('GET', '/', headers={'Origin': 'hackers.com'}), conf)
            self.assertIn("'hackers.com' are not allowed", log.output[0])
            self.assertIn("'allowed_origin' limits requests to: 'localhost'", log.output[0]) 
Example #22
Source File: engine.py    From bottery with MIT License 5 votes vote down vote up
def verify_webhook(self, request):
        hub_mode = request.query.get('hub.mode')
        verify_token = request.query.get('hub.verify_token')
        secret_key = settings.SECRET_KEY

        if hub_mode and verify_token:
            if hub_mode == 'subscribe' and verify_token == secret_key:
                return web.Response(text=request.query['hub.challenge'])

            return web.HTTPForbidden() 
Example #23
Source File: preflight_handler.py    From aiohttp-cors with Apache License 2.0 5 votes vote down vote up
def _parse_request_method(request: web.Request):
        """Parse Access-Control-Request-Method header of the preflight request
        """
        method = request.headers.get(hdrs.ACCESS_CONTROL_REQUEST_METHOD)
        if method is None:
            raise web.HTTPForbidden(
                text="CORS preflight request failed: "
                     "'Access-Control-Request-Method' header is not specified")

        # FIXME: validate method string (ABNF: method = token), if parsing
        # fails, raise HTTPForbidden.

        return method 
Example #24
Source File: example.py    From transmute-core with MIT License 5 votes vote down vote up
def error(request):
    raise HTTPForbidden(reason="unauthorized") 
Example #25
Source File: api.py    From aiohttp-security with Apache License 2.0 5 votes vote down vote up
def check_permission(request, permission, context=None):
    """Checker that passes only to authoraised users with given permission.

    If user is not authorized - raises HTTPUnauthorized,
    if user is authorized and does not have permission -
    raises HTTPForbidden.
    """

    await check_authorized(request)
    allowed = await permits(request, permission, context)
    if not allowed:
        raise web.HTTPForbidden() 
Example #26
Source File: api.py    From aiohttp-security with Apache License 2.0 5 votes vote down vote up
def has_permission(
    permission,
    context=None,
):
    """Decorator that restricts access only for authorized users
    with correct permissions.

    If user is not authorized - raises HTTPUnauthorized,
    if user is authorized and does not have permission -
    raises HTTPForbidden.
    """
    def wrapper(fn):
        @wraps(fn)
        async def wrapped(*args, **kwargs):
            request = args[-1]
            if not isinstance(request, web.BaseRequest):
                msg = ("Incorrect decorator usage. "
                       "Expecting `def handler(request)` "
                       "or `def handler(self, request)`.")
                raise RuntimeError(msg)

            await check_permission(request, permission, context)
            return await fn(*args, **kwargs)

        return wrapped

    warnings.warn("has_permission decorator is deprecated, "
                  "use check_permission instead",
                  DeprecationWarning)
    return wrapper 
Example #27
Source File: test_context_processors.py    From aiohttp-jinja2 with Apache License 2.0 5 votes vote down vote up
def test_context_is_response(aiohttp_client):

    @aiohttp_jinja2.template('tmpl.jinja2')
    async def func(request):
        raise web.HTTPForbidden()

    app = web.Application()
    aiohttp_jinja2.setup(app, loader=jinja2.DictLoader(
        {'tmpl.jinja2': "template"}))

    app.router.add_route('GET', '/', func)
    client = await aiohttp_client(app)

    resp = await client.get('/')
    assert 403 == resp.status 
Example #28
Source File: routes.py    From dask-gateway with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_cluster(request):
    user = request["user"]
    cluster_name = request.match_info["cluster_name"]
    backend = request.app["backend"]
    wait = request.query.get("wait")
    wait = _parse_query_flag(wait)
    cluster = await backend.get_cluster(cluster_name, wait=wait)
    if cluster is None:
        raise web.HTTPNotFound(reason=f"Cluster {cluster_name} not found")
    if not user.has_permissions(cluster):
        raise web.HTTPForbidden(
            reason=f"User {user.name} lacks permissions to view cluster {cluster_name}"
        )
    return web.json_response(cluster.to_dict()) 
Example #29
Source File: routes.py    From dask-gateway with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def delete_cluster(request):
    user = request["user"]
    cluster_name = request.match_info["cluster_name"]
    backend = request.app["backend"]
    cluster = await backend.get_cluster(cluster_name)
    if cluster is not None:
        if user is not None and not user.has_permissions(cluster):
            raise web.HTTPForbidden(
                reason=f"User {user.name} lacks permissions to stop cluster {cluster_name}"
            )
        await backend.stop_cluster(cluster_name)
    return web.Response(status=204) 
Example #30
Source File: routes.py    From dask-gateway with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def scale_cluster(request):
    user = request["user"]
    cluster_name = request.match_info["cluster_name"]
    backend = request.app["backend"]
    cluster = await backend.get_cluster(cluster_name)
    if cluster is None:
        raise web.HTTPNotFound(reason=f"Cluster {cluster_name} not found")
    if not user.has_permissions(cluster):
        raise web.HTTPForbidden(
            reason=f"User {user.name} lacks permissions to view cluster {cluster_name}"
        )

    msg = await request.json()
    count = msg.get("count", None)
    if not isinstance(count, int) or count < 0:
        raise web.HTTPUnprocessableEntity(
            reason=f"Scale expects a non-negative integer, got {count}"
        )

    try:
        await backend.forward_message_to_scheduler(
            cluster, {"op": "scale", "count": count}
        )
    except PublicException as exc:
        raise web.HTTPConflict(reason=str(exc))
    return web.Response()