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-06-21 10:54:57 +00:00
|
|
|
// GateData is an ID used to store GateData in a context.
|
|
|
|
var GateData = KeyWrapper("__context_gate_data_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) {
|
2021-06-11 16:29:55 +00:00
|
|
|
var ctx context.Context
|
2021-06-21 10:54:57 +00:00
|
|
|
tokens, err := center.Authenticate(r)
|
2020-07-16 15:33:47 +00:00
|
|
|
if err != nil {
|
2021-06-11 16:29:55 +00:00
|
|
|
if err == auth.ErrNoAuthorizationHeader {
|
|
|
|
log.Debug("couldn't receive bearer token, using neofs-key")
|
|
|
|
ctx = r.Context()
|
|
|
|
} else {
|
|
|
|
log.Error("failed to pass authentication", zap.Error(err))
|
|
|
|
WriteErrorResponse(r.Context(), w, GetAPIError(ErrAccessDenied), r.URL)
|
|
|
|
return
|
|
|
|
}
|
2021-06-11 11:52:03 +00:00
|
|
|
} else {
|
2021-06-21 10:54:57 +00:00
|
|
|
ctx = context.WithValue(r.Context(), GateData, tokens)
|
2021-06-11 11:52:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
h.ServeHTTP(w, r.WithContext(ctx))
|
2020-07-16 15:33:47 +00:00
|
|
|
})
|
2020-11-24 07:00:49 +00:00
|
|
|
})
|
2020-07-16 15:33:47 +00:00
|
|
|
}
|