RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.
Go agent-harnessagent-native-databaseagentic-aiagentic-retrievalagentic-searchaiai-agentscontext-enginecontext-engineeringcontext-managementharness-engineeringknowledge-compilationragretrieval-augmented-generationretrieval-harnesssearch-harness
feat(admin): add user search, status filtering, sorting, and CLI pagination (#21729)
adwsd554abacabee
diff --git a/internal/admin/handler.go b/internal/admin/handler.goindex 35923cbe49..6bc20dde6a 100644--- a/internal/admin/handler.go+++ b/internal/admin/handler.go@@ -31,6 +31,7 @@ import ("ragflow/internal/storage""ragflow/internal/utility""strconv"+ "strings""time""github.com/gin-gonic/gin"@@ -152,24 +153,13 @@ func (h *Handler) AuthCheck(c *gin.Context) {common.SuccessNoData(c, "Admin is authorized")}-// ListUsersRequest list users request-type ListUsersRequest struct {- Enterprise *bool `json:"enterprise"`- UserStatus *string `json:"user_status"`- OrderBy *string `json:"order_by"`- Top *int `json:"top"`- Days *int `json:"days"`- Quota *int `json:"quota"`- Plan *string `json:"plan"`-}-// ListUsers handle list usersfunc (h *Handler) ListUsers(c *gin.Context) {name := c.DefaultQuery("keyword", "")status := c.DefaultQuery("status", "")role := c.DefaultQuery("role", "")- sort := c.DefaultQuery("sort", "") // descending or ascending+ sort := c.DefaultQuery("sort", "") // asc or descorderBy := c.DefaultQuery("order", "") // order by fieldpageInt, err := common.ParseRequestIntPositive(c, c.Query("page"), "page", 1)if err != nil {@@ -187,6 +177,9 @@ func (h *Handler) ListUsers(c *gin.Context) {common.ErrorWithCode(c, common.CodeBadRequest, err.Error())return}+ if !validateAdminUserListPagination(c, pageInt, pageSizeInt, topInt) {+ return+ }// quota is optional: nil when the query param is absent, &v when present// (including 0). This lets ListUsersEE distinguish "no quota filter" from// "filter by quota threshold 0".@@ -221,6 +214,10 @@ func (h *Handler) ListUsers(c *gin.Context) {common.ErrorWithCode(c, common.CodeBadRequest, "Invalid RAGFlow type")return}+ if errors.Is(err, errInvalidUserListQuery) {+ common.ErrorWithCode(c, common.CodeBadRequest, err.Error())+ return+ }if err != nil {common.ErrorWithCode(c, common.CodeServerError, err.Error())return@@ -228,6 +225,31 @@ func (h *Handler) ListUsers(c *gin.Context) {common.SuccessWithDataAndTotal(c, users, total, "List users")}+func validateAdminUserListPagination(c *gin.Context, page, pageSize, top int) bool {+ if page < 1 || pageSize < 1 {+ common.ErrorWithCode(c, common.CodeBadRequest, "page and page_size must be positive integers")+ return false+ }+ query := c.Request.URL.Query()+ if query.Has("top") {+ if top < 1 {+ common.ErrorWithCode(c, common.CodeBadRequest, "top must be a positive integer")+ return false+ }+ if query.Has("page") || query.Has("page_size") {+ common.ErrorWithCode(c, common.CodeBadRequest, "top cannot be combined with page or page_size")+ return false+ }+ switch strings.ToLower(strings.TrimSpace(c.Query("order"))) {+ case "storage", "documents", "index":+ default:+ common.ErrorWithCode(c, common.CodeBadRequest, "top is only supported for storage, documents and index")+ return false+ }+ }+ return true+}+// CreateUserHTTPRequest create user requesttype CreateUserHTTPRequest struct {Username string `json:"username" binding:"required"`diff --git a/internal/admin/service.go b/internal/admin/service.goindex 6bb154f21e..8d5fd3d8bd 100644--- a/internal/admin/service.go+++ b/internal/admin/service.go@@ -145,26 +145,6 @@ func generateRandomHex(n int) string {return hex.EncodeToString(bytes)}-// ListUsers returns a page of users and the total number of users.-func (s *Service) ListUsers(ctx context.Context, pageIndex, pageSize int, name, status, sort, orderBy string) ([]map[string]interface{}, int64, error) {- users, total, err := s.userDAO.List(ctx, dao.DB, (pageIndex-1)*pageSize, pageSize, name, status, sort, orderBy)- if err != nil {- return nil, 0, err- }-- result := make([]map[string]interface{}, 0, len(users))- for _, user := range users {- result = append(result, map[string]interface{}{- "email": user.Email,- "nickname": user.Nickname,- "create_date": user.CreateTime,- "is_active": user.IsActive,- "is_superuser": user.IsSuperuser,- })- }- return result, total, nil-}-// CreateUser create a new user// Parameters:// - username: email address of the userdiff --git a/internal/admin/user_detail_test.go b/internal/admin/user_detail_test.goindex 940b475be2..20e2c286cd 100644--- a/internal/admin/user_detail_test.go+++ b/internal/admin/user_detail_test.go@@ -19,6 +19,7 @@ package adminimport ("encoding/json""fmt"+ "math""net/http""net/http/httptest""testing"@@ -38,6 +39,8 @@ type adminTestResponse struct {Total *int64 `json:"total"`}+var adminUserDetailTestModels = []any{&entity.User{}}+func TestListUsersReturnsTotalForEachPage(t *testing.T) {handler := setupAdminUserDetailTest(t)for i := 0; i < 11; i++ {@@ -88,14 +91,105 @@ func TestListUsersReturnsTotalForEachPage(t *testing.T) {}}+func TestListUsersQueryParameters(t *testing.T) {+ handler := setupAdminUserDetailTest(t)+ type queryTest struct {+ query string+ code common.ErrorCode+ total int64+ }+ tests := []queryTest{+ {"?keyword=USER&status=active&order=create_time&sort=asc", common.CodeSuccess, 1},+ {"?keyword=missing", common.CodeSuccess, 0},+ {"?status=unknown", common.CodeBadRequest, 0},+ {"?order=password", common.CodeBadRequest, 0},+ {"?order=email", common.CodeBadRequest, 0},+ {"?order=nickname", common.CodeBadRequest, 0},+ {"?order=is_active", common.CodeBadRequest, 0},+ {"?order=is_superuser", common.CodeBadRequest, 0},+ {"?order=id", common.CodeBadRequest, 0},+ {"?order=create_date", common.CodeBadRequest, 0},+ {"?sort=unknown", common.CodeBadRequest, 0},+ {"?top=5&page=1", common.CodeBadRequest, 0},+ {"?top=5&page_size=10", common.CodeBadRequest, 0},+ {"?top=5&page=", common.CodeBadRequest, 0},+ {"?top=0", common.CodeBadRequest, 0},+ {"?page=0", common.CodeBadRequest, 0},+ {"?page_size=0", common.CodeBadRequest, 0},+ {fmt.Sprintf("?page=%d&page_size=10", math.MaxInt), common.CodeBadRequest, 0},+ {fmt.Sprintf("?page=%d&page_size=4", math.MaxInt/2+2), common.CodeBadRequest, 0},+ {fmt.Sprintf("?page=%d&page_size=4", math.MaxInt/2+3), common.CodeBadRequest, 0},+ }+ if common.GetRAGFlowType() == common.OpenSourceVersion {+ tests = append(tests, queryTest{"?status=inactive", common.CodeSuccess, 0})+ }+ for _, tt := range tests {+ t.Run(tt.query, func(t *testing.T) {+ recorder := httptest.NewRecorder()+ ctx, _ := gin.CreateTestContext(recorder)+ ctx.Request = httptest.NewRequest(http.MethodGet, "/api/v1/admin/users"+tt.query, nil)+ handler.ListUsers(ctx)+ var response adminTestResponse+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {+ t.Fatal(err)+ }+ if response.Code != int(tt.code) || (tt.code == common.CodeSuccess && (response.Total == nil || *response.Total != tt.total)) {+ t.Fatalf("unexpected response: %s", recorder.Body.String())+ }+ })+ }+}++func TestListUsersAcceptsSharedClientParameters(t *testing.T) {+ if common.GetRAGFlowType() != common.OpenSourceVersion {+ t.Skip("enterprise filters are exercised by enterprise user-list tests")+ }+ handler := setupAdminUserDetailTest(t)+ for _, user := range []entity.User{+ {ID: "shared-active", Email: "[email protected]", Nickname: "User Two", IsActive: "1"},+ {ID: "shared-inactive", Email: "[email protected]", Nickname: "Other", IsActive: "0"},+ } {+ if err := dao.DB.Create(&user).Error; err != nil {+ t.Fatal(err)+ }+ }+ for _, tt := range []struct {+ query string+ total int64+ count int+ }{+ {"?keyword=User&status=active&role=Reader&plan=Pro"a=0&days=30&order=create_time&sort=asc&page=1&page_size=1", 2, 1},+ {"?keyword=User&status=active&role=Reader&plan=Pro"a=80&days=30&order=create_time&sort=asc", 2, 2},+ {"?keyword=missing&role=Reader&plan=Pro"a=0", 0, 0},+ {"?status=inactive&plan=Pro&days=30", 1, 1},+ } {+ t.Run(tt.query, func(t *testing.T) {+ recorder := httptest.NewRecorder()+ ctx, _ := gin.CreateTestContext(recorder)+ ctx.Request = httptest.NewRequest(http.MethodGet, "/api/v1/admin/users"+tt.query, nil)+ handler.ListUsers(ctx)+ var response adminTestResponse+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {+ t.Fatal(err)+ }+ var users []map[string]interface{}+ if err := json.Unmarshal(response.Data, &users); err != nil {+ t.Fatalf("invalid user data: %s, error: %v", recorder.Body.String(), err)+ }+ if response.Code != int(common.CodeSuccess) || response.Total == nil || *response.Total != tt.total || len(users) != tt.count {+ t.Fatalf("unexpected response: %s", recorder.Body.String())+ }+ })+ }+}+func setupAdminUserDetailTest(t *testing.T) *Handler {t.Helper()- db := testutil.SetupTestDB(t,- &entity.User{},- )+ db := testutil.SetupTestDB(t, adminUserDetailTestModels...)t.Cleanup(testutil.ReplaceDBForTest(t, db))now := time.Date(2026, time.September, 16, 12, 0, 0, 0, time.UTC)+ createdAt := now.UnixMilli()isSuperuser := falsestatusValid := string(entity.StatusValid)language := "English"@@ -111,7 +205,7 @@ func setupAdminUserDetailTest(t *testing.T) *Handler {LoginChannel: &loginChannel,Status: &statusValid,IsSuperuser: &isSuperuser,- BaseModel: entity.BaseModel{CreateDate: &now, UpdateDate: &now},+ BaseModel: entity.BaseModel{CreateTime: &createdAt, CreateDate: &now, UpdateDate: &now},}if err := db.Create(&user).Error; err != nil {t.Fatalf("create user: %v", err)diff --git a/internal/admin/user_list.go b/internal/admin/user_list.gonew file mode 100644index 0000000000..485f8349f9--- /dev/null+++ b/internal/admin/user_list.go@@ -0,0 +1,91 @@+//+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.+//++package admin++import (+ "context"+ "errors"+ "fmt"+ "math"+ "strings"++ "ragflow/internal/dao"+)++var errInvalidUserListQuery = errors.New("invalid user list query")++// ListUsers returns a page of users and the total number of users.+func (s *Service) ListUsers(ctx context.Context, pageIndex, pageSize int, name, status, sort, orderBy string) ([]map[string]interface{}, int64, error) {+ opts, err := parseUserListOptions(pageIndex, pageSize, name, status, sort, orderBy)+ if err != nil {+ return nil, 0, err+ }+ users, total, err := s.userDAO.List(ctx, dao.DB, opts)+ if err != nil {+ return nil, 0, err+ }++ result := make([]map[string]interface{}, 0, len(users))+ for _, user := range users {+ result = append(result, map[string]interface{}{+ "email": user.Email,+ "nickname": user.Nickname,+ "create_date": user.CreateTime,+ "is_active": user.IsActive,+ "is_superuser": user.IsSuperuser,+ })+ }+ return result, total, nil+}++func parseUserListOptions(page, pageSize int, keyword, status, direction, field string) (dao.UserListOptions, error) {+ opts := dao.UserListOptions{Keyword: strings.TrimSpace(keyword), Limit: pageSize}+ if page < 1 || pageSize < 1 {+ return opts, fmt.Errorf("%w: page and page_size must be positive integers", errInvalidUserListQuery)+ }+ if page-1 > math.MaxInt/pageSize {+ return opts, fmt.Errorf("%w: pagination offset is too large", errInvalidUserListQuery)+ }+ opts.Offset = (page - 1) * pageSize+ status = strings.ToLower(strings.TrimSpace(status))+ switch status {+ case "":+ case "active", "inactive":+ active := status == "active"+ opts.Active = &active+ default:+ return opts, fmt.Errorf("%w: status must be active or inactive", errInvalidUserListQuery)+ }++ field = strings.ToLower(strings.TrimSpace(field))+ switch field {+ case "", "create_time":+ opts.OrderBy = dao.UserListByCreateTime+ case "last_login_time":+ opts.OrderBy = dao.UserListByLastLoginTime+ default:+ return opts, fmt.Errorf("%w: unsupported order field %q", errInvalidUserListQuery, field)+ }+ switch strings.ToLower(strings.TrimSpace(direction)) {+ case "", "desc":+ opts.Desc = true+ case "asc":+ default:+ return opts, fmt.Errorf("%w: sort must be asc or desc", errInvalidUserListQuery)+ }+ return opts, nil+}diff --git a/internal/admin/user_list_test.go b/internal/admin/user_list_test.gonew file mode 100644index 0000000000..21f48d411d--- /dev/null+++ b/internal/admin/user_list_test.go@@ -0,0 +1,141 @@+//+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.+//++package admin++import (+ "errors"+ "math"+ "reflect"+ "testing"+ "time"++ "ragflow/internal/dao"+ "ragflow/internal/entity"+)++func TestListUsersRejectsInvalidQueryBeforeDatabaseAccess(t *testing.T) {+ for _, tt := range []struct {+ name, status, direction, field string+ page, pageSize int+ }{+ {name: "status", status: "unknown", page: 1, pageSize: 10},+ {name: "direction", direction: "unknown", page: 1, pageSize: 10},+ {name: "direction injection", direction: "desc; DROP TABLE user", page: 1, pageSize: 10},+ {name: "field injection", field: "email DESC; DROP TABLE user", page: 1, pageSize: 10},+ {name: "email", field: "email", page: 1, pageSize: 10},+ {name: "nickname", field: "nickname", page: 1, pageSize: 10},+ {name: "is_active", field: "is_active", page: 1, pageSize: 10},+ {name: "is_superuser", field: "is_superuser", page: 1, pageSize: 10},+ {name: "id", field: "id", page: 1, pageSize: 10},+ {name: "create_date", field: "create_date", page: 1, pageSize: 10},+ {name: "role", field: "role", page: 1, pageSize: 10},+ {name: "plan", field: "plan", page: 1, pageSize: 10},+ {name: "storage", field: "storage", page: 1, pageSize: 10},+ {name: "documents", field: "documents", page: 1, pageSize: 10},+ {name: "index", field: "index", page: 1, pageSize: 10},+ {name: "zero page", pageSize: 10},+ {name: "negative page", page: -1, pageSize: 10},+ {name: "zero page size", page: 1},+ {name: "negative page size", page: 1, pageSize: -1},+ {name: "offset overflow to negative", page: math.MaxInt, pageSize: 10},+ {name: "offset overflow to zero", page: math.MaxInt/2 + 2, pageSize: 4},+ {name: "offset overflow to positive", page: math.MaxInt/2 + 3, pageSize: 4},+ } {+ t.Run(tt.name, func(t *testing.T) {+ // No DAO or database is configured: invalid input must fail in the service.+ var svc Service+ users, total, err := svc.ListUsers(t.Context(), tt.page, tt.pageSize, "", tt.status, tt.direction, tt.field)+ if !errors.Is(err, errInvalidUserListQuery) || users != nil || total != 0 {+ t.Fatalf("ListUsers() = (%v, %d, %v)", users, total, err)+ }+ })+ }+}++func TestParseUserListOptionsPaginationBounds(t *testing.T) {+ for _, tt := range []struct {+ name string+ page, pageSize, wantOffset int+ }{+ {name: "normal page", page: 3, pageSize: 10, wantOffset: 20},+ {name: "maximum page with unit size", page: math.MaxInt, pageSize: 1, wantOffset: math.MaxInt - 1},+ {name: "maximum page size on first page", page: 1, pageSize: math.MaxInt},+ {name: "maximum valid offset", page: 2, pageSize: math.MaxInt, wantOffset: math.MaxInt},+ } {+ t.Run(tt.name, func(t *testing.T) {+ opts, err := parseUserListOptions(tt.page, tt.pageSize, "", "", "", "")+ if err != nil || opts.Offset != tt.wantOffset || opts.Limit != tt.pageSize {+ t.Fatalf("parseUserListOptions() = (%+v, %v), want offset %d, limit %d", opts, err, tt.wantOffset, tt.pageSize)+ }+ })+ }+}++func TestListUsersFiltersAndOrdering(t *testing.T) {+ handler := setupAdminUserDetailTest(t)+ created := time.Date(2026, time.September, 17, 12, 0, 0, 0, time.UTC)+ secondCreatedAt, thirdCreatedAt := created.UnixMilli()+1, created.UnixMilli()+2+ lastLogin := created.Add(24 * time.Hour)+ if err := dao.DB.Model(&entity.User{}).Where("id = ?", "user-1").Update("last_login_time", lastLogin.Add(24*time.Hour)).Error; err != nil {+ t.Fatal(err)+ }+ zeroStatus := "0"+ for _, user := range []entity.User{+ {ID: "user-2", Email: "[email protected]", Nickname: "USER Two", IsActive: "0", Status: &zeroStatus, LastLoginTime: &lastLogin, BaseModel: entity.BaseModel{CreateTime: &secondCreatedAt, CreateDate: &created}},+ {ID: "user-3", Email: "[email protected]", Nickname: "Other", IsActive: "1", LastLoginTime: &created, BaseModel: entity.BaseModel{CreateTime: &thirdCreatedAt, CreateDate: &created}},+ } {+ if err := dao.DB.Create(&user).Error; err != nil {+ t.Fatal(err)+ }+ }+ if err := dao.DB.Model(&entity.User{}).Where("id = ?", "user-3").UpdateColumn("status", nil).Error; err != nil {+ t.Fatal(err)+ }+ for _, tt := range []struct {+ name, keyword, status, direction, field string+ page, pageSize int+ emails []string+ total int64+ }{+ {name: "defaults", page: 1, pageSize: 10, emails: []string{"[email protected]", "[email protected]", "[email protected]"}, total: 3},+ {name: "blank defaults", status: " ", direction: " ", field: " ", page: 1, pageSize: 10, emails: []string{"[email protected]", "[email protected]", "[email protected]"}, total: 3},+ {name: "keyword normalization", keyword: " usER ", page: 1, pageSize: 10, emails: []string{"[email protected]", "[email protected]"}, total: 2},+ {name: "active", status: "active", page: 1, pageSize: 10, emails: []string{"[email protected]", "[email protected]"}, total: 2},+ {name: "inactive", status: " INACTIVE ", page: 1, pageSize: 10, emails: []string{"[email protected]"}, total: 1},+ {name: "combined normalization", keyword: " USER ", status: " AcTiVe ", direction: " ASC ", field: " LAST_LOGIN_TIME ", page: 1, pageSize: 10, emails: []string{"[email protected]"}, total: 1},+ {name: "ascending creation time", direction: "asc", field: "create_time", page: 1, pageSize: 10, emails: []string{"[email protected]", "[email protected]", "[email protected]"}, total: 3},+ {name: "normalized creation time", direction: " DESC ", field: " CREATE_TIME ", page: 1, pageSize: 10, emails: []string{"[email protected]", "[email protected]", "[email protected]"}, total: 3},+ {name: "ascending last login", direction: "asc", field: "last_login_time", page: 1, pageSize: 10, emails: []string{"[email protected]", "[email protected]", "[email protected]"}, total: 3},+ {name: "descending last login", field: "last_login_time", page: 1, pageSize: 10, emails: []string{"[email protected]", "[email protected]", "[email protected]"}, total: 3},+ {name: "filtered page", keyword: "user", page: 2, pageSize: 1, emails: []string{"[email protected]"}, total: 2},+ {name: "no matches", keyword: "missing", page: 1, pageSize: 10, emails: []string{}, total: 0},+ } {+ t.Run(tt.name, func(t *testing.T) {+ users, total, err := handler.service.ListUsers(t.Context(), tt.page, tt.pageSize, tt.keyword, tt.status, tt.direction, tt.field)+ if err != nil {+ t.Fatal(err)+ }+ emails := make([]string, 0, len(users))+ for _, user := range users {+ emails = append(emails, user["email"].(string))+ }+ if total != tt.total || !reflect.DeepEqual(emails, tt.emails) {+ t.Fatalf("emails = %v, total = %d; want %v, %d", emails, total, tt.emails, tt.total)+ }+ })+ }+}diff --git a/internal/cli/admin_command.go b/internal/cli/admin_command.goindex c184f4b162..1efa729456 100644--- a/internal/cli/admin_command.go+++ b/internal/cli/admin_command.go@@ -1765,37 +1765,10 @@ func (c *CLI) AdminStatsSummaryCommand(commandCount int, cmd *Command) (Responsereturn HandleCommonDataResponse(resp, "get stats summary")}-// ListUsers lists all users (admin mode only)-// Returns (result_map, error) - result_map is non-nil for benchmark mode-func (c *CLI) AdminListUsersCommand(commandCount int, cmd *Command) (ResponseIf, error) {- if c.Config.CLIMode != AdminMode || c.AdminServerClient.LoginToken == nil {- return nil, fmt.Errorf("this command is only allowed in ADMIN mode or already login")- }-- resp, err := c.AdminServerClient.Request(commandCount, "GET", "/admin/users", "admin", nil, nil)- if err != nil {- return nil, fmt.Errorf("failed to list users: %w", err)- }-- if resp.StatusCode != 200 {- return nil, fmt.Errorf("failed to list users: HTTP %d, body: %s", resp.StatusCode, string(resp.Body))- }-- var result CommonResponse- if err = json.Unmarshal(resp.Body, &result); err != nil {- return nil, fmt.Errorf("list users failed: invalid JSON (%w), body: %s", err, string(resp.Body))- }-- if result.Code != 0 {- return nil, fmt.Errorf("%s", result.Message)- }-- for _, user := range result.Data {- delete(user, "create_date")- }-- result.Duration = resp.Duration- return &result, nil+// adminUserReportRunner is implemented by *CLI in the EE file+// internal/cli/admin_user_report_ee.go, enabled by the ee build tag.+type adminUserReportRunner interface {+ runAdminUserReport(int, *Command) (ResponseIf, error)}func (c *CLI) AdminListUsersConditionCommand(commandCount int, cmd *Command) (ResponseIf, error) {@@ -1803,6 +1776,9 @@ func (c *CLI) AdminListUsersConditionCommand(commandCount int, cmd *Command) (Reif c.Config.CLIMode != AdminMode || c.AdminServerClient.LoginToken == nil {return nil, fmt.Errorf("this command is only allowed in ADMIN mode or already login")}+ if reports, ok := any(c).(adminUserReportRunner); ok {+ return reports.runAdminUserReport(commandCount, cmd)+ }// Server-side ListUsers reads these via c.Query(), so GET parameters must// travel in the URL query string, not the request body. Parameter names@@ -1826,6 +1802,11 @@ func (c *CLI) AdminListUsersConditionCommand(commandCount int, cmd *Command) (Reif daysInt, ok := cmd.Params["days"].(int); ok {q.Set("days", fmt.Sprintf("%d", daysInt))}+ for _, name := range []string{"page", "page_size"} {+ if value, ok := cmd.Params[name].(int); ok {+ q.Set(name, strconv.Itoa(value))+ }+ }apiURL := "/admin/users"if encoded := q.Encode(); encoded != "" {diff --git a/internal/cli/admin_parser.go b/internal/cli/admin_parser.goindex 48bcb2400b..e9c723a9f1 100644--- a/internal/cli/admin_parser.go+++ b/internal/cli/admin_parser.go@@ -2787,17 +2787,20 @@ func (p *Parser) parseAdminShowUsersPlan() (*Command, error) {}// LIST USERS;-// LIST USERS ACTIVE 30 DAYS; // default 7 days-// LIST USERS INACTIVE 30 DAYS; // default 7 days+// LIST USERS ACTIVE DAYS 30;+// LIST USERS INACTIVE DAYS 30;// LIST USERS STORAGE TOP 10;// LIST USERS DOCUMENTS TOP 10;// LIST USERS INDEX TOP 10;-// LIST USERS QUOTA TOP 10;-// LIST USERS QUOTA OVER;-// LIST USERS PLAN 'plan_name' QUOTA OVER DAYS 30; // default 7 days-// LIST USERS PLAN 'plan_name' DAYS 30; // default 7 days+// LIST USERS STORAGE PAGE 2 PAGE_SIZE 10;+// LIST USERS QUOTA 80 PAGE 1 PAGE_SIZE 10;+// LIST USERS PLAN 'plan_name' QUOTA 80 DAYS 30;+// LIST USERS PLAN 'plan_name' DAYS 30;func (p *Parser) parseAdminListUsersCommand() (*Command, error) {p.nextToken() // consume USERS+ if p.curToken.Type == TokenWith {+ return p.parseAdminUserListOptions()+ }var orderBy stringvar userStatus string@@ -2805,6 +2808,7 @@ func (p *Parser) parseAdminListUsersCommand() (*Command, error) {var plan *stringvar quota *intvar days *int+ pagination := make(map[string]interface{})condition := falsecommandLoop:for {@@ -2816,7 +2820,7 @@ commandLoop:if err != nil {return nil, err}- if topInt < 0 {+ if topInt < 1 {return nil, fmt.Errorf("invalid number of TOP")}p.nextToken()@@ -2868,6 +2872,21 @@ commandLoop:condition = trueuserStatus = p.curToken.Valuep.nextToken()+ case TokenIdentifier:+ name := strings.ToLower(p.curToken.Value)+ if name != "page" && name != "page_size" {+ break commandLoop+ }+ if _, exists := pagination[name]; exists {+ return nil, fmt.Errorf("duplicate %s", name)+ }+ p.nextToken()+ value, err := p.parseNumber()+ if err != nil || value < 1 {+ return nil, fmt.Errorf("%s must be a positive integer", name)+ }+ pagination[name] = value+ p.nextToken()case TokenSemicolon:p.nextToken()break commandLoop // done@@ -2881,12 +2900,18 @@ commandLoop:if p.curToken.Type == TokenSemicolon {p.nextToken()}-- if !condition {- return NewCommand("admin_list_users_command"), nil+ if p.curToken.Type != TokenEOF {+ return nil, fmt.Errorf("unexpected token after LIST USERS: %s", p.curToken.Value)}- cmd := NewCommand("admin_list_users_condition_command")+ commandType := "admin_list_users_command"+ if condition {+ commandType = "admin_list_users_condition_command"+ }+ cmd := NewCommand(commandType)+ for name, value := range pagination {+ cmd.Params[name] = value+ }if orderBy != "" {cmd.Params["order_by"] = orderBy}@@ -2905,6 +2930,9 @@ commandLoop:if days != nil {cmd.Params["days"] = *days}+ if err := validateAdminUserListMode(cmd.Params); err != nil {+ return nil, err+ }return cmd, nil}diff --git a/internal/cli/admin_user_list.go b/internal/cli/admin_user_list.gonew file mode 100644index 0000000000..ab89ca6373--- /dev/null+++ b/internal/cli/admin_user_list.go@@ -0,0 +1,160 @@+//+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.+//++package cli++import (+ "encoding/json"+ "fmt"+ "net/http"+ "net/url"+ "strconv"+ "strings"+)++// LIST USERS WITH keyword 'alice' status 'active' order 'create_time' sort 'asc'+// page 1 page_size 10 role 'Reader' plan 'Pro' quota 80 days 30;+func (p *Parser) parseAdminUserListOptions() (*Command, error) {+ p.nextToken() // WITH+ cmd := NewCommand("admin_list_users_command")+ for p.curToken.Type != TokenEOF && p.curToken.Type != TokenSemicolon {+ name := strings.ToLower(p.curToken.Value)+ if !isAdminUserListParameter(name) {+ return nil, fmt.Errorf("unknown LIST USERS parameter %q", name)+ }+ if _, exists := cmd.Params[name]; exists {+ return nil, fmt.Errorf("duplicate LIST USERS parameter %q", name)+ }+ p.nextToken()+ var value string+ if name == "page" || name == "page_size" || name == "quota" || name == "top" || name == "days" {+ number, err := p.parseNumber()+ if err != nil {+ return nil, fmt.Errorf("invalid %s: %w", name, err)+ }+ if number < 0 || ((name == "page" || name == "page_size" || name == "top") && number == 0) || (name == "quota" && number > 100) {+ return nil, fmt.Errorf("invalid %s value %d", name, number)+ }+ value = strconv.Itoa(number)+ } else {+ var err error+ value, err = p.parseQuotedString()+ if err != nil {+ return nil, fmt.Errorf("invalid %s: %w", name, err)+ }+ }+ cmd.Params[name] = value+ p.nextToken()+ }+ if len(cmd.Params) == 0 {+ return nil, fmt.Errorf("expected a LIST USERS parameter after WITH")+ }+ if p.curToken.Type == TokenSemicolon {+ p.nextToken()+ }+ if p.curToken.Type != TokenEOF {+ return nil, fmt.Errorf("unexpected token after LIST USERS: %s", p.curToken.Value)+ }+ if err := validateAdminUserListMode(cmd.Params); err != nil {+ return nil, err+ }+ return cmd, nil+}++func validateAdminUserListMode(params map[string]interface{}) error {+ if _, top := params["top"]; top {+ for _, name := range []string{"page", "page_size"} {+ if _, present := params[name]; present {+ return fmt.Errorf("top cannot be combined with page or page_size")+ }+ }+ field, ok := params["order_by"]+ if !ok {+ field = params["order"]+ }+ switch strings.ToLower(fmt.Sprint(field)) {+ case "storage", "documents", "index":+ default:+ return fmt.Errorf("top is only supported for storage, documents and index")+ }+ }+ return nil+}++func isAdminUserListParameter(name string) bool {+ switch name {+ case "keyword", "status", "order", "sort", "page", "page_size", "role", "plan", "quota", "top", "days":+ return true+ default:+ return false+ }+}++func (c *CLI) AdminListUsersCommand(commandCount int, cmd *Command) (ResponseIf, error) {+ if c.Config == nil || c.Config.CLIMode != AdminMode || c.AdminServerClient == nil || c.AdminServerClient.LoginToken == nil {+ return nil, fmt.Errorf("listing users requires admin mode and login")+ }+ query := url.Values{}+ for name, value := range cmd.Params {+ if !isAdminUserListParameter(name) {+ return nil, fmt.Errorf("unknown LIST USERS parameter %q", name)+ }+ query.Set(name, fmt.Sprint(value))+ }+ path := "/admin/users"+ if len(query) > 0 {+ path += "?" + query.Encode()+ }+ response, err := c.AdminServerClient.Request(commandCount, http.MethodGet, path, "admin", nil, nil)+ if err != nil {+ return nil, fmt.Errorf("failed to list users: %w", err)+ }+ if response.StatusCode != http.StatusOK {+ return nil, fmt.Errorf("failed to list users: HTTP %d, body: %s", response.StatusCode, response.Body)+ }+ var result adminUserListResponse+ if err := json.Unmarshal(response.Body, &result); err != nil {+ return nil, fmt.Errorf("list users failed: invalid JSON (%w)", err)+ }+ if result.Code != 0 {+ return nil, fmt.Errorf("%s", result.Message)+ }+ result.Duration = response.Duration+ result.SetOutputFormat(c.Config.OutputFormat)+ return &result, nil+}++type adminUserListResponse struct {+ CommonResponse+ Total int64 `json:"total"`+}++func (r *adminUserListResponse) PrintOut() {+ if r.OutputFormat == OutputFormatJSON {+ data, err := json.MarshalIndent(struct {+ Users []map[string]interface{} `json:"users"`+ Total int64 `json:"total"`+ }{Users: r.Data, Total: r.Total}, "", " ")+ if err != nil {+ fmt.Printf("Error marshaling JSON: %v\n", err)+ return+ }+ fmt.Println(string(data))+ return+ }+ r.CommonResponse.PrintOut()+ fmt.Printf("Total: %d\n", r.Total)+}diff --git a/internal/cli/admin_user_list_test.go b/internal/cli/admin_user_list_test.gonew file mode 100644index 0000000000..6e8fdb2bf4--- /dev/null+++ b/internal/cli/admin_user_list_test.go@@ -0,0 +1,189 @@+//+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.+//++package cli++import (+ "encoding/json"+ "io"+ "net/http"+ "os"+ "strings"+ "testing"+)++func TestAdminUserListRequests(t *testing.T) {+ for _, tt := range []struct{ input, query string }{+ {"LIST USERS;", ""},+ {"LIST USERS WITH keyword 'Alice + 日志' status 'active' order 'create_time' sort 'asc' page 2 page_size 5;", "keyword=Alice+%2B+%E6%97%A5%E5%BF%97&order=create_time&page=2&page_size=5&sort=asc&status=active"},+ {"LIST USERS WITH role 'Reader' plan 'Pro' quota 0;", "plan=Pro"a=0&role=Reader"},+ {"LIST USERS WITH plan 'Pro' days 30 page 2 page_size 10;", "days=30&page=2&page_size=10&plan=Pro"},+ {"LIST USERS WITH order 'storage' top 50;", "order=storage&top=50"},+ {"LIST USERS WITH days 0;", "days=0"},+ {"LIST USERS PAGE 2 PAGE_SIZE 5;", "page=2&page_size=5"},+ } {+ t.Run(tt.input, func(t *testing.T) {+ client := newTestHTTPClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ body, _ := io.ReadAll(r.Body)+ if r.Method != http.MethodGet || r.URL.Path != "/api/v1/admin/users" || r.URL.RawQuery != tt.query || len(body) != 0 || r.Header.Get("Authorization") != "admin-token" {+ t.Errorf("request = %s %s body=%q", r.Method, r.URL, body)+ }+ _, _ = io.WriteString(w, `{"code":0,"data":[{"email":"[email protected]","create_date":123}],"total":17}`)+ }))+ token := "admin-token"+ client.LoginToken = &token+ c := &CLI{Config: &CommandLineConfig{CLIMode: AdminMode, OutputFormat: OutputFormatJSON}, AdminServerClient: client}+ cmd, err := NewParser(tt.input).Parse(AdminMode)+ if err != nil {+ t.Fatal(err)+ }+ response, err := c.ExecuteCommand(1, cmd)+ if err != nil {+ t.Fatal(err)+ }+ result := response.(*adminUserListResponse)+ if result.Total != 17 || len(result.Data) != 1 || result.Data[0]["create_date"] == nil || result.OutputFormat != OutputFormatJSON {+ t.Fatalf("unexpected response: %#v", result)+ }+ })+ }+}++func TestAdminUserReportsKeepListEndpoint(t *testing.T) {+ if _, ok := any(&CLI{}).(adminUserReportRunner); ok {+ t.Skip("enterprise report routing is covered by enterprise command tests")+ }+ for _, tt := range []struct{ input, query string }{+ {"LIST USERS INACTIVE DAYS 30;", "days=30&status=INACTIVE"},+ {"LIST USERS ACTIVE DAYS 7;", "days=7&status=ACTIVE"},+ {"LIST USERS STORAGE TOP 3;", "order=STORAGE&top=3"},+ {"LIST USERS DOCUMENTS TOP 2;", "order=DOCUMENTS&top=2"},+ {"LIST USERS INDEX TOP 2;", "order=INDEX&top=2"},+ {"LIST USERS PLAN 'Pro' QUOTA 80 DAYS 7;", "days=7&plan=Pro"a=80"},+ {"LIST USERS INACTIVE DAYS 30 PAGE 2 PAGE_SIZE 10;", "days=30&page=2&page_size=10&status=INACTIVE"},+ } {+ t.Run(tt.input, func(t *testing.T) {+ client := newTestHTTPClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ body, _ := io.ReadAll(r.Body)+ if r.Method != http.MethodGet || r.URL.Path != "/api/v1/admin/users" || r.URL.RawQuery != tt.query || len(body) != 0 {+ t.Errorf("request = %s %s body=%q", r.Method, r.URL, body)+ }+ _, _ = io.WriteString(w, `{"code":0,"data":[{"user":"[email protected]"}],"total":1}`)+ }))+ token := "admin-token"+ client.LoginToken = &token+ c := &CLI{Config: &CommandLineConfig{CLIMode: AdminMode}, AdminServerClient: client}+ cmd, err := NewParser(tt.input).Parse(AdminMode)+ if err != nil {+ t.Fatal(err)+ }+ response, err := c.ExecuteCommand(1, cmd)+ if err != nil {+ t.Fatal(err)+ }+ result := response.(*OrderedCommonResponse)+ if len(result.Data) != 1 || result.Data[0]["user"] != "[email protected]" {+ t.Fatalf("unexpected report response: %#v", result)+ }+ })+ }+}++func TestAdminUserListRejectsInvalidOptions(t *testing.T) {+ for _, input := range []string{+ "LIST USERS WITH;", "LIST USERS WITH unknown 'value';",+ "LIST USERS WITH keyword;", "LIST USERS WITH keyword 'a' keyword 'b';",+ "LIST USERS WITH page 0;", "LIST USERS WITH page_size 0;", "LIST USERS WITH page 1.5;",+ "LIST USERS WITH quota 101;", "LIST USERS WITH status active;",+ "LIST USERS WITH days -1;", "LIST USERS WITH top -1;",+ "LIST USERS WITH top 0;", "LIST USERS STORAGE TOP 0;",+ "LIST USERS WITH top 10;", "LIST USERS QUOTA 80 TOP 10;", "LIST USERS ACTIVE TOP 10;",+ "LIST USERS WITH order 'storage' top 10 page 1;", "LIST USERS WITH order 'index' page_size 10 top 10;",+ "LIST USERS STORAGE TOP 10 PAGE 1;", "LIST USERS DOCUMENTS PAGE_SIZE 10 TOP 10;",+ "LIST USERS ACTIVE PAGE 0;", "LIST USERS ACTIVE PAGE_SIZE 0;",+ "LIST USERS ACTIVE PAGE 1 PAGE 2;",+ "LIST USERS WITH keyword 'a'; trailing", "LIST USERS ACTIVE WITH keyword 'a';",+ } {+ t.Run(input, func(t *testing.T) {+ if cmd, err := NewParser(input).Parse(AdminMode); cmd != nil || err == nil {+ t.Fatalf("Parse() = (%v, %v)", cmd, err)+ }+ })+ }+}++func TestAdminUserListErrors(t *testing.T) {+ for _, tt := range []struct {+ status int+ body, message string+ }{+ {http.StatusForbidden, `{"code":403}`, "HTTP 403"},+ {http.StatusOK, `{"code":400,"message":"unsupported order"}`, "unsupported order"},+ {http.StatusOK, `{"code":0,"data":`, "invalid JSON"},+ } {+ t.Run(tt.message, func(t *testing.T) {+ client := newTestHTTPClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(tt.status)+ _, _ = io.WriteString(w, tt.body)+ }))+ token := "admin-token"+ client.LoginToken = &token+ c := &CLI{Config: &CommandLineConfig{CLIMode: AdminMode}, AdminServerClient: client}+ _, err := c.AdminListUsersCommand(1, NewCommand("admin_list_users_command"))+ if err == nil || !strings.Contains(err.Error(), tt.message) {+ t.Fatalf("error = %v", err)+ }+ })+ }+ if _, err := (&CLI{}).AdminListUsersCommand(1, NewCommand("admin_list_users_command")); err == nil {+ t.Fatal("unauthenticated client was accepted")+ }+}++func TestAdminUserListOutputIncludesTotal(t *testing.T) {+ for _, format := range []OutputFormat{OutputFormatJSON, OutputFormatPlain, OutputFormatTable} {+ t.Run(string(format), func(t *testing.T) {+ result := &adminUserListResponse{CommonResponse: CommonResponse{Data: []map[string]interface{}{{"email": "[email protected]"}}, OutputFormat: format}, Total: 17}+ file, err := os.CreateTemp(t.TempDir(), "user-list-output-*")+ if err != nil {+ t.Fatal(err)+ }+ defer file.Close()+ stdout := os.Stdout+ os.Stdout = file+ defer func() { os.Stdout = stdout }()+ result.PrintOut()+ if _, err := file.Seek(0, io.SeekStart); err != nil {+ t.Fatal(err)+ }+ output, err := io.ReadAll(file)+ if err != nil {+ t.Fatal(err)+ }+ if format == OutputFormatJSON {+ var value struct {+ Users []map[string]interface{} `json:"users"`+ Total int64 `json:"total"`+ }+ if err := json.Unmarshal(output, &value); err != nil || value.Total != 17 || len(value.Users) != 1 {+ t.Fatalf("output = %s, err = %v", output, err)+ }+ } else if !strings.Contains(string(output), "Total: 17") || !strings.Contains(string(output), "[email protected]") {+ t.Fatalf("output = %s", output)+ }+ })+ }+}diff --git a/internal/cli/cli.go b/internal/cli/cli.goindex 2a96ef9abf..7e06ebefcb 100644--- a/internal/cli/cli.go+++ b/internal/cli/cli.go@@ -847,6 +847,20 @@ Commands (User Mode):CHAT COMPLETIONS 'question' [options] ; - Chat completions via /api/v1/chat/completions(run chat completions -h for detailed options)+Commands (Admin Mode):+ LIST USERS; - List the first page of users+ LIST USERS WITH keyword 'alice' status 'active' order 'create_time' sort 'asc' page 1 page_size 10;+ - Search, filter, sort, and paginate users+ User list sorting supports create_time and last_login_time.+ LIST USERS WITH role 'Reader' plan 'Pro' quota 80 days 30 page 2 page_size 10;+ - Enterprise filters with pagination+ LIST USERS STORAGE TOP 20; - Enterprise storage ranking, top results+ LIST USERS DOCUMENTS PAGE 2 PAGE_SIZE 10; - Enterprise document ranking, paginated+ LIST USERS INDEX TOP 20; - Enterprise index ranking (individual indices)+ Only storage, documents and index support top. Do not combine top with page or page_size.+ In EE user filters, days limits recent logins.+ WITH text values must be quoted. JSON output includes users and total.+Filesystem Commands (no quotes):ls [path] - List resourcese.g., ls - List root (providers and folders)diff --git a/internal/dao/user.go b/internal/dao/user.goindex 11a4bf5f67..4cda5b3158 100644--- a/internal/dao/user.go+++ b/internal/dao/user.go@@ -18,9 +18,12 @@ package daoimport ("context"+ "fmt""ragflow/internal/entity"+ "strings""gorm.io/gorm"+ "gorm.io/gorm/clause")// UserDAO user data access object@@ -132,27 +135,81 @@ func (dao *UserDAO) UpdateAccessToken(ctx context.Context, db *gorm.DB, user *enreturn db.WithContext(ctx).Model(user).Update("access_token", token).Error}-// List users (only active users with status != "0")-func (dao *UserDAO) List(ctx context.Context, db *gorm.DB, offset, limit int, name, status, sort, orderBy string) ([]*entity.User, int64, error) {- var users []*entity.User- var total int64+// UserListOrder identifies a supported database ordering for user lists.+type UserListOrder uint8++const (+ UserListByCreateTime UserListOrder = iota+ UserListByLastLoginTime+)++// UserListOptions contains resolved filters, ordering, and pagination.+type UserListOptions struct {+ Keyword string+ Active *bool // nil includes both active and inactive users.+ OrderBy UserListOrder+ Desc bool+ Offset int+ Limit int+}- // Only count users with status != "0" (not deleted)- if err := db.WithContext(ctx).Model(&entity.User{}).Count(&total).Error; err != nil {+// List returns a page of users and their filtered total. Conditions on db are+// applied before counting and pagination, so callers can add further filters.+func (dao *UserDAO) List(ctx context.Context, db *gorm.DB, opts UserListOptions) ([]*entity.User, int64, error) {+ order, err := userListOrder(opts.OrderBy, opts.Desc)+ if err != nil {+ return nil, 0, err+ }+ query := userListQuery(ctx, db, opts.Keyword, opts.Active)+ var total int64+ if err := query.Session(&gorm.Session{}).Count(&total).Error; err != nil {return nil, 0, err}- query := db.WithContext(ctx).Model(&entity.User{})- if offset > 0 {- query = query.Offset(offset)+ query = query.Order(order).+ Order(clause.OrderByColumn{Column: clause.Column{Table: "user", Name: "id"}})+ if opts.Offset > 0 {+ query = query.Offset(opts.Offset)}- if limit > 0 {- query = query.Limit(limit)+ if opts.Limit > 0 {+ query = query.Limit(opts.Limit)}- err := query.Find(&users).Error+ users := make([]*entity.User, 0)+ err = query.Select("user.*").Find(&users).Errorreturn users, total, err}+func userListQuery(ctx context.Context, db *gorm.DB, keyword string, active *bool) *gorm.DB {+ query := db.WithContext(ctx).Model(&entity.User{})+ if keyword != "" {+ pattern := "%" + strings.NewReplacer("!", "!!", "%", "!%", "_", "!_").Replace(strings.ToLower(keyword)) + "%"+ query = query.Where("(LOWER(?) LIKE ? ESCAPE '!' OR LOWER(?) LIKE ? ESCAPE '!')",+ clause.Column{Table: "user", Name: "email"}, pattern,+ clause.Column{Table: "user", Name: "nickname"}, pattern)+ }+ if active != nil {+ value := "0"+ if *active {+ value = "1"+ }+ query = query.Where(clause.Eq{Column: clause.Column{Table: "user", Name: "is_active"}, Value: value})+ }+ return query+}++func userListOrder(order UserListOrder, desc bool) (clause.OrderByColumn, error) {+ var field string+ switch order {+ case UserListByCreateTime:+ field = "create_time"+ case UserListByLastLoginTime:+ field = "last_login_time"+ default:+ return clause.OrderByColumn{}, fmt.Errorf("unsupported user list order: %d", order)+ }+ return clause.OrderByColumn{Column: clause.Column{Table: "user", Name: field}, Desc: desc}, nil+}+// Delete delete userfunc (dao *UserDAO) Delete(ctx context.Context, db *gorm.DB, id uint) error {return db.WithContext(ctx).Delete(&entity.User{}, id).Error@@ -163,8 +220,7 @@ func (dao *UserDAO) HardDelete(ctx context.Context, db *gorm.DB, id string) erroreturn db.WithContext(ctx).Unscoped().Where("id = ?", id).Delete(&entity.User{}).Error}-// ListByEmail list users by email (only active users with status != "0")-// Returns all users matching the given email address+// ListByEmail returns all users matching the given email address.func (dao *UserDAO) ListByEmail(ctx context.Context, db *gorm.DB, email string) ([]*entity.User, error) {var users []*entity.Usererr := db.WithContext(ctx).Where("email = ?", email).Find(&users).Errordiff --git a/internal/dao/user_list_test.go b/internal/dao/user_list_test.gonew file mode 100644index 0000000000..8b39d22965--- /dev/null+++ b/internal/dao/user_list_test.go@@ -0,0 +1,188 @@+//+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.+//++package dao++import (+ "reflect"+ "strings"+ "testing"+ "time"++ "ragflow/internal/entity"++ "github.com/glebarez/sqlite"+ "gorm.io/gorm"+)++func setupUserListDB(t *testing.T) *gorm.DB {+ t.Helper()+ db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})+ if err != nil {+ t.Fatal(err)+ }+ sqlDB, err := db.DB()+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = sqlDB.Close() })+ if err := db.AutoMigrate(&entity.User{}); err != nil {+ t.Fatal(err)+ }+ created := time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC)+ createdAt := created.UnixMilli()+ role := int32(7)+ users := []entity.User{+ {ID: "a", Email: "[email protected]", Nickname: "Reader", IsActive: "1", RoleID: &role, Status: userListTestString("0")},+ {ID: "b", Email: "[email protected]", Nickname: "ALICE", IsActive: "0"},+ {ID: "c", Email: "[email protected]", Nickname: "100%_Ready!", IsActive: "1", RoleID: &role},+ }+ for i := range users {+ users[i].CreateTime = &createdAt+ users[i].CreateDate = &created+ if err := db.Create(&users[i]).Error; err != nil {+ t.Fatal(err)+ }+ }+ // Write NULL explicitly because GORM fills omitted statuses with the model default.+ if err := db.Model(&entity.User{}).Where("id = ?", "b").UpdateColumn("status", nil).Error; err != nil {+ t.Fatal(err)+ }+ return db+}++func userListTestString(value string) *string { return &value }++func TestUserListFiltersAndPagination(t *testing.T) {+ db := setupUserListDB(t)+ active, inactive := true, false+ for i, id := range []string{"a", "b", "c"} {+ lastLogin := time.Date(2026, 10, 1, i, 0, 0, 0, time.UTC)+ if err := db.Model(&entity.User{}).Where("id = ?", id).Update("last_login_time", lastLogin).Error; err != nil {+ t.Fatal(err)+ }+ }+ for _, tt := range []struct {+ name string+ opts UserListOptions+ ids []string+ total int64+ }{+ {name: "all record statuses", ids: []string{"a", "b", "c"}, total: 3},+ {name: "email or nickname case insensitive", opts: UserListOptions{Keyword: "ALiCe"}, ids: []string{"a", "b"}, total: 2},+ {name: "combined", opts: UserListOptions{Keyword: "alice", Active: &active}, ids: []string{"a"}, total: 1},+ {name: "disabled account", opts: UserListOptions{Active: &inactive}, ids: []string{"b"}, total: 1},+ {name: "literal wildcard", opts: UserListOptions{Keyword: "%_"}, ids: []string{"c"}, total: 1},+ {name: "escape character", opts: UserListOptions{Keyword: "!"}, ids: []string{"c"}, total: 1},+ {name: "bound keyword", opts: UserListOptions{Keyword: "' OR 1=1 --"}, ids: []string{}, total: 0},+ {name: "descending last login", opts: UserListOptions{OrderBy: UserListByLastLoginTime, Desc: true}, ids: []string{"c", "b", "a"}, total: 3},+ {name: "ascending last login", opts: UserListOptions{OrderBy: UserListByLastLoginTime}, ids: []string{"a", "b", "c"}, total: 3},+ {name: "creation time tie breaker", opts: UserListOptions{OrderBy: UserListByCreateTime}, ids: []string{"a", "b", "c"}, total: 3},+ {name: "filtered page", opts: UserListOptions{Keyword: "alice", Offset: 1, Limit: 1}, ids: []string{"b"}, total: 2},+ {name: "past last page", opts: UserListOptions{Offset: 10, Limit: 2}, ids: []string{}, total: 3},+ } {+ t.Run(tt.name, func(t *testing.T) {+ users, total, err := NewUserDAO().List(t.Context(), db, tt.opts)+ if err != nil {+ t.Fatal(err)+ }+ ids := make([]string, 0, len(users))+ for _, user := range users {+ ids = append(ids, user.ID)+ }+ if total != tt.total || !reflect.DeepEqual(ids, tt.ids) {+ t.Fatalf("ids = %v, total = %d; want %v, %d", ids, total, tt.ids, tt.total)+ }+ })+ }+}++func TestUserListCreationTimeOrder(t *testing.T) {+ db := setupUserListDB(t)+ createdAt := time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC).UnixMilli()+ // All create_date values are equal; millisecond timestamps must decide the order.+ for i, id := range []string{"a", "b", "c"} {+ if err := db.Model(&entity.User{}).Where("id = ?", id).Update("create_time", createdAt+int64(2-i)).Error; err != nil {+ t.Fatal(err)+ }+ }+ for _, tt := range []struct {+ name string+ opts UserListOptions+ ids []string+ }{+ {name: "ascending", ids: []string{"c", "b", "a"}},+ {name: "descending", opts: UserListOptions{OrderBy: UserListByCreateTime, Desc: true}, ids: []string{"a", "b", "c"}},+ {name: "first page", opts: UserListOptions{Limit: 1}, ids: []string{"c"}},+ {name: "second page", opts: UserListOptions{Offset: 1, Limit: 1}, ids: []string{"b"}},+ } {+ t.Run(tt.name, func(t *testing.T) {+ users, total, err := NewUserDAO().List(t.Context(), db, tt.opts)+ if err != nil {+ t.Fatal(err)+ }+ ids := make([]string, 0, len(users))+ for _, user := range users {+ ids = append(ids, user.ID)+ }+ if total != 3 || !reflect.DeepEqual(ids, tt.ids) {+ t.Fatalf("ids = %v, total = %d; want %v, 3", ids, total, tt.ids)+ }+ })+ }+}++func TestUserListCountsCallerConditionsBeforePagination(t *testing.T) {+ db := setupUserListDB(t)+ query := db.Where("user.role_id = ?", 7)+ active := true+ users, total, err := NewUserDAO().List(t.Context(), query, UserListOptions{Active: &active, Offset: 1, Limit: 1})+ if err != nil || total != 2 || len(users) != 1 || users[0].ID != "c" {+ t.Fatalf("List() = (%v, %d, %v)", users, total, err)+ }+ // Reusing the caller's query must not inherit LIMIT/OFFSET or COUNT selection.+ users, total, err = NewUserDAO().List(t.Context(), query, UserListOptions{Keyword: "alice", Limit: 10, Desc: true})+ if err != nil || total != 1 || len(users) != 1 || users[0].ID != "a" {+ t.Fatalf("reused List() = (%v, %d, %v)", users, total, err)+ }+}++func TestUserListQueryDryRun(t *testing.T) {+ db := setupUserListDB(t)+ inactive := false+ query := userListQuery(t.Context(), db.Session(&gorm.Session{DryRun: true}).Where("user.role_id = ?", 7), "a%_", &inactive)+ result := query.Find(&[]entity.User{})+ sql := result.Statement.SQL.String()+ if !strings.Contains(sql, "LOWER(`user`.`email`) LIKE ? ESCAPE '!' OR LOWER(`user`.`nickname`) LIKE ? ESCAPE '!'") ||+ !strings.Contains(sql, "`user`.`is_active` = ?") || strings.Contains(sql, "`user`.`status`") {+ t.Fatalf("unexpected SQL: %s", sql)+ }+ if !reflect.DeepEqual(result.Statement.Vars, []interface{}{7, "%a!%!_%", "%a!%!_%", "0"}) {+ t.Fatalf("unexpected bindings: %#v", result.Statement.Vars)+ }+}++func TestUserListCreationTimeOrderDryRun(t *testing.T) {+ db := setupUserListDB(t)+ order, err := userListOrder(UserListByCreateTime, true)+ if err != nil {+ t.Fatal(err)+ }+ result := db.Session(&gorm.Session{DryRun: true}).Model(&entity.User{}).Order(order).Find(&[]entity.User{})+ if sql := result.Statement.SQL.String(); !strings.Contains(sql, "ORDER BY `user`.`create_time` DESC") {+ t.Fatalf("unexpected SQL: %s", sql)+ }+}