feat(api): enhance API handler to support unauthenticated local access

- Updated NewHandler function to accept a requireAuth parameter for authentication control.
- Introduced a new local API server that allows unauthenticated access when LocalAPIHTTPAddr is set.
- Adjusted server startup logic to handle both authenticated and unauthenticated API routes.
This commit is contained in:
yusing
2026-01-21 22:36:22 +08:00
parent 92f8590edd
commit f5047f4dfa
3 changed files with 18 additions and 4 deletions

View File

@@ -69,9 +69,18 @@ func main() {
server.StartServer(task.RootTask("api_server", false), server.Options{ server.StartServer(task.RootTask("api_server", false), server.Options{
Name: "api", Name: "api",
HTTPAddr: common.APIHTTPAddr, HTTPAddr: common.APIHTTPAddr,
Handler: api.NewHandler(), Handler: api.NewHandler(true),
}) })
// Local API Handler is used for unauthenticated access.
if common.LocalAPIHTTPAddr != "" {
server.StartServer(task.RootTask("local_api_server", false), server.Options{
Name: "local_api",
HTTPAddr: common.LocalAPIHTTPAddr,
Handler: api.NewHandler(false),
})
}
listenDebugServer() listenDebugServer()
uptime.Poller.Start() uptime.Poller.Start()

View File

@@ -38,7 +38,7 @@ import (
// @externalDocs.description GoDoxy Docs // @externalDocs.description GoDoxy Docs
// @externalDocs.url https://docs.godoxy.dev // @externalDocs.url https://docs.godoxy.dev
func NewHandler() *gin.Engine { func NewHandler(requireAuth bool) *gin.Engine {
if !common.IsDebug { if !common.IsDebug {
gin.SetMode("release") gin.SetMode("release")
} }
@@ -51,7 +51,7 @@ func NewHandler() *gin.Engine {
r.GET("/api/v1/version", apiV1.Version) r.GET("/api/v1/version", apiV1.Version)
if auth.IsEnabled() { if auth.IsEnabled() && requireAuth {
v1Auth := r.Group("/api/v1/auth") v1Auth := r.Group("/api/v1/auth")
{ {
v1Auth.HEAD("/check", authApi.Check) v1Auth.HEAD("/check", authApi.Check)
@@ -64,7 +64,7 @@ func NewHandler() *gin.Engine {
} }
v1 := r.Group("/api/v1") v1 := r.Group("/api/v1")
if auth.IsEnabled() { if auth.IsEnabled() && requireAuth {
v1.Use(AuthMiddleware()) v1.Use(AuthMiddleware())
} }
if common.APISkipOriginCheck { if common.APISkipOriginCheck {

View File

@@ -30,6 +30,11 @@ var (
APIHTTPPort, APIHTTPPort,
APIHTTPURL = env.GetAddrEnv("API_ADDR", "127.0.0.1:8888", "http") APIHTTPURL = env.GetAddrEnv("API_ADDR", "127.0.0.1:8888", "http")
LocalAPIHTTPAddr,
LocalAPIHTTPHost,
LocalAPIHTTPPort,
LocalAPIHTTPURL = env.GetAddrEnv("LOCAL_API_ADDR", "", "http")
APIJWTSecure = env.GetEnvBool("API_JWT_SECURE", true) APIJWTSecure = env.GetEnvBool("API_JWT_SECURE", true)
APIJWTSecret = decodeJWTKey(env.GetEnvString("API_JWT_SECRET", "")) APIJWTSecret = decodeJWTKey(env.GetEnvString("API_JWT_SECRET", ""))
APIJWTTokenTTL = env.GetEnvDuation("API_JWT_TOKEN_TTL", 24*time.Hour) APIJWTTokenTTL = env.GetEnvDuation("API_JWT_TOKEN_TTL", 24*time.Hour)