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"
|
|
|
|
|
2022-12-14 16:58:00 +00:00
|
|
|
"github.com/TrueCloudLab/frostfs-s3-gw/api/auth"
|
|
|
|
"github.com/TrueCloudLab/frostfs-s3-gw/api/errors"
|
2020-07-16 15:33:47 +00:00
|
|
|
"github.com/gorilla/mux"
|
|
|
|
"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
|
|
|
|
2022-11-08 09:12:55 +00:00
|
|
|
// ClientTime is an ID used to store client time.Time in a context.
|
|
|
|
var ClientTime = KeyWrapper("__context_client_time")
|
|
|
|
|
2022-12-27 12:30:11 +00:00
|
|
|
// AuthMiddleware adds user authentication via center to router using log for logging.
|
|
|
|
func AuthMiddleware(log *zap.Logger, center auth.Center) mux.MiddlewareFunc {
|
|
|
|
return 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 {
|
2021-10-19 15:08:07 +00:00
|
|
|
log.Debug("couldn't receive access box for gate key, random key will be used")
|
2021-06-11 16:29:55 +00:00
|
|
|
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 {
|
2022-11-08 09:12:55 +00:00
|
|
|
ctx = context.WithValue(r.Context(), BoxData, box.AccessBox)
|
|
|
|
if !box.ClientTime.IsZero() {
|
|
|
|
ctx = context.WithValue(ctx, ClientTime, box.ClientTime)
|
|
|
|
}
|
2021-06-11 11:52:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
h.ServeHTTP(w, r.WithContext(ctx))
|
2020-07-16 15:33:47 +00:00
|
|
|
})
|
2022-12-27 12:30:11 +00:00
|
|
|
}
|
2020-07-16 15:33:47 +00:00
|
|
|
}
|