37 lines
972 B
Go
37 lines
972 B
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"nova_task/internal/consts"
|
|
"nova_task/internal/model"
|
|
"nova_task/internal/pkg/errs"
|
|
)
|
|
|
|
type KGeNApiKeyCheckMiddleware struct {
|
|
conf model.NhSystemConfigModel
|
|
}
|
|
|
|
func NewKGeNApiKeyCheckMiddleware(conf model.NhSystemConfigModel) *KGeNApiKeyCheckMiddleware {
|
|
return &KGeNApiKeyCheckMiddleware{conf: conf}
|
|
}
|
|
|
|
func (m *KGeNApiKeyCheckMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
ctx := r.Context()
|
|
key, err := m.conf.GetApiKey(ctx, consts.KgenApiKey)
|
|
if err != nil {
|
|
_, result := errs.ErrorHandle(errs.New(errs.ErrDatabaseOperate, "api key config not exist"))
|
|
errs.WriteHttpResponse(ctx, w, result)
|
|
return
|
|
}
|
|
apiKey := r.Header.Get("x-api-key")
|
|
if apiKey == "" || apiKey != key {
|
|
_, result := errs.ErrorHandle(errs.New(errs.ErrUnauthorized, "invalid api key"))
|
|
errs.WriteHttpResponse(ctx, w, result)
|
|
return
|
|
}
|
|
|
|
next(w, r)
|
|
}
|
|
}
|