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"
|
2021-08-09 08:53:58 +00:00
|
|
|
"github.com/nspcc-dev/neofs-s3-gw/api/errors"
|
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-07-16 12:35:07 +00:00
|
|
|
// BoxData is an ID used to store accessbox.Box in a context.
|
|
|
|
var BoxData = KeyWrapper("__context_box_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-07-16 12:35:07 +00:00
|
|
|
box, 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))
|
2021-08-09 08:53:58 +00:00
|
|
|
if _, ok := err.(errors.Error); !ok {
|
|
|
|
err = errors.GetAPIError(errors.ErrAccessDenied)
|
|
|
|
}
|
|
|
|
WriteErrorResponse(w, GetReqInfo(r.Context()), err)
|
2021-06-11 16:29:55 +00:00
|
|
|
return
|
|
|
|
}
|
2021-06-11 11:52:03 +00:00
|
|
|
} else {
|
2021-07-16 12:35:07 +00:00
|
|
|
ctx = context.WithValue(r.Context(), BoxData, box)
|
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
|
|
|
}
|