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