2020-07-22 19:48:34 +00:00
|
|
|
package api
|
2020-07-16 15:33:47 +00:00
|
|
|
|
|
|
|
import (
|
2021-05-26 16:48:27 +00:00
|
|
|
"context"
|
2020-07-16 15:33:47 +00:00
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/gorilla/mux"
|
2021-05-18 11:10:08 +00:00
|
|
|
"github.com/nspcc-dev/neofs-s3-gw/api/auth"
|
2020-07-16 15:33:47 +00:00
|
|
|
"go.uber.org/zap"
|
|
|
|
)
|
|
|
|
|
2021-05-26 18:25:05 +00:00
|
|
|
// KeyWrapper is wrapper for context keys.
|
|
|
|
type KeyWrapper string
|
|
|
|
|
2021-05-26 18:23:36 +00:00
|
|
|
// BearerTokenKey is an ID used to store bearer token in a context.
|
2021-05-26 18:25:05 +00:00
|
|
|
var BearerTokenKey = KeyWrapper("__context_bearer_token_key")
|
2021-05-26 16:48:27 +00:00
|
|
|
|
2021-05-13 20:25:31 +00:00
|
|
|
// AttachUserAuth adds user authentication via center to router using log for logging.
|
2020-11-24 07:00:49 +00:00
|
|
|
func AttachUserAuth(router *mux.Router, center auth.Center, log *zap.Logger) {
|
|
|
|
router.Use(func(h http.Handler) http.Handler {
|
2020-07-16 15:33:47 +00:00
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
2020-11-24 07:00:49 +00:00
|
|
|
token, err := center.Authenticate(r)
|
2020-07-16 15:33:47 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Error("failed to pass authentication", zap.Error(err))
|
2020-07-27 22:54:47 +00:00
|
|
|
WriteErrorResponse(r.Context(), w, GetAPIError(ErrAccessDenied), r.URL)
|
2020-07-24 14:05:33 +00:00
|
|
|
return
|
2020-07-16 15:33:47 +00:00
|
|
|
}
|
2020-11-24 07:00:49 +00:00
|
|
|
|
|
|
|
h.ServeHTTP(w, r.WithContext(
|
2021-05-26 16:48:27 +00:00
|
|
|
context.WithValue(r.Context(), BearerTokenKey, token)))
|
2020-07-16 15:33:47 +00:00
|
|
|
})
|
2020-11-24 07:00:49 +00:00
|
|
|
})
|
2020-07-16 15:33:47 +00:00
|
|
|
}
|