Add navigation service for centralized login redirect routing

- Simplify token validation logic in API
- Update axios interceptor to use navigation service
This commit is contained in:
yangdx
2025-03-18 19:45:43 +08:00
parent 79b32026ec
commit c42f08c0e6
5 changed files with 51 additions and 41 deletions

View File

@@ -42,45 +42,38 @@ def get_auth_dependency():
request: Request,
token: str = Depends(OAuth2PasswordBearer(tokenUrl="login", auto_error=False)),
):
if request.url.path in whitelist:
return
# Check if authentication is configured
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, skip all validation
if not auth_configured:
if token: # If token is provided, still validate it
try:
# Validate token but don't raise exception
token_info = auth_handler.validate_token(token)
# Check if it's a guest token
if token_info.get("role") != "guest":
# Non-guest tokens are not valid when auth is not configured
pass
except Exception as e:
# 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
# For configured auth, allow whitelist paths without token
if request.url.path in whitelist:
return
# Require token for all other paths when auth is configured
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":
try:
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.",
)
except Exception:
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="Invalid token"
)
# At this point, we have a valid non-guest token
return
return dependency