tok = self.headers.get("Authorization", "").removeprefix("Bearer ").strip()
if TOKENS.get(tok, 0) > time.time():
return True
self.send_json(401, {"error": "token expired or missing"})
return False
def do_POST(self):
url = urllib.parse.urlparse(self.path)
length = int(self.headers.get("Content-Length") or 0)
data = json.loads(self.rfile.read(length) or b"{}")
if url.path == "/oauth/token":
if data.get("username") == USER and data.get("password") == PASS:
tok = secrets.token_hex(16)
TOKENS[tok] = time.time() + 120
return self.send_json(200, {"access_token": tok, "expires_in": 120})
return self.send_json(401, {"error": "invalid_grant", "message": "Wrong username or password"})
if url.path.startswith("/api/books/") and url.path.endswith("/download"):
if not self.authed(): return
book_id = url.path.split("/")[3]
book = next((b for b in catalog() if b["id"] == book_id), None)
if not book: return self.send_json(404, {"error": "no such book"})
return self.send_json(200, {"url": "/files/" + urllib.parse.quote(book["file"])}) # a server path
self.send_json(404, {"error": "not found"})
def do_GET(self):
url = urllib.parse.urlparse(self.path)
q = urllib.parse.parse_qs(url.query)