Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/build-release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ jobs:
matrix:
goos: [linux, darwin, windows]
goarch: [amd64, arm64]
include:
- goos: android
goarch: arm64
exclude:
- goos: windows
goarch: arm64
Expand Down
58 changes: 43 additions & 15 deletions api/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,35 +14,63 @@ type tokenContextKey struct{}

// AuthMiddleware 返回认证中间件
func AuthMiddleware() func(http.Handler) http.Handler {
return TokenAuthMiddleware(func() string {
return config.C().API.Token
})
}

func TokenAuthMiddleware(tokenProvider func() string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cfg := config.C().API

// 从请求头获取 token
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
WriteError(w, http.StatusUnauthorized, "unauthorized", "missing authorization header")
if isPublicConfigWebPath(r) {
next.ServeHTTP(w, r)
return
}

// 提取 Bearer token
parts := strings.SplitN(authHeader, " ", 2)
if len(parts) != 2 || strings.ToLower(parts[0]) != "bearer" {
WriteError(w, http.StatusUnauthorized, "unauthorized", "invalid authorization header format")
token := tokenProvider()
if token == "" {
next.ServeHTTP(w, r)
return
}

token := parts[1]
requestToken := getRequestToken(r)
if requestToken == "" {
WriteError(w, http.StatusUnauthorized, "unauthorized", "missing authorization header")
return
}

// 验证 token
if subtle.ConstantTimeCompare([]byte(token), []byte(cfg.Token)) != 1 {
if subtle.ConstantTimeCompare([]byte(requestToken), []byte(token)) != 1 {
WriteError(w, http.StatusUnauthorized, "unauthorized", "invalid token")
return
}

// 将 token 添加到 context
ctx := context.WithValue(r.Context(), tokenContextKey{}, token)
ctx := context.WithValue(r.Context(), tokenContextKey{}, requestToken)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}

func getRequestToken(r *http.Request) string {
authHeader := r.Header.Get("Authorization")
if authHeader != "" {
parts := strings.SplitN(authHeader, " ", 2)
if len(parts) != 2 || strings.ToLower(parts[0]) != "bearer" {
return ""
}
return parts[1]
}
if token := r.Header.Get("X-API-Token"); token != "" {
return token
}
if cookie, err := r.Cookie("saveany_api_token"); err == nil {
return cookie.Value
}
return r.URL.Query().Get("token")
}

func isPublicConfigWebPath(r *http.Request) bool {
if r.Method != http.MethodGet && r.Method != http.MethodHead {
return false
}
return r.URL.Path == "/config" || strings.HasPrefix(r.URL.Path, "/config/")
}
Loading