NextWks/src/core/admin/auth.go

34 lines
981 B
Go

package admin
import (
"crypto/subtle"
"net/http"
)
// TokenAuthMiddleware protects admin routes with a static bearer token.
// All /admin/* routes require the Authorization: Bearer <token> header
// matching the configured admin.secret_token.
func TokenAuthMiddleware(secretToken string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("Authorization")
// Expect "Bearer <token>" format
const bearerPrefix = "Bearer "
if len(token) < len(bearerPrefix) {
http.Error(w, `{"error":"unauthorized"}`, http.StatusUnauthorized)
return
}
token = token[len(bearerPrefix):]
// Constant-time comparison to prevent timing attacks
if subtle.ConstantTimeCompare([]byte(token), []byte(secretToken)) != 1 {
http.Error(w, `{"error":"unauthorized"}`, http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
}