Fix linting

This commit is contained in:
yangdx
2025-03-18 03:30:43 +08:00
parent a1a74d3338
commit 43996656d3
9 changed files with 79 additions and 81 deletions

View File

@@ -17,9 +17,17 @@ class AuthHandler:
self.secret = os.getenv("TOKEN_SECRET", "4f85ds4f56dsf46") self.secret = os.getenv("TOKEN_SECRET", "4f85ds4f56dsf46")
self.algorithm = "HS256" self.algorithm = "HS256"
self.expire_hours = int(os.getenv("TOKEN_EXPIRE_HOURS", 4)) 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 Create JWT token
@@ -45,10 +53,7 @@ class AuthHandler:
# Create payload # Create payload
payload = TokenPayload( payload = TokenPayload(
sub=username, sub=username, exp=expire, role=role, metadata=metadata or {}
exp=expire,
role=role,
metadata=metadata or {}
) )
return jwt.encode(payload.dict(), self.secret, algorithm=self.algorithm) return jwt.encode(payload.dict(), self.secret, algorithm=self.algorithm)
@@ -81,7 +86,7 @@ class AuthHandler:
"username": payload["sub"], "username": payload["sub"],
"role": payload.get("role", "user"), "role": payload.get("role", "user"),
"metadata": payload.get("metadata", {}), "metadata": payload.get("metadata", {}),
"exp": expire_time "exp": expire_time,
} }
except jwt.PyJWTError: except jwt.PyJWTError:
raise HTTPException( raise HTTPException(

View File

@@ -350,22 +350,17 @@ def create_app(args):
if not (username and password): if not (username and password):
# Authentication not configured, return guest token # Authentication not configured, return guest token
guest_token = auth_handler.create_token( guest_token = auth_handler.create_token(
username="guest", username="guest", role="guest", metadata={"auth_mode": "disabled"}
role="guest",
metadata={"auth_mode": "disabled"}
) )
return { return {
"auth_configured": False, "auth_configured": False,
"access_token": guest_token, "access_token": guest_token,
"token_type": "bearer", "token_type": "bearer",
"auth_mode": "disabled", "auth_mode": "disabled",
"message": "Authentication is disabled. Using guest access." "message": "Authentication is disabled. Using guest access.",
} }
return { return {"auth_configured": True, "auth_mode": "enabled"}
"auth_configured": True,
"auth_mode": "enabled"
}
@app.post("/login", dependencies=[Depends(optional_api_key)]) @app.post("/login", dependencies=[Depends(optional_api_key)])
async def login(form_data: OAuth2PasswordRequestForm = Depends()): async def login(form_data: OAuth2PasswordRequestForm = Depends()):
@@ -375,15 +370,13 @@ def create_app(args):
if not (username and password): if not (username and password):
# Authentication not configured, return guest token # Authentication not configured, return guest token
guest_token = auth_handler.create_token( guest_token = auth_handler.create_token(
username="guest", username="guest", role="guest", metadata={"auth_mode": "disabled"}
role="guest",
metadata={"auth_mode": "disabled"}
) )
return { return {
"access_token": guest_token, "access_token": guest_token,
"token_type": "bearer", "token_type": "bearer",
"auth_mode": "disabled", "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: if form_data.username != username or form_data.password != password:
@@ -393,14 +386,12 @@ def create_app(args):
# Regular user login # Regular user login
user_token = auth_handler.create_token( user_token = auth_handler.create_token(
username=username, username=username, role="user", metadata={"auth_mode": "enabled"}
role="user",
metadata={"auth_mode": "enabled"}
) )
return { return {
"access_token": user_token, "access_token": user_token,
"token_type": "bearer", "token_type": "bearer",
"auth_mode": "enabled" "auth_mode": "enabled",
} }
@app.get("/health", dependencies=[Depends(optional_api_key)]) @app.get("/health", dependencies=[Depends(optional_api_key)])

View File

@@ -46,7 +46,9 @@ def get_auth_dependency():
return return
# Check if authentication is configured # 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 authentication is not configured, accept any token including guest tokens
if not auth_configured: if not auth_configured:
@@ -75,7 +77,7 @@ def get_auth_dependency():
if token_info.get("role") == "guest": if token_info.get("role") == "guest":
raise HTTPException( raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED, status_code=status.HTTP_401_UNAUTHORIZED,
detail="Authentication required. Guest access not allowed when authentication is configured." detail="Authentication required. Guest access not allowed when authentication is configured.",
) )
# At this point, we have a valid non-guest token # At this point, we have a valid non-guest token

View File

@@ -29,8 +29,8 @@
"successMessage": "Login succeeded", "successMessage": "Login succeeded",
"errorEmptyFields": "Please enter your username and password", "errorEmptyFields": "Please enter your username and password",
"errorInvalidCredentials": "Login failed, please check username and password", "errorInvalidCredentials": "Login failed, please check username and password",
"authDisabled": "Authentication is disabled. Using guest access.", "authDisabled": "Authentication is disabled. Using login free mode.",
"guestMode": "Guest Mode" "guestMode": "Login Free"
}, },
"documentPanel": { "documentPanel": {
"clearDocuments": { "clearDocuments": {

View File

@@ -29,8 +29,8 @@
"successMessage": "登录成功", "successMessage": "登录成功",
"errorEmptyFields": "请输入您的用户名和密码", "errorEmptyFields": "请输入您的用户名和密码",
"errorInvalidCredentials": "登录失败,请检查用户名和密码", "errorInvalidCredentials": "登录失败,请检查用户名和密码",
"authDisabled": "认证已禁用,使用访客访问模式。", "authDisabled": "认证已禁用,使用无需登陆模式。",
"guestMode": "访客模式" "guestMode": "无需登陆"
}, },
"documentPanel": { "documentPanel": {
"clearDocuments": { "clearDocuments": {