Add no-auth mode

This commit is contained in:
ultrablob 2025-07-01 19:39:33 -04:00
parent e9f63e8658
commit 126b693e7c

39
app.py
View file

@ -19,7 +19,7 @@ PASSWORD = os.getenv("BEAVERHABITS_PASSWORD", "")
# How long to reuse a token (secs) # How long to reuse a token (secs)
TOKEN_TTL = int(os.getenv("BEAVERHABITS_TOKEN_TTL", "3600")) TOKEN_TTL = int(os.getenv("BEAVERHABITS_TOKEN_TTL", "3600"))
TZ = ZoneInfo(os.getenv("TIMEZONE", "UTC")) TZ = ZoneInfo(os.getenv("TZ", "EST"))
# ----------------------------------------------------------------------------- # -----------------------------------------------------------------------------
# Logging # Logging
@ -50,19 +50,28 @@ _token: str | None = None
_token_ts: float = 0.0 _token_ts: float = 0.0
_session = requests.Session() _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 global _token, _token_ts
now = time.time()
with _token_lock: with _token_lock:
now = time.time() if _token and now - _token_ts < TOKEN_TTL:
if _token and (now - _token_ts) < TOKEN_TTL:
return _token return _token
# fetch a new token # fetch a new token
log.info("Requesting new Beaver Habits token")
r = _session.post( r = _session.post(
f"{BEAVER_URL}/auth/login", f"{BEAVER_URL}/auth/login",
headers={"Accept": "application/json", headers={
"Content-Type": "application/x-www-form-urlencoded"}, "Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded",
},
data={ data={
"grant_type": "password", "grant_type": "password",
"username": USERNAME, "username": USERNAME,
@ -72,13 +81,23 @@ def get_token() -> str:
) )
r.raise_for_status() r.raise_for_status()
js = r.json() js = r.json()
_token = js["access_token"] _token = js["access_token"]
_token_ts = now _token_ts = now
return _token return _token
def beaver_headers() -> dict[str,str]: 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 # Utility: Datetime functions