36 lines
1.2 KiB
Go
36 lines
1.2 KiB
Go
package auth
|
|
|
|
import "net/http"
|
|
|
|
// BearerMiddleware wraps next, requiring a valid bearer credential from a.
|
|
// On success the request is forwarded unchanged; on failure a 401 is
|
|
// returned.
|
|
func BearerMiddleware(a Authenticator, next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if _, err := a.Authenticate(r); err != nil {
|
|
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
|
|
// WriteMiddleware wraps next, requiring a valid bearer credential from a
|
|
// only for mutating HTTP methods (POST, PUT, PATCH, DELETE). Safe methods
|
|
// (GET, HEAD, OPTIONS) pass through unauthenticated — suitable for
|
|
// services that serve public reads but gate writes behind auth.
|
|
func WriteMiddleware(a Authenticator, next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
switch r.Method {
|
|
case http.MethodGet, http.MethodHead, http.MethodOptions:
|
|
next.ServeHTTP(w, r)
|
|
default:
|
|
if _, err := a.Authenticate(r); err != nil {
|
|
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
next.ServeHTTP(w, r)
|
|
}
|
|
})
|
|
}
|