Fixed auth
This commit is contained in:
29
app/auth.py
29
app/auth.py
@@ -1,6 +1,7 @@
|
||||
import os
|
||||
from fastapi import HTTPException, Request
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import HTTPBasic, HTTPBasicCredentials
|
||||
import secrets
|
||||
import os
|
||||
|
||||
security = HTTPBasic()
|
||||
|
||||
@@ -8,12 +9,18 @@ DISABLE_AUTH = os.getenv("DISABLE_AUTH", "false").strip().lower() in ("1","true"
|
||||
USER = os.getenv("OPDS_BASIC_USER", "").strip()
|
||||
PASS = os.getenv("OPDS_BASIC_PASS", "").strip()
|
||||
|
||||
def require_basic(request: Request, credentials: HTTPBasicCredentials = None):
|
||||
# If disabled, or no credentials configured at all, allow through
|
||||
if DISABLE_AUTH or not USER or not PASS:
|
||||
return
|
||||
if credentials is None:
|
||||
credentials = security(request)
|
||||
if not (credentials.username == USER and credentials.password == PASS):
|
||||
raise HTTPException(status_code=401, detail="Not authenticated",
|
||||
headers={"WWW-Authenticate": "Basic"})
|
||||
async def require_basic(credentials: HTTPBasicCredentials = Depends(security)):
|
||||
if DISABLE_AUTH:
|
||||
return True
|
||||
|
||||
# Use secrets.compare_digest to avoid timing attacks
|
||||
correct_user = secrets.compare_digest(credentials.username, USER or "")
|
||||
correct_pass = secrets.compare_digest(credentials.password, PASS or "")
|
||||
|
||||
if not (correct_user and correct_pass):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid credentials",
|
||||
headers={"WWW-Authenticate": "Basic"},
|
||||
)
|
||||
return True
|
||||
Reference in New Issue
Block a user