package api import ( "context" "fmt" "log" "net/http" "time" "git.freecumextremist.com/grumbulon/pomme/internal" "git.freecumextremist.com/grumbulon/pomme/internal/db" "github.com/go-chi/chi/v5" "github.com/go-chi/jwtauth/v5" "github.com/go-chi/render" ) func SetDBMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { db := db.InitDb() timeoutContext, _ := context.WithTimeout(context.Background(), time.Second) ctx := context.WithValue(r.Context(), "DB", db.WithContext(timeoutContext)) next.ServeHTTP(w, r.WithContext(ctx)) }) } func basicAuthFailed(w http.ResponseWriter, realm string) { w.Header().Add("WWW-Authenticate", fmt.Sprintf(`Basic realm="%s"`, realm)) w.WriteHeader(http.StatusUnauthorized) } // API handler func Api() http.Handler { api := chi.NewRouter() // Protected routes api.Group(func(api chi.Router) { api.Use(jwtauth.Verifier(tokenAuth)) api.Use(jwtauth.Authenticator) api.Post("/check", Ingest) api.Get("/private", AuthTest) }) // Open routes api.Group(func(api chi.Router) { api.Use(SetDBMiddleware) api.With(SetDBMiddleware).Post("/create", NewUser) api.With(SetDBMiddleware).Post("/login", Login) api.Post("/logout", Logout) }) return api } func Ingest(w http.ResponseWriter, r *http.Request) { data := &internal.ZoneRequest{} log.Println(data) if err := render.Bind(r, data); err != nil { http.Error(w, "Unable to parse Zonefile", http.StatusBadRequest) return } zonefile := data.Zone render.Status(r, http.StatusAccepted) render.Render(w, r, internal.NewZoneResponse(zonefile)) // todo write to database, maybe? // todo -- add functions to apply to master zonefile if above check is OK } func AuthTest(w http.ResponseWriter, r *http.Request) { _, claims, _ := jwtauth.FromContext(r.Context()) w.Write([]byte(fmt.Sprintf("protected area. hi %v", claims["username"]))) }