implement admin key authentication and refactor API key handling

This commit is contained in:
Flavio Fois
2026-03-17 16:13:48 +01:00
parent 8097be88a6
commit c61afa45c7
6 changed files with 87 additions and 53 deletions

39
main.go
View File

@@ -9,6 +9,7 @@ import (
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/httprate"
"github.com/jmoiron/sqlx"
"github.com/joho/godotenv"
"emly-api-go/internal/config"
@@ -27,27 +28,31 @@ func main() {
if err != nil {
log.Fatalf("database connection failed: %v", err)
}
defer db.Close()
defer func(db *sqlx.DB) {
err := db.Close()
if err != nil {
log.Fatalf("closing database failed: %v", err)
}
}(db)
r := chi.NewRouter()
// ── Global middleware ────────────────────────────────────────────────────
// Global middlewares
r.Use(middleware.RequestID)
r.Use(middleware.RealIP)
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
r.Use(middleware.Timeout(30 * time.Second))
// ── Global rate-limit: 100 req / min per IP ──────────────────────────────
// Global rate limit to 100 requests per minute
r.Use(httprate.LimitByIP(100, time.Minute))
// ── Public routes ────────────────────────────────────────────────────────
// Public routes (Not protected by any API Key)
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("emly-api-go"))
})
r.Route("/api/v1", func(r chi.Router) {
// Add a header called X-Server
r.Use(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Server", "emly-api-go")
@@ -58,17 +63,7 @@ func main() {
// Health public, no API key required
r.Get("/health", handlers.Health(db))
// ── Protected routes: require valid API key ──────────────────────────
r.Group(func(r chi.Router) {
r.Use(apimw.APIKeyAuth(db))
// Tighter rate-limit on protected group: 30 req / min per IP
r.Use(httprate.LimitByIP(30, time.Minute))
r.Get("/example", handlers.ExampleGet)
r.Post("/example", handlers.ExamplePost)
})
// ROUTE: Bug Reports - Protected via API Key
r.Route("/bug-reports", func(r chi.Router) {
r.Group(func(r chi.Router) {
r.Use(apimw.APIKeyAuth(db))
@@ -76,9 +71,19 @@ func main() {
// Tighter rate-limit on protected group: 30 req / min per IP
r.Use(httprate.LimitByIP(30, time.Minute))
r.Get("/count", handlers.GetReportsCount(db))
})
r.Group(func(r chi.Router) {
// More strict auth due to sensitive info
r.Use(apimw.APIKeyAuth(db))
r.Use(apimw.AdminKeyAuth(db))
// Tighter rate-limit on protected group: 30 req / min per IP
r.Use(httprate.LimitByIP(30, time.Minute))
r.Get("/", handlers.GetAllBugReports(db))
r.Get("/{id}", handlers.GetBugReportByID(db))
r.Get("/count", handlers.GetReportsCount(db))
r.Get("/{id}/files", handlers.GetReportFilesByReportID(db))
r.Get("/{id}/files/{file_id}", handlers.GetReportFileByFileID(db))
r.Get("/{id}/zip", handlers.GetBugReportZipById(db))