Skip to content

6 ‐ Usage Examples

stblr edited this page Jul 27, 2024 · 5 revisions

Usage Examples

Access the session

# You can also simply access the session as usual and not use makeRequest, but still reuse everything.

from secureRequests import SecureRequests
from myModules import secureRequestsConfig

secRequests = SecureRequests(**secureRequestsConfig) 
response = secRequests.session.get("https://example.com")

In a GUI with passed responses

For example a defined login method

from typing import Tuple, Optional
from secureRequests import SecureRequests, HeaderKeys
from modules import config # Holds relative folder paths and ensures it
from data import URL # Holds URLs relating to an API for example

class API():
    def __init__(self):
        self.secRequests = SecureRequests()
        self.config = config
        self.token = None
        self.sessionID = None
        self.secRequests = SecureRequests(
            headers={
                HeaderKeys.ORIGIN.value: "https://example.com",
                HeaderKeys.REFERER.value: "https://example.com/",
            },
            certificatePath=f"{self.config.folderResources}/cert.pem",
            logPath=f"{self.config.folderLogs}/network.log",
            logToFile=True,
        )

    def headerAuthenticated(self):
        self.secRequests.headerUpdateMultiple(
            newHeader={
                HeaderKeys.ACCEPT: "application/json",
                HeaderKeys.CONTENT_TYPE: "application/json",
                HeaderKeys.AUTHORIZATION: self.token,
            }
        )

    def loginRequest(
            self, username, password, useScripts
        ) -> Tuple[bool, Optional[str]]:
            data = {"username": username, "password": password}

            try:
                response = self.secRequests.makeRequest(
                    url=URL.API_LOGIN, payload=data, method="POST"
                )
                loginResponse = response.json()
                self.token = loginResponse.get("token")
                self.sessionID = self.__loginCalcSessionID()
                if self.config.debug:
                    print("-------------------------------------")
                    print("Login successful.")
                    print(f"HTTP Status Code: {response.status_code}")
                    print(f"Response URL: {response.request.url}")
                    filteredHeaders = {
                        key: value
                        for key, value in response.headers.items()
                        if key != "Report-To"
                    }
                    print(f"Response Headers: {filteredHeaders}")
                    print("---------------------------------")
                self.headerAuthenticated()
                return True, None  # Indicate success with no error message
            except Exception as e:
                return False, str(e)  # Return the exception message



api = API()
try:
    success, message = api.loginRequest(username, password, useScripts)
    if success:
        print("Login successful")
    else:
        print(f"Login failed: {message}")
except Exception as e:
    print(f"Error: {str(e)}")

# Will log depending on inputs of course (not extensive logging):
# [INFO   ] [[2024-07-25 23]53:14][SAFE][TLS] GET request to https://api.example.com/account/login with Status Code 200 - OK
# [INFO   ] [[2024-07-25 23]58:43][SAFE][TLS] POST request to https://api.example.com/account/login with Status Code 500 - Internal Server Error - Account does not exist
# [INFO   ] [[2024-07-25 23]58:43][SAFE][TLS] POST request to https://api.example.com/account/login with Status Code 500 - Internal Server Error - Wrong username
# [INFO   ] [[2024-07-25 23]58:43][SAFE][TLS] POST request to https://api.example.com/account/login with Status Code 500 - Internal Server Error - Password not matching

As a file download stream

from secureRequests import SecureRequests, HeaderKeys
from os.path import join as pathJoin

class Config:
    folderResources = "resources"
    folderLogs = "logs"
    folderUpdates = "updates"

class API:
    def __init__(self):
        self.secRequests = SecureRequests()
        self.config = Config
        self.token = None
        self.sessionID = None
        self.gitToken = "git_pat_token"
        self.secRequests = SecureRequests(
            headers={
                HeaderKeys.ORIGIN.value: "https://example.com",
                HeaderKeys.REFERER.value: "https://example.com/",
            },
            certificatePath=f"{self.config.folderResources}/cert.pem",
            logPath=f"{self.config.folderLogs}/network.log",
            logToFile=True,
        )
        self.updateDownloadHeaders = self.secRequests.headerGenerate(
            customHeaders={
                HeaderKeys.AUTHORIZATION.value: f"token {self.gitToken}",
                HeaderKeys.ACCEPT.value: "application/octet-stream",
            }
        )

    def downloadFileStream(self, url, filename):
        try:
            updateFilename = pathJoin(self.config.folderUpdates, filename)
            # Download the update zip file
            with self.secRequests.makeRequest(
                url, stream=True, headers=self.updateDownloadHeaders
            ) as r:
                r.raise_for_status()
                with open(updateFilename, "wb") as f:
                    for chunk in r.iter_content(chunk_size=8192):
                        f.write(chunk)
        except Exception as e:
            self.logger.error(f"Error downloading file: {e}")
            return False

Clone this wiki locally