62 lines
1.5 KiB
Go
62 lines
1.5 KiB
Go
package handlers
|
|
|
|
import (
|
|
"context"
|
|
"log"
|
|
"net/http"
|
|
"time"
|
|
|
|
"crowdsec-dashy/internal/geoip"
|
|
)
|
|
|
|
// GeoIPHandler serves the GeoIP database status and manual refresh page.
|
|
type GeoIPHandler struct {
|
|
deps Deps
|
|
updater *geoip.Updater
|
|
}
|
|
|
|
func NewGeoIPHandler(deps Deps, updater *geoip.Updater) *GeoIPHandler {
|
|
return &GeoIPHandler{deps: deps, updater: updater}
|
|
}
|
|
|
|
type GeoIPData struct {
|
|
PageData
|
|
Status geoip.Status
|
|
}
|
|
|
|
func (h *GeoIPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
pd := NewPageData(r, "GeoIP Database", h.deps.CLIAvailable, h.deps.PollInterval)
|
|
if f := readFlash(r); f.Message != "" {
|
|
pd.Flash = f
|
|
}
|
|
h.deps.Renderer.Render(w, "geoip", GeoIPData{
|
|
PageData: pd,
|
|
Status: h.updater.Status(),
|
|
})
|
|
}
|
|
|
|
func (h *GeoIPHandler) Refresh(w http.ResponseWriter, r *http.Request) {
|
|
r.Body = http.MaxBytesReader(w, r.Body, 256)
|
|
if err := r.ParseForm(); err != nil {
|
|
http.Error(w, "bad request", http.StatusBadRequest)
|
|
return
|
|
}
|
|
if !checkCSRF(r) {
|
|
http.Error(w, "forbidden", http.StatusForbidden)
|
|
return
|
|
}
|
|
|
|
// Kick off in background — download can take 10-30s.
|
|
go func() {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
|
|
defer cancel()
|
|
if err := h.updater.Refresh(ctx); err != nil {
|
|
log.Printf("[geoip] manual refresh failed: %v", err)
|
|
} else {
|
|
log.Printf("[geoip] manual refresh complete")
|
|
}
|
|
}()
|
|
|
|
flashRedirect(w, r, "/geoip", "success", "Download started — refresh this page in a moment")
|
|
}
|