]> git.mxchange.org Git - fba.git/blob - fba/csrf.py
Continued:
[fba.git] / fba / csrf.py
1 # Fedi API Block - An aggregator for fetching blocking data from fediverse nodes
2 # Copyright (C) 2023 Free Software Foundation
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU Affero General Public License as published
6 # by the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 # GNU Affero General Public License for more details.
13 #
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program.  If not, see <https://www.gnu.org/licenses/>.
16
17 import logging
18
19 import bs4
20 import reqto
21
22 from fba.helpers import config
23 from fba.helpers import cookies
24 from fba.helpers import domain as domain_helper
25
26 from fba.http import network
27
28 logging.basicConfig(level=logging.INFO)
29 logger = logging.getLogger(__name__)
30
31 def determine(domain: str, headers: dict) -> dict:
32     logger.debug(f"domain='{domain}',headers()={len(headers)} - CALLED!")
33     domain_helper.raise_on(domain)
34     if not isinstance(headers, dict):
35         raise ValueError(f"Parameter headers[]='{type(headers)}' is not 'dict'")
36
37     # Default headers with no CSRF
38     reqheaders = headers
39
40     # Fetch / to check for meta tag indicating csrf
41     logger.debug(f"Fetching / from domain='{domain}' for CSRF check ...")
42     response = reqto.get(
43         f"https://{domain}/",
44         headers=network.web_headers,
45         timeout=(config.get("connection_timeout"), config.get("read_timeout"))
46     )
47
48     logger.debug("response.ok='%s',response.status_code=%d,response.text()=%d", response.ok, response.status_code, len(response.text))
49     if response.ok and response.status_code < 300 and response.text != "" and response.text.find("<html") > 0:
50         # Save cookies
51         logger.debug(f"Parsing response.text()={len(response.text)} Bytes ...")
52         cookies.store(domain, response.cookies.get_dict())
53
54         # Parse text
55         meta = bs4.BeautifulSoup(
56             response.text,
57             "html.parser"
58         )
59         logger.debug(f"meta[]='{type(meta)}'")
60         tag = meta.find("meta", attrs={"name": "csrf-token"})
61
62         logger.debug(f"tag={tag}")
63         if tag is not None:
64             logger.debug(f"Adding CSRF token='{tag['content']}' for domain='{domain}'")
65             reqheaders["X-CSRF-Token"] = tag["content"]
66
67     logger.debug(f"reqheaders()={len(reqheaders)} - EXIT!")
68     return reqheaders