51 lines
1.1 KiB
Go
51 lines
1.1 KiB
Go
package middleware
|
|
|
|
import (
|
|
"errors"
|
|
"net/http"
|
|
"nova_task/internal/model"
|
|
"nova_task/internal/pkg/errs"
|
|
"nova_task/internal/types"
|
|
)
|
|
|
|
type ApiKeyCheckMiddleware struct {
|
|
conf model.NhSystemConfigModel
|
|
user model.NhUserModel
|
|
}
|
|
|
|
func NewApiKeyCheckMiddleware(conf model.NhSystemConfigModel) *ApiKeyCheckMiddleware {
|
|
return &ApiKeyCheckMiddleware{conf: conf}
|
|
}
|
|
|
|
func (m *ApiKeyCheckMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
ctx := r.Context()
|
|
key, err := m.conf.GetCarvApiKey(ctx)
|
|
if err != nil {
|
|
if !errors.Is(err, model.ErrNotFound) {
|
|
result := types.CarvResult{
|
|
Error: &types.Error{
|
|
Code: int(errs.ErrDatabaseOperate),
|
|
Message: "api key config not exist",
|
|
},
|
|
}
|
|
errs.WriteHttpResponse(ctx, w, result)
|
|
return
|
|
}
|
|
}
|
|
apiKey := r.Header.Get("x-api-key")
|
|
if apiKey == "" || apiKey != key {
|
|
result := types.CarvResult{
|
|
Error: &types.Error{
|
|
Code: int(errs.ErrInvalidApiKey),
|
|
Message: "invalid api key",
|
|
},
|
|
}
|
|
errs.WriteHttpResponse(ctx, w, result)
|
|
return
|
|
}
|
|
|
|
next(w, r)
|
|
}
|
|
}
|