Exemplo n.º 1
0
def delete_file(
    repo: Optional[str],
    package: Optional[str],
    version: Optional[str],
    filename: Optional[str],
):
    username, header = get_auth_header_and_username()
    if not username:
        return
    if not repo:
        repo = repositories.select_from_available_repo(subject=username)
    if not package:
        package = packages_core.select_from_available_packages(
            subject=username, repo=repo)
    if not version:
        version = select_from_available_versions(subject=username,
                                                 repo=repo,
                                                 package=package,
                                                 filename=filename)

    if not filename:
        filename = select_from_available_files(subject=username,
                                               repo=repo,
                                               package=package,
                                               version=version)
    print_message(f"Deleting file {filename} version {version}")
    url = get_url(f"/{username}/{repo}/{package}/{version}/{filename}")
    password = typer.prompt("Password", hide_input=True)
    response = httpx.delete(url=url,
                            auth=httpx.BasicAuth(username=username,
                                                 password=password))
    response_handler(response=response, return_model=FileDeleteResponseModel)
    return
Exemplo n.º 2
0
    async def process_login(self, code: str, request: Request) -> Optional[OpenID]:
        """This method should be called from callback endpoint to verify the user and request user info endpoint.
        This is low level, you should use {verify_and_process} instead.
        """
        logging.debug(f'redirect_uri: {self.redirect_uri}')
        current_path = f'{self.redirect_uri}?code={code}'
        logging.debug(f'current_path with query_params: {current_path}')
        if self.state is not None and self.use_state and request.query_params.get("state"):
            current_path = f'{current_path}&state={request.query_params.get("state")}'
        logging.debug(f'current_path with query_params: {current_path}')
        token_url, headers, body = self.oauth_client.prepare_token_request(
            await self.token_endpoint, authorization_response=current_path, redirect_url=self.redirect_uri, code=code
        )  # type: ignore

        if token_url is None:
            return None

        auth = httpx.BasicAuth(str(self.client_id), self.client_secret)
        async with httpx.AsyncClient() as session:
            logging.debug(f'token_url: {token_url}')
            logging.debug(f'request_body: {body}')
            response = await session.post(token_url, headers=headers, content=body, auth=auth)
            content = response.json()
            logging.debug(f'response: {content}')
            self.oauth_client.parse_request_body_response(json.dumps(content))

            uri, headers, _ = self.oauth_client.add_token(await self.userinfo_endpoint)
            logging.debug(f'userinfo_endpoint: {uri}')
            response = await session.get(uri, headers=headers)
            content = response.json()

        return await self.openid_from_response(content)
Exemplo n.º 3
0
def file_upload(repo: Optional[str], package: Optional[str], version: str,
                filename: str):
    username, header = get_auth_header_and_username()
    if not username:
        return
    if not repo:
        repo = repositories.select_from_available_repo(subject=username)
    if not package:
        package = packages_core.select_from_available_packages(
            subject=username, repo=repo)
    file_path: str = filename
    if os.path.isabs(file_path):
        filename = os.path.basename(file_path)

    url = get_url(f"/content/{username}/{repo}/{package}/{version}/{filename}")
    try:
        with open(file_path, "br") as file:
            data = file.read()
            headers = {
                "x-bintray-publish": "1",
                "content-type": "application/octet-stream",
                "x-bintray-override": "1",
            }
            headers.update(header)
            password = typer.prompt("Password", hide_input=True)
            response = httpx.put(
                url=url,
                data=data,
                headers=headers,
                auth=httpx.BasicAuth(username=username, password=password),
            )
            response_handler(response=response, return_with_out_model=True)
    except Exception as e:
        print_error(f"{e.args[0]}")
    async def zabbix_login(self):
        """ Логинится на Zabbix по главной странице """
        login_data = {
            "name": self.username,
            "password": self.password,
            "enter": "Sign in"
        }
        auth = httpx.BasicAuth(self.username, self.password)
        async with httpx.AsyncClient() as client:
            login_request = await client.post(str(self.host) + "/",
                                              data=login_data,
                                              auth=auth)

            if login_request.status_code != 200:
                self.log.warning('Login on Zabbix Failed!')
                self.log.debug(login_request.text)

            cookies = login_request.cookies
            if self.AUTH_COOKIE_NAME in cookies.keys():
                self.log.info("LOGGING SUCCESS on Zabbix Web Interface")
            else:
                self.log.warning('Authentication on Zabbix Failed!')
                self.log.debug(login_request.text)

            self.cookies = cookies
            return login_request.text
Exemplo n.º 5
0
    async def _async_generate_token(self) -> None:
        """Create authentation to use with requests."""
        cmd = "magicBox.cgi?action=getMachineName"
        _LOGGER.debug("%s Trying async Basic Authentication", self)
        self._async_token = httpx.BasicAuth(self._user, self._password)
        try:
            try:
                resp = (await self._async_command(cmd)).content.decode()
            except LoginError:
                _LOGGER.debug("%s Trying async Digest Authentication", self)
                self._async_token = httpx.DigestAuth(self._user,
                                                     self._password)
                resp = (await self._async_command(cmd)).content.decode()
        except CommError:
            self._async_token = None
            raise

        # check if user passed
        result = resp.lower()
        if "invalid" in result or "error" in result:
            _LOGGER.debug(
                "%s Result from camera: %s",
                self,
                resp.strip().replace("\r\n", ": "),
            )
            self._async_token = None
            raise LoginError("Invalid credentials")

        self._name = pretty(resp.strip())

        _LOGGER.debug("%s Retrieving serial number", self)
        self._serial = pretty(
            (await self._async_command("magicBox.cgi?action=getSerialNo")
             ).content.decode().strip())
Exemplo n.º 6
0
    def __init__(self, hass, device_info):
        """Initialize a generic camera."""
        super().__init__()
        self.hass = hass
        self._authentication = device_info.get(CONF_AUTHENTICATION)
        self._name = device_info.get(CONF_NAME)
        self._still_image_url = device_info[CONF_STILL_IMAGE_URL]
        self._stream_source = device_info.get(CONF_STREAM_SOURCE)
        self._still_image_url.hass = hass
        if self._stream_source is not None:
            self._stream_source.hass = hass
        self._limit_refetch = device_info[CONF_LIMIT_REFETCH_TO_URL_CHANGE]
        self._frame_interval = 1 / device_info[CONF_FRAMERATE]
        self._supported_features = SUPPORT_STREAM if self._stream_source else 0
        self.content_type = device_info[CONF_CONTENT_TYPE]
        self.verify_ssl = device_info[CONF_VERIFY_SSL]
        if device_info.get(CONF_RTSP_TRANSPORT):
            self.stream_options[FFMPEG_OPTION_MAP[
                CONF_RTSP_TRANSPORT]] = device_info[CONF_RTSP_TRANSPORT]

        username = device_info.get(CONF_USERNAME)
        password = device_info.get(CONF_PASSWORD)

        if username and password:
            if self._authentication == HTTP_DIGEST_AUTHENTICATION:
                self._auth = httpx.DigestAuth(username=username,
                                              password=password)
            else:
                self._auth = httpx.BasicAuth(username=username,
                                             password=password)
        else:
            self._auth = None

        self._last_url = None
        self._last_image = None
Exemplo n.º 7
0
    def refresh_token(self):
        refresh_token = self.token.get('refresh_token')

        body = self.oauth_client.prepare_refresh_body(
            body='',
            refresh_token=refresh_token,
            scope=self.scope,
            client_id=self.client_id,
            client_secret=self.client_secret)

        response = self.request(
            'POST',
            self.token_url,
            headers={
                'Accept': 'application/json',
                'Content-Type':
                'application/x-www-form-urlencoded;charset=UTF-8',
            },
            data=dict(urldecode(body)),
            auth=httpx.BasicAuth(self.client_id, self.client_secret),
            withhold_token=True)

        self.token = self.oauth_client.parse_request_body_response(
            response.text, scope=self.scope)
        if 'refresh_token' not in self.token:
            self.token['refresh_token'] = refresh_token

        return self.token
Exemplo n.º 8
0
 def _get_token__get_kwargs(self):
     return {
         "url": f"{self.base_url}/token",
         "headers": self.headers,
         "timeout": self.timeout,
         "auth": httpx.BasicAuth(username=self.user,
                                 password=self.password),
     }
Exemplo n.º 9
0
    def __init__(
        self,
        host: Optional[str] = None,
        username: Optional[str] = None,
        password: Optional[str] = None,
        proto: Optional[str] = "https",
        port=None,
        **kwargs,
    ):
        """
        Initializes the Device class.  As a subclass to httpx.AsyncClient, the
        Caller can provide any of those initializers.  Specific paramertes for
        Device class are all optional and described below.

        Parameters
        ----------
        host: Optional[str]
            The EOS target device, either hostname (DNS) or ipaddress.

        username: Optional[str]
            The login user-name; requires the password parameter.

        password: Optional[str]
            The login password; requires the username parameter.

        proto: Optional[str]
            The protocol, http or https, to communicate eAPI with the device.

        port: Optional[Union[str,int]]
            If not provided, the proto value is used to lookup the associated
            port (http=80, https=443).  If provided, overrides the port used to
            communite with the device.

        Other Parameters
        ----------------
        base_url: str
            If provided, the complete URL to the device eAPI endpoint.

        auth:
            If provided, used as the httpx authorization initializer value. If
            not provided, then username+password is assumed by the Caller and
            used to create a BasicAuth instance.
        """

        self.port = port or getservbyname(proto)
        self.host = host
        kwargs.setdefault("base_url", httpx.URL(f"{proto}://{self.host}:{self.port}"))
        kwargs.setdefault("verify", False)

        if username and password:
            self.auth = httpx.BasicAuth(username, password)

        kwargs.setdefault("auth", self.auth)

        super(Device, self).__init__(**kwargs)
        self.headers["Content-Type"] = "application/json-rpc"
Exemplo n.º 10
0
def generate_auth(device_info) -> httpx.Auth | None:
    """Generate httpx.Auth object from credentials."""
    username = device_info.get(CONF_USERNAME)
    password = device_info.get(CONF_PASSWORD)
    authentication = device_info.get(CONF_AUTHENTICATION)
    if username:
        if authentication == HTTP_DIGEST_AUTHENTICATION:
            return httpx.DigestAuth(username=username, password=password)
        return httpx.BasicAuth(username=username, password=password)
    return None
Exemplo n.º 11
0
def change_password(current_password: str, new_password: str):
    username, headers = get_auth_header_and_username()
    if not username:
        return
    url = get_url(f"/user/profile/security/change-password")
    response = httpx.put(
        url=url,
        auth=httpx.BasicAuth(username=username, password=current_password),
        json=UserUpdatePasswordBodyModel(new_password=new_password).dict(),
    )
    response_handler(response=response,
                     return_model=UserUpdatePasswordResponseModel)
Exemplo n.º 12
0
def test_basic_auth():
    auth = httpx.BasicAuth(username="******", password="******")
    request = httpx.Request("GET", "https://www.example.com")

    # The initial request should include a basic auth header.
    flow = auth.sync_auth_flow(request)
    request = next(flow)
    assert request.headers["Authorization"].startswith("Basic")

    # No other requests are made.
    response = httpx.Response(content=b"Hello, world!", status_code=200)
    with pytest.raises(StopIteration):
        flow.send(response)
Exemplo n.º 13
0
    async def _detect_auth_method(self):
        """Establish the connection with device"""
        full_url = urljoin(self.host, self.isapi_prefix + '/System/status')
        for method in [
                httpx.BasicAuth(self.login, self.password),
                httpx.DigestAuth(self.login, self.password),
        ]:
            async with httpx.AsyncClient(auth=method) as client:
                response = await client.get(full_url)
                if response.status_code == 200:
                    self._auth_method = method

        if not self._auth_method:
            response.raise_for_status()
Exemplo n.º 14
0
 async def _async_publish(self, *, url: str, message: Dict) -> None:
     """
     publish MQ using async http request
     """
     try:
         r = await self.async_httpx_client.post(
             url,
             json=message,
             auth=httpx.BasicAuth(self.username, self.password),
         )
         self._check_mq_response(r)
     except MQSendFailedException as e:
         raise e
     except Exception as e:
         raise MQSendFailedException(str(e))
Exemplo n.º 15
0
 async def request(self, method, url):
     self.method = method
     self.rest_url = url
     async with httpx.AsyncClient(
             verify=False,
             auth=httpx.BasicAuth(self.oracle_user, self.oracle_pass),
             params=self.params,
             headers=self.headers,
             timeout=self.timeout) as client:
         try:
             r = await client.request(self.method, f'{self.oracle_endpoint}{self.rest_url}', data=self.data, params=self.params)
             logger.info(f"""{self.__class__.__name__} - {inspect.stack()[1].function} - {r.status_code}""")
             return r
         except httpx.HTTPError as e:
             logger.exception(f"""{self.__class__.__name__} - {inspect.stack()[1].function} - {e}""")
Exemplo n.º 16
0
def user_auth(user: Optional[User]):
    if user is None:
        return None

    if user.token is not None:
        return BearerAuth(user.token)

    if user.exec:
        return ExecAuth(user.exec)

    if user.username and user.password:
        return httpx.BasicAuth(user.username, user.password)

    if user.auth_provider:
        raise ConfigError("auth-provider not supported")
Exemplo n.º 17
0
    async def process_login(self, code: str,
                            request: Request) -> Optional[OpenID]:
        """
        This method should be called from callback endpoint to verify the user and request user info endpoint.
        This is low level, you should use {verify_and_process} instead.
        """
        url = request.url
        scheme = url.scheme
        if not self.allow_insecure_http and scheme != "https":
            current_url = str(url).replace("http://", "https://")
        else:
            current_url = str(url)
        current_path = self.redirect_uri

        token_url, headers, body = self.oauth_client.prepare_token_request(
            await self.token_endpoint,
            authorization_response=current_url,
            redirect_url=current_path,
            code=code)  # type: ignore

        if token_url is None:
            return {}

        auth = httpx.BasicAuth(self.client_id, self.client_secret)
        async with httpx.AsyncClient() as session:
            logging.debug(f'redirect_uri: {current_path}')
            logging.debug(f'request_body: {body}')
            response = await session.post(token_url,
                                          headers=headers,
                                          content=body,
                                          auth=auth)
            content = response.json()
            logging.debug(f'response: {content}')
            self.oauth_client.parse_request_body_response(json.dumps(content))

            uri, headers, _ = self.oauth_client.add_token(
                await self.userinfo_endpoint)
            response = await session.get(uri, headers=headers)
            profile_details = response.json()

            uri, headers, _ = self.oauth_client.add_token(
                await self.useremail_endpoint)
            response = await session.get(uri, headers=headers)
            content = response.json()
            profile_details['emailAddress'] = content.get(
                'elements', [{}])[0].get('handle~', {}).get('emailAddress')

        return await self.openid_from_response(profile_details)
Exemplo n.º 18
0
    def _get_client(self) -> httpx.AsyncClient:
        if (self.http_username
                and not self.http_password) or (not self.http_username
                                                and self.http_password):
            raise ValueError(
                "Both http_username and http_password should be defined")

        auth = None
        if self.http_username:
            auth = httpx.BasicAuth(self.http_username, self.http_password)

        return self._httpx_client_class(
            auth=auth,
            verify=self.ssl_verify,
            timeout=self.timeout,
        )
Exemplo n.º 19
0
    def auth_method(self, value):
        """Set the authentication method to use for the requests."""
        self._auth_method = value
        if len(self._auth_credentials) == 2:
            username, password = self._auth_credentials
            self._auth = None

            if self._auth_method == "basic":
                self._auth = httpx.BasicAuth(username, password)
            elif self._auth_method == "digest":
                self._auth = httpx.DigestAuth(username, password)
            elif self._auth_method == "ntlm":
                # https://github.com/ulodciv/httpx-ntlm
                from httpx_ntlm import HttpNtlmAuth
                self._auth = HttpNtlmAuth(
                    username, password)  # username in the form domain\user

            self.client.auth = self._auth
Exemplo n.º 20
0
    def fetch_token(self, code):
        body = self.oauth_client.prepare_request_body(
            code=code,
            body='',
            redirect_uri=self.redirect_uri,
            include_client_id=None)

        response = self.request(
            'POST',
            self.token_url,
            headers={
                'Accept': 'application/json',
                'Content-Type':
                'application/x-www-form-urlencoded;charset=UTF-8',
            },
            data=dict(urldecode(body)),
            auth=httpx.BasicAuth(self.client_id, self.client_secret))

        self.token = self.oauth_client.parse_request_body_response(
            response.text, scope=self.scope)

        return self.token
Exemplo n.º 21
0
def accept_legal_document(document_id: str, username: str, password: str):
    url = get_url(f"/v1/legals/{document_id}/accept")
    response = httpx.post(url=url,
                          auth=httpx.BasicAuth(username=username,
                                               password=password))
    response_handler(response=response, print_result=False)
Exemplo n.º 22
0
 def __init__(self, endpoint, origin='http://localhost:80', name='localhost', username=None, password=None, timeout=30):
     self.endpoint = endpoint
     self.origin = origin
     self.name = name
     self.timeout = timeout
     self.http_auth = httpx.BasicAuth(username, password=password) if (username and password) else None
Exemplo n.º 23
0
                    "type": "index-pattern",
                },
            ],
        },
        headers=[("kbn-xsrf", "true")],
        params={"overwrite": "true"},
    )


if __name__ == "__main__":
    username = getpass.getpass("Kibana username: "******"Kibana password: "******"Kibana endpoint: ")

    client = httpx.Client(base_url=endpoint,
                          auth=httpx.BasicAuth(username, password))

    for service_name in get_service_names():

        # Skip services that don't log to Elasticsearch.
        if any(s in service_name for s in ("logstash_transit", "loris")):
            continue

        # For catalogue services that include a date in the service name
        # (e.g. catalogue-20200701_matcher), replace this with an asterisk (*)
        # as a wildcard search in ES.
        #
        # This avoids us having to recreate the saved searches every time
        # we redeploy in the catalogue.
        service_name = re.sub(r"([-_])[0-9-]+([-_]?)", r"\g<1>*\g<2>",
                              service_name).strip("-")