完善续期通知与前端界面
This commit is contained in:
1 parent
25419c027f
commit
45f895d0c4
64 files changed
+2948
-487
No files matched your search
@@ -249,6 +249,7 @@ func (s *Server) updateCookieLoginInfo(w http.ResponseWriter, r *http.Request) {
|
||||
Password string `json:"password"`
|
||||
LoginPassword string `json:"login_password"`
|
||||
ShowBrowser bool `json:"show_browser"`
|
||||
ClearPassword bool `json:"clear_password"`
|
||||
}
|
||||
if err := decodeJSON(r, &req); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "请求格式错误")
|
||||
@@ -258,7 +259,9 @@ func (s *Server) updateCookieLoginInfo(w http.ResponseWriter, r *http.Request) {
|
||||
if password == "" {
|
||||
password = req.LoginPassword
|
||||
}
|
||||
if password == "" && detail != nil {
|
||||
if req.ClearPassword {
|
||||
password = ""
|
||||
} else if password == "" && detail != nil {
|
||||
password = detail.Password
|
||||
}
|
||||
if err := s.Store.Cookies.UpdateLoginInfo(r.Context(), cid, req.Username, password, req.ShowBrowser); err != nil {
|
||||
|
||||
@@ -255,6 +255,22 @@ func TestUpdateCookieLoginInfo(t *testing.T) {
|
||||
if d.Username != "u2" || d.Password != "p1" || d.ShowBrowser {
|
||||
t.Fatalf("空密码更新应保留原密码并更新其他字段: %+v", d)
|
||||
}
|
||||
|
||||
body = `{"username":"u2","clear_password":true,"show_browser":false}`
|
||||
req = httptest.NewRequest(http.MethodPut, "/cookies/acc1/login-info", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec = httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("clear password status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
d, err = store.Cookies.GetDetails(ctx, "acc1")
|
||||
if err != nil {
|
||||
t.Fatalf("GetDetails after clear password: %v", err)
|
||||
}
|
||||
if d.Username != "u2" || d.Password != "" || d.ShowBrowser {
|
||||
t.Fatalf("clear_password 应清空密码并保留其他更新: %+v", d)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUpdateCookieLoginInfoBadJSON 非法 JSON 400。
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -70,8 +71,7 @@ func TestSetDefaultReplyBadJSON(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestGetDefaultReplyNotFound 不存在返回默认。
|
||||
func TestGetDefaultReplyNotFound(t *testing.T) {
|
||||
func TestGetDefaultReplyMissingAccountIsNotFound(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
@@ -81,8 +81,23 @@ func TestGetDefaultReplyNotFound(t *testing.T) {
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("status=%d", rec.Code)
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("不存在账号应 404,got %d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetDefaultReplyExistingAccountWithoutConfigReturnsDefault(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/default-replies/acc1", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var got map[string]any
|
||||
json.Unmarshal(rec.Body.Bytes(), &got)
|
||||
@@ -91,6 +106,32 @@ func TestGetDefaultReplyNotFound(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetDefaultReplyRejectsCrossUserAccount(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
if _, err := store.Users.Create(ctx, "default-other", "[email protected]", "pw"); err != nil {
|
||||
t.Fatalf("create other user: %v", err)
|
||||
}
|
||||
other, err := store.Users.GetByUsername(ctx, "default-other")
|
||||
if err != nil {
|
||||
t.Fatalf("get other user: %v", err)
|
||||
}
|
||||
if err := store.Cookies.Save(ctx, "other-acc", "unb=456; _m_h5_tk=tk2_1;", other.ID); err != nil {
|
||||
t.Fatalf("save other cookie: %v", err)
|
||||
}
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/default-replies/other-acc", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("跨用户账号应 403,got %d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeleteDefaultReply 删除。
|
||||
func TestDeleteDefaultReply(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
@@ -41,18 +40,7 @@ func (s *Server) mountDefaultRepliesReal(r chi.Router) {
|
||||
|
||||
func (s *Server) getDefaultReply(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cid")
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
if sess == nil {
|
||||
writeErr(w, http.StatusUnauthorized, "未授权访问")
|
||||
return
|
||||
}
|
||||
if d, err := s.Store.Cookies.GetDetails(r.Context(), cid); err == nil {
|
||||
if d.UserID != sess.UserID {
|
||||
writeErr(w, http.StatusForbidden, "无权限操作该账号")
|
||||
return
|
||||
}
|
||||
} else if !errors.Is(err, db.ErrNotFound) {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
|
||||
return
|
||||
}
|
||||
dr, err := s.Store.DefaultReps.Get(r.Context(), cid)
|
||||
|
||||
@@ -443,24 +443,64 @@ func (s *Server) updateItem(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
itemID := chi.URLParam(r, "item_id")
|
||||
var req struct {
|
||||
ItemTitle string `json:"item_title"`
|
||||
ItemDescription string `json:"item_description"`
|
||||
ItemCategory string `json:"item_category"`
|
||||
ItemPrice string `json:"item_price"`
|
||||
ItemDetail string `json:"item_detail"`
|
||||
IsMultiSpec bool `json:"is_multi_spec"`
|
||||
MultiQuantityDelivery bool `json:"multi_quantity_delivery"`
|
||||
IsMultiQtyShip bool `json:"is_multi_qty_ship"`
|
||||
ItemTitle *string `json:"item_title"`
|
||||
ItemDescription *string `json:"item_description"`
|
||||
ItemCategory *string `json:"item_category"`
|
||||
ItemPrice *string `json:"item_price"`
|
||||
ItemDetail *string `json:"item_detail"`
|
||||
IsMultiSpec *bool `json:"is_multi_spec"`
|
||||
MultiQuantityDelivery *bool `json:"multi_quantity_delivery"`
|
||||
IsMultiQtyShip *bool `json:"is_multi_qty_ship"`
|
||||
}
|
||||
if err := decodeJSON(r, &req); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "请求格式错误")
|
||||
return
|
||||
}
|
||||
if err := s.Store.Items.Upsert(r.Context(), &db.ItemInfoRow{
|
||||
CookieID: cid, ItemID: itemID, ItemTitle: req.ItemTitle, ItemDescription: req.ItemDescription,
|
||||
ItemCategory: req.ItemCategory, ItemPrice: req.ItemPrice, ItemDetail: req.ItemDetail,
|
||||
IsMultiSpec: req.IsMultiSpec, MultiQuantityDelivery: req.MultiQuantityDelivery || req.IsMultiQtyShip,
|
||||
}); err != nil {
|
||||
existing, err := s.Store.Items.Get(r.Context(), cid, itemID)
|
||||
if errors.Is(err, db.ErrNotFound) {
|
||||
writeErr(w, http.StatusNotFound, "商品不存在")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "更新失败")
|
||||
return
|
||||
}
|
||||
row := &db.ItemInfoRow{
|
||||
CookieID: cid,
|
||||
ItemID: itemID,
|
||||
ItemTitle: existing.ItemTitle,
|
||||
ItemDescription: existing.ItemDescription,
|
||||
ItemCategory: existing.ItemCategory,
|
||||
ItemPrice: existing.ItemPrice,
|
||||
ItemDetail: existing.ItemDetail,
|
||||
IsMultiSpec: existing.IsMultiSpec,
|
||||
MultiQuantityDelivery: existing.MultiQuantityDelivery,
|
||||
}
|
||||
if req.ItemTitle != nil {
|
||||
row.ItemTitle = *req.ItemTitle
|
||||
}
|
||||
if req.ItemDescription != nil {
|
||||
row.ItemDescription = *req.ItemDescription
|
||||
}
|
||||
if req.ItemCategory != nil {
|
||||
row.ItemCategory = *req.ItemCategory
|
||||
}
|
||||
if req.ItemPrice != nil {
|
||||
row.ItemPrice = *req.ItemPrice
|
||||
}
|
||||
if req.ItemDetail != nil {
|
||||
row.ItemDetail = *req.ItemDetail
|
||||
}
|
||||
if req.IsMultiSpec != nil {
|
||||
row.IsMultiSpec = *req.IsMultiSpec
|
||||
}
|
||||
if req.MultiQuantityDelivery != nil {
|
||||
row.MultiQuantityDelivery = *req.MultiQuantityDelivery
|
||||
}
|
||||
if req.IsMultiQtyShip != nil {
|
||||
row.MultiQuantityDelivery = *req.IsMultiQtyShip
|
||||
}
|
||||
if err := s.Store.Items.Upsert(r.Context(), row); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "更新失败")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -429,7 +429,11 @@ func TestItemCRUD(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
store.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id, item_id, item_title) VALUES ('acc1','it-crud','商品C')`)
|
||||
if _, err := store.DB.ExecContext(ctx, `INSERT INTO item_info
|
||||
(cookie_id, item_id, item_title, item_description, item_category, item_price, item_detail, is_multi_spec, multi_quantity_delivery)
|
||||
VALUES ('acc1','it-crud','商品C','原描述','原分类','12.00','原详情',1,1)`); err != nil {
|
||||
t.Fatalf("seed item: %v", err)
|
||||
}
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
@@ -465,6 +469,61 @@ func TestItemCRUD(t *testing.T) {
|
||||
if rec3.Code != 200 {
|
||||
t.Fatalf("update status=%d body=%s", rec3.Code, rec3.Body.String())
|
||||
}
|
||||
updated, err := store.Items.Get(ctx, "acc1", "it-crud")
|
||||
if err != nil {
|
||||
t.Fatalf("get updated item: %v", err)
|
||||
}
|
||||
if updated.ItemTitle != "改名商品" || updated.ItemPrice != "88.00" {
|
||||
t.Fatalf("update text fields failed: %+v", updated)
|
||||
}
|
||||
if updated.ItemDescription != "原描述" || updated.ItemCategory != "原分类" || updated.ItemDetail != "原详情" {
|
||||
t.Fatalf("omitted text fields should be preserved: %+v", updated)
|
||||
}
|
||||
if !updated.IsMultiSpec || !updated.MultiQuantityDelivery {
|
||||
t.Fatalf("omitted multi flags should be preserved: %+v", updated)
|
||||
}
|
||||
|
||||
// 显式传空字符串时允许清空文本字段。
|
||||
clearBody := `{"item_description":""}`
|
||||
reqClear := httptest.NewRequest(http.MethodPut, "/items/acc1/it-crud", strings.NewReader(clearBody))
|
||||
reqClear.AddCookie(cookie)
|
||||
recClear := httptest.NewRecorder()
|
||||
h.ServeHTTP(recClear, reqClear)
|
||||
if recClear.Code != 200 {
|
||||
t.Fatalf("clear text status=%d body=%s", recClear.Code, recClear.Body.String())
|
||||
}
|
||||
updated, err = store.Items.Get(ctx, "acc1", "it-crud")
|
||||
if err != nil {
|
||||
t.Fatalf("get cleared item: %v", err)
|
||||
}
|
||||
if updated.ItemDescription != "" || updated.ItemCategory != "原分类" || updated.ItemDetail != "原详情" {
|
||||
t.Fatalf("explicit empty text should clear only requested field: %+v", updated)
|
||||
}
|
||||
|
||||
// 显式传 false 时仍允许清除布尔配置。
|
||||
updFlagsBody := `{"item_title":"改名商品","item_price":"88.00","is_multi_spec":false,"is_multi_qty_ship":false}`
|
||||
reqFlags := httptest.NewRequest(http.MethodPut, "/items/acc1/it-crud", strings.NewReader(updFlagsBody))
|
||||
reqFlags.AddCookie(cookie)
|
||||
recFlags := httptest.NewRecorder()
|
||||
h.ServeHTTP(recFlags, reqFlags)
|
||||
if recFlags.Code != 200 {
|
||||
t.Fatalf("update flags status=%d body=%s", recFlags.Code, recFlags.Body.String())
|
||||
}
|
||||
updated, err = store.Items.Get(ctx, "acc1", "it-crud")
|
||||
if err != nil {
|
||||
t.Fatalf("get updated flags item: %v", err)
|
||||
}
|
||||
if updated.IsMultiSpec || updated.MultiQuantityDelivery {
|
||||
t.Fatalf("explicit false flags should be persisted: %+v", updated)
|
||||
}
|
||||
|
||||
reqMissing := httptest.NewRequest(http.MethodPut, "/items/acc1/missing-item", strings.NewReader(`{"item_title":"不会创建"}`))
|
||||
reqMissing.AddCookie(cookie)
|
||||
recMissing := httptest.NewRecorder()
|
||||
h.ServeHTTP(recMissing, reqMissing)
|
||||
if recMissing.Code != http.StatusNotFound {
|
||||
t.Fatalf("missing item update should be 404, got %d body=%s", recMissing.Code, recMissing.Body.String())
|
||||
}
|
||||
|
||||
// 多规格 + 多件发货。
|
||||
multiBody := `{"multi_quantity_delivery":true}`
|
||||
|
||||
@@ -78,13 +78,13 @@ func TestCreateChannelBadJSON(t *testing.T) {
|
||||
|
||||
// TestUpdateChannel 更新渠道。
|
||||
func TestUpdateChannel(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
// 创建。
|
||||
body := `{"name":"钉钉","type":"dingtalk","config":"{}","enabled":true}`
|
||||
body := `{"name":"钉钉","type":"dingtalk","config":"{\"webhook_url\":\"https://example.com\"}","event_types":"[\"account_offline\"]","enabled":true}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/notification-channels", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
@@ -93,8 +93,8 @@ func TestUpdateChannel(t *testing.T) {
|
||||
json.Unmarshal(rec.Body.Bytes(), &cr)
|
||||
id := int64(cr["id"].(float64))
|
||||
|
||||
// 更新。
|
||||
upd := `{"name":"改名钉钉","type":"dingtalk","config":"{}","enabled":false}`
|
||||
// 部分更新:只切换 enabled,不应清空 name/type/config/event_types。
|
||||
upd := `{"enabled":false}`
|
||||
req2 := httptest.NewRequest(http.MethodPut, "/notification-channels/"+itoa(id), strings.NewReader(upd))
|
||||
req2.AddCookie(cookie)
|
||||
rec2 := httptest.NewRecorder()
|
||||
@@ -102,6 +102,33 @@ func TestUpdateChannel(t *testing.T) {
|
||||
if rec2.Code != 200 {
|
||||
t.Fatalf("update status=%d body=%s", rec2.Code, rec2.Body.String())
|
||||
}
|
||||
row, err := store.Notifications.GetChannelRowForUser(context.Background(), id, 1)
|
||||
if err != nil {
|
||||
t.Fatalf("get channel row: %v", err)
|
||||
}
|
||||
if row == nil {
|
||||
t.Fatal("channel row missing")
|
||||
}
|
||||
if row.Name != "钉钉" || row.Type != "dingtalk" || row.Config != `{"webhook_url":"https://example.com"}` ||
|
||||
row.EventTypes != `["account_offline"]` || row.Enabled {
|
||||
t.Fatalf("partial update should preserve omitted fields and change enabled: %+v", row)
|
||||
}
|
||||
|
||||
// 显式传空 event_types 表示恢复为接收全部事件,其它字段仍保留。
|
||||
req3 := httptest.NewRequest(http.MethodPut, "/notification-channels/"+itoa(id), strings.NewReader(`{"event_types":""}`))
|
||||
req3.AddCookie(cookie)
|
||||
rec3 := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec3, req3)
|
||||
if rec3.Code != 200 {
|
||||
t.Fatalf("clear event_types status=%d body=%s", rec3.Code, rec3.Body.String())
|
||||
}
|
||||
row, err = store.Notifications.GetChannelRowForUser(context.Background(), id, 1)
|
||||
if err != nil {
|
||||
t.Fatalf("get channel row after clear: %v", err)
|
||||
}
|
||||
if row.EventTypes != "" || row.Name != "钉钉" || row.Config != `{"webhook_url":"https://example.com"}` {
|
||||
t.Fatalf("event_types clear should not affect other fields: %+v", row)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUpdateChannelBadID 无效 ID 400。
|
||||
@@ -294,6 +321,29 @@ func TestMessageNotificationsFilterCrossUserChannels(t *testing.T) {
|
||||
if len(ids) != 1 || int64(ids[0].(float64)) != ownID {
|
||||
t.Fatalf("bindings should filter dirty binding: %+v", got)
|
||||
}
|
||||
|
||||
updateOtherReq := httptest.NewRequest(http.MethodPut, "/notification-channels/"+itoa(otherID), strings.NewReader(`{"enabled":false}`))
|
||||
updateOtherReq.AddCookie(cookie)
|
||||
updateOtherRec := httptest.NewRecorder()
|
||||
h.ServeHTTP(updateOtherRec, updateOtherReq)
|
||||
if updateOtherRec.Code != http.StatusForbidden {
|
||||
t.Fatalf("cross-user update should be 403, got %d body=%s", updateOtherRec.Code, updateOtherRec.Body.String())
|
||||
}
|
||||
otherRow, err := store.Notifications.GetChannelRowForUser(ctx, otherID, u2.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("get other channel: %v", err)
|
||||
}
|
||||
if otherRow == nil || !otherRow.Enabled {
|
||||
t.Fatalf("cross-user update should not mutate other channel: %+v", otherRow)
|
||||
}
|
||||
|
||||
deleteOtherReq := httptest.NewRequest(http.MethodDelete, "/notification-channels/"+itoa(otherID), nil)
|
||||
deleteOtherReq.AddCookie(cookie)
|
||||
deleteOtherRec := httptest.NewRecorder()
|
||||
h.ServeHTTP(deleteOtherRec, deleteOtherReq)
|
||||
if deleteOtherRec.Code != http.StatusForbidden {
|
||||
t.Fatalf("cross-user delete should be 403, got %d body=%s", deleteOtherRec.Code, deleteOtherRec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeleteMessageNotification 删除单条消息通知。
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
@@ -37,17 +38,18 @@ func (s *Server) listChannels(w http.ResponseWriter, r *http.Request) {
|
||||
func (s *Server) createChannel(w http.ResponseWriter, r *http.Request) {
|
||||
sess := authSess(r)
|
||||
var req struct {
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Config string `json:"config"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Config string `json:"config"`
|
||||
EventTypes string `json:"event_types"`
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
if err := decodeJSON(r, &req); err != nil || req.Name == "" || req.Type == "" {
|
||||
writeErr(w, http.StatusBadRequest, "name 和 type 必填")
|
||||
return
|
||||
}
|
||||
id, err := s.Store.Notifications.CreateChannel(r.Context(), &db.NotificationChannelRow{
|
||||
Name: req.Name, Type: req.Type, Config: req.Config, Enabled: req.Enabled, UserID: sess.UserID,
|
||||
Name: req.Name, Type: req.Type, Config: req.Config, EventTypes: req.EventTypes, Enabled: req.Enabled, UserID: sess.UserID,
|
||||
})
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "创建失败")
|
||||
@@ -63,21 +65,50 @@ func (s *Server) updateChannel(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Config string `json:"config"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Name *string `json:"name"`
|
||||
Type *string `json:"type"`
|
||||
Config *string `json:"config"`
|
||||
EventTypes *string `json:"event_types"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
}
|
||||
if err := decodeJSON(r, &req); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "请求格式错误")
|
||||
return
|
||||
}
|
||||
if !s.requireChannelOwner(w, r, id) {
|
||||
sess := authSess(r)
|
||||
row, err := s.Store.Notifications.GetChannelRowForUser(r.Context(), id, sess.UserID)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
if err := s.Store.Notifications.UpdateChannel(r.Context(), &db.NotificationChannelRow{
|
||||
ID: id, Name: req.Name, Type: req.Type, Config: req.Config, Enabled: req.Enabled,
|
||||
}); err != nil {
|
||||
if row == nil {
|
||||
writeErr(w, http.StatusForbidden, "无权操作该通知渠道")
|
||||
return
|
||||
}
|
||||
if req.Name != nil {
|
||||
row.Name = *req.Name
|
||||
}
|
||||
if req.Type != nil {
|
||||
row.Type = *req.Type
|
||||
}
|
||||
if req.Config != nil {
|
||||
row.Config = *req.Config
|
||||
}
|
||||
if req.EventTypes != nil {
|
||||
row.EventTypes = *req.EventTypes
|
||||
}
|
||||
if req.Enabled != nil {
|
||||
row.Enabled = *req.Enabled
|
||||
}
|
||||
if row.Name == "" || row.Type == "" {
|
||||
writeErr(w, http.StatusBadRequest, "name 和 type 必填")
|
||||
return
|
||||
}
|
||||
if err := s.Store.Notifications.UpdateChannelForUser(r.Context(), row, sess.UserID); err != nil {
|
||||
if errors.Is(err, db.ErrNotFound) {
|
||||
writeErr(w, http.StatusForbidden, "无权操作该通知渠道")
|
||||
return
|
||||
}
|
||||
writeErr(w, http.StatusInternalServerError, "更新失败")
|
||||
return
|
||||
}
|
||||
@@ -90,10 +121,12 @@ func (s *Server) deleteChannel(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusBadRequest, "无效ID")
|
||||
return
|
||||
}
|
||||
if !s.requireChannelOwner(w, r, id) {
|
||||
return
|
||||
}
|
||||
if err := s.Store.Notifications.DeleteChannel(r.Context(), id); err != nil {
|
||||
sess := authSess(r)
|
||||
if err := s.Store.Notifications.DeleteChannelForUser(r.Context(), id, sess.UserID); err != nil {
|
||||
if errors.Is(err, db.ErrNotFound) {
|
||||
writeErr(w, http.StatusForbidden, "无权操作该通知渠道")
|
||||
return
|
||||
}
|
||||
writeErr(w, http.StatusInternalServerError, "删除失败")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -177,7 +177,7 @@ func (s *Server) runPasswordLoginSession(ctx context.Context, session *passwordL
|
||||
cookies map[string]string
|
||||
err error
|
||||
)
|
||||
headless := !session.ShowBrowser
|
||||
headless := browser.ResolveHeadless(session.ShowBrowser)
|
||||
if runner, ok := s.PasswordLogin.(passwordLoginEventRunner); ok {
|
||||
cookies, err = runner.PasswordLoginWithEvents(ctx, session.Account, password, session.AccountID, "", headless, func(event browser.PasswordLoginEvent) {
|
||||
s.applyPasswordLoginEvent(session, event)
|
||||
@@ -405,10 +405,6 @@ func cookieAccountID(cookies map[string]string, fallback string) string {
|
||||
return fallback
|
||||
}
|
||||
|
||||
func loginStatusForPasswordError(err error) string {
|
||||
return browser.PasswordLoginEventFromError(err).Status
|
||||
}
|
||||
|
||||
func passwordLoginReason(err error) string {
|
||||
if err == nil {
|
||||
return ""
|
||||
|
||||
@@ -3,10 +3,13 @@ package server
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"xianyu-go/internal/logging"
|
||||
)
|
||||
|
||||
// TestListAIModels 通过 mock OpenAI 端点返回模型列表。
|
||||
@@ -103,6 +106,38 @@ func TestSetSettingBadJSON(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetLogLevelValidatesAndAppliesRuntimeLevel(t *testing.T) {
|
||||
defer logging.Level.Set(slog.LevelInfo)
|
||||
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
badReq := httptest.NewRequest(http.MethodPut, "/system-settings/log_level", strings.NewReader(`{"value":"verbose"}`))
|
||||
badReq.AddCookie(cookie)
|
||||
badRec := httptest.NewRecorder()
|
||||
h.ServeHTTP(badRec, badReq)
|
||||
if badRec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("invalid log level should be 400, got %d body=%s", badRec.Code, badRec.Body.String())
|
||||
}
|
||||
|
||||
goodReq := httptest.NewRequest(http.MethodPut, "/system-settings/log_level", strings.NewReader(`{"value":"debug"}`))
|
||||
goodReq.AddCookie(cookie)
|
||||
goodRec := httptest.NewRecorder()
|
||||
h.ServeHTTP(goodRec, goodReq)
|
||||
if goodRec.Code != http.StatusOK {
|
||||
t.Fatalf("valid log level should be 200, got %d body=%s", goodRec.Code, goodRec.Body.String())
|
||||
}
|
||||
if got := logging.Level.Level(); got != slog.LevelDebug {
|
||||
t.Fatalf("runtime log level=%v want debug", got)
|
||||
}
|
||||
saved, err := srv.Store.Settings.Get(context.Background(), "log_level")
|
||||
if err != nil || saved != "debug" {
|
||||
t.Fatalf("saved log_level=%q err=%v", saved, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSystemSettingsRequireAdmin(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
@@ -225,8 +260,7 @@ func TestSetAIReplyBadJSON(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestGetAIReplyNotFound 不存在账号返回默认值。
|
||||
func TestGetAIReplyNotFound(t *testing.T) {
|
||||
func TestGetAIReplyMissingAccountIsNotFound(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
@@ -236,8 +270,23 @@ func TestGetAIReplyNotFound(t *testing.T) {
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("status=%d", rec.Code)
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("不存在账号应 404,got %d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetAIReplyExistingAccountWithoutConfigReturnsDefault(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/ai-reply-settings/acc1", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var res map[string]any
|
||||
json.Unmarshal(rec.Body.Bytes(), &res)
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
|
||||
"xianyu-go/internal/auth"
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/logging"
|
||||
)
|
||||
|
||||
const maxOpenAIModelsResponseBytes = 4 << 20
|
||||
@@ -60,6 +61,12 @@ func (s *Server) setSetting(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusBadRequest, "请求格式错误")
|
||||
return
|
||||
}
|
||||
if key == "log_level" {
|
||||
if err := logging.SetLevel(req.Value); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
if err := s.Store.Settings.Set(r.Context(), key, req.Value); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "保存失败")
|
||||
return
|
||||
@@ -115,18 +122,7 @@ func (s *Server) listAIReply(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
func (s *Server) getAIReply(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cookie_id")
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
if sess == nil {
|
||||
writeErr(w, http.StatusUnauthorized, "未授权访问")
|
||||
return
|
||||
}
|
||||
if d, err := s.Store.Cookies.GetDetails(r.Context(), cid); err == nil {
|
||||
if d.UserID != sess.UserID {
|
||||
writeErr(w, http.StatusForbidden, "无权限操作该账号")
|
||||
return
|
||||
}
|
||||
} else if !errors.Is(err, db.ErrNotFound) {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
|
||||
return
|
||||
}
|
||||
cfg, err := s.Store.AIReply.Get(r.Context(), cid)
|
||||
|
||||
Reference in new issue
Block a user