carv api logic

This commit is contained in:
lianghuanjie
2025-01-08 17:53:43 +08:00
parent 5c4862fd70
commit 5d2a0a8b5d
14 changed files with 252 additions and 62 deletions

View File

@@ -4,6 +4,8 @@ import (
"errors"
"net/http"
"nova_task/internal/model"
"nova_task/internal/pkg/errs"
"nova_task/internal/types"
)
type ApiKeyCheckMiddleware struct {
@@ -17,16 +19,29 @@ func NewApiKeyCheckMiddleware(conf model.NhSystemConfigModel) *ApiKeyCheckMiddle
func (m *ApiKeyCheckMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
key, err := m.conf.GetCarvApiKey(r.Context())
ctx := r.Context()
key, err := m.conf.GetCarvApiKey(ctx)
if err != nil {
if !errors.Is(err, model.ErrNotFound) {
http.Error(w, "system error", http.StatusInternalServerError)
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 {
http.Error(w, "Invalid API key", http.StatusUnauthorized)
result := types.CarvResult{
Error: &types.Error{
Code: int(errs.ErrInvalidApiKey),
Message: "invalid api key",
},
}
errs.WriteHttpResponse(ctx, w, result)
return
}