Files
gitea/models/user/search.go
T
silverwindandwxiaoguang 5264304a34 refactor: carry the API token on the doer (#39690)
The token a request authenticated with now lives on the doer, so
permission and visibility checks apply its scope from the doer alone.
Replaces https://github.com/go-gitea/gitea/pull/39167, following
https://github.com/go-gitea/gitea/pull/39167#issuecomment-6063839619.

1. Public-only tokens get 404 instead of 403 for hidden users, orgs and
repos, like GitHub.
2. Org ownership, site admin, repo and org creation, generation and
transfer endpoints reject public-only tokens.
3. API pull request responses set `head.repo` to `null` and
`head.repo_id` to `-1` when the caller cannot see the head repository.
4. Public-only tokens see org memberships like anonymous callers, so
concealed members stay hidden.
5. Site admin access in activity feeds, follower lists, org members,
Actions run lists and packages needs a session or an `all`-scoped token.

Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
2026-10-19 00:34:01 +00:00

188 lines
5.8 KiB
Go

// Copyright 2021 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package user
import (
"context"
"fmt"
"strings"
"gitea.dev/models/db"
"gitea.dev/modules/container"
"gitea.dev/modules/optional"
"gitea.dev/modules/structs"
"xorm.io/builder"
)
// AdminUserOrderByMap represents all possible admin user search orders
// This should only be used for admin API endpoints as we should not expose "updated" ordering which could expose recent user activity including logins.
var AdminUserOrderByMap = map[string]map[string]db.SearchOrderBy{
"asc": {
"name": db.SearchOrderByAlphabetically,
"created": db.SearchOrderByOldest,
"updated": db.SearchOrderByLeastUpdated,
"id": db.SearchOrderByID,
},
"desc": {
"name": db.SearchOrderByAlphabeticallyReverse,
"created": db.SearchOrderByNewest,
"updated": db.SearchOrderByRecentUpdated,
"id": db.SearchOrderByIDReverse,
},
}
// SearchUserOptions contains the options for searching
type SearchUserOptions struct {
db.ListOptions
Keyword string
Types []UserType
UID int64
LoginName string // this option should be used only for admin user
SourceID optional.Option[int64] // this option should be used only for admin user, Some(0) means local users
OrderBy db.SearchOrderBy
Visible []structs.VisibleType
Actor *User // The user doing the search
SearchByEmail bool // Search by email as well as username/full name
SupportedSortOrders container.Set[string] // if not nil, only allow to use the sort orders in this set
IsActive optional.Option[bool]
IsAdmin optional.Option[bool]
IsRestricted optional.Option[bool]
IsTwoFactorEnabled optional.Option[bool]
IsProhibitLogin optional.Option[bool]
}
func (opts *SearchUserOptions) ToOrders() string {
return "id"
}
func (opts *SearchUserOptions) toSearchQueryBase(ctx context.Context) db.Session {
var cond builder.Cond
cond = builder.In("type", opts.Types)
if len(opts.Keyword) > 0 {
lowerKeyword := strings.ToLower(opts.Keyword)
keywordCond := builder.Or(
builder.Like{"lower_name", lowerKeyword},
builder.Like{"LOWER(full_name)", lowerKeyword},
)
if opts.SearchByEmail {
var emailCond builder.Cond
emailCond = builder.Like{"LOWER(email)", lowerKeyword}
if opts.Actor == nil {
emailCond = emailCond.And(builder.Eq{"keep_email_private": false})
} else if !opts.Actor.IsAdmin {
emailCond = emailCond.And(
builder.Or(
builder.Eq{"keep_email_private": false},
builder.Eq{"id": opts.Actor.ID},
),
)
}
keywordCond = keywordCond.Or(emailCond)
}
cond = cond.And(keywordCond)
}
// If visibility filtered
if len(opts.Visible) > 0 {
cond = cond.And(builder.In("visibility", opts.Visible))
}
cond = cond.And(BuildCanSeeUserCondition(opts.Actor))
if opts.UID > 0 {
cond = cond.And(builder.Eq{"id": opts.UID})
}
if opts.SourceID.Has() {
cond = cond.And(builder.Eq{"login_source": opts.SourceID.Value()})
}
if opts.LoginName != "" {
cond = cond.And(builder.Eq{"login_name": opts.LoginName})
}
if opts.IsActive.Has() {
cond = cond.And(builder.Eq{"is_active": opts.IsActive.Value()})
}
if opts.IsAdmin.Has() {
cond = cond.And(builder.Eq{"is_admin": opts.IsAdmin.Value()})
}
if opts.IsRestricted.Has() {
cond = cond.And(builder.Eq{"is_restricted": opts.IsRestricted.Value()})
}
if opts.IsProhibitLogin.Has() {
cond = cond.And(builder.Eq{"prohibit_login": opts.IsProhibitLogin.Value()})
}
e := db.GetEngine(ctx)
if !opts.IsTwoFactorEnabled.Has() {
return e.Where(cond)
}
// 2fa filter uses LEFT JOIN to check whether a user has a 2fa record
// While using LEFT JOIN, sometimes the performance might not be good, but it won't be a problem now, such SQL is seldom executed.
// There are some possible methods to refactor this SQL in future when we really need to optimize the performance (but not now):
// (1) add a column in user table (2) add a setting value in user_setting table (3) use search engines (bleve/elasticsearch)
if opts.IsTwoFactorEnabled.Value() {
cond = cond.And(builder.Expr("two_factor.uid IS NOT NULL"))
} else {
cond = cond.And(builder.Expr("two_factor.uid IS NULL"))
}
return e.Join("LEFT OUTER", "two_factor", "two_factor.uid = `user`.id").
Where(cond)
}
// SearchUsers takes options i.e. keyword and part of user name to search,
// it returns results in given range and number of total results.
func SearchUsers(ctx context.Context, opts SearchUserOptions) (users []*User, _ int64, _ error) {
sessCount := opts.toSearchQueryBase(ctx)
defer sessCount.Close()
count, err := sessCount.Count(new(User))
if err != nil {
return nil, 0, fmt.Errorf("count: %w", err)
}
if len(opts.OrderBy) == 0 {
opts.OrderBy = db.SearchOrderByAlphabetically
}
sessQuery := opts.toSearchQueryBase(ctx)
defer sessQuery.Close()
sessQuery.OrderBy(opts.OrderBy.String())
if opts.Page > 0 {
db.SetSessionPagination(sessQuery, &opts)
}
// the sql may contain JOIN, so we must only select User related columns
sessQuery.Select("`user`.*")
users = make([]*User, 0, opts.PageSize)
return users, count, sessQuery.Find(&users)
}
// BuildCanSeeUserCondition creates a condition which can be used to restrict results to users/orgs the actor can see
func BuildCanSeeUserCondition(actor *User) builder.Cond {
canViewPrivate := DoerCanViewPrivate(actor)
cond := builder.NewCond()
if actor != nil && !actor.IsAdmin && (canViewPrivate || actor.IsRestricted) {
cond = builder.In("`user`.id", builder.Select("org_id").From("org_user").Where(builder.Eq{"uid": actor.ID}))
if !actor.IsRestricted {
cond = cond.Or(builder.In("`user`.visibility", structs.VisibleTypePublic, structs.VisibleTypeLimited))
}
cond = cond.Or(builder.Eq{"`user`.id": actor.ID})
}
if !canViewPrivate {
cond = cond.And(builder.In("`user`.visibility", structs.VisibleTypePublic))
}
return cond
}