add auth middleware

This commit is contained in:
Odweta
2026-03-22 14:44:44 +01:00
parent 6cd68a6725
commit 8d192f8be3
2 changed files with 30 additions and 2 deletions
+2 -2
View File
@@ -1,5 +1,3 @@
// TODO: READ, UNDERSTAND AND ALTER
package main
import (
@@ -14,6 +12,8 @@ func main() {
r := chi.NewRouter()
r.Use(authMiddleware)
// routes
r.Get("/quotes", getQuotes)
r.Post("/quotes", createQuote)
+28
View File
@@ -0,0 +1,28 @@
package main
import (
"net/http"
"os"
)
func authMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
expectedKey := os.Getenv("FRONTEND_API_KEY")
if expectedKey == "" {
http.Error(w, "server misconfigured", 500)
return
}
authHeader := r.Header.Get("Authorization")
expectedHeader := "Bearer " + expectedKey
if authHeader != expectedHeader {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}