Skip to content

Take control over your live stream video by running it yourself. Streaming + chat out of the box.

feat(admin): sort the users list across all pages by creation date

Gabe Kangasb28dc40cb746
diff --git a/db/query.sql b/db/query.sql
index b600f4cccd..cd2f34f433 100644
--- a/db/query.sql
+++ b/db/query.sql
@@ -183,7 +183,9 @@ UPDATE users SET display_color = ? WHERE id = ?;
-- 'active' (not banned) or 'bots' (API users). An empty @search matches every
-- user (LIKE '%%'). The complete banned and moderator sets come from
-- GetDisabledUsers and GetModeratorUsers instead, since those need every match
--- rather than a page.
+-- rather than a page. GetUsersPaginatedAsc is the oldest-first counterpart;
+-- the two exist as separate queries because sqlc can't bind a sort direction
+-- into ORDER BY.
SELECT id, display_name, display_color, created_at, disabled_at, previous_names, namechanged_at, authenticated_at, scopes, type = 'API' AS is_bot
FROM users
WHERE display_name LIKE '%' || @search || '%'
@@ -195,6 +197,20 @@ WHERE display_name LIKE '%' || @search || '%'
ORDER BY created_at DESC
LIMIT @page_limit OFFSET @page_offset;
+-- name: GetUsersPaginatedAsc :many
+-- Oldest-first counterpart to GetUsersPaginated. Same @search/@status filter,
+-- only the created_at ordering differs.
+SELECT id, display_name, display_color, created_at, disabled_at, previous_names, namechanged_at, authenticated_at, scopes, type = 'API' AS is_bot
+FROM users
+WHERE display_name LIKE '%' || @search || '%'
+ AND (
+ @status = '' OR @status = 'all'
+ OR (@status = 'active' AND disabled_at IS NULL)
+ OR (@status = 'bots' AND type = 'API')
+ )
+ORDER BY created_at ASC
+LIMIT @page_limit OFFSET @page_offset;
+
-- name: CountUsers :one
-- Total number of users matching the same @search/@status filter as GetUsersPaginated.
SELECT count(*) FROM users
diff --git a/db/query.sql.go b/db/query.sql.go
index cd5f7f5ff8..bc60224325 100644
--- a/db/query.sql.go
+++ b/db/query.sql.go
@@ -1362,7 +1362,9 @@ type GetUsersPaginatedRow struct {
// 'active' (not banned) or 'bots' (API users). An empty @search matches every
// user (LIKE '%%'). The complete banned and moderator sets come from
// GetDisabledUsers and GetModeratorUsers instead, since those need every match
-// rather than a page.
+// rather than a page. GetUsersPaginatedAsc is the oldest-first counterpart;
+// the two exist as separate queries because sqlc can't bind a sort direction
+// into ORDER BY.
func (q *Queries) GetUsersPaginated(ctx context.Context, arg GetUsersPaginatedParams) ([]GetUsersPaginatedRow, error) {
rows, err := q.db.QueryContext(ctx, getUsersPaginated,
arg.Search,
@@ -1402,6 +1404,80 @@ func (q *Queries) GetUsersPaginated(ctx context.Context, arg GetUsersPaginatedPa
return items, nil
}
+const getUsersPaginatedAsc = `-- name: GetUsersPaginatedAsc :many
+SELECT id, display_name, display_color, created_at, disabled_at, previous_names, namechanged_at, authenticated_at, scopes, type = 'API' AS is_bot
+FROM users
+WHERE display_name LIKE '%' || ?1 || '%'
+ AND (
+ ?2 = '' OR ?2 = 'all'
+ OR (?2 = 'active' AND disabled_at IS NULL)
+ OR (?2 = 'bots' AND type = 'API')
+ )
+ORDER BY created_at ASC
+LIMIT ?4 OFFSET ?3
+`
+
+type GetUsersPaginatedAscParams struct {
+ Search sql.NullString
+ Status interface{}
+ PageOffset int64
+ PageLimit int64
+}
+
+type GetUsersPaginatedAscRow struct {
+ ID string
+ DisplayName string
+ DisplayColor int64
+ CreatedAt sql.NullTime
+ DisabledAt sql.NullTime
+ PreviousNames sql.NullString
+ NamechangedAt sql.NullTime
+ AuthenticatedAt sql.NullTime
+ Scopes sql.NullString
+ IsBot bool
+}
+
+// Oldest-first counterpart to GetUsersPaginated. Same @search/@status filter,
+// only the created_at ordering differs.
+func (q *Queries) GetUsersPaginatedAsc(ctx context.Context, arg GetUsersPaginatedAscParams) ([]GetUsersPaginatedAscRow, error) {
+ rows, err := q.db.QueryContext(ctx, getUsersPaginatedAsc,
+ arg.Search,
+ arg.Status,
+ arg.PageOffset,
+ arg.PageLimit,
+ )
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var items []GetUsersPaginatedAscRow
+ for rows.Next() {
+ var i GetUsersPaginatedAscRow
+ if err := rows.Scan(
+ &i.ID,
+ &i.DisplayName,
+ &i.DisplayColor,
+ &i.CreatedAt,
+ &i.DisabledAt,
+ &i.PreviousNames,
+ &i.NamechangedAt,
+ &i.AuthenticatedAt,
+ &i.Scopes,
+ &i.IsBot,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Close(); err != nil {
+ return nil, err
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const isDisplayNameAvailable = `-- name: IsDisplayNameAvailable :one
SELECT count(*) FROM users WHERE display_name = ? AND ( type='API' OR authenticated_at IS NOT NULL ) AND disabled_at IS NULL
`
diff --git a/openapi.yaml b/openapi.yaml
index c065c44928..556b3ee2db 100644
--- a/openapi.yaml
+++ b/openapi.yaml
@@ -810,6 +810,13 @@ paths:
schema:
type: string
enum: [all, active, bots]
+ - in: query
+ name: sort
+ description: Sort direction by creation date (defaults to newest first)
+ schema:
+ type: string
+ enum: [asc, desc]
+ default: desc
responses:
'200':
description: A paginated list of users
diff --git a/persistence/userrepository/userrepository.go b/persistence/userrepository/userrepository.go
index ce73af1f54..6498e44515 100644
--- a/persistence/userrepository/userrepository.go
+++ b/persistence/userrepository/userrepository.go
@@ -28,7 +28,7 @@ type UserRepository interface {
DeleteExternalAPIUser(token string) error
GetDisabledUsers() []*models.User
GetUsers() []*models.User
- GetUsersPaginated(offset int, limit int, search string, status string) ([]*models.User, int, error)
+ GetUsersPaginated(offset int, limit int, search string, status string, sort string) ([]*models.User, int, error)
DeleteUser(userID string) error
GetExternalAPIUser() ([]models.ExternalAPIUser, error)
GetExternalAPIUserForAccessTokenAndScope(token string, scope string) (*models.ExternalAPIUser, error)
@@ -496,13 +496,14 @@ func (r *SqlUserRepository) GetUsers() []*models.User {
}
// GetUsersPaginated returns a page of users of every type (chat viewers,
-// authenticated/plugin users, and API integrations), most-recently-created
-// first, filtered to display names containing search and an optional status
-// ("" / "all" = every user; else "active", "banned", "moderators", "bots"). It also
-// returns the total number of users matching the filter so the admin
-// user-management page can paginate. The search arg is always Valid (even when
-// empty) so the LIKE binds to ” and matches every user rather than NULL.
-func (r *SqlUserRepository) GetUsersPaginated(offset int, limit int, search string, status string) ([]*models.User, int, error) {
+// authenticated/plugin users, and API integrations), filtered to display names
+// containing search and an optional status ("" / "all" = every user; else
+// "active", "banned", "moderators", "bots"). The page is ordered by creation
+// date: sort == "asc" is oldest-first, anything else is most-recently-created
+// first. It also returns the total number of users matching the filter so the
+// admin user-management page can paginate. The search arg is always Valid (even
+// when empty) so the LIKE binds to ” and matches every user rather than NULL.
+func (r *SqlUserRepository) GetUsersPaginated(offset int, limit int, search string, status string, sort string) ([]*models.User, int, error) {
if limit <= 0 {
limit = 50
}
@@ -521,19 +522,33 @@ func (r *SqlUserRepository) GetUsersPaginated(offset int, limit int, search stri
return nil, 0, errors.Wrap(err, "unable to count users")
}
- rows, err := r.datastore.GetQueries().GetUsersPaginated(ctx, db.GetUsersPaginatedParams{
- Search: searchArg,
- Status: status,
- PageLimit: int64(limit),
- PageOffset: int64(offset),
- })
- if err != nil {
- return nil, 0, errors.Wrap(err, "unable to query users")
- }
-
- users := make([]*models.User, 0, len(rows))
- for _, u := range rows {
- users = append(users, userFromColumns(u.ID, u.DisplayName, u.DisplayColor, u.CreatedAt, u.DisabledAt, u.PreviousNames, u.NamechangedAt, u.AuthenticatedAt, u.Scopes, u.IsBot))
+ users := make([]*models.User, 0, limit)
+ if sort == "asc" {
+ rows, err := r.datastore.GetQueries().GetUsersPaginatedAsc(ctx, db.GetUsersPaginatedAscParams{
+ Search: searchArg,
+ Status: status,
+ PageLimit: int64(limit),
+ PageOffset: int64(offset),
+ })
+ if err != nil {
+ return nil, 0, errors.Wrap(err, "unable to query users")
+ }
+ for _, u := range rows {
+ users = append(users, userFromColumns(u.ID, u.DisplayName, u.DisplayColor, u.CreatedAt, u.DisabledAt, u.PreviousNames, u.NamechangedAt, u.AuthenticatedAt, u.Scopes, u.IsBot))
+ }
+ } else {
+ rows, err := r.datastore.GetQueries().GetUsersPaginated(ctx, db.GetUsersPaginatedParams{
+ Search: searchArg,
+ Status: status,
+ PageLimit: int64(limit),
+ PageOffset: int64(offset),
+ })
+ if err != nil {
+ return nil, 0, errors.Wrap(err, "unable to query users")
+ }
+ for _, u := range rows {
+ users = append(users, userFromColumns(u.ID, u.DisplayName, u.DisplayColor, u.CreatedAt, u.DisabledAt, u.PreviousNames, u.NamechangedAt, u.AuthenticatedAt, u.Scopes, u.IsBot))
+ }
}
if err := r.attachAuthProviders(ctx, users); err != nil {
diff --git a/test/automated/api/012_usermanagement.test.js b/test/automated/api/012_usermanagement.test.js
index d703e106c3..88fe3b02fb 100644
--- a/test/automated/api/012_usermanagement.test.js
+++ b/test/automated/api/012_usermanagement.test.js
@@ -60,6 +60,32 @@ test('authProviders is empty for an anonymous user', async () => {
expect(match[0].authProviders || []).toHaveLength(0);
});
+test('sort orders the page by creation date in both directions', async () => {
+ const asc = await getAdminResponse('users?offset=0&limit=50&sort=asc');
+ const desc = await getAdminResponse('users?offset=0&limit=50&sort=desc');
+
+ const ascTimes = asc.body.results.map((user) =>
+ new Date(user.createdAt).getTime(),
+ );
+ const descTimes = desc.body.results.map((user) =>
+ new Date(user.createdAt).getTime(),
+ );
+
+ // Each page is monotonically ordered by creation date.
+ for (let i = 1; i < ascTimes.length; i++) {
+ expect(ascTimes[i]).toBeGreaterThanOrEqual(ascTimes[i - 1]);
+ }
+ for (let i = 1; i < descTimes.length; i++) {
+ expect(descTimes[i]).toBeLessThanOrEqual(descTimes[i - 1]);
+ }
+
+ // Omitting sort keeps the default newest-first order, i.e. sort=desc.
+ const def = await getAdminResponse('users?offset=0&limit=50');
+ expect(def.body.results.map((user) => user.id)).toEqual(
+ desc.body.results.map((user) => user.id),
+ );
+});
+
// Moderators and banned users come from their own endpoints, which return the
// complete set rather than a page of the users API.
test('moderators list includes a promoted moderator', async () => {
diff --git a/web/pages/admin/users.tsx b/web/pages/admin/users.tsx
index 8e819aa88c..8b595f3907 100644
--- a/web/pages/admin/users.tsx
+++ b/web/pages/admin/users.tsx
@@ -13,7 +13,7 @@ import {
fetchData,
} from '../../utils/apis';
import { User, Client } from '../../types/chat';
-import { formatDisplayDate } from '../../utils/format';
+import { formatDateOnly } from '../../utils/format';
import { ClientTable } from '../../components/admin/ClientTable';
import { BannedIPsTable } from '../../components/admin/BannedIPsTable';
import { UserActionsDropdown } from '../../components/admin/UserActionsDropdown';
@@ -40,6 +40,10 @@ export default function UsersAdmin() {
const [currentPage, setCurrentPage] = useState<number>(1);
const [search, setSearch] = useState<string>('');
const [status, setStatus] = useState<string>('all');
+ // Server-side sort of the paginated list by creation date ('desc' = newest
+ // first, 'asc' = oldest first). The API sorts across every page, not just the
+ // rows already fetched.
+ const [sort, setSort] = useState<'asc' | 'desc'>('desc');
const [loading, setLoading] = useState<boolean>(false);
// Exhaustive lists (the paginated endpoint can't return a complete set).
@@ -56,6 +60,7 @@ export default function UsersAdmin() {
const params = new URLSearchParams({
offset: String((currentPage - 1) * PAGE_SIZE),
limit: String(PAGE_SIZE),
+ sort,
});
if (search) {
params.set('search', search);
@@ -117,7 +122,7 @@ export default function UsersAdmin() {
useEffect(() => {
getUsers();
- }, [currentPage, search, status]);
+ }, [currentPage, search, status, sort]);
useEffect(() => {
getLists();
@@ -172,7 +177,7 @@ export default function UsersAdmin() {
title: 'Created',
dataIndex: 'createdAt',
key: 'createdAt',
- render: (date: Date) => formatDisplayDate(date),
+ render: (date: Date) => formatDateOnly(date),
sorter: (a: User, b: User) =>
new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime(),
sortDirections: ['descend', 'ascend'] as SortOrder[],
@@ -185,6 +190,16 @@ export default function UsersAdmin() {
},
];
+ // The "All Users" table is server-paginated, so its Created column sorts via
+ // the API across every page rather than only the rows in hand. The dedicated
+ // Moderators/Banned tables hold complete sets, so they keep the shared
+ // client-side sorter from `columns`.
+ const usersColumns: ColumnsType<User> = columns.map(col =>
+ col.key === 'createdAt'
+ ? { ...col, sorter: true, sortOrder: (sort === 'asc' ? 'ascend' : 'descend') as SortOrder }
+ : col,
+ );
+
const allUsersTab = (
<>
<Typography.Paragraph>
@@ -219,7 +234,7 @@ export default function UsersAdmin() {
<Table
loading={loading}
className="table-container"
- columns={columns}
+ columns={usersColumns}
dataSource={users}
size="small"
rowKey="id"
@@ -230,7 +245,20 @@ export default function UsersAdmin() {
showSizeChanger: false,
hideOnSinglePage: true,
}}
- onChange={pagination => setCurrentPage(pagination.current || 1)}
+ onChange={(pagination, _filters, sorter) => {
+ // A sort change resets to the first page; a page change keeps the
+ // current sort.
+ const activeSorter = Array.isArray(sorter) ? sorter[0] : sorter;
+ if (activeSorter?.columnKey === 'createdAt') {
+ const nextSort = activeSorter.order === 'ascend' ? 'asc' : 'desc';
+ if (nextSort !== sort) {
+ setSort(nextSort);
+ setCurrentPage(1);
+ return;
+ }
+ }
+ setCurrentPage(pagination.current || 1);
+ }}
/>
</>
);
diff --git a/web/utils/format.ts b/web/utils/format.ts
index 454d3f1fc5..0bb68a2f93 100644
--- a/web/utils/format.ts
+++ b/web/utils/format.ts
@@ -12,6 +12,12 @@ export function formatDisplayDate(date: string | Date) {
return format(new Date(date), 'MMM d H:mma');
}
+// formatDateOnly renders just the calendar date (no time of day), e.g.
+// "Jun 25, 2026". Used for the admin user table's "Created" column.
+export function formatDateOnly(date: string | Date) {
+ return format(new Date(date), 'MMM d, yyyy');
+}
+
export function formatIPAddress(ipAddress: string): string {
const ipAddressComponents = ipAddress.split(':');
diff --git a/webserver/handlers/admin/users.go b/webserver/handlers/admin/users.go
index 431e9e5e89..f42eb888cd 100644
--- a/webserver/handlers/admin/users.go
+++ b/webserver/handlers/admin/users.go
@@ -30,7 +30,14 @@ func (a *Admin) GetUsers(w http.ResponseWriter, r *http.Request) {
search := query.Get("search")
status := query.Get("status")
- users, total, err := a.userRepository.GetUsersPaginated(offset, limit, search, status)
+ // Only "asc" (oldest first) flips the ordering; everything else, including
+ // an empty value, keeps the default newest-first sort.
+ sort := query.Get("sort")
+ if sort != "asc" {
+ sort = "desc"
+ }
+
+ users, total, err := a.userRepository.GetUsersPaginated(offset, limit, search, status, sort)
if err != nil {
webutils.WriteSimpleResponse(w, false, err.Error())
return
diff --git a/webserver/handlers/generated/generated-types.gen.go b/webserver/handlers/generated/generated-types.gen.go
index 28274fb08c..22023fde03 100644
--- a/webserver/handlers/generated/generated-types.gen.go
+++ b/webserver/handlers/generated/generated-types.gen.go
@@ -93,6 +93,24 @@ func (e GetUsersParamsStatus) Valid() bool {
}
}
+// Defines values for GetUsersParamsSort.
+const (
+ Asc GetUsersParamsSort = "asc"
+ Desc GetUsersParamsSort = "desc"
+)
+
+// Valid indicates whether the value is a known member of the GetUsersParamsSort enum.
+func (e GetUsersParamsSort) Valid() bool {
+ switch e {
+ case Asc:
+ return true
+ case Desc:
+ return true
+ default:
+ return false
+ }
+}
+
// ActionMessage defines model for ActionMessage.
type ActionMessage struct {
Body *string `json:"body,omitempty"`
@@ -901,11 +919,17 @@ type GetUsersParams struct {
// Status Filter users by status
Status *GetUsersParamsStatus `form:"status,omitempty" json:"status,omitempty"`
+
+ // Sort Sort direction by creation date (defaults to newest first)
+ Sort *GetUsersParamsSort `form:"sort,omitempty" json:"sort,omitempty"`
}
// GetUsersParamsStatus defines parameters for GetUsers.
type GetUsersParamsStatus string
+// GetUsersParamsSort defines parameters for GetUsers.
+type GetUsersParamsSort string
+
// DeleteUserJSONBody defines parameters for DeleteUser.
type DeleteUserJSONBody struct {
UserId *string `json:"userId,omitempty"`
diff --git a/webserver/handlers/generated/generated.gen.go b/webserver/handlers/generated/generated.gen.go
index 5f67d1bc94..10450bfd53 100644
--- a/webserver/handlers/generated/generated.gen.go
+++ b/webserver/handlers/generated/generated.gen.go
@@ -5016,6 +5016,19 @@ func (siw *ServerInterfaceWrapper) GetUsers(w http.ResponseWriter, r *http.Reque
return
}
+ // ------------- Optional query parameter "sort" -------------
+
+ err = runtime.BindQueryParameterWithOptions("form", true, false, "sort", r.URL.Query(), &params.Sort, runtime.BindQueryParameterOptions{Type: "string", Format: ""})
+ if err != nil {
+ var requiredError *runtime.RequiredParameterError
+ if errors.As(err, &requiredError) {
+ siw.ErrorHandlerFunc(w, r, &RequiredParamError{ParamName: "sort"})
+ } else {
+ siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "sort", Err: err})
+ }
+ return
+ }
+
handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
siw.Handler.GetUsers(w, r, params)
}))