37 lines
978 B
Go
37 lines
978 B
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"nova_task/internal/consts"
|
|
"nova_task/internal/model"
|
|
"nova_task/internal/pkg/errs"
|
|
)
|
|
|
|
type Game7ApiKeyCheckMiddleware struct {
|
|
conf model.NhSystemConfigModel
|
|
}
|
|
|
|
func NewGame7ApiKeyCheckMiddleware(conf model.NhSystemConfigModel) *Game7ApiKeyCheckMiddleware {
|
|
return &Game7ApiKeyCheckMiddleware{conf: conf}
|
|
}
|
|
|
|
func (m *Game7ApiKeyCheckMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
ctx := r.Context()
|
|
key, err := m.conf.GetApiKey(ctx, consts.Game7ApiKey)
|
|
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)
|
|
}
|
|
}
|