acme-dns-httpreq/http.go

75 lines
1.4 KiB
Go

package main
import (
"encoding/json"
"fmt"
"net/http"
"strings"
)
func init() {
http.HandleFunc("/present", present)
http.HandleFunc("/cleanup", cleanup)
}
type request struct {
FQDN string `json:"fqdn"`
Value string `json:"value"`
}
func httpCommon(res http.ResponseWriter, req *http.Request, fn func(request)) {
if req.Method != http.MethodPost {
res.WriteHeader(http.StatusBadRequest)
return
}
users, _, basicAuthOk := req.BasicAuth()
if !basicAuthOk {
fmt.Printf("basic auth failed\n")
res.WriteHeader(http.StatusForbidden)
return
}
body := request{}
d := json.NewDecoder(req.Body)
d.DisallowUnknownFields()
if err := d.Decode(&body); err != nil {
res.WriteHeader(http.StatusBadRequest)
return
}
if d.More() {
res.WriteHeader(http.StatusBadRequest)
return
}
passed := false
for _, user := range strings.Split(users, ",") {
if user == body.FQDN {
passed = true
}
}
if !passed {
fmt.Printf("expected %s in %s\n", body.FQDN, users)
res.WriteHeader(http.StatusForbidden)
return
}
fn(body)
}
func present(res http.ResponseWriter, req *http.Request) {
httpCommon(res, req, func(body request) {
fmt.Printf("add %s to %s\n", body.Value, body.FQDN)
db.Add(body.FQDN, body.Value)
})
}
func cleanup(res http.ResponseWriter, req *http.Request) {
httpCommon(res, req, func(body request) {
fmt.Printf("remove %s from %s\n", body.Value, body.FQDN)
db.Remove(body.FQDN, body.Value)
})
}