Thanks to visit codestin.com
Credit goes to github.com

Skip to content

feat: add count endpoint for users, enabling better pagination #4848

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 18 commits into from
Nov 8, 2022
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions coderd/coderd.go
Original file line number Diff line number Diff line change
Expand Up @@ -433,6 +433,7 @@ func New(options *Options) *API {
)
r.Post("/", api.postUser)
r.Get("/", api.users)
r.Get("/count", api.userCount)
r.Post("/logout", api.postLogout)
// These routes query information about site wide roles.
r.Route("/roles", func(r chi.Router) {
Expand Down
1 change: 1 addition & 0 deletions coderd/coderdtest/authorize.go
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,7 @@ func AGPLRoutes(a *AuthTester) (map[string]string, map[string]RouteCheck) {
// Endpoints that use the SQLQuery filter.
"GET:/api/v2/workspaces/": {StatusCode: http.StatusOK, NoAuthorize: true},
"GET:/api/v2/workspaces/count": {StatusCode: http.StatusOK, NoAuthorize: true},
"GET:/api/v2/users/count": {StatusCode: http.StatusOK, NoAuthorize: true},
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not doing an auth check here, combined with the fact that you can query for username or email substrings means that you can easily dump all usernames and emails by repeatedly hitting this endpoint and doing a tree search.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To follow up, you can follow how we do this for workspaces.

type workspaceQuerier interface {
GetAuthorizedWorkspaces(ctx context.Context, arg GetWorkspacesParams, authorizedFilter rbac.AuthorizeFilter) ([]Workspace, error)
GetAuthorizedWorkspaceCount(ctx context.Context, arg GetWorkspaceCountParams, authorizedFilter rbac.AuthorizeFilter) (int64, error)
}

If you add api.Authorize(r, rbac.ActionRead, rbac.ResourceUser) it is technically ok as it checks if you can read all users. We should really do it proper though so we can mess with perms later and everything still works.

Add a new function called GetAuthorizedUsersCount

}

// Routes like proxy routes support all HTTP methods. A helper func to expand
Expand Down
54 changes: 54 additions & 0 deletions coderd/database/databasefake/databasefake.go
Original file line number Diff line number Diff line change
Expand Up @@ -457,6 +457,60 @@ func (q *fakeQuerier) GetActiveUserCount(_ context.Context) (int64, error) {
return active, nil
}

func (q *fakeQuerier) GetFilteredUserCount(_ context.Context, params database.GetFilteredUserCountParams) (int64, error) {
q.mutex.RLock()
defer q.mutex.RUnlock()

users := append([]database.User{}, q.users...)

if params.Deleted {
tmp := make([]database.User, 0, len(users))
for _, user := range users {
if user.Deleted {
tmp = append(tmp, user)
}
}
users = tmp
}

if params.Search != "" {
tmp := make([]database.User, 0, len(users))
for i, user := range users {
if strings.Contains(strings.ToLower(user.Email), strings.ToLower(params.Search)) {
tmp = append(tmp, users[i])
} else if strings.Contains(strings.ToLower(user.Username), strings.ToLower(params.Search)) {
tmp = append(tmp, users[i])
}
}
users = tmp
}

if len(params.Status) > 0 {
usersFilteredByStatus := make([]database.User, 0, len(users))
for i, user := range users {
if slice.ContainsCompare(params.Status, user.Status, func(a, b database.UserStatus) bool {
return strings.EqualFold(string(a), string(b))
}) {
usersFilteredByStatus = append(usersFilteredByStatus, users[i])
}
}
users = usersFilteredByStatus
}

if len(params.RbacRole) > 0 && !slice.Contains(params.RbacRole, rbac.RoleMember()) {
usersFilteredByRole := make([]database.User, 0, len(users))
for i, user := range users {
if slice.OverlapCompare(params.RbacRole, user.RBACRoles, strings.EqualFold) {
usersFilteredByRole = append(usersFilteredByRole, users[i])
}
}

users = usersFilteredByRole
}

return int64(len(users)), nil
}

func (q *fakeQuerier) UpdateUserDeletedByID(_ context.Context, params database.UpdateUserDeletedByIDParams) error {
q.mutex.Lock()
defer q.mutex.Unlock()
Expand Down
1 change: 1 addition & 0 deletions coderd/database/querier.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

52 changes: 52 additions & 0 deletions coderd/database/queries.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

32 changes: 32 additions & 0 deletions coderd/database/queries/users.sql
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,38 @@ FROM
WHERE
status = 'active'::public.user_status AND deleted = false;

-- name: GetFilteredUserCount :one
SELECT
COUNT(*)
FROM
users
WHERE
users.deleted = @deleted
-- Start filters
-- Filter by name, email or username
AND CASE
WHEN @search :: text != '' THEN (
email ILIKE concat('%', @search, '%')
OR username ILIKE concat('%', @search, '%')
)
ELSE true
END
-- Filter by status
AND CASE
-- @status needs to be a text because it can be empty, If it was
-- user_status enum, it would not.
WHEN cardinality(@status :: user_status[]) > 0 THEN
status = ANY(@status :: user_status[])
ELSE true
END
-- Filter by rbac_roles
AND CASE
-- @rbac_role allows filtering by rbac roles. If 'member' is included, show everyone, as everyone is a member.
WHEN cardinality(@rbac_role :: text[]) > 0 AND 'member' != ANY(@rbac_role :: text[])
THEN rbac_roles && @rbac_role :: text[]
ELSE true
END;

-- name: InsertUser :one
INSERT INTO
users (
Expand Down
27 changes: 27 additions & 0 deletions coderd/users.go
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,33 @@ func (api *API) users(rw http.ResponseWriter, r *http.Request) {
render.JSON(rw, r, convertUsers(users, organizationIDsByUserID))
}

func (api *API) userCount(rw http.ResponseWriter, r *http.Request) {
ctx := r.Context()
query := r.URL.Query().Get("q")
params, errs := userSearchQuery(query)
if len(errs) > 0 {
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
Message: "Invalid user search query.",
Validations: errs,
})
return
}

count, err := api.Database.GetFilteredUserCount(ctx, database.GetFilteredUserCountParams{
Search: params.Search,
Status: params.Status,
RbacRole: params.RbacRole,
})
if err != nil {
httpapi.InternalServerError(rw, err)
return
}

httpapi.Write(ctx, rw, http.StatusOK, codersdk.UserCountResponse{
Count: count,
})
}

// Creates a new user.
func (api *API) postUser(rw http.ResponseWriter, r *http.Request) {
ctx := r.Context()
Expand Down
52 changes: 52 additions & 0 deletions coderd/users_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1255,6 +1255,58 @@ func TestGetUsers(t *testing.T) {
})
}

func TestGetFilteredUserCount(t *testing.T) {
t.Parallel()
t.Run("AllUsers", func(t *testing.T) {
t.Parallel()
client := coderdtest.New(t, nil)
user := coderdtest.CreateFirstUser(t, client)

ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
defer cancel()

client.CreateUser(ctx, codersdk.CreateUserRequest{
Email: "[email protected]",
Username: "alice",
Password: "password",
OrganizationID: user.OrganizationID,
})
// No params is all users
response, err := client.UserCount(ctx, codersdk.UserCountRequest{})
require.NoError(t, err)
require.Equal(t, 2, int(response.Count))
})
t.Run("ActiveUsers", func(t *testing.T) {
t.Parallel()
client := coderdtest.New(t, nil)
first := coderdtest.CreateFirstUser(t, client)

ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
defer cancel()

_, err := client.User(ctx, first.UserID.String())
require.NoError(t, err, "")

// Alice will be suspended
alice, err := client.CreateUser(ctx, codersdk.CreateUserRequest{
Email: "[email protected]",
Username: "alice",
Password: "password",
OrganizationID: first.OrganizationID,
})
require.NoError(t, err)

_, err = client.UpdateUserStatus(ctx, alice.Username, codersdk.UserStatusSuspended)
require.NoError(t, err)

response, err := client.UserCount(ctx, codersdk.UserCountRequest{
Status: codersdk.UserStatusActive,
})
require.NoError(t, err)
require.Equal(t, 1, int(response.Count))
})
}

func TestPostTokens(t *testing.T) {
t.Parallel()
client := coderdtest.New(t, nil)
Expand Down
48 changes: 48 additions & 0 deletions codersdk/users.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,20 @@ type User struct {
AvatarURL string `json:"avatar_url"`
}

type UserCountRequest struct {
Search string `json:"search,omitempty" typescript:"-"`
// Filter users by status.
Status UserStatus `json:"status,omitempty" typescript:"-"`
// Filter users that have the given role.
Role string `json:"role,omitempty" typescript:"-"`

SearchQuery string `json:"q,omitempty"`
}

type UserCountResponse struct {
Count int64 `json:"count"`
}

type CreateFirstUserRequest struct {
Email string `json:"email" validate:"required,email"`
Username string `json:"username" validate:"required,username"`
Expand Down Expand Up @@ -345,6 +359,40 @@ func (c *Client) Users(ctx context.Context, req UsersRequest) ([]User, error) {
return users, json.NewDecoder(res.Body).Decode(&users)
}

func (c *Client) UserCount(ctx context.Context, req UserCountRequest) (UserCountResponse, error) {
res, err := c.Request(ctx, http.MethodGet, "/api/v2/users/count", nil,
func(r *http.Request) {
q := r.URL.Query()
var params []string
if req.Search != "" {
params = append(params, req.Search)
}
if req.Status != "" {
params = append(params, "status:"+string(req.Status))
}
if req.Role != "" {
params = append(params, "role:"+req.Role)
}
if req.SearchQuery != "" {
params = append(params, req.SearchQuery)
}
q.Set("q", strings.Join(params, " "))
r.URL.RawQuery = q.Encode()
},
)
if err != nil {
return UserCountResponse{}, err
}
defer res.Body.Close()

if res.StatusCode != http.StatusOK {
return UserCountResponse{}, readBodyAsError(res)
}

var count UserCountResponse
return count, json.NewDecoder(res.Body).Decode(&count)
}

// OrganizationsByUser returns all organizations the user is a member of.
func (c *Client) OrganizationsByUser(ctx context.Context, user string) ([]Organization, error) {
res, err := c.Request(ctx, http.MethodGet, fmt.Sprintf("/api/v2/users/%s/organizations", user), nil)
Expand Down
8 changes: 8 additions & 0 deletions site/src/api/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,14 @@ export const getUsers = async (
return response.data
}

export const getUserCount = async (
options: TypesGen.UserCountRequest,
): Promise<TypesGen.UserCountResponse> => {
const url = getURLWithSearchParams("/api/v2/users/count", options)
const response = await axios.get(url.toString())
return response.data
}

export const getOrganization = async (
organizationId: string,
): Promise<TypesGen.Organization> => {
Expand Down
10 changes: 10 additions & 0 deletions site/src/api/typesGenerated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -739,6 +739,16 @@ export interface User {
readonly avatar_url: string
}

// From codersdk/users.go
export interface UserCountRequest {
readonly q?: string
}

// From codersdk/users.go
export interface UserCountResponse {
readonly count: number
}

// From codersdk/users.go
export interface UserRoles {
readonly roles: string[]
Expand Down
Loading