Files
coredns-powerdns-api-wrapper/auth.go
2026-07-10 23:53:43 +02:00

29 lines
869 B
Go

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2026 Bryan Joshua Pedini
package main
import (
"encoding/json"
"net/http"
)
// writeJSONError writes a PowerDNS-shaped error body: {"error": msg}.
func writeJSONError(w http.ResponseWriter, status int, msg string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(map[string]string{"error": msg})
}
// authMiddleware guards the /api/v1 subrouter: requests must carry
// X-API-Key equal to Config.PDNSAPIKey, or they get a 401 in PowerDNS shape.
func (s *WebServer) authMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("X-API-Key") != s.Config.PDNSAPIKey {
writeJSONError(w, http.StatusUnauthorized, "Unauthorized")
return
}
next.ServeHTTP(w, r)
})
}