code.gitea.io/gitea@v1.22.3/models/user/search.go (about)

     1  // Copyright 2021 The Gitea Authors. All rights reserved.
     2  // SPDX-License-Identifier: MIT
     3  
     4  package user
     5  
     6  import (
     7  	"context"
     8  	"fmt"
     9  	"strings"
    10  
    11  	"code.gitea.io/gitea/models/db"
    12  	"code.gitea.io/gitea/modules/container"
    13  	"code.gitea.io/gitea/modules/optional"
    14  	"code.gitea.io/gitea/modules/structs"
    15  
    16  	"xorm.io/builder"
    17  	"xorm.io/xorm"
    18  )
    19  
    20  // SearchUserOptions contains the options for searching
    21  type SearchUserOptions struct {
    22  	db.ListOptions
    23  
    24  	Keyword       string
    25  	Type          UserType
    26  	UID           int64
    27  	LoginName     string // this option should be used only for admin user
    28  	SourceID      int64  // this option should be used only for admin user
    29  	OrderBy       db.SearchOrderBy
    30  	Visible       []structs.VisibleType
    31  	Actor         *User // The user doing the search
    32  	SearchByEmail bool  // Search by email as well as username/full name
    33  
    34  	SupportedSortOrders container.Set[string] // if not nil, only allow to use the sort orders in this set
    35  
    36  	IsActive           optional.Option[bool]
    37  	IsAdmin            optional.Option[bool]
    38  	IsRestricted       optional.Option[bool]
    39  	IsTwoFactorEnabled optional.Option[bool]
    40  	IsProhibitLogin    optional.Option[bool]
    41  	IncludeReserved    bool
    42  
    43  	ExtraParamStrings map[string]string
    44  }
    45  
    46  func (opts *SearchUserOptions) toSearchQueryBase(ctx context.Context) *xorm.Session {
    47  	var cond builder.Cond
    48  	cond = builder.Eq{"type": opts.Type}
    49  	if opts.IncludeReserved {
    50  		if opts.Type == UserTypeIndividual {
    51  			cond = cond.Or(builder.Eq{"type": UserTypeUserReserved}).Or(
    52  				builder.Eq{"type": UserTypeBot},
    53  			).Or(
    54  				builder.Eq{"type": UserTypeRemoteUser},
    55  			)
    56  		} else if opts.Type == UserTypeOrganization {
    57  			cond = cond.Or(builder.Eq{"type": UserTypeOrganizationReserved})
    58  		}
    59  	}
    60  
    61  	if len(opts.Keyword) > 0 {
    62  		lowerKeyword := strings.ToLower(opts.Keyword)
    63  		keywordCond := builder.Or(
    64  			builder.Like{"lower_name", lowerKeyword},
    65  			builder.Like{"LOWER(full_name)", lowerKeyword},
    66  		)
    67  		if opts.SearchByEmail {
    68  			keywordCond = keywordCond.Or(builder.Like{"LOWER(email)", lowerKeyword})
    69  		}
    70  
    71  		cond = cond.And(keywordCond)
    72  	}
    73  
    74  	// If visibility filtered
    75  	if len(opts.Visible) > 0 {
    76  		cond = cond.And(builder.In("visibility", opts.Visible))
    77  	}
    78  
    79  	cond = cond.And(BuildCanSeeUserCondition(opts.Actor))
    80  
    81  	if opts.UID > 0 {
    82  		cond = cond.And(builder.Eq{"id": opts.UID})
    83  	}
    84  
    85  	if opts.SourceID > 0 {
    86  		cond = cond.And(builder.Eq{"login_source": opts.SourceID})
    87  	}
    88  	if opts.LoginName != "" {
    89  		cond = cond.And(builder.Eq{"login_name": opts.LoginName})
    90  	}
    91  
    92  	if opts.IsActive.Has() {
    93  		cond = cond.And(builder.Eq{"is_active": opts.IsActive.Value()})
    94  	}
    95  
    96  	if opts.IsAdmin.Has() {
    97  		cond = cond.And(builder.Eq{"is_admin": opts.IsAdmin.Value()})
    98  	}
    99  
   100  	if opts.IsRestricted.Has() {
   101  		cond = cond.And(builder.Eq{"is_restricted": opts.IsRestricted.Value()})
   102  	}
   103  
   104  	if opts.IsProhibitLogin.Has() {
   105  		cond = cond.And(builder.Eq{"prohibit_login": opts.IsProhibitLogin.Value()})
   106  	}
   107  
   108  	e := db.GetEngine(ctx)
   109  	if !opts.IsTwoFactorEnabled.Has() {
   110  		return e.Where(cond)
   111  	}
   112  
   113  	// 2fa filter uses LEFT JOIN to check whether a user has a 2fa record
   114  	// While using LEFT JOIN, sometimes the performance might not be good, but it won't be a problem now, such SQL is seldom executed.
   115  	// There are some possible methods to refactor this SQL in future when we really need to optimize the performance (but not now):
   116  	// (1) add a column in user table (2) add a setting value in user_setting table (3) use search engines (bleve/elasticsearch)
   117  	if opts.IsTwoFactorEnabled.Value() {
   118  		cond = cond.And(builder.Expr("two_factor.uid IS NOT NULL"))
   119  	} else {
   120  		cond = cond.And(builder.Expr("two_factor.uid IS NULL"))
   121  	}
   122  
   123  	return e.Join("LEFT OUTER", "two_factor", "two_factor.uid = `user`.id").
   124  		Where(cond)
   125  }
   126  
   127  // SearchUsers takes options i.e. keyword and part of user name to search,
   128  // it returns results in given range and number of total results.
   129  func SearchUsers(ctx context.Context, opts *SearchUserOptions) (users []*User, _ int64, _ error) {
   130  	sessCount := opts.toSearchQueryBase(ctx)
   131  	defer sessCount.Close()
   132  	count, err := sessCount.Count(new(User))
   133  	if err != nil {
   134  		return nil, 0, fmt.Errorf("count: %w", err)
   135  	}
   136  
   137  	if len(opts.OrderBy) == 0 {
   138  		opts.OrderBy = db.SearchOrderByAlphabetically
   139  	}
   140  
   141  	sessQuery := opts.toSearchQueryBase(ctx).OrderBy(opts.OrderBy.String())
   142  	defer sessQuery.Close()
   143  	if opts.Page != 0 {
   144  		sessQuery = db.SetSessionPagination(sessQuery, opts)
   145  	}
   146  
   147  	// the sql may contain JOIN, so we must only select User related columns
   148  	sessQuery = sessQuery.Select("`user`.*")
   149  	users = make([]*User, 0, opts.PageSize)
   150  	return users, count, sessQuery.Find(&users)
   151  }
   152  
   153  // BuildCanSeeUserCondition creates a condition which can be used to restrict results to users/orgs the actor can see
   154  func BuildCanSeeUserCondition(actor *User) builder.Cond {
   155  	if actor != nil {
   156  		// If Admin - they see all users!
   157  		if !actor.IsAdmin {
   158  			// Users can see an organization they are a member of
   159  			cond := builder.In("`user`.id", builder.Select("org_id").From("org_user").Where(builder.Eq{"uid": actor.ID}))
   160  			if !actor.IsRestricted {
   161  				// Not-Restricted users can see public and limited users/organizations
   162  				cond = cond.Or(builder.In("`user`.visibility", structs.VisibleTypePublic, structs.VisibleTypeLimited))
   163  			}
   164  			// Don't forget about self
   165  			return cond.Or(builder.Eq{"`user`.id": actor.ID})
   166  		}
   167  
   168  		return nil
   169  	}
   170  
   171  	// Force visibility for privacy
   172  	// Not logged in - only public users
   173  	return builder.In("`user`.visibility", structs.VisibleTypePublic)
   174  }