34 lines
856 B
Go
34 lines
856 B
Go
package api
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
)
|
|
|
|
// bearerAuthMiddleware enforces Bearer token authentication for protected routes.
|
|
func bearerAuthMiddleware(requiredToken string) func(http.Handler) http.Handler {
|
|
return func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if r.URL.Path == "/api/events" {
|
|
if r.URL.Query().Get("access_token") == requiredToken {
|
|
next.ServeHTTP(w, r)
|
|
return
|
|
}
|
|
}
|
|
|
|
auth := r.Header.Get("Authorization")
|
|
if !strings.HasPrefix(auth, "Bearer ") {
|
|
writeError(w, http.StatusUnauthorized, "Missing or invalid Authorization header")
|
|
return
|
|
}
|
|
token := strings.TrimPrefix(auth, "Bearer ")
|
|
if token != requiredToken {
|
|
writeError(w, http.StatusUnauthorized, "Invalid token")
|
|
return
|
|
}
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
}
|
|
|