| 8 | |
| 9 | |
| 10 | class RequestManager: |
| 11 | def __init__(self, config: Config): |
| 12 | self.config = config |
| 13 | |
| 14 | def _verify(self): |
| 15 | return requests_verify_arg(self.config) |
| 16 | |
| 17 | @staticmethod |
| 18 | def format_cookie(cookie: dict) -> str: |
| 19 | """ |
| 20 | Format the cookie string for headers. |
| 21 | """ |
| 22 | return f"JSESSIONID={cookie.get('JSESSIONID', '')};" |
| 23 | |
| 24 | def login(self) -> tuple[bool, str, dict]: |
| 25 | try: |
| 26 | session = requests.Session() |
| 27 | |
| 28 | # Fetch the login page to get the CSRF token |
| 29 | response = session.get( |
| 30 | self.config.data["server_url"] + LOGIN_URL, |
| 31 | verify=self._verify(), |
| 32 | ) |
| 33 | |
| 34 | if response.status_code != 200: |
| 35 | msg = f"Failed to fetch login page: {response.status_code}" |
| 36 | logging.error(msg) |
| 37 | return False, msg, None |
| 38 | |
| 39 | soup = BeautifulSoup(response.text, "html.parser") |
| 40 | csrf_token = soup.find("input", {"name": "_csrf"})["value"] |
| 41 | |
| 42 | # Login with the credentials |
| 43 | form_data = { |
| 44 | "username": self.config.data["username"], |
| 45 | "password": self.config.data["password"], |
| 46 | "_csrf": csrf_token, |
| 47 | } |
| 48 | response = session.post( |
| 49 | self.config.data["server_url"] + LOGIN_URL, |
| 50 | data=form_data, |
| 51 | verify=self._verify(), |
| 52 | ) |
| 53 | if ( |
| 54 | response.status_code == 200 |
| 55 | and "bad credentials" not in response.text.lower() |
| 56 | ): |
| 57 | # login successful |
| 58 | cookie = session.cookies.get_dict() |
| 59 | logging.info(f"Login successful: {response.status_code}") |
| 60 | return True, "Login successful", cookie |
| 61 | else: |
| 62 | # login failed |
| 63 | msg = f"Login failed: {response.status_code}" |
| 64 | logging.error(msg) |
| 65 | return False, msg, None |
| 66 | except Exception as e: |
| 67 | msg = f"An error occurred during login: {e}" |