Files

73 lines
2.0 KiB
Go

package httpapi
import (
"net/http"
"sea-vhost/internal/scope"
"sea-vhost/internal/store"
"strconv"
)
func (s *Server) requireUserAccount(next http.HandlerFunc) http.HandlerFunc {
return s.requireAuth(func(w http.ResponseWriter, r *http.Request) {
u := currentUser(r)
if u.Role != "tenant" || u.TenantID == nil {
writeError(w, 403, "计划任务仅供用户账号使用")
return
}
next(w, r.WithContext(scope.WithAccount(r.Context(), *u.TenantID)))
})
}
func (s *Server) userSchedules(w http.ResponseWriter, r *http.Request) {
if action := r.PathValue("action"); action != "" && action != "run" {
writeError(w, 404, "操作不存在")
return
}
u := currentUser(r)
id, _ := strconv.ParseUint(r.PathValue("scheduleID"), 10, 64)
if r.Method == "GET" {
if r.PathValue("scheduleID") != "" {
items, e := s.projects.ScheduleRuns(r.Context(), u, id)
if e != nil {
writeError(w, 404, "任务不存在")
return
}
writeJSON(w, 200, map[string]any{"runs": items})
return
}
items, e := s.projects.UserSchedules(r.Context(), u)
if e != nil {
writeError(w, 503, "无法读取计划任务")
return
}
writeJSON(w, 200, map[string]any{"schedules": items})
return
}
var err error
action := "update"
if r.Method == "DELETE" {
err = s.store.DeleteUserSchedule(r.Context(), u.ID, id)
action = "delete"
} else if r.PathValue("action") == "run" {
err = s.store.RequestUserScheduleRun(r.Context(), u.ID, id)
action = "queue"
} else {
var input store.UserSchedule
if decodeJSON(r, &input) != nil {
writeError(w, 400, "任务配置格式无效")
return
}
input.ID = id
var saved uint64
saved, err = s.projects.SaveUserSchedule(r.Context(), u, input)
if err == nil {
id = saved
}
}
s.store.Log(r.Context(), u.TenantID, u.ID, action, "schedule", strconv.FormatUint(id, 10), requestClientIP(r), err == nil, "管理用户计划任务")
if err != nil {
writeError(w, 422, err.Error())
return
}
writeJSON(w, 200, map[string]any{"id": id})
}