add auth middleware
This commit is contained in:
+2
-2
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user