diff --git a/app.py b/app.py index 566745d..ee09916 100644 --- a/app.py +++ b/app.py @@ -19,7 +19,7 @@ PASSWORD = os.getenv("BEAVERHABITS_PASSWORD", "") # How long to reuse a token (secs) TOKEN_TTL = int(os.getenv("BEAVERHABITS_TOKEN_TTL", "3600")) -TZ = ZoneInfo(os.getenv("TIMEZONE", "UTC")) +TZ = ZoneInfo(os.getenv("TZ", "EST")) # ----------------------------------------------------------------------------- # Logging @@ -50,19 +50,28 @@ _token: str | None = None _token_ts: float = 0.0 _session = requests.Session() -def get_token() -> str: +def get_token() -> str | None: + """ + Return a valid access token, or None if we're in no-auth mode. + """ + # 1) If either USERNAME or PASSWORD is missing, we are in "no-auth" mode. + if not USERNAME or not PASSWORD: + return None + + # 2) Otherwise, normal token+TTL caching: global _token, _token_ts + now = time.time() with _token_lock: - now = time.time() - if _token and (now - _token_ts) < TOKEN_TTL: + if _token and now - _token_ts < TOKEN_TTL: return _token # fetch a new token - log.info("Requesting new Beaver Habits token") r = _session.post( f"{BEAVER_URL}/auth/login", - headers={"Accept": "application/json", - "Content-Type": "application/x-www-form-urlencoded"}, + headers={ + "Accept": "application/json", + "Content-Type": "application/x-www-form-urlencoded", + }, data={ "grant_type": "password", "username": USERNAME, @@ -72,13 +81,23 @@ def get_token() -> str: ) r.raise_for_status() js = r.json() - _token = js["access_token"] + _token = js["access_token"] _token_ts = now return _token def beaver_headers() -> dict[str,str]: - return {"Accept": "application/json", - "Authorization": f"Bearer {get_token()}"} + """ + Base headers for Beaver Habits API calls. + In no-auth mode, we only send Accept: application/json. + Otherwise we include the Bearer token. + """ + headers = { + "Accept": "application/json", + } + token = get_token() + if token: + headers["Authorization"] = f"Bearer {token}" + return headers # ----------------------------------------------------------------------------- # Utility: Datetime functions