51 lines
2.0 KiB
Go
51 lines
2.0 KiB
Go
package admission
|
|
|
|
import (
|
|
"net/http"
|
|
"yovision.local/sense/app/sense/identity"
|
|
"yovision.local/sense/internal/platform"
|
|
)
|
|
|
|
type Module struct{ service *Service }
|
|
|
|
func NewModule(service *Service) *Module { return &Module{service: service} }
|
|
func (m *Module) Register(app *platform.App) {
|
|
setCurrentService(m.service)
|
|
app.Handle("GET /api/v1/admission/discover", identity.Require(identity.PermissionDeviceWrite, http.HandlerFunc(m.discover)))
|
|
app.Handle("POST /api/v1/admission/probe", identity.Require(identity.PermissionDeviceWrite, http.HandlerFunc(m.probe)))
|
|
app.Handle("GET /api/v1/admission/devices/{id}", identity.Require(identity.PermissionDeviceRead, http.HandlerFunc(m.get)))
|
|
}
|
|
func (m *Module) discover(w http.ResponseWriter, r *http.Request) {
|
|
items, err := m.service.Discover(r.Context())
|
|
if err != nil {
|
|
platform.WriteError(w, &platform.APIError{Status: http.StatusServiceUnavailable, Code: "discovery_unavailable", Message: "未配置获准的发现网卡"})
|
|
return
|
|
}
|
|
platform.WriteJSON(w, http.StatusOK, map[string]any{"items": items})
|
|
}
|
|
func (m *Module) probe(w http.ResponseWriter, r *http.Request) {
|
|
var request struct {
|
|
DeviceID string `json:"device_id"`
|
|
Address string `json:"address"`
|
|
}
|
|
if err := platform.DecodeJSON(r, &request); err != nil {
|
|
platform.WriteError(w, err)
|
|
return
|
|
}
|
|
actor, _ := identity.PrincipalFromContext(r.Context())
|
|
result, err := m.service.Probe(r.Context(), actor, request.DeviceID, request.Address)
|
|
if err != nil {
|
|
platform.WriteError(w, &platform.APIError{Status: http.StatusBadRequest, Code: "admission_failed", Message: err.Error()})
|
|
return
|
|
}
|
|
platform.WriteJSON(w, http.StatusOK, result)
|
|
}
|
|
func (m *Module) get(w http.ResponseWriter, r *http.Request) {
|
|
result, ok := m.service.Get(r.PathValue("id"))
|
|
if !ok {
|
|
platform.WriteError(w, &platform.APIError{Status: http.StatusNotFound, Code: "admission_not_found", Message: "尚未执行接入验证"})
|
|
return
|
|
}
|
|
platform.WriteJSON(w, http.StatusOK, result)
|
|
}
|