1
Fork 0

Use db.Find instead of writing methods for every object (#28084)

For those simple objects, it's unnecessary to write the find and count
methods again and again.
This commit is contained in:
Lunny Xiao 2023-11-24 11:49:41 +08:00 committed by GitHub
parent d24a8223ce
commit df1e7d0067
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
88 changed files with 611 additions and 685 deletions

View file

@ -17,6 +17,7 @@ import (
"code.gitea.io/gitea/modules/util"
lru "github.com/hashicorp/golang-lru/v2"
"xorm.io/builder"
)
// ErrAccessTokenNotExist represents a "AccessTokenNotExist" kind of error.
@ -201,25 +202,18 @@ type ListAccessTokensOptions struct {
UserID int64
}
// ListAccessTokens returns a list of access tokens belongs to given user.
func ListAccessTokens(ctx context.Context, opts ListAccessTokensOptions) ([]*AccessToken, error) {
sess := db.GetEngine(ctx).Where("uid=?", opts.UserID)
if len(opts.Name) != 0 {
sess = sess.Where("name=?", opts.Name)
func (opts ListAccessTokensOptions) ToConds() builder.Cond {
cond := builder.NewCond()
// user id is required, otherwise it will return all result which maybe a possible bug
cond = cond.And(builder.Eq{"uid": opts.UserID})
if len(opts.Name) > 0 {
cond = cond.And(builder.Eq{"name": opts.Name})
}
return cond
}
sess = sess.Desc("created_unix")
if opts.Page != 0 {
sess = db.SetSessionPagination(sess, &opts)
tokens := make([]*AccessToken, 0, opts.PageSize)
return tokens, sess.Find(&tokens)
}
tokens := make([]*AccessToken, 0, 5)
return tokens, sess.Find(&tokens)
func (opts ListAccessTokensOptions) ToOrders() string {
return "created_unix DESC"
}
// UpdateAccessToken updates information of access token.
@ -228,15 +222,6 @@ func UpdateAccessToken(ctx context.Context, t *AccessToken) error {
return err
}
// CountAccessTokens count access tokens belongs to given user by options
func CountAccessTokens(ctx context.Context, opts ListAccessTokensOptions) (int64, error) {
sess := db.GetEngine(ctx).Where("uid=?", opts.UserID)
if len(opts.Name) != 0 {
sess = sess.Where("name=?", opts.Name)
}
return sess.Count(&AccessToken{})
}
// DeleteAccessTokenByID deletes access token by given ID.
func DeleteAccessTokenByID(ctx context.Context, id, userID int64) error {
cnt, err := db.GetEngine(ctx).ID(id).Delete(&AccessToken{

View file

@ -85,7 +85,7 @@ func TestGetAccessTokenBySHA(t *testing.T) {
func TestListAccessTokens(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
tokens, err := auth_model.ListAccessTokens(db.DefaultContext, auth_model.ListAccessTokensOptions{UserID: 1})
tokens, err := db.Find[auth_model.AccessToken](db.DefaultContext, auth_model.ListAccessTokensOptions{UserID: 1})
assert.NoError(t, err)
if assert.Len(t, tokens, 2) {
assert.Equal(t, int64(1), tokens[0].UID)
@ -94,14 +94,14 @@ func TestListAccessTokens(t *testing.T) {
assert.Contains(t, []string{tokens[0].Name, tokens[1].Name}, "Token B")
}
tokens, err = auth_model.ListAccessTokens(db.DefaultContext, auth_model.ListAccessTokensOptions{UserID: 2})
tokens, err = db.Find[auth_model.AccessToken](db.DefaultContext, auth_model.ListAccessTokensOptions{UserID: 2})
assert.NoError(t, err)
if assert.Len(t, tokens, 1) {
assert.Equal(t, int64(2), tokens[0].UID)
assert.Equal(t, "Token A", tokens[0].Name)
}
tokens, err = auth_model.ListAccessTokens(db.DefaultContext, auth_model.ListAccessTokensOptions{UserID: 100})
tokens, err = db.Find[auth_model.AccessToken](db.DefaultContext, auth_model.ListAccessTokensOptions{UserID: 100})
assert.NoError(t, err)
assert.Empty(t, tokens)
}

View file

@ -5,6 +5,7 @@ package auth
import (
"context"
"crypto/sha256"
"encoding/base32"
"encoding/base64"
"fmt"
@ -19,7 +20,6 @@ import (
"code.gitea.io/gitea/modules/util"
uuid "github.com/google/uuid"
"github.com/minio/sha256-simd"
"golang.org/x/crypto/bcrypt"
"xorm.io/builder"
"xorm.io/xorm"
@ -243,13 +243,6 @@ func GetOAuth2ApplicationByID(ctx context.Context, id int64) (app *OAuth2Applica
return app, nil
}
// GetOAuth2ApplicationsByUserID returns all oauth2 applications owned by the user
func GetOAuth2ApplicationsByUserID(ctx context.Context, userID int64) (apps []*OAuth2Application, err error) {
apps = make([]*OAuth2Application, 0)
err = db.GetEngine(ctx).Where("uid = ?", userID).Find(&apps)
return apps, err
}
// CreateOAuth2ApplicationOptions holds options to create an oauth2 application
type CreateOAuth2ApplicationOptions struct {
Name string
@ -372,25 +365,6 @@ func DeleteOAuth2Application(ctx context.Context, id, userid int64) error {
return committer.Commit()
}
// ListOAuth2Applications returns a list of oauth2 applications belongs to given user.
func ListOAuth2Applications(ctx context.Context, uid int64, listOptions db.ListOptions) ([]*OAuth2Application, int64, error) {
sess := db.GetEngine(ctx).
Where("uid=?", uid).
Desc("id")
if listOptions.Page != 0 {
sess = db.SetSessionPagination(sess, &listOptions)
apps := make([]*OAuth2Application, 0, listOptions.PageSize)
total, err := sess.FindAndCount(&apps)
return apps, total, err
}
apps := make([]*OAuth2Application, 0, 5)
total, err := sess.FindAndCount(&apps)
return apps, total, err
}
//////////////////////////////////////////////////////
// OAuth2AuthorizationCode is a code to obtain an access token in combination with the client secret once. It has a limited lifetime.

View file

@ -0,0 +1,32 @@
// Copyright 2023 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package auth
import (
"code.gitea.io/gitea/models/db"
"xorm.io/builder"
)
type FindOAuth2ApplicationsOptions struct {
db.ListOptions
// OwnerID is the user id or org id of the owner of the application
OwnerID int64
// find global applications, if true, then OwnerID will be igonred
IsGlobal bool
}
func (opts FindOAuth2ApplicationsOptions) ToConds() builder.Cond {
conds := builder.NewCond()
if opts.IsGlobal {
conds = conds.And(builder.Eq{"uid": 0})
} else if opts.OwnerID != 0 {
conds = conds.And(builder.Eq{"uid": opts.OwnerID})
}
return conds
}
func (opts FindOAuth2ApplicationsOptions) ToOrders() string {
return "id DESC"
}

View file

@ -242,6 +242,7 @@ func CreateSource(ctx context.Context, source *Source) error {
}
type FindSourcesOptions struct {
db.ListOptions
IsActive util.OptionalBool
LoginType Type
}
@ -257,27 +258,22 @@ func (opts FindSourcesOptions) ToConds() builder.Cond {
return conds
}
// FindSources returns a slice of login sources found in DB according to given conditions.
func FindSources(ctx context.Context, opts FindSourcesOptions) ([]*Source, error) {
auths := make([]*Source, 0, 6)
return auths, db.GetEngine(ctx).Where(opts.ToConds()).Find(&auths)
}
// IsSSPIEnabled returns true if there is at least one activated login
// source of type LoginSSPI
func IsSSPIEnabled(ctx context.Context) bool {
if !db.HasEngine {
return false
}
sources, err := FindSources(ctx, FindSourcesOptions{
exist, err := db.Exists[Source](ctx, FindSourcesOptions{
IsActive: util.OptionalBoolTrue,
LoginType: SSPI,
})
if err != nil {
log.Error("ActiveSources: %v", err)
log.Error("Active SSPI Sources: %v", err)
return false
}
return len(sources) > 0
return exist
}
// GetSourceByID returns login source by given ID.
@ -346,12 +342,6 @@ func UpdateSource(ctx context.Context, source *Source) error {
return err
}
// CountSources returns number of login sources.
func CountSources(ctx context.Context, opts FindSourcesOptions) int64 {
count, _ := db.GetEngine(ctx).Where(opts.ToConds()).Count(new(Source))
return count
}
// ErrSourceNotExist represents a "SourceNotExist" kind of error.
type ErrSourceNotExist struct {
ID int64