Add support for searching users by email (#30908)
Some checks are pending
release-nightly / nightly-binary (push) Waiting to run
release-nightly / nightly-docker-rootful (push) Waiting to run
release-nightly / nightly-docker-rootless (push) Waiting to run

Fix #30898

we have an option `SearchByEmail`, so enable it, then we can search user
by email.
Also added a test for it.
This commit is contained in:
yp05327 2024-10-05 02:45:06 +09:00 committed by GitHub
parent 7e68bc8823
commit 5d6d025c9b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 55 additions and 6 deletions

View File

@ -65,7 +65,19 @@ func (opts *SearchUserOptions) toSearchQueryBase(ctx context.Context) *xorm.Sess
builder.Like{"LOWER(full_name)", lowerKeyword},
)
if opts.SearchByEmail {
keywordCond = keywordCond.Or(builder.Like{"LOWER(email)", lowerKeyword})
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)

View File

@ -72,6 +72,7 @@ func Search(ctx *context.APIContext) {
Keyword: ctx.FormTrim("q"),
UID: uid,
Type: user_model.UserTypeIndividual,
SearchByEmail: true,
ListOptions: listOptions,
})
if err != nil {

View File

@ -109,3 +109,39 @@ func TestAPIUserSearchNotLoggedInUserHidden(t *testing.T) {
DecodeJSON(t, resp, &results)
assert.Empty(t, results.Data)
}
func TestAPIUserSearchByEmail(t *testing.T) {
defer tests.PrepareTestEnv(t)()
// admin can search user with private email
adminUsername := "user1"
session := loginUser(t, adminUsername)
token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadUser)
query := "user2@example.com"
req := NewRequestf(t, "GET", "/api/v1/users/search?q=%s", query).
AddTokenAuth(token)
resp := MakeRequest(t, req, http.StatusOK)
var results SearchResults
DecodeJSON(t, resp, &results)
assert.Equal(t, 1, len(results.Data))
assert.Equal(t, query, results.Data[0].Email)
// no login user can not search user with private email
req = NewRequestf(t, "GET", "/api/v1/users/search?q=%s", query)
resp = MakeRequest(t, req, http.StatusOK)
DecodeJSON(t, resp, &results)
assert.Empty(t, results.Data)
// user can search self with private email
user2 := "user2"
session = loginUser(t, user2)
token = getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadUser)
req = NewRequestf(t, "GET", "/api/v1/users/search?q=%s", query).
AddTokenAuth(token)
resp = MakeRequest(t, req, http.StatusOK)
DecodeJSON(t, resp, &results)
assert.Equal(t, 1, len(results.Data))
assert.Equal(t, query, results.Data[0].Email)
}