48 lines
1.1 KiB
Go
48 lines
1.1 KiB
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"nova_task/internal/consts"
|
|
"nova_task/internal/model"
|
|
"nova_task/internal/pkg/errs"
|
|
"nova_task/internal/types"
|
|
)
|
|
|
|
type ApiKeyCheckMiddleware struct {
|
|
conf model.NhSystemConfigModel
|
|
}
|
|
|
|
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.GetApiKey(ctx, consts.CarvApiKey)
|
|
if err != nil {
|
|
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.ErrUnauthorized),
|
|
Message: "invalid api key",
|
|
},
|
|
}
|
|
errs.WriteHttpResponse(ctx, w, result)
|
|
return
|
|
}
|
|
|
|
next(w, r)
|
|
}
|
|
}
|