pomme/internal/api/api.go
Sam Therapy 16de4f0a43
I am stupid
Signed-off-by: Sam Therapy <sam@samtherapy.net>
2023-01-19 15:41:29 +01:00

59 lines
1.4 KiB
Go

package api
import (
"context"
"fmt"
"net/http"
"time"
"git.freecumextremist.com/grumbulon/pomme/internal/db"
"github.com/go-chi/chi/v5"
"github.com/go-chi/jwtauth/v5"
)
type key int
const (
keyPrincipalContextID key = iota
)
// SetDBMiddleware is the http Handler func for the GORM middleware with context.
func SetDBMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
db := db.InitDb()
timeoutContext, cancelContext := context.WithTimeout(context.Background(), time.Second)
ctx := context.WithValue(r.Context(), keyPrincipalContextID, db.WithContext(timeoutContext))
defer cancelContext()
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 subroute 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.With(SetDBMiddleware).Post("/upload", ReceiveFile)
api.With(SetDBMiddleware).Post("/parse", ZoneFiles)
})
// 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
}