diff --git a/internal/adminweb/control.go b/internal/adminweb/control.go
index 3ce0628..cbacf4b 100644
--- a/internal/adminweb/control.go
+++ b/internal/adminweb/control.go
@@ -21,6 +21,10 @@ type ConfigRepository interface {
CreateBootstrapChallenge(context.Context, string, string, time.Time) error
ConfirmBootstrap(context.Context, string) error
}
+type AdministratorRepository interface {
+ ListAdministrators(context.Context, string) ([]settings.Administrator, error)
+ DisableAdministrator(context.Context, string, string) error
+}
type CandidateActivator interface{ ActivateCandidate(context.Context) error }
type OperationalStatusProvider interface {
Components(context.Context) ([]Component, error)
@@ -56,6 +60,27 @@ func (s *ControlService) Snapshot(ctx context.Context) (Snapshot, error) {
if err != nil {
return Snapshot{}, err
}
+ administratorViews := []AdministratorView{}
+ if administratorRepo, ok := s.repo.(AdministratorRepository); ok {
+ administrators, listErr := administratorRepo.ListAdministrators(ctx, s.tenant)
+ if listErr != nil {
+ return Snapshot{}, listErr
+ }
+ activeCount := 0
+ for _, administrator := range administrators {
+ if administrator.Status == "active" {
+ activeCount++
+ }
+ }
+ for _, administrator := range administrators {
+ administratorViews = append(administratorViews, AdministratorView{
+ StaffID: administrator.StaffID, StaffIDMasked: maskID(administrator.StaffID),
+ DisplayName: administrator.DisplayName, Department: administrator.Department,
+ Role: administrator.Role, Status: administrator.Status,
+ CanDisable: administrator.Status == "active" && activeCount > 1,
+ })
+ }
+ }
state := settings.DetermineState(settings.Snapshot{ClientID: id, SecretConfigured: s.secrets.Configured(ref), CredentialsVerified: verified, AdministratorCount: admins})
now := time.Now()
components := []Component{
@@ -74,7 +99,7 @@ func (s *ControlService) Snapshot(ctx context.Context) (Snapshot, error) {
components = append(components, operational...)
}
}
- return Snapshot{SystemState: string(state), ClientIDMasked: maskID(id), SecretConfigured: s.secrets.Configured(ref), Components: components}, nil
+ return Snapshot{SystemState: string(state), ClientIDMasked: maskID(id), SecretConfigured: s.secrets.Configured(ref), Components: components, Administrators: administratorViews}, nil
}
func (s *ControlService) VerifyCredentials(ctx context.Context, id, secret string) Verification {
r := s.verifier.Verify(ctx, id, secret)
@@ -119,6 +144,17 @@ func (s *ControlService) CreateBootstrap(ctx context.Context, code string) error
func (s *ControlService) ConfirmBootstrap(ctx context.Context) error {
return s.repo.ConfirmBootstrap(ctx, s.tenant)
}
+func (s *ControlService) DisableAdministrator(ctx context.Context, staffID string) error {
+ staffID = strings.TrimSpace(staffID)
+ if staffID == "" {
+ return settings.ErrAdministratorNotFound
+ }
+ repo, ok := s.repo.(AdministratorRepository)
+ if !ok {
+ return errors.New("administrator management unavailable")
+ }
+ return repo.DisableAdministrator(ctx, s.tenant, staffID)
+}
func maskID(v string) string {
v = strings.TrimSpace(v)
if len(v) <= 6 {
diff --git a/internal/adminweb/control_test.go b/internal/adminweb/control_test.go
index 70d8582..8746381 100644
--- a/internal/adminweb/control_test.go
+++ b/internal/adminweb/control_test.go
@@ -16,6 +16,9 @@ type controlRepo struct {
savedRef string
candidateRef string
failedCode string
+ admins []settings.Administrator
+ disabledStaff string
+ disableErr error
}
func (*controlRepo) ActiveDingTalkConfig(context.Context, string) (string, string, bool, error) {
@@ -34,7 +37,25 @@ func (r *controlRepo) MarkDingTalkCandidateFailed(_ context.Context, _, _, code
r.failedCode = code
return nil
}
-func (*controlRepo) AdministratorCount(context.Context, string) (int, error) { return 1, nil }
+func (r *controlRepo) AdministratorCount(context.Context, string) (int, error) {
+ if r.admins == nil {
+ return 1, nil
+ }
+ n := 0
+ for _, admin := range r.admins {
+ if admin.Status == "active" {
+ n++
+ }
+ }
+ return n, nil
+}
+func (r *controlRepo) ListAdministrators(context.Context, string) ([]settings.Administrator, error) {
+ return r.admins, nil
+}
+func (r *controlRepo) DisableAdministrator(_ context.Context, _, staffID string) error {
+ r.disabledStaff = staffID
+ return r.disableErr
+}
func (*controlRepo) ActiveBindings(context.Context, string) (map[string]settings.ResourceBinding, error) {
return map[string]settings.ResourceBinding{}, nil
}
@@ -149,3 +170,41 @@ func TestActivateCandidateDelegatesAndMarksFailure(t *testing.T) {
t.Fatalf("calls=%d code=%q", activator.calls, repo.failedCode)
}
}
+
+func TestSnapshotIncludesAdministratorsAndOnlyAllowsDisableWhenAnotherIsActive(t *testing.T) {
+ secrets, _ := secretstore.New(t.TempDir())
+ repo := &controlRepo{admins: []settings.Administrator{
+ {StaffID: "staff-old", DisplayName: "旧管理员", Department: "技术部", Role: "super_admin", Status: "active"},
+ {StaffID: "staff-new", DisplayName: "新管理员", Department: "产品部", Role: "super_admin", Status: "active"},
+ {StaffID: "staff-off", DisplayName: "停用管理员", Role: "admin", Status: "disabled"},
+ }}
+ service, err := NewControlService("tenant", repo, secrets, verifyOK{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ snapshot, err := service.Snapshot(context.Background())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(snapshot.Administrators) != 3 || !snapshot.Administrators[0].CanDisable || !snapshot.Administrators[1].CanDisable || snapshot.Administrators[2].CanDisable {
+ t.Fatalf("administrators=%+v", snapshot.Administrators)
+ }
+ if snapshot.Administrators[0].StaffIDMasked == "staff-old" || snapshot.Administrators[0].StaffIDMasked == "" {
+ t.Fatalf("staff ID must be masked: %+v", snapshot.Administrators[0])
+ }
+}
+
+func TestControlServiceDelegatesAdministratorDisable(t *testing.T) {
+ secrets, _ := secretstore.New(t.TempDir())
+ repo := &controlRepo{}
+ service, err := NewControlService("tenant", repo, secrets, verifyOK{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = service.DisableAdministrator(context.Background(), "staff-old"); err != nil {
+ t.Fatal(err)
+ }
+ if repo.disabledStaff != "staff-old" {
+ t.Fatalf("disabled=%q", repo.disabledStaff)
+ }
+}
diff --git a/internal/adminweb/server.go b/internal/adminweb/server.go
index aacd6ae..fc532bd 100644
--- a/internal/adminweb/server.go
+++ b/internal/adminweb/server.go
@@ -2,18 +2,28 @@ package adminweb
import (
"context"
+ "crypto/rand"
"crypto/subtle"
+ "encoding/hex"
+ "errors"
"fmt"
"html/template"
"net/http"
"strings"
"time"
+
+ "gitea.zheromiku.top/Weknora/dobotai-platform/internal/settings"
)
type Snapshot struct {
SystemState, ClientIDMasked string
SecretConfigured bool
Components []Component
+ Administrators []AdministratorView
+}
+type AdministratorView struct {
+ StaffID, StaffIDMasked, DisplayName, Department, Role, Status string
+ CanDisable bool
}
type Component struct {
Name, State, Code, Detail string
@@ -36,14 +46,41 @@ type BootstrapService interface {
type CandidateService interface {
ActivateCandidate(context.Context) error
}
+type AdministratorService interface {
+ DisableAdministrator(context.Context, string) error
+}
type server struct {
- service Service
- token string
- mux *http.ServeMux
- page *template.Template
+ service Service
+ token string
+ csrfToken string
+ mux *http.ServeMux
+ page *template.Template
+}
+type pageData struct {
+ Snapshot
+ CSRFToken string
}
-const settingsPage = `
DobotAI 设置DobotAI 配置中心
系统状态:{{.SystemState}}
Client ID:{{.ClientIDMasked}}
Client Secret:{{if .SecretConfigured}}已配置(不可查看){{else}}未配置{{end}}
配置/切换钉钉应用
新凭据先在线验证并保存为候选。激活后受控重启整组钉钉组件,失败自动回滚。
首位管理员
组件检查
{{range .Components}}{{.Name}}:{{.State}}
错误码:{{if .Code}}{{.Code}}{{else}}—{{end}}
最后成功:{{timeText .LastSuccess}}
最后检查:{{timeText .CheckedAt}}
{{.Detail}}
{{end}}`
+const settingsPage = `
+
+
+
+DobotAI 设置
+
+
+
+DobotAI 配置中心
+系统状态:{{.SystemState}}
Client ID:{{.ClientIDMasked}}
Client Secret:{{if .SecretConfigured}}已配置(不可查看){{else}}未配置{{end}}
+配置/切换钉钉应用
新凭据先在线验证并保存为候选。激活后受控重启整组钉钉组件,失败自动回滚。
+新增/更换管理员
必须先加后停:先确认新管理员已生效,再停用旧管理员。系统禁止停用最后一位有效管理员。
- 输入任意6位一次性绑定码并生成,有效期10分钟。
- 新管理员私聊机器人发送
/setting 6位码。 - 回到本页确认检测到的新管理员。
- 在下方确认新管理员状态为active,再停用旧管理员。
管理员列表
| 姓名 | 部门 | Staff ID | 角色 | 状态 | 操作 |
{{range .Administrators}}| {{if .DisplayName}}{{.DisplayName}}{{else}}—{{end}} | {{if .Department}}{{.Department}}{{else}}—{{end}} | {{.StaffIDMasked}} | {{.Role}} | {{.Status}} | {{if .CanDisable}}{{else}}—{{end}} |
{{else}}| 暂无管理员记录 |
{{end}}
+组件检查
{{range .Components}}{{.Name}}:{{.State}}
错误码:{{if .Code}}{{.Code}}{{else}}—{{end}}
最后成功:{{timeText .LastSuccess}}
最后检查:{{timeText .CheckedAt}}
{{.Detail}}
{{end}}
+`
func New(service Service, token string) http.Handler {
functions := template.FuncMap{"timeText": func(value time.Time) string {
@@ -52,13 +89,18 @@ func New(service Service, token string) http.Handler {
}
return value.UTC().Format("2006-01-02 15:04:05")
}}
- s := &server{service: service, token: strings.TrimSpace(token), mux: http.NewServeMux(), page: template.Must(template.New("settings").Funcs(functions).Parse(settingsPage))}
+ csrfBytes := make([]byte, 32)
+ if _, err := rand.Read(csrfBytes); err != nil {
+ panic("admin CSRF token unavailable")
+ }
+ s := &server{service: service, token: strings.TrimSpace(token), csrfToken: hex.EncodeToString(csrfBytes), mux: http.NewServeMux(), page: template.Must(template.New("settings").Funcs(functions).Parse(settingsPage))}
s.mux.HandleFunc("GET /admin/settings", s.settings)
s.mux.HandleFunc("GET /admin/setup", s.settings)
s.mux.HandleFunc("POST /admin/setup/credentials", s.saveCredentials)
s.mux.HandleFunc("POST /admin/setup/candidate/activate", s.activateCandidate)
s.mux.HandleFunc("POST /admin/setup/bootstrap", s.createBootstrap)
s.mux.HandleFunc("POST /admin/setup/bootstrap/confirm", s.confirmBootstrap)
+ s.mux.HandleFunc("POST /admin/settings/administrators/disable", s.disableAdministrator)
return s
}
func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
@@ -80,6 +122,19 @@ func (s *server) authorized(r *http.Request) bool {
v := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
return len(v) == len(s.token) && subtle.ConstantTimeCompare([]byte(v), []byte(s.token)) == 1
}
+func (s *server) requireCSRFForm(w http.ResponseWriter, r *http.Request, maxBytes int64) bool {
+ r.Body = http.MaxBytesReader(w, r.Body, maxBytes)
+ if err := r.ParseForm(); err != nil {
+ http.Error(w, "invalid form", http.StatusBadRequest)
+ return false
+ }
+ provided := strings.TrimSpace(r.FormValue("csrf_token"))
+ if len(provided) != len(s.csrfToken) || subtle.ConstantTimeCompare([]byte(provided), []byte(s.csrfToken)) != 1 {
+ http.Error(w, "forbidden", http.StatusForbidden)
+ return false
+ }
+ return true
+}
func (s *server) settings(w http.ResponseWriter, r *http.Request) {
snap, err := s.service.Snapshot(r.Context())
if err != nil {
@@ -87,12 +142,10 @@ func (s *server) settings(w http.ResponseWriter, r *http.Request) {
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
- _ = s.page.Execute(w, snap)
+ _ = s.page.Execute(w, pageData{Snapshot: snap, CSRFToken: s.csrfToken})
}
func (s *server) saveCredentials(w http.ResponseWriter, r *http.Request) {
- r.Body = http.MaxBytesReader(w, r.Body, 16<<10)
- if err := r.ParseForm(); err != nil {
- http.Error(w, "invalid form", 400)
+ if !s.requireCSRFForm(w, r, 16<<10) {
return
}
id, secret := strings.TrimSpace(r.FormValue("client_id")), strings.TrimSpace(r.FormValue("client_secret"))
@@ -108,6 +161,9 @@ func (s *server) saveCredentials(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/admin/settings", http.StatusSeeOther)
}
func (s *server) activateCandidate(w http.ResponseWriter, r *http.Request) {
+ if !s.requireCSRFForm(w, r, 4<<10) {
+ return
+ }
service, ok := s.service.(CandidateService)
if !ok {
http.Error(w, "candidate unavailable", http.StatusNotImplemented)
@@ -121,16 +177,14 @@ func (s *server) activateCandidate(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("候选已激活,DobotAI正在受控重启。\n"))
}
func (s *server) createBootstrap(w http.ResponseWriter, r *http.Request) {
+ if !s.requireCSRFForm(w, r, 4<<10) {
+ return
+ }
service, ok := s.service.(BootstrapService)
if !ok {
http.Error(w, "bootstrap unavailable", http.StatusNotImplemented)
return
}
- r.Body = http.MaxBytesReader(w, r.Body, 4<<10)
- if err := r.ParseForm(); err != nil {
- http.Error(w, "invalid form", 400)
- return
- }
code := strings.TrimSpace(r.FormValue("code"))
if !sixDigits(code) {
http.Error(w, "binding code must be 6 digits", 400)
@@ -144,6 +198,9 @@ func (s *server) createBootstrap(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "请在10分钟内私聊机器人发送:/setting %s\n", code)
}
func (s *server) confirmBootstrap(w http.ResponseWriter, r *http.Request) {
+ if !s.requireCSRFForm(w, r, 4<<10) {
+ return
+ }
service, ok := s.service.(BootstrapService)
if !ok {
http.Error(w, "bootstrap unavailable", http.StatusNotImplemented)
@@ -155,6 +212,34 @@ func (s *server) confirmBootstrap(w http.ResponseWriter, r *http.Request) {
}
http.Redirect(w, r, "/admin/settings", http.StatusSeeOther)
}
+func (s *server) disableAdministrator(w http.ResponseWriter, r *http.Request) {
+ if !s.requireCSRFForm(w, r, 4<<10) {
+ return
+ }
+ service, ok := s.service.(AdministratorService)
+ if !ok {
+ http.Error(w, "administrator management unavailable", http.StatusNotImplemented)
+ return
+ }
+ staffID := strings.TrimSpace(r.FormValue("staff_id"))
+ if staffID == "" {
+ http.Error(w, "administrator not found", http.StatusNotFound)
+ return
+ }
+ err := service.DisableAdministrator(r.Context(), staffID)
+ switch {
+ case err == nil:
+ http.Redirect(w, r, "/admin/settings", http.StatusSeeOther)
+ case errors.Is(err, settings.ErrLastAdministrator):
+ http.Error(w, "至少保留一位有效管理员;请先确认新管理员已生效。", http.StatusConflict)
+ case errors.Is(err, settings.ErrAdministratorAlreadyDisabled):
+ http.Error(w, "管理员已经停用。", http.StatusConflict)
+ case errors.Is(err, settings.ErrAdministratorNotFound):
+ http.Error(w, "administrator not found", http.StatusNotFound)
+ default:
+ http.Error(w, "administrator update failed", http.StatusInternalServerError)
+ }
+}
func sixDigits(value string) bool {
if len(value) != 6 {
return false
diff --git a/internal/adminweb/server_test.go b/internal/adminweb/server_test.go
index 43ab5b1..b060f9b 100644
--- a/internal/adminweb/server_test.go
+++ b/internal/adminweb/server_test.go
@@ -7,12 +7,16 @@ import (
"strings"
"testing"
"time"
+
+ "gitea.zheromiku.top/Weknora/dobotai-platform/internal/settings"
)
type fakeService struct {
- snapshot Snapshot
- verified bool
- saved bool
+ snapshot Snapshot
+ verified bool
+ saved bool
+ disabled string
+ disableErr error
}
func (f *fakeService) Snapshot(context.Context) (Snapshot, error) { return f.snapshot, nil }
@@ -24,6 +28,28 @@ func (f *fakeService) VerifyCredentials(context.Context, string, string) Verific
f.verified = true
return Verification{OK: true, Code: "ok", CheckedAt: time.Unix(1, 0)}
}
+func (f *fakeService) DisableAdministrator(_ context.Context, staffID string) error {
+ f.disabled = staffID
+ return f.disableErr
+}
+func csrfTokenFromPage(t *testing.T, h http.Handler) string {
+ t.Helper()
+ get := httptest.NewRequest(http.MethodGet, "/admin/settings", nil)
+ get.Header.Set("Authorization", "Bearer admin-token")
+ page := httptest.NewRecorder()
+ h.ServeHTTP(page, get)
+ marker := `name="csrf_token" value="`
+ start := strings.Index(page.Body.String(), marker)
+ if start < 0 {
+ t.Fatalf("csrf token missing: %s", page.Body.String())
+ }
+ start += len(marker)
+ end := strings.Index(page.Body.String()[start:], `"`)
+ if end < 0 {
+ t.Fatal("csrf token terminator missing")
+ }
+ return page.Body.String()[start : start+end]
+}
func TestDashboardNeverRendersSecrets(t *testing.T) {
svc := &fakeService{snapshot: Snapshot{SystemState: "active", ClientIDMasked: "ding***", SecretConfigured: true}}
h := New(svc, "admin-token")
@@ -64,7 +90,8 @@ func TestDashboardRendersOperationalComponentFields(t *testing.T) {
func TestSaveCredentialsRequiresVerification(t *testing.T) {
svc := &fakeService{}
h := New(svc, "admin-token")
- req := httptest.NewRequest(http.MethodPost, "/admin/setup/credentials", strings.NewReader("client_id=id&client_secret=secret"))
+ csrf := csrfTokenFromPage(t, h)
+ req := httptest.NewRequest(http.MethodPost, "/admin/setup/credentials", strings.NewReader("client_id=id&client_secret=secret&csrf_token="+csrf))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Authorization", "Bearer admin-token")
w := httptest.NewRecorder()
@@ -73,3 +100,67 @@ func TestSaveCredentialsRequiresVerification(t *testing.T) {
t.Fatalf("status=%d verified=%v saved=%v", w.Code, svc.verified, svc.saved)
}
}
+
+func TestAllAdminPOSTRoutesRejectMissingCSRF(t *testing.T) {
+ svc := &fakeService{}
+ h := New(svc, "admin-token")
+ for _, route := range []string{"/admin/setup/credentials", "/admin/setup/candidate/activate", "/admin/setup/bootstrap", "/admin/setup/bootstrap/confirm", "/admin/settings/administrators/disable"} {
+ req := httptest.NewRequest(http.MethodPost, route, strings.NewReader("client_id=id&client_secret=secret&code=123456&staff_id=staff-old"))
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.Header.Set("Authorization", "Bearer admin-token")
+ w := httptest.NewRecorder()
+ h.ServeHTTP(w, req)
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("route=%s status=%d body=%q", route, w.Code, w.Body.String())
+ }
+ }
+ if svc.saved || svc.disabled != "" {
+ t.Fatalf("business service called saved=%v disabled=%q", svc.saved, svc.disabled)
+ }
+}
+
+func TestDashboardRendersAdministratorReplacementWorkflow(t *testing.T) {
+ svc := &fakeService{snapshot: Snapshot{Administrators: []AdministratorView{{StaffID: "staff-old", StaffIDMasked: "sta***old", DisplayName: "旧管理员", Department: "技术部", Role: "super_admin", Status: "active", CanDisable: true}}}}
+ h := New(svc, "admin-token")
+ req := httptest.NewRequest(http.MethodGet, "/admin/settings", nil)
+ req.Header.Set("Authorization", "Bearer admin-token")
+ w := httptest.NewRecorder()
+ h.ServeHTTP(w, req)
+ for _, want := range []string{"新增/更换管理员", "先加后停", "旧管理员", "技术部", "sta***old", "生成6位绑定码", "停用此管理员"} {
+ if !strings.Contains(w.Body.String(), want) {
+ t.Fatalf("dashboard missing %q: %s", want, w.Body.String())
+ }
+ }
+ if strings.Contains(w.Body.String(), ">staff-old<") {
+ t.Fatalf("raw staff ID must not be rendered as visible text: %s", w.Body.String())
+ }
+}
+
+func TestDisableAdministratorRequiresCSRFAndMapsLastAdminConflict(t *testing.T) {
+ svc := &fakeService{}
+ h := New(svc, "admin-token")
+ post := func(body string) *httptest.ResponseRecorder {
+ req := httptest.NewRequest(http.MethodPost, "/admin/settings/administrators/disable", strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.Header.Set("Authorization", "Bearer admin-token")
+ w := httptest.NewRecorder()
+ h.ServeHTTP(w, req)
+ return w
+ }
+ if w := post("staff_id=staff-old"); w.Code != http.StatusForbidden || svc.disabled != "" {
+ t.Fatalf("missing csrf status=%d disabled=%q", w.Code, svc.disabled)
+ }
+
+ csrf := csrfTokenFromPage(t, h)
+
+ svc.disableErr = settings.ErrLastAdministrator
+ w := post("staff_id=staff-old&csrf_token=" + csrf)
+ if w.Code != http.StatusConflict || !strings.Contains(w.Body.String(), "至少保留一位有效管理员") {
+ t.Fatalf("last-admin status=%d body=%q", w.Code, w.Body.String())
+ }
+ svc.disableErr = nil
+ w = post("staff_id=staff-old&csrf_token=" + csrf)
+ if w.Code != http.StatusSeeOther || svc.disabled != "staff-old" {
+ t.Fatalf("success status=%d disabled=%q body=%q", w.Code, svc.disabled, w.Body.String())
+ }
+}
diff --git a/internal/settings/administrator.go b/internal/settings/administrator.go
new file mode 100644
index 0000000..9b5a20c
--- /dev/null
+++ b/internal/settings/administrator.go
@@ -0,0 +1,17 @@
+package settings
+
+import "errors"
+
+type Administrator struct {
+ StaffID string
+ DisplayName string
+ Department string
+ Role string
+ Status string
+}
+
+var (
+ ErrAdministratorNotFound = errors.New("administrator not found")
+ ErrLastAdministrator = errors.New("last active administrator cannot be disabled")
+ ErrAdministratorAlreadyDisabled = errors.New("administrator already disabled")
+)
diff --git a/internal/settings/controller.go b/internal/settings/controller.go
index 3e865fe..1f6de4a 100644
--- a/internal/settings/controller.go
+++ b/internal/settings/controller.go
@@ -96,9 +96,9 @@ func (c *Controller) Handle(ctx context.Context, in SettingInput) (string, error
return "", err
}
if admin {
- return "⚙️ 我的设置:/setting language \n🛠 系统管理:support、question、faq", nil
+ return settingMenu(true, strings.TrimSpace(in.ConversationType) == "direct"), nil
}
- return "⚙️ 我的设置:/setting language ", nil
+ return settingMenu(false, false), nil
}
if action == "" {
action = strings.ToLower(args[0])
@@ -161,6 +161,30 @@ func (c *Controller) Handle(ctx context.Context, in SettingInput) (string, error
return "", err
}
+func settingMenu(admin, direct bool) string {
+ menu := "⚙️ 个人设置\n" +
+ "回答语言:/setting language \n" +
+ "- auto:跟随当前提问语言(推荐)\n" +
+ "- zh-CN:简体中文\n" +
+ "- en / ja / ko / es:英语 / 日语 / 韩语 / 西班牙语\n" +
+ "例如:/setting language en"
+ if !admin {
+ return menu
+ }
+ menu += "\n\n🛠 系统管理(仅管理员)\n" +
+ "- support:在目标技术支持群@机器人发送 /setting support 保存;再发送 /setting support test,测试成功后激活。\n" +
+ "- question:私聊发送 /setting question,再在10分钟内发送问题AI表链接;Schema验证通过后激活并短暂重启。\n" +
+ "- faq:私聊发送 /setting faq,再在10分钟内发送FAQ表链接;Schema验证通过后激活并短暂重启。"
+ if !direct {
+ return menu + "\n\n🌐 管理后台与管理员更换:请私聊机器人发送 /setting 查看。"
+ }
+ return menu + "\n\n🌐 管理后台(仅PC)\n" +
+ "1. 通过SSH隧道将本地8090转发到服务器127.0.0.1:8090。\n" +
+ "2. 浏览器打开:http://127.0.0.1:8090/admin/settings\n" +
+ "3. Basic Auth用户名任意;密码为服务器DOBOTAI_ADMIN_TOKEN(仅从服务器安全获取,禁止发送到钉钉)。\n" +
+ "4. 更换管理员:后台生成6位码 → 新管理员私聊 /setting <6位码> → 回后台确认 → 新管理员生效后再停用旧管理员。"
+}
+
func tableBindingFailureReply(action string, err error) string {
label := map[string]string{"question": "问题AI表格", "faq": "FAQ表格"}[action]
if label == "" {
diff --git a/internal/settings/controller_test.go b/internal/settings/controller_test.go
index 97f142f..1ad03b4 100644
--- a/internal/settings/controller_test.go
+++ b/internal/settings/controller_test.go
@@ -68,6 +68,53 @@ func TestControllerLanguageForOrdinaryUser(t *testing.T) {
t.Fatalf("prefs=%v out=%q", r.prefs, out)
}
}
+
+func TestControllerSettingMenuExplainsLanguageWithoutAdminActionsToOrdinaryUser(t *testing.T) {
+ r := newMemoryRepo()
+ c := NewController(r)
+ out, err := c.Handle(context.Background(), SettingInput{TenantKey: "t", Channel: "dingtalk", StaffID: "u", Text: "/setting", ConversationType: "direct"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, want := range []string{"个人设置", "/setting language ", "auto:跟随当前提问语言", "zh-CN:简体中文", "例如:/setting language en"} {
+ if !strings.Contains(out, want) {
+ t.Fatalf("reply=%q must contain %q", out, want)
+ }
+ }
+ for _, forbidden := range []string{"系统管理", "/setting support", "/admin/settings", "DOBOTAI_ADMIN_TOKEN"} {
+ if strings.Contains(out, forbidden) {
+ t.Fatalf("ordinary-user reply=%q must not contain %q", out, forbidden)
+ }
+ }
+}
+
+func TestControllerSettingMenuExplainsAdminActionsAndBackendAccess(t *testing.T) {
+ r := newMemoryRepo()
+ r.admins["t/a"] = true
+ c := NewController(r)
+ out, err := c.Handle(context.Background(), SettingInput{TenantKey: "t", Channel: "dingtalk", StaffID: "a", Text: "/setting", ConversationType: "direct"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, want := range []string{
+ "系统管理(仅管理员)",
+ "/setting support",
+ "/setting support test",
+ "/setting question",
+ "/setting faq",
+ "Schema验证通过后激活并短暂重启",
+ "SSH隧道",
+ "127.0.0.1:8090/admin/settings",
+ "Basic Auth",
+ "DOBOTAI_ADMIN_TOKEN",
+ "新管理员私聊 /setting <6位码>",
+ "新管理员生效后再停用旧管理员",
+ } {
+ if !strings.Contains(out, want) {
+ t.Fatalf("reply=%q must contain %q", out, want)
+ }
+ }
+}
func TestControllerRejectsOrdinaryUserSystemBinding(t *testing.T) {
r := newMemoryRepo()
c := NewController(r)
diff --git a/internal/store/postgres/settings.go b/internal/store/postgres/settings.go
index 4a60a3e..16ed2a1 100644
--- a/internal/store/postgres/settings.go
+++ b/internal/store/postgres/settings.go
@@ -157,6 +157,81 @@ func (r *SettingsRepository) AdministratorCount(ctx context.Context, tenant stri
err := r.store.pool.QueryRow(ctx, `SELECT COUNT(*) FROM administrators WHERE tenant_key=$1 AND status='active'`, tenant).Scan(&n)
return n, err
}
+func (r *SettingsRepository) ListAdministrators(ctx context.Context, tenant string) ([]settings.Administrator, error) {
+ rows, err := r.store.pool.Query(ctx, `SELECT staff_id,display_name,department,role,status FROM administrators WHERE tenant_key=$1 ORDER BY CASE status WHEN 'active' THEN 0 ELSE 1 END,created_at`, strings.TrimSpace(tenant))
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ administrators := []settings.Administrator{}
+ for rows.Next() {
+ var administrator settings.Administrator
+ if err = rows.Scan(&administrator.StaffID, &administrator.DisplayName, &administrator.Department, &administrator.Role, &administrator.Status); err != nil {
+ return nil, err
+ }
+ administrators = append(administrators, administrator)
+ }
+ return administrators, rows.Err()
+}
+func (r *SettingsRepository) DisableAdministrator(ctx context.Context, tenant, staffID string) error {
+ tenant, staffID = strings.TrimSpace(tenant), strings.TrimSpace(staffID)
+ if tenant == "" || staffID == "" {
+ return settings.ErrAdministratorNotFound
+ }
+ tx, err := r.store.pool.Begin(ctx)
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback(ctx)
+ rows, err := tx.Query(ctx, `SELECT staff_id,status FROM administrators WHERE tenant_key=$1 FOR UPDATE`, tenant)
+ if err != nil {
+ return err
+ }
+ activeCount, targetStatus, found := 0, "", false
+ for rows.Next() {
+ var currentStaffID, status string
+ if err = rows.Scan(¤tStaffID, &status); err != nil {
+ rows.Close()
+ return err
+ }
+ if status == "active" {
+ activeCount++
+ }
+ if currentStaffID == staffID {
+ targetStatus, found = status, true
+ }
+ }
+ rows.Close()
+ if err = rows.Err(); err != nil {
+ return err
+ }
+ if !found {
+ return settings.ErrAdministratorNotFound
+ }
+ if err = canDisableAdministrator(targetStatus, activeCount); err != nil {
+ return err
+ }
+ result, err := tx.Exec(ctx, `UPDATE administrators SET status='disabled',updated_at=NOW() WHERE tenant_key=$1 AND staff_id=$2 AND status='active'`, tenant, staffID)
+ if err != nil {
+ return err
+ }
+ if result.RowsAffected() != 1 {
+ return settings.ErrAdministratorNotFound
+ }
+ if _, err = tx.Exec(ctx, `INSERT INTO config_audit_events(id,tenant_key,actor_staff_id,action,target_kind,target_revision,result_code,metadata) VALUES($1,$2,'','administrator.disable','administrator',0,'administrator_disabled',jsonb_build_object('target_staff_id',$3,'source','admin_web'))`, newSettingsID(), tenant, staffID); err != nil {
+ return err
+ }
+ return tx.Commit(ctx)
+}
+func canDisableAdministrator(status string, activeCount int) error {
+ if status != "active" {
+ return settings.ErrAdministratorAlreadyDisabled
+ }
+ if activeCount <= 1 {
+ return settings.ErrLastAdministrator
+ }
+ return nil
+}
func (r *SettingsRepository) SaveDingTalkConfig(ctx context.Context, tenant, clientID, secretRef string, verified bool) error {
payload, _ := json.Marshal(map[string]string{"client_id": clientID})
state := "validated"
diff --git a/internal/store/postgres/settings_admin_test.go b/internal/store/postgres/settings_admin_test.go
new file mode 100644
index 0000000..1fe73c2
--- /dev/null
+++ b/internal/store/postgres/settings_admin_test.go
@@ -0,0 +1,28 @@
+package postgres
+
+import (
+ "errors"
+ "testing"
+
+ "gitea.zheromiku.top/Weknora/dobotai-platform/internal/settings"
+)
+
+func TestCanDisableAdministratorProtectsLastActiveAdministrator(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ status string
+ activeCount int
+ wantErr error
+ }{
+ {name: "two active", status: "active", activeCount: 2},
+ {name: "last active", status: "active", activeCount: 1, wantErr: settings.ErrLastAdministrator},
+ {name: "already disabled", status: "disabled", activeCount: 2, wantErr: settings.ErrAdministratorAlreadyDisabled},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ err := canDisableAdministrator(tc.status, tc.activeCount)
+ if !errors.Is(err, tc.wantErr) {
+ t.Fatalf("err=%v want=%v", err, tc.wantErr)
+ }
+ })
+ }
+}