Fix linting
This commit is contained in:
@@ -17,18 +17,26 @@ class AuthHandler:
|
||||
self.secret = os.getenv("TOKEN_SECRET", "4f85ds4f56dsf46")
|
||||
self.algorithm = "HS256"
|
||||
self.expire_hours = int(os.getenv("TOKEN_EXPIRE_HOURS", 4))
|
||||
self.guest_expire_hours = int(os.getenv("GUEST_TOKEN_EXPIRE_HOURS", 2)) # Guest token default expiration time
|
||||
self.guest_expire_hours = int(
|
||||
os.getenv("GUEST_TOKEN_EXPIRE_HOURS", 2)
|
||||
) # Guest token default expiration time
|
||||
|
||||
def create_token(self, username: str, role: str = "user", custom_expire_hours: int = None, metadata: dict = None) -> str:
|
||||
def create_token(
|
||||
self,
|
||||
username: str,
|
||||
role: str = "user",
|
||||
custom_expire_hours: int = None,
|
||||
metadata: dict = None,
|
||||
) -> str:
|
||||
"""
|
||||
Create JWT token
|
||||
|
||||
|
||||
Args:
|
||||
username: Username
|
||||
role: User role, default is "user", guest is "guest"
|
||||
custom_expire_hours: Custom expiration time (hours), if None use default value
|
||||
metadata: Additional metadata
|
||||
|
||||
|
||||
Returns:
|
||||
str: Encoded JWT token
|
||||
"""
|
||||
@@ -40,29 +48,26 @@ class AuthHandler:
|
||||
expire_hours = self.expire_hours
|
||||
else:
|
||||
expire_hours = custom_expire_hours
|
||||
|
||||
|
||||
expire = datetime.utcnow() + timedelta(hours=expire_hours)
|
||||
|
||||
|
||||
# Create payload
|
||||
payload = TokenPayload(
|
||||
sub=username,
|
||||
exp=expire,
|
||||
role=role,
|
||||
metadata=metadata or {}
|
||||
sub=username, exp=expire, role=role, metadata=metadata or {}
|
||||
)
|
||||
|
||||
|
||||
return jwt.encode(payload.dict(), self.secret, algorithm=self.algorithm)
|
||||
|
||||
def validate_token(self, token: str) -> dict:
|
||||
"""
|
||||
Validate JWT token
|
||||
|
||||
|
||||
Args:
|
||||
token: JWT token
|
||||
|
||||
|
||||
Returns:
|
||||
dict: Dictionary containing user information
|
||||
|
||||
|
||||
Raises:
|
||||
HTTPException: If token is invalid or expired
|
||||
"""
|
||||
@@ -75,13 +80,13 @@ class AuthHandler:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED, detail="Token expired"
|
||||
)
|
||||
|
||||
|
||||
# Return complete payload instead of just username
|
||||
return {
|
||||
"username": payload["sub"],
|
||||
"role": payload.get("role", "user"),
|
||||
"metadata": payload.get("metadata", {}),
|
||||
"exp": expire_time
|
||||
"exp": expire_time,
|
||||
}
|
||||
except jwt.PyJWTError:
|
||||
raise HTTPException(
|
||||
|
@@ -350,22 +350,17 @@ def create_app(args):
|
||||
if not (username and password):
|
||||
# Authentication not configured, return guest token
|
||||
guest_token = auth_handler.create_token(
|
||||
username="guest",
|
||||
role="guest",
|
||||
metadata={"auth_mode": "disabled"}
|
||||
username="guest", role="guest", metadata={"auth_mode": "disabled"}
|
||||
)
|
||||
return {
|
||||
"auth_configured": False,
|
||||
"access_token": guest_token,
|
||||
"token_type": "bearer",
|
||||
"auth_mode": "disabled",
|
||||
"message": "Authentication is disabled. Using guest access."
|
||||
"message": "Authentication is disabled. Using guest access.",
|
||||
}
|
||||
|
||||
return {
|
||||
"auth_configured": True,
|
||||
"auth_mode": "enabled"
|
||||
}
|
||||
|
||||
return {"auth_configured": True, "auth_mode": "enabled"}
|
||||
|
||||
@app.post("/login", dependencies=[Depends(optional_api_key)])
|
||||
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
|
||||
@@ -375,15 +370,13 @@ def create_app(args):
|
||||
if not (username and password):
|
||||
# Authentication not configured, return guest token
|
||||
guest_token = auth_handler.create_token(
|
||||
username="guest",
|
||||
role="guest",
|
||||
metadata={"auth_mode": "disabled"}
|
||||
username="guest", role="guest", metadata={"auth_mode": "disabled"}
|
||||
)
|
||||
return {
|
||||
"access_token": guest_token,
|
||||
"token_type": "bearer",
|
||||
"auth_mode": "disabled",
|
||||
"message": "Authentication is disabled. Using guest access."
|
||||
"message": "Authentication is disabled. Using guest access.",
|
||||
}
|
||||
|
||||
if form_data.username != username or form_data.password != password:
|
||||
@@ -393,14 +386,12 @@ def create_app(args):
|
||||
|
||||
# Regular user login
|
||||
user_token = auth_handler.create_token(
|
||||
username=username,
|
||||
role="user",
|
||||
metadata={"auth_mode": "enabled"}
|
||||
username=username, role="user", metadata={"auth_mode": "enabled"}
|
||||
)
|
||||
return {
|
||||
"access_token": user_token,
|
||||
"token_type": "bearer",
|
||||
"auth_mode": "enabled"
|
||||
"auth_mode": "enabled",
|
||||
}
|
||||
|
||||
@app.get("/health", dependencies=[Depends(optional_api_key)])
|
||||
|
@@ -46,8 +46,10 @@ def get_auth_dependency():
|
||||
return
|
||||
|
||||
# Check if authentication is configured
|
||||
auth_configured = bool(os.getenv("AUTH_USERNAME") and os.getenv("AUTH_PASSWORD"))
|
||||
|
||||
auth_configured = bool(
|
||||
os.getenv("AUTH_USERNAME") and os.getenv("AUTH_PASSWORD")
|
||||
)
|
||||
|
||||
# If authentication is not configured, accept any token including guest tokens
|
||||
if not auth_configured:
|
||||
if token: # If token is provided, still validate it
|
||||
@@ -62,22 +64,22 @@ def get_auth_dependency():
|
||||
# Ignore validation errors but log them
|
||||
print(f"Token validation error (ignored): {str(e)}")
|
||||
return
|
||||
|
||||
|
||||
# If authentication is configured, validate the token and reject guest tokens
|
||||
if not token:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED, detail="Token required"
|
||||
)
|
||||
|
||||
|
||||
token_info = auth_handler.validate_token(token)
|
||||
|
||||
|
||||
# Reject guest tokens when authentication is configured
|
||||
if token_info.get("role") == "guest":
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Authentication required. Guest access not allowed when authentication is configured."
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Authentication required. Guest access not allowed when authentication is configured.",
|
||||
)
|
||||
|
||||
|
||||
# At this point, we have a valid non-guest token
|
||||
return
|
||||
|
||||
|
Reference in New Issue
Block a user