59 lines
1.9 KiB
Go
59 lines
1.9 KiB
Go
package synthetic
|
|
|
|
import (
|
|
"errors"
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/gin-gonic/gin/binding"
|
|
"github.com/go-admin-team/go-admin-core/sdk/api"
|
|
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
|
|
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
|
|
|
|
"go-admin/app/bell/event"
|
|
)
|
|
|
|
const maxRequestBytes = 64 * 1024
|
|
|
|
type Handler struct{ api.Api }
|
|
|
|
func IsAdministrator(c *gin.Context) bool {
|
|
claims := jwt.ExtractClaims(c)
|
|
role, _ := claims[jwt.RoleKey].(string)
|
|
return role == "admin"
|
|
}
|
|
|
|
func (h Handler) Create(c *gin.Context) {
|
|
if !IsAdministrator(c) {
|
|
h.MakeContext(c).Error(http.StatusForbidden, errors.New("无权使用合成事件入口"), "无权使用合成事件入口")
|
|
return
|
|
}
|
|
if err := restoreRequestBody(c); err != nil {
|
|
h.MakeContext(c).Error(http.StatusBadRequest, errors.New("请求内容格式不正确"), "请求内容格式不正确")
|
|
return
|
|
}
|
|
var request CreateRequest
|
|
h.MakeContext(c).MakeOrm().Bind(&request, binding.JSON)
|
|
if h.Errors != nil {
|
|
h.Error(http.StatusBadRequest, errors.New("请求内容格式不正确"), "请求内容格式不正确")
|
|
return
|
|
}
|
|
result, err := event.NewService(h.Orm).Ingest(c.Request.Context(), request.Command(), user.GetUserId(c))
|
|
if err != nil {
|
|
switch {
|
|
case errors.Is(err, event.ErrInvalid):
|
|
h.Error(http.StatusBadRequest, event.ErrInvalid, event.ErrInvalid.Error())
|
|
case errors.Is(err, event.ErrConflict):
|
|
h.Error(http.StatusConflict, event.ErrConflict, event.ErrConflict.Error())
|
|
default:
|
|
h.Logger.Errorf("synthetic event ingest failed: %v", err)
|
|
h.Error(http.StatusInternalServerError, errors.New("合成事件写入失败"), "合成事件写入失败")
|
|
}
|
|
return
|
|
}
|
|
h.OK(result, "合成事件已接收")
|
|
// The client already received the full response. Keep only a fixed marker
|
|
// for GoAdmin's generic operation audit, which runs after the handler.
|
|
c.Set("result", gin.H{"code": http.StatusOK, "data": "<redacted>"})
|
|
}
|