diff options
Diffstat (limited to 'models')
65 files changed, 500 insertions, 478 deletions
diff --git a/models/access.go b/models/access.go index 88fbe8189f..560234aae8 100644 --- a/models/access.go +++ b/models/access.go @@ -225,7 +225,7 @@ func (repo *Repository) refreshAccesses(e db.Engine, accessMap map[int64]*userAc // refreshCollaboratorAccesses retrieves repository collaborations with their access modes. func (repo *Repository) refreshCollaboratorAccesses(e db.Engine, accessMap map[int64]*userAccess) error { - collaborators, err := repo.getCollaborators(e, ListOptions{}) + collaborators, err := repo.getCollaborators(e, db.ListOptions{}) if err != nil { return fmt.Errorf("getCollaborations: %v", err) } diff --git a/models/commit_status.go b/models/commit_status.go index ada94667cc..a6ded049c3 100644 --- a/models/commit_status.go +++ b/models/commit_status.go @@ -163,7 +163,7 @@ func CalcCommitStatus(statuses []*CommitStatus) *CommitStatus { // CommitStatusOptions holds the options for query commit statuses type CommitStatusOptions struct { - ListOptions + db.ListOptions State string SortType string } @@ -178,7 +178,7 @@ func GetCommitStatuses(repo *Repository, sha string, opts *CommitStatusOptions) } countSession := listCommitStatusesStatement(repo, sha, opts) - countSession = setSessionPagination(countSession, opts) + countSession = db.SetSessionPagination(countSession, opts) maxResults, err := countSession.Count(new(CommitStatus)) if err != nil { log.Error("Count PRs: %v", err) @@ -187,7 +187,7 @@ func GetCommitStatuses(repo *Repository, sha string, opts *CommitStatusOptions) statuses := make([]*CommitStatus, 0, opts.PageSize) findSession := listCommitStatusesStatement(repo, sha, opts) - findSession = setSessionPagination(findSession, opts) + findSession = db.SetSessionPagination(findSession, opts) sortCommitStatusesSession(findSession, opts.SortType) return statuses, maxResults, findSession.Find(&statuses) } @@ -227,18 +227,18 @@ type CommitStatusIndex struct { } // GetLatestCommitStatus returns all statuses with a unique context for a given commit. -func GetLatestCommitStatus(repoID int64, sha string, listOptions ListOptions) ([]*CommitStatus, error) { +func GetLatestCommitStatus(repoID int64, sha string, listOptions db.ListOptions) ([]*CommitStatus, error) { return getLatestCommitStatus(db.GetEngine(db.DefaultContext), repoID, sha, listOptions) } -func getLatestCommitStatus(e db.Engine, repoID int64, sha string, listOptions ListOptions) ([]*CommitStatus, error) { +func getLatestCommitStatus(e db.Engine, repoID int64, sha string, listOptions db.ListOptions) ([]*CommitStatus, error) { ids := make([]int64, 0, 10) sess := e.Table(&CommitStatus{}). Where("repo_id = ?", repoID).And("sha = ?", sha). Select("max( id ) as id"). GroupBy("context_hash").OrderBy("max( id ) desc") - sess = setSessionPagination(sess, &listOptions) + sess = db.SetSessionPagination(sess, &listOptions) err := sess.Find(&ids) if err != nil { @@ -336,7 +336,7 @@ func ParseCommitsWithStatus(oldCommits []*SignCommit, repo *Repository) []*SignC commit := &SignCommitWithStatuses{ SignCommit: c, } - statuses, err := GetLatestCommitStatus(repo.ID, commit.ID.String(), ListOptions{}) + statuses, err := GetLatestCommitStatus(repo.ID, commit.ID.String(), db.ListOptions{}) if err != nil { log.Error("GetLatestCommitStatus: %v", err) } else { diff --git a/models/commit_status_test.go b/models/commit_status_test.go index 0d8dbf2646..7f4709144c 100644 --- a/models/commit_status_test.go +++ b/models/commit_status_test.go @@ -19,7 +19,7 @@ func TestGetCommitStatuses(t *testing.T) { sha1 := "1234123412341234123412341234123412341234" - statuses, maxResults, err := GetCommitStatuses(repo1, sha1, &CommitStatusOptions{ListOptions: ListOptions{Page: 1, PageSize: 50}}) + statuses, maxResults, err := GetCommitStatuses(repo1, sha1, &CommitStatusOptions{ListOptions: db.ListOptions{Page: 1, PageSize: 50}}) assert.NoError(t, err) assert.Equal(t, int(maxResults), 5) assert.Len(t, statuses, 5) diff --git a/models/list_options.go b/models/db/list_options.go index 25b9a05f16..f31febfe25 100644 --- a/models/list_options.go +++ b/models/db/list_options.go @@ -2,10 +2,9 @@ // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. -package models +package db import ( - "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/modules/setting" "xorm.io/xorm" @@ -17,22 +16,22 @@ type Paginator interface { GetStartEnd() (start, end int) } -// getPaginatedSession creates a paginated database session -func getPaginatedSession(p Paginator) *xorm.Session { +// GetPaginatedSession creates a paginated database session +func GetPaginatedSession(p Paginator) *xorm.Session { skip, take := p.GetSkipTake() - return db.GetEngine(db.DefaultContext).Limit(take, skip) + return x.Limit(take, skip) } -// setSessionPagination sets pagination for a database session -func setSessionPagination(sess *xorm.Session, p Paginator) *xorm.Session { +// SetSessionPagination sets pagination for a database session +func SetSessionPagination(sess *xorm.Session, p Paginator) *xorm.Session { skip, take := p.GetSkipTake() return sess.Limit(take, skip) } -// setSessionPagination sets pagination for a database engine -func setEnginePagination(e db.Engine, p Paginator) db.Engine { +// SetEnginePagination sets pagination for a database engine +func SetEnginePagination(e Engine, p Paginator) Engine { skip, take := p.GetSkipTake() return e.Limit(take, skip) @@ -46,7 +45,7 @@ type ListOptions struct { // GetSkipTake returns the skip and take values func (opts *ListOptions) GetSkipTake() (skip, take int) { - opts.setDefaultValues() + opts.SetDefaultValues() return (opts.Page - 1) * opts.PageSize, opts.PageSize } @@ -57,7 +56,8 @@ func (opts *ListOptions) GetStartEnd() (start, end int) { return } -func (opts *ListOptions) setDefaultValues() { +// SetDefaultValues sets default values +func (opts *ListOptions) SetDefaultValues() { if opts.PageSize <= 0 { opts.PageSize = setting.API.DefaultPagingNum } diff --git a/models/list_options_test.go b/models/db/list_options_test.go index 3145aa7c16..2c860afdfb 100644 --- a/models/list_options_test.go +++ b/models/db/list_options_test.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. -package models +package db import ( "testing" diff --git a/models/db/test_fixtures.go b/models/db/test_fixtures.go index 1727015133..2715b688ea 100644 --- a/models/db/test_fixtures.go +++ b/models/db/test_fixtures.go @@ -17,13 +17,18 @@ import ( var fixtures *testfixtures.Loader // InitFixtures initialize test fixtures for a test database -func InitFixtures(dir string, engine ...*xorm.Engine) (err error) { +func InitFixtures(opts FixturesOptions, engine ...*xorm.Engine) (err error) { e := x if len(engine) == 1 { e = engine[0] } - testfiles := testfixtures.Directory(dir) + var testfiles func(*testfixtures.Loader) error + if opts.Dir != "" { + testfiles = testfixtures.Directory(opts.Dir) + } else { + testfiles = testfixtures.Files(opts.Files...) + } dialect := "unknown" switch e.Dialect().URI().DBType { case schemas.POSTGRES: diff --git a/models/db/unit_tests.go b/models/db/unit_tests.go index 781f0ecca2..d81610df6b 100644 --- a/models/db/unit_tests.go +++ b/models/db/unit_tests.go @@ -44,11 +44,21 @@ func fatalTestError(fmtStr string, args ...interface{}) { // MainTest a reusable TestMain(..) function for unit tests that need to use a // test database. Creates the test database, and sets necessary settings. -func MainTest(m *testing.M, pathToGiteaRoot string) { +func MainTest(m *testing.M, pathToGiteaRoot string, fixtureFiles ...string) { var err error giteaRoot = pathToGiteaRoot fixturesDir = filepath.Join(pathToGiteaRoot, "models", "fixtures") - if err = CreateTestEngine(fixturesDir); err != nil { + + var opts FixturesOptions + if len(fixtureFiles) == 0 { + opts.Dir = fixturesDir + } else { + for _, f := range fixtureFiles { + opts.Files = append(opts.Files, filepath.Join(fixturesDir, f)) + } + } + + if err = CreateTestEngine(opts); err != nil { fatalTestError("Error creating test engine: %v\n", err) } @@ -102,8 +112,14 @@ func MainTest(m *testing.M, pathToGiteaRoot string) { os.Exit(exitStatus) } +// FixturesOptions fixtures needs to be loaded options +type FixturesOptions struct { + Dir string + Files []string +} + // CreateTestEngine creates a memory database and loads the fixture data from fixturesDir -func CreateTestEngine(fixturesDir string) error { +func CreateTestEngine(opts FixturesOptions) error { var err error x, err = xorm.NewEngine("sqlite3", "file::memory:?cache=shared&_txlock=immediate") if err != nil { @@ -123,7 +139,7 @@ func CreateTestEngine(fixturesDir string) error { e: x, } - return InitFixtures(fixturesDir) + return InitFixtures(opts) } // PrepareTestDatabase load test fixtures into test database diff --git a/models/error.go b/models/error.go index fd8f2771ae..956b240097 100644 --- a/models/error.go +++ b/models/error.go @@ -1836,58 +1836,6 @@ func (err ErrAttachmentNotExist) Error() string { return fmt.Sprintf("attachment does not exist [id: %d, uuid: %s]", err.ID, err.UUID) } -// .____ .__ _________ -// | | ____ ____ |__| ____ / _____/ ____ __ _________ ____ ____ -// | | / _ \ / ___\| |/ \ \_____ \ / _ \| | \_ __ \_/ ___\/ __ \ -// | |__( <_> ) /_/ > | | \ / ( <_> ) | /| | \/\ \__\ ___/ -// |_______ \____/\___ /|__|___| / /_______ /\____/|____/ |__| \___ >___ > -// \/ /_____/ \/ \/ \/ \/ - -// ErrLoginSourceNotExist represents a "LoginSourceNotExist" kind of error. -type ErrLoginSourceNotExist struct { - ID int64 -} - -// IsErrLoginSourceNotExist checks if an error is a ErrLoginSourceNotExist. -func IsErrLoginSourceNotExist(err error) bool { - _, ok := err.(ErrLoginSourceNotExist) - return ok -} - -func (err ErrLoginSourceNotExist) Error() string { - return fmt.Sprintf("login source does not exist [id: %d]", err.ID) -} - -// ErrLoginSourceAlreadyExist represents a "LoginSourceAlreadyExist" kind of error. -type ErrLoginSourceAlreadyExist struct { - Name string -} - -// IsErrLoginSourceAlreadyExist checks if an error is a ErrLoginSourceAlreadyExist. -func IsErrLoginSourceAlreadyExist(err error) bool { - _, ok := err.(ErrLoginSourceAlreadyExist) - return ok -} - -func (err ErrLoginSourceAlreadyExist) Error() string { - return fmt.Sprintf("login source already exists [name: %s]", err.Name) -} - -// ErrLoginSourceInUse represents a "LoginSourceInUse" kind of error. -type ErrLoginSourceInUse struct { - ID int64 -} - -// IsErrLoginSourceInUse checks if an error is a ErrLoginSourceInUse. -func IsErrLoginSourceInUse(err error) bool { - _, ok := err.(ErrLoginSourceInUse) - return ok -} - -func (err ErrLoginSourceInUse) Error() string { - return fmt.Sprintf("login source is still used by some users [id: %d]", err.ID) -} - // ___________ // \__ ___/___ _____ _____ // | |_/ __ \\__ \ / \ @@ -2159,42 +2107,3 @@ func (err ErrNotValidReviewRequest) Error() string { err.UserID, err.RepoID) } - -// ________ _____ __ .__ -// \_____ \ / _ \ __ ___/ |_| |__ -// / | \ / /_\ \| | \ __\ | \ -// / | \/ | \ | /| | | Y \ -// \_______ /\____|__ /____/ |__| |___| / -// \/ \/ \/ - -// ErrOAuthClientIDInvalid will be thrown if client id cannot be found -type ErrOAuthClientIDInvalid struct { - ClientID string -} - -// IsErrOauthClientIDInvalid checks if an error is a ErrReviewNotExist. -func IsErrOauthClientIDInvalid(err error) bool { - _, ok := err.(ErrOAuthClientIDInvalid) - return ok -} - -// Error returns the error message -func (err ErrOAuthClientIDInvalid) Error() string { - return fmt.Sprintf("Client ID invalid [Client ID: %s]", err.ClientID) -} - -// ErrOAuthApplicationNotFound will be thrown if id cannot be found -type ErrOAuthApplicationNotFound struct { - ID int64 -} - -// IsErrOAuthApplicationNotFound checks if an error is a ErrReviewNotExist. -func IsErrOAuthApplicationNotFound(err error) bool { - _, ok := err.(ErrOAuthApplicationNotFound) - return ok -} - -// Error returns the error message -func (err ErrOAuthApplicationNotFound) Error() string { - return fmt.Sprintf("OAuth application not found [ID: %d]", err.ID) -} diff --git a/models/external_login_user.go b/models/external_login_user.go index c6a4b71b53..6b023a4cb2 100644 --- a/models/external_login_user.go +++ b/models/external_login_user.go @@ -8,6 +8,7 @@ import ( "time" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/login" "code.gitea.io/gitea/modules/structs" "github.com/markbates/goth" @@ -106,7 +107,7 @@ func GetUserIDByExternalUserID(provider, userID string) (int64, error) { // UpdateExternalUser updates external user's information func UpdateExternalUser(user *User, gothUser goth.User) error { - loginSource, err := GetActiveOAuth2LoginSourceByName(gothUser.Provider) + loginSource, err := login.GetActiveOAuth2LoginSourceByName(gothUser.Provider) if err != nil { return err } diff --git a/models/gpg_key.go b/models/gpg_key.go index d8dd79c285..a62ed61966 100644 --- a/models/gpg_key.go +++ b/models/gpg_key.go @@ -62,14 +62,14 @@ func (key *GPGKey) AfterLoad(session *xorm.Session) { } // ListGPGKeys returns a list of public keys belongs to given user. -func ListGPGKeys(uid int64, listOptions ListOptions) ([]*GPGKey, error) { +func ListGPGKeys(uid int64, listOptions db.ListOptions) ([]*GPGKey, error) { return listGPGKeys(db.GetEngine(db.DefaultContext), uid, listOptions) } -func listGPGKeys(e db.Engine, uid int64, listOptions ListOptions) ([]*GPGKey, error) { +func listGPGKeys(e db.Engine, uid int64, listOptions db.ListOptions) ([]*GPGKey, error) { sess := e.Table(&GPGKey{}).Where("owner_id=? AND primary_key_id=''", uid) if listOptions.Page != 0 { - sess = setSessionPagination(sess, &listOptions) + sess = db.SetSessionPagination(sess, &listOptions) } keys := make([]*GPGKey, 0, 2) diff --git a/models/gpg_key_commit_verification.go b/models/gpg_key_commit_verification.go index a4c7d70285..f508303a09 100644 --- a/models/gpg_key_commit_verification.go +++ b/models/gpg_key_commit_verification.go @@ -9,6 +9,7 @@ import ( "hash" "strings" + "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" @@ -156,7 +157,7 @@ func ParseCommitWithSignature(c *git.Commit) *CommitVerification { // Now try to associate the signature with the committer, if present if committer.ID != 0 { - keys, err := ListGPGKeys(committer.ID, ListOptions{}) + keys, err := ListGPGKeys(committer.ID, db.ListOptions{}) if err != nil { // Skipping failed to get gpg keys of user log.Error("ListGPGKeys: %v", err) return &CommitVerification{ diff --git a/models/issue.go b/models/issue.go index cafd996ac5..b8c7053b2d 100644 --- a/models/issue.go +++ b/models/issue.go @@ -1122,7 +1122,7 @@ func GetIssuesByIDs(issueIDs []int64) ([]*Issue, error) { // IssuesOptions represents options of an issue. type IssuesOptions struct { - ListOptions + db.ListOptions RepoIDs []int64 // include all repos if empty AssigneeID int64 PosterID int64 diff --git a/models/issue_comment.go b/models/issue_comment.go index d8f8e36df2..01e41814a4 100644 --- a/models/issue_comment.go +++ b/models/issue_comment.go @@ -964,7 +964,7 @@ func getCommentByID(e db.Engine, id int64) (*Comment, error) { // FindCommentsOptions describes the conditions to Find comments type FindCommentsOptions struct { - ListOptions + db.ListOptions RepoID int64 IssueID int64 ReviewID int64 @@ -1012,7 +1012,7 @@ func findComments(e db.Engine, opts *FindCommentsOptions) ([]*Comment, error) { } if opts.Page != 0 { - sess = setSessionPagination(sess, opts) + sess = db.SetSessionPagination(sess, opts) } // WARNING: If you change this order you will need to fix createCodeComment diff --git a/models/issue_label.go b/models/issue_label.go index 87d7eb9221..293b7140f7 100644 --- a/models/issue_label.go +++ b/models/issue_label.go @@ -447,7 +447,7 @@ func GetLabelsInRepoByIDs(repoID int64, labelIDs []int64) ([]*Label, error) { Find(&labels) } -func getLabelsByRepoID(e db.Engine, repoID int64, sortType string, listOptions ListOptions) ([]*Label, error) { +func getLabelsByRepoID(e db.Engine, repoID int64, sortType string, listOptions db.ListOptions) ([]*Label, error) { if repoID <= 0 { return nil, ErrRepoLabelNotExist{0, repoID} } @@ -466,14 +466,14 @@ func getLabelsByRepoID(e db.Engine, repoID int64, sortType string, listOptions L } if listOptions.Page != 0 { - sess = setSessionPagination(sess, &listOptions) + sess = db.SetSessionPagination(sess, &listOptions) } return labels, sess.Find(&labels) } // GetLabelsByRepoID returns all labels that belong to given repository by ID. -func GetLabelsByRepoID(repoID int64, sortType string, listOptions ListOptions) ([]*Label, error) { +func GetLabelsByRepoID(repoID int64, sortType string, listOptions db.ListOptions) ([]*Label, error) { return getLabelsByRepoID(db.GetEngine(db.DefaultContext), repoID, sortType, listOptions) } @@ -564,7 +564,7 @@ func GetLabelsInOrgByIDs(orgID int64, labelIDs []int64) ([]*Label, error) { Find(&labels) } -func getLabelsByOrgID(e db.Engine, orgID int64, sortType string, listOptions ListOptions) ([]*Label, error) { +func getLabelsByOrgID(e db.Engine, orgID int64, sortType string, listOptions db.ListOptions) ([]*Label, error) { if orgID <= 0 { return nil, ErrOrgLabelNotExist{0, orgID} } @@ -583,14 +583,14 @@ func getLabelsByOrgID(e db.Engine, orgID int64, sortType string, listOptions Lis } if listOptions.Page != 0 { - sess = setSessionPagination(sess, &listOptions) + sess = db.SetSessionPagination(sess, &listOptions) } return labels, sess.Find(&labels) } // GetLabelsByOrgID returns all labels that belong to given organization by ID. -func GetLabelsByOrgID(orgID int64, sortType string, listOptions ListOptions) ([]*Label, error) { +func GetLabelsByOrgID(orgID int64, sortType string, listOptions db.ListOptions) ([]*Label, error) { return getLabelsByOrgID(db.GetEngine(db.DefaultContext), orgID, sortType, listOptions) } diff --git a/models/issue_label_test.go b/models/issue_label_test.go index 384965b846..93807a326f 100644 --- a/models/issue_label_test.go +++ b/models/issue_label_test.go @@ -123,7 +123,7 @@ func TestGetLabelsInRepoByIDs(t *testing.T) { func TestGetLabelsByRepoID(t *testing.T) { assert.NoError(t, db.PrepareTestDatabase()) testSuccess := func(repoID int64, sortType string, expectedIssueIDs []int64) { - labels, err := GetLabelsByRepoID(repoID, sortType, ListOptions{}) + labels, err := GetLabelsByRepoID(repoID, sortType, db.ListOptions{}) assert.NoError(t, err) assert.Len(t, labels, len(expectedIssueIDs)) for i, label := range labels { @@ -214,7 +214,7 @@ func TestGetLabelsInOrgByIDs(t *testing.T) { func TestGetLabelsByOrgID(t *testing.T) { assert.NoError(t, db.PrepareTestDatabase()) testSuccess := func(orgID int64, sortType string, expectedIssueIDs []int64) { - labels, err := GetLabelsByOrgID(orgID, sortType, ListOptions{}) + labels, err := GetLabelsByOrgID(orgID, sortType, db.ListOptions{}) assert.NoError(t, err) assert.Len(t, labels, len(expectedIssueIDs)) for i, label := range labels { @@ -227,10 +227,10 @@ func TestGetLabelsByOrgID(t *testing.T) { testSuccess(3, "default", []int64{3, 4}) var err error - _, err = GetLabelsByOrgID(0, "leastissues", ListOptions{}) + _, err = GetLabelsByOrgID(0, "leastissues", db.ListOptions{}) assert.True(t, IsErrOrgLabelNotExist(err)) - _, err = GetLabelsByOrgID(-1, "leastissues", ListOptions{}) + _, err = GetLabelsByOrgID(-1, "leastissues", db.ListOptions{}) assert.True(t, IsErrOrgLabelNotExist(err)) } diff --git a/models/issue_milestone.go b/models/issue_milestone.go index fb6ced5b41..3898e5b397 100644 --- a/models/issue_milestone.go +++ b/models/issue_milestone.go @@ -378,7 +378,7 @@ func (milestones MilestoneList) getMilestoneIDs() []int64 { // GetMilestonesOption contain options to get milestones type GetMilestonesOption struct { - ListOptions + db.ListOptions RepoID int64 State api.StateType Name string @@ -413,7 +413,7 @@ func GetMilestones(opts GetMilestonesOption) (MilestoneList, int64, error) { sess := db.GetEngine(db.DefaultContext).Where(opts.toCond()) if opts.Page != 0 { - sess = setSessionPagination(sess, &opts) + sess = db.SetSessionPagination(sess, &opts) } switch opts.SortType { diff --git a/models/issue_milestone_test.go b/models/issue_milestone_test.go index 519b65715d..099fe47c7c 100644 --- a/models/issue_milestone_test.go +++ b/models/issue_milestone_test.go @@ -102,7 +102,7 @@ func TestGetMilestones(t *testing.T) { test := func(sortType string, sortCond func(*Milestone) int) { for _, page := range []int{0, 1} { milestones, _, err := GetMilestones(GetMilestonesOption{ - ListOptions: ListOptions{ + ListOptions: db.ListOptions{ Page: page, PageSize: setting.UI.IssuePagingNum, }, @@ -119,7 +119,7 @@ func TestGetMilestones(t *testing.T) { assert.True(t, sort.IntsAreSorted(values)) milestones, _, err = GetMilestones(GetMilestonesOption{ - ListOptions: ListOptions{ + ListOptions: db.ListOptions{ Page: page, PageSize: setting.UI.IssuePagingNum, }, diff --git a/models/issue_reaction.go b/models/issue_reaction.go index 4e49add5c2..423eb8b96c 100644 --- a/models/issue_reaction.go +++ b/models/issue_reaction.go @@ -35,7 +35,7 @@ func init() { // FindReactionsOptions describes the conditions to Find reactions type FindReactionsOptions struct { - ListOptions + db.ListOptions IssueID int64 CommentID int64 UserID int64 @@ -78,7 +78,7 @@ func FindCommentReactions(comment *Comment) (ReactionList, error) { } // FindIssueReactions returns a ReactionList of all reactions from an issue -func FindIssueReactions(issue *Issue, listOptions ListOptions) (ReactionList, error) { +func FindIssueReactions(issue *Issue, listOptions db.ListOptions) (ReactionList, error) { return findReactions(db.GetEngine(db.DefaultContext), FindReactionsOptions{ ListOptions: listOptions, IssueID: issue.ID, @@ -92,7 +92,7 @@ func findReactions(e db.Engine, opts FindReactionsOptions) ([]*Reaction, error) In("reaction.`type`", setting.UI.Reactions). Asc("reaction.issue_id", "reaction.comment_id", "reaction.created_unix", "reaction.id") if opts.Page != 0 { - e = setEnginePagination(e, &opts) + e = db.SetEnginePagination(e, &opts) reactions := make([]*Reaction, 0, opts.PageSize) return reactions, e.Find(&reactions) diff --git a/models/issue_stopwatch.go b/models/issue_stopwatch.go index 157658e182..e8f19dd738 100644 --- a/models/issue_stopwatch.go +++ b/models/issue_stopwatch.go @@ -46,11 +46,11 @@ func getStopwatch(e db.Engine, userID, issueID int64) (sw *Stopwatch, exists boo } // GetUserStopwatches return list of all stopwatches of a user -func GetUserStopwatches(userID int64, listOptions ListOptions) ([]*Stopwatch, error) { +func GetUserStopwatches(userID int64, listOptions db.ListOptions) ([]*Stopwatch, error) { sws := make([]*Stopwatch, 0, 8) sess := db.GetEngine(db.DefaultContext).Where("stopwatch.user_id = ?", userID) if listOptions.Page != 0 { - sess = setSessionPagination(sess, &listOptions) + sess = db.SetSessionPagination(sess, &listOptions) } err := sess.Find(&sws) diff --git a/models/issue_test.go b/models/issue_test.go index d5f6f36e9c..d726a24344 100644 --- a/models/issue_test.go +++ b/models/issue_test.go @@ -151,7 +151,7 @@ func TestIssues(t *testing.T) { IssuesOptions{ RepoIDs: []int64{1, 3}, SortType: "oldest", - ListOptions: ListOptions{ + ListOptions: db.ListOptions{ Page: 1, PageSize: 4, }, @@ -161,7 +161,7 @@ func TestIssues(t *testing.T) { { IssuesOptions{ LabelIDs: []int64{1}, - ListOptions: ListOptions{ + ListOptions: db.ListOptions{ Page: 1, PageSize: 4, }, @@ -171,7 +171,7 @@ func TestIssues(t *testing.T) { { IssuesOptions{ LabelIDs: []int64{1, 2}, - ListOptions: ListOptions{ + ListOptions: db.ListOptions{ Page: 1, PageSize: 4, }, diff --git a/models/issue_tracked_time.go b/models/issue_tracked_time.go index d024c6896f..79de891019 100644 --- a/models/issue_tracked_time.go +++ b/models/issue_tracked_time.go @@ -75,7 +75,7 @@ func (tl TrackedTimeList) LoadAttributes() (err error) { // FindTrackedTimesOptions represent the filters for tracked times. If an ID is 0 it will be ignored. type FindTrackedTimesOptions struct { - ListOptions + db.ListOptions IssueID int64 UserID int64 RepositoryID int64 @@ -118,7 +118,7 @@ func (opts *FindTrackedTimesOptions) toSession(e db.Engine) db.Engine { sess = sess.Where(opts.toCond()) if opts.Page != 0 { - sess = setEnginePagination(sess, opts) + sess = db.SetEnginePagination(sess, opts) } return sess diff --git a/models/issue_watch.go b/models/issue_watch.go index cc1edcba1b..5bac406ad0 100644 --- a/models/issue_watch.go +++ b/models/issue_watch.go @@ -103,11 +103,11 @@ func getIssueWatchersIDs(e db.Engine, issueID int64, watching bool) ([]int64, er } // GetIssueWatchers returns watchers/unwatchers of a given issue -func GetIssueWatchers(issueID int64, listOptions ListOptions) (IssueWatchList, error) { +func GetIssueWatchers(issueID int64, listOptions db.ListOptions) (IssueWatchList, error) { return getIssueWatchers(db.GetEngine(db.DefaultContext), issueID, listOptions) } -func getIssueWatchers(e db.Engine, issueID int64, listOptions ListOptions) (IssueWatchList, error) { +func getIssueWatchers(e db.Engine, issueID int64, listOptions db.ListOptions) (IssueWatchList, error) { sess := e. Where("`issue_watch`.issue_id = ?", issueID). And("`issue_watch`.is_watching = ?", true). @@ -116,7 +116,7 @@ func getIssueWatchers(e db.Engine, issueID int64, listOptions ListOptions) (Issu Join("INNER", "`user`", "`user`.id = `issue_watch`.user_id") if listOptions.Page != 0 { - sess = setSessionPagination(sess, &listOptions) + sess = db.SetSessionPagination(sess, &listOptions) watches := make([]*IssueWatch, 0, listOptions.PageSize) return watches, sess.Find(&watches) } diff --git a/models/issue_watch_test.go b/models/issue_watch_test.go index f85e7cef59..139ed41cb6 100644 --- a/models/issue_watch_test.go +++ b/models/issue_watch_test.go @@ -43,22 +43,22 @@ func TestGetIssueWatch(t *testing.T) { func TestGetIssueWatchers(t *testing.T) { assert.NoError(t, db.PrepareTestDatabase()) - iws, err := GetIssueWatchers(1, ListOptions{}) + iws, err := GetIssueWatchers(1, db.ListOptions{}) assert.NoError(t, err) // Watcher is inactive, thus 0 assert.Len(t, iws, 0) - iws, err = GetIssueWatchers(2, ListOptions{}) + iws, err = GetIssueWatchers(2, db.ListOptions{}) assert.NoError(t, err) // Watcher is explicit not watching assert.Len(t, iws, 0) - iws, err = GetIssueWatchers(5, ListOptions{}) + iws, err = GetIssueWatchers(5, db.ListOptions{}) assert.NoError(t, err) // Issue has no Watchers assert.Len(t, iws, 0) - iws, err = GetIssueWatchers(7, ListOptions{}) + iws, err = GetIssueWatchers(7, db.ListOptions{}) assert.NoError(t, err) // Issue has one watcher assert.Len(t, iws, 1) diff --git a/models/login/main_test.go b/models/login/main_test.go new file mode 100644 index 0000000000..ef4b5907bf --- /dev/null +++ b/models/login/main_test.go @@ -0,0 +1,21 @@ +// Copyright 2020 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package login + +import ( + "path/filepath" + "testing" + + "code.gitea.io/gitea/models/db" +) + +func TestMain(m *testing.M) { + db.MainTest(m, filepath.Join("..", ".."), + "login_source.yml", + "oauth2_application.yml", + "oauth2_authorization_code.yml", + "oauth2_grant.yml", + ) +} diff --git a/models/login/oauth2.go b/models/login/oauth2.go new file mode 100644 index 0000000000..45ab59dd78 --- /dev/null +++ b/models/login/oauth2.go @@ -0,0 +1,70 @@ +// Copyright 2017 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package login + +import ( + "fmt" + + "code.gitea.io/gitea/models/db" +) + +// ________ _____ __ .__ +// \_____ \ / _ \ __ ___/ |_| |__ +// / | \ / /_\ \| | \ __\ | \ +// / | \/ | \ | /| | | Y \ +// \_______ /\____|__ /____/ |__| |___| / +// \/ \/ \/ + +// ErrOAuthClientIDInvalid will be thrown if client id cannot be found +type ErrOAuthClientIDInvalid struct { + ClientID string +} + +// IsErrOauthClientIDInvalid checks if an error is a ErrReviewNotExist. +func IsErrOauthClientIDInvalid(err error) bool { + _, ok := err.(ErrOAuthClientIDInvalid) + return ok +} + +// Error returns the error message +func (err ErrOAuthClientIDInvalid) Error() string { + return fmt.Sprintf("Client ID invalid [Client ID: %s]", err.ClientID) +} + +// ErrOAuthApplicationNotFound will be thrown if id cannot be found +type ErrOAuthApplicationNotFound struct { + ID int64 +} + +// IsErrOAuthApplicationNotFound checks if an error is a ErrReviewNotExist. +func IsErrOAuthApplicationNotFound(err error) bool { + _, ok := err.(ErrOAuthApplicationNotFound) + return ok +} + +// Error returns the error message +func (err ErrOAuthApplicationNotFound) Error() string { + return fmt.Sprintf("OAuth application not found [ID: %d]", err.ID) +} + +// GetActiveOAuth2ProviderLoginSources returns all actived LoginOAuth2 sources +func GetActiveOAuth2ProviderLoginSources() ([]*Source, error) { + sources := make([]*Source, 0, 1) + if err := db.GetEngine(db.DefaultContext).Where("is_active = ? and type = ?", true, OAuth2).Find(&sources); err != nil { + return nil, err + } + return sources, nil +} + +// GetActiveOAuth2LoginSourceByName returns a OAuth2 LoginSource based on the given name +func GetActiveOAuth2LoginSourceByName(name string) (*Source, error) { + loginSource := new(Source) + has, err := db.GetEngine(db.DefaultContext).Where("name = ? and type = ? and is_active = ?", name, OAuth2, true).Get(loginSource) + if !has || err != nil { + return nil, err + } + + return loginSource, nil +} diff --git a/models/oauth2_application.go b/models/login/oauth2_application.go index 0fd2e38472..060bfe5bc3 100644 --- a/models/oauth2_application.go +++ b/models/login/oauth2_application.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. -package models +package login import ( "crypto/sha256" @@ -23,19 +23,14 @@ import ( // OAuth2Application represents an OAuth2 client (RFC 6749) type OAuth2Application struct { - ID int64 `xorm:"pk autoincr"` - UID int64 `xorm:"INDEX"` - User *User `xorm:"-"` - - Name string - + ID int64 `xorm:"pk autoincr"` + UID int64 `xorm:"INDEX"` + Name string ClientID string `xorm:"unique"` ClientSecret string - - RedirectURIs []string `xorm:"redirect_uris JSON TEXT"` - - CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"` - UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"` + RedirectURIs []string `xorm:"redirect_uris JSON TEXT"` + CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"` + UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"` } func init() { @@ -57,14 +52,6 @@ func (app *OAuth2Application) PrimaryRedirectURI() string { return app.RedirectURIs[0] } -// LoadUser will load User by UID -func (app *OAuth2Application) LoadUser() (err error) { - if app.User == nil { - app.User, err = GetUserByID(app.UID) - } - return -} - // ContainsRedirectURI checks if redirectURI is allowed for app func (app *OAuth2Application) ContainsRedirectURI(redirectURI string) bool { return util.IsStringInSlice(redirectURI, app.RedirectURIs, true) @@ -276,13 +263,13 @@ func DeleteOAuth2Application(id, userid int64) error { } // ListOAuth2Applications returns a list of oauth2 applications belongs to given user. -func ListOAuth2Applications(uid int64, listOptions ListOptions) ([]*OAuth2Application, int64, error) { +func ListOAuth2Applications(uid int64, listOptions db.ListOptions) ([]*OAuth2Application, int64, error) { sess := db.GetEngine(db.DefaultContext). Where("uid=?", uid). Desc("id") if listOptions.Page != 0 { - sess = setSessionPagination(sess, &listOptions) + sess = db.SetSessionPagination(sess, &listOptions) apps := make([]*OAuth2Application, 0, listOptions.PageSize) total, err := sess.FindAndCount(&apps) diff --git a/models/oauth2_application_test.go b/models/login/oauth2_application_test.go index b01ef967fc..cb064cef1b 100644 --- a/models/oauth2_application_test.go +++ b/models/login/oauth2_application_test.go @@ -2,12 +2,13 @@ // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. -package models +package login import ( "testing" "code.gitea.io/gitea/models/db" + "github.com/stretchr/testify/assert" ) @@ -69,13 +70,6 @@ func TestCreateOAuth2Application(t *testing.T) { db.AssertExistsAndLoadBean(t, &OAuth2Application{Name: "newapp"}) } -func TestOAuth2Application_LoadUser(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - app := db.AssertExistsAndLoadBean(t, &OAuth2Application{ID: 1}).(*OAuth2Application) - assert.NoError(t, app.LoadUser()) - assert.NotNil(t, app.User) -} - func TestOAuth2Application_TableName(t *testing.T) { assert.Equal(t, "oauth2_application", new(OAuth2Application).TableName()) } diff --git a/models/login_source.go b/models/login/source.go index e1f7a7e08e..1001d49b51 100644 --- a/models/login_source.go +++ b/models/login/source.go @@ -3,9 +3,10 @@ // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. -package models +package login import ( + "fmt" "reflect" "strconv" @@ -17,43 +18,43 @@ import ( "xorm.io/xorm/convert" ) -// LoginType represents an login type. -type LoginType int +// Type represents an login type. +type Type int // Note: new type must append to the end of list to maintain compatibility. const ( - LoginNoType LoginType = iota - LoginPlain // 1 - LoginLDAP // 2 - LoginSMTP // 3 - LoginPAM // 4 - LoginDLDAP // 5 - LoginOAuth2 // 6 - LoginSSPI // 7 + NoType Type = iota + Plain // 1 + LDAP // 2 + SMTP // 3 + PAM // 4 + DLDAP // 5 + OAuth2 // 6 + SSPI // 7 ) // String returns the string name of the LoginType -func (typ LoginType) String() string { - return LoginNames[typ] +func (typ Type) String() string { + return Names[typ] } // Int returns the int value of the LoginType -func (typ LoginType) Int() int { +func (typ Type) Int() int { return int(typ) } -// LoginNames contains the name of LoginType values. -var LoginNames = map[LoginType]string{ - LoginLDAP: "LDAP (via BindDN)", - LoginDLDAP: "LDAP (simple auth)", // Via direct bind - LoginSMTP: "SMTP", - LoginPAM: "PAM", - LoginOAuth2: "OAuth2", - LoginSSPI: "SPNEGO with SSPI", +// Names contains the name of LoginType values. +var Names = map[Type]string{ + LDAP: "LDAP (via BindDN)", + DLDAP: "LDAP (simple auth)", // Via direct bind + SMTP: "SMTP", + PAM: "PAM", + OAuth2: "OAuth2", + SSPI: "SPNEGO with SSPI", } -// LoginConfig represents login config as far as the db is concerned -type LoginConfig interface { +// Config represents login config as far as the db is concerned +type Config interface { convert.Conversion } @@ -83,33 +84,33 @@ type RegisterableSource interface { UnregisterSource() error } -// LoginSourceSettable configurations can have their loginSource set on them -type LoginSourceSettable interface { - SetLoginSource(*LoginSource) +// SourceSettable configurations can have their loginSource set on them +type SourceSettable interface { + SetLoginSource(*Source) } -// RegisterLoginTypeConfig register a config for a provided type -func RegisterLoginTypeConfig(typ LoginType, exemplar LoginConfig) { +// RegisterTypeConfig register a config for a provided type +func RegisterTypeConfig(typ Type, exemplar Config) { if reflect.TypeOf(exemplar).Kind() == reflect.Ptr { // Pointer: - registeredLoginConfigs[typ] = func() LoginConfig { - return reflect.New(reflect.ValueOf(exemplar).Elem().Type()).Interface().(LoginConfig) + registeredConfigs[typ] = func() Config { + return reflect.New(reflect.ValueOf(exemplar).Elem().Type()).Interface().(Config) } return } // Not a Pointer - registeredLoginConfigs[typ] = func() LoginConfig { - return reflect.New(reflect.TypeOf(exemplar)).Elem().Interface().(LoginConfig) + registeredConfigs[typ] = func() Config { + return reflect.New(reflect.TypeOf(exemplar)).Elem().Interface().(Config) } } -var registeredLoginConfigs = map[LoginType]func() LoginConfig{} +var registeredConfigs = map[Type]func() Config{} -// LoginSource represents an external way for authorizing users. -type LoginSource struct { +// Source represents an external way for authorizing users. +type Source struct { ID int64 `xorm:"pk autoincr"` - Type LoginType + Type Type Name string `xorm:"UNIQUE"` IsActive bool `xorm:"INDEX NOT NULL DEFAULT false"` IsSyncEnabled bool `xorm:"INDEX NOT NULL DEFAULT false"` @@ -119,8 +120,13 @@ type LoginSource struct { UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"` } +// TableName xorm will read the table name from this method +func (Source) TableName() string { + return "login_source" +} + func init() { - db.RegisterModel(new(LoginSource)) + db.RegisterModel(new(Source)) } // Cell2Int64 converts a xorm.Cell type to int64, @@ -137,82 +143,82 @@ func Cell2Int64(val xorm.Cell) int64 { } // BeforeSet is invoked from XORM before setting the value of a field of this object. -func (source *LoginSource) BeforeSet(colName string, val xorm.Cell) { +func (source *Source) BeforeSet(colName string, val xorm.Cell) { if colName == "type" { - typ := LoginType(Cell2Int64(val)) - constructor, ok := registeredLoginConfigs[typ] + typ := Type(Cell2Int64(val)) + constructor, ok := registeredConfigs[typ] if !ok { return } source.Cfg = constructor() - if settable, ok := source.Cfg.(LoginSourceSettable); ok { + if settable, ok := source.Cfg.(SourceSettable); ok { settable.SetLoginSource(source) } } } // TypeName return name of this login source type. -func (source *LoginSource) TypeName() string { - return LoginNames[source.Type] +func (source *Source) TypeName() string { + return Names[source.Type] } // IsLDAP returns true of this source is of the LDAP type. -func (source *LoginSource) IsLDAP() bool { - return source.Type == LoginLDAP +func (source *Source) IsLDAP() bool { + return source.Type == LDAP } // IsDLDAP returns true of this source is of the DLDAP type. -func (source *LoginSource) IsDLDAP() bool { - return source.Type == LoginDLDAP +func (source *Source) IsDLDAP() bool { + return source.Type == DLDAP } // IsSMTP returns true of this source is of the SMTP type. -func (source *LoginSource) IsSMTP() bool { - return source.Type == LoginSMTP +func (source *Source) IsSMTP() bool { + return source.Type == SMTP } // IsPAM returns true of this source is of the PAM type. -func (source *LoginSource) IsPAM() bool { - return source.Type == LoginPAM +func (source *Source) IsPAM() bool { + return source.Type == PAM } // IsOAuth2 returns true of this source is of the OAuth2 type. -func (source *LoginSource) IsOAuth2() bool { - return source.Type == LoginOAuth2 +func (source *Source) IsOAuth2() bool { + return source.Type == OAuth2 } // IsSSPI returns true of this source is of the SSPI type. -func (source *LoginSource) IsSSPI() bool { - return source.Type == LoginSSPI +func (source *Source) IsSSPI() bool { + return source.Type == SSPI } // HasTLS returns true of this source supports TLS. -func (source *LoginSource) HasTLS() bool { +func (source *Source) HasTLS() bool { hasTLSer, ok := source.Cfg.(HasTLSer) return ok && hasTLSer.HasTLS() } // UseTLS returns true of this source is configured to use TLS. -func (source *LoginSource) UseTLS() bool { +func (source *Source) UseTLS() bool { useTLSer, ok := source.Cfg.(UseTLSer) return ok && useTLSer.UseTLS() } // SkipVerify returns true if this source is configured to skip SSL // verification. -func (source *LoginSource) SkipVerify() bool { +func (source *Source) SkipVerify() bool { skipVerifiable, ok := source.Cfg.(SkipVerifiable) return ok && skipVerifiable.IsSkipVerify() } -// CreateLoginSource inserts a LoginSource in the DB if not already +// CreateSource inserts a LoginSource in the DB if not already // existing with the given name. -func CreateLoginSource(source *LoginSource) error { - has, err := db.GetEngine(db.DefaultContext).Where("name=?", source.Name).Exist(new(LoginSource)) +func CreateSource(source *Source) error { + has, err := db.GetEngine(db.DefaultContext).Where("name=?", source.Name).Exist(new(Source)) if err != nil { return err } else if has { - return ErrLoginSourceAlreadyExist{source.Name} + return ErrSourceAlreadyExist{source.Name} } // Synchronization is only available with LDAP for now if !source.IsLDAP() { @@ -228,7 +234,7 @@ func CreateLoginSource(source *LoginSource) error { return nil } - if settable, ok := source.Cfg.(LoginSourceSettable); ok { + if settable, ok := source.Cfg.(SourceSettable); ok { settable.SetLoginSource(source) } @@ -241,40 +247,40 @@ func CreateLoginSource(source *LoginSource) error { if err != nil { // remove the LoginSource in case of errors while registering configuration if _, err := db.GetEngine(db.DefaultContext).Delete(source); err != nil { - log.Error("CreateLoginSource: Error while wrapOpenIDConnectInitializeError: %v", err) + log.Error("CreateSource: Error while wrapOpenIDConnectInitializeError: %v", err) } } return err } -// LoginSources returns a slice of all login sources found in DB. -func LoginSources() ([]*LoginSource, error) { - auths := make([]*LoginSource, 0, 6) +// Sources returns a slice of all login sources found in DB. +func Sources() ([]*Source, error) { + auths := make([]*Source, 0, 6) return auths, db.GetEngine(db.DefaultContext).Find(&auths) } -// LoginSourcesByType returns all sources of the specified type -func LoginSourcesByType(loginType LoginType) ([]*LoginSource, error) { - sources := make([]*LoginSource, 0, 1) +// SourcesByType returns all sources of the specified type +func SourcesByType(loginType Type) ([]*Source, error) { + sources := make([]*Source, 0, 1) if err := db.GetEngine(db.DefaultContext).Where("type = ?", loginType).Find(&sources); err != nil { return nil, err } return sources, nil } -// AllActiveLoginSources returns all active sources -func AllActiveLoginSources() ([]*LoginSource, error) { - sources := make([]*LoginSource, 0, 5) +// AllActiveSources returns all active sources +func AllActiveSources() ([]*Source, error) { + sources := make([]*Source, 0, 5) if err := db.GetEngine(db.DefaultContext).Where("is_active = ?", true).Find(&sources); err != nil { return nil, err } return sources, nil } -// ActiveLoginSources returns all active sources of the specified type -func ActiveLoginSources(loginType LoginType) ([]*LoginSource, error) { - sources := make([]*LoginSource, 0, 1) - if err := db.GetEngine(db.DefaultContext).Where("is_active = ? and type = ?", true, loginType).Find(&sources); err != nil { +// ActiveSources returns all active sources of the specified type +func ActiveSources(tp Type) ([]*Source, error) { + sources := make([]*Source, 0, 1) + if err := db.GetEngine(db.DefaultContext).Where("is_active = ? and type = ?", true, tp).Find(&sources); err != nil { return nil, err } return sources, nil @@ -286,19 +292,19 @@ func IsSSPIEnabled() bool { if !db.HasEngine { return false } - sources, err := ActiveLoginSources(LoginSSPI) + sources, err := ActiveSources(SSPI) if err != nil { - log.Error("ActiveLoginSources: %v", err) + log.Error("ActiveSources: %v", err) return false } return len(sources) > 0 } -// GetLoginSourceByID returns login source by given ID. -func GetLoginSourceByID(id int64) (*LoginSource, error) { - source := new(LoginSource) +// GetSourceByID returns login source by given ID. +func GetSourceByID(id int64) (*Source, error) { + source := new(Source) if id == 0 { - source.Cfg = registeredLoginConfigs[LoginNoType]() + source.Cfg = registeredConfigs[NoType]() // Set this source to active // FIXME: allow disabling of db based password authentication in future source.IsActive = true @@ -309,18 +315,18 @@ func GetLoginSourceByID(id int64) (*LoginSource, error) { if err != nil { return nil, err } else if !has { - return nil, ErrLoginSourceNotExist{id} + return nil, ErrSourceNotExist{id} } return source, nil } -// UpdateSource updates a LoginSource record in DB. -func UpdateSource(source *LoginSource) error { - var originalLoginSource *LoginSource +// UpdateSource updates a Source record in DB. +func UpdateSource(source *Source) error { + var originalLoginSource *Source if source.IsOAuth2() { // keep track of the original values so we can restore in case of errors while registering OAuth2 providers var err error - if originalLoginSource, err = GetLoginSourceByID(source.ID); err != nil { + if originalLoginSource, err = GetSourceByID(source.ID); err != nil { return err } } @@ -334,7 +340,7 @@ func UpdateSource(source *LoginSource) error { return nil } - if settable, ok := source.Cfg.(LoginSourceSettable); ok { + if settable, ok := source.Cfg.(SourceSettable); ok { settable.SetLoginSource(source) } @@ -353,34 +359,53 @@ func UpdateSource(source *LoginSource) error { return err } -// DeleteSource deletes a LoginSource record in DB. -func DeleteSource(source *LoginSource) error { - count, err := db.GetEngine(db.DefaultContext).Count(&User{LoginSource: source.ID}) - if err != nil { - return err - } else if count > 0 { - return ErrLoginSourceInUse{source.ID} - } +// CountSources returns number of login sources. +func CountSources() int64 { + count, _ := db.GetEngine(db.DefaultContext).Count(new(Source)) + return count +} - count, err = db.GetEngine(db.DefaultContext).Count(&ExternalLoginUser{LoginSourceID: source.ID}) - if err != nil { - return err - } else if count > 0 { - return ErrLoginSourceInUse{source.ID} - } +// ErrSourceNotExist represents a "SourceNotExist" kind of error. +type ErrSourceNotExist struct { + ID int64 +} - if registerableSource, ok := source.Cfg.(RegisterableSource); ok { - if err := registerableSource.UnregisterSource(); err != nil { - return err - } - } +// IsErrSourceNotExist checks if an error is a ErrSourceNotExist. +func IsErrSourceNotExist(err error) bool { + _, ok := err.(ErrSourceNotExist) + return ok +} - _, err = db.GetEngine(db.DefaultContext).ID(source.ID).Delete(new(LoginSource)) - return err +func (err ErrSourceNotExist) Error() string { + return fmt.Sprintf("login source does not exist [id: %d]", err.ID) } -// CountLoginSources returns number of login sources. -func CountLoginSources() int64 { - count, _ := db.GetEngine(db.DefaultContext).Count(new(LoginSource)) - return count +// ErrSourceAlreadyExist represents a "SourceAlreadyExist" kind of error. +type ErrSourceAlreadyExist struct { + Name string +} + +// IsErrSourceAlreadyExist checks if an error is a ErrSourceAlreadyExist. +func IsErrSourceAlreadyExist(err error) bool { + _, ok := err.(ErrSourceAlreadyExist) + return ok +} + +func (err ErrSourceAlreadyExist) Error() string { + return fmt.Sprintf("login source already exists [name: %s]", err.Name) +} + +// ErrSourceInUse represents a "SourceInUse" kind of error. +type ErrSourceInUse struct { + ID int64 +} + +// IsErrSourceInUse checks if an error is a ErrSourceInUse. +func IsErrSourceInUse(err error) bool { + _, ok := err.(ErrSourceInUse) + return ok +} + +func (err ErrSourceInUse) Error() string { + return fmt.Sprintf("login source is still used by some users [id: %d]", err.ID) } diff --git a/models/login_source_test.go b/models/login/source_test.go index ea1812238f..d98609037c 100644 --- a/models/login_source_test.go +++ b/models/login/source_test.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. -package models +package login import ( "strings" @@ -36,13 +36,13 @@ func (source *TestSource) ToDB() ([]byte, error) { func TestDumpLoginSource(t *testing.T) { assert.NoError(t, db.PrepareTestDatabase()) - loginSourceSchema, err := db.TableInfo(new(LoginSource)) + loginSourceSchema, err := db.TableInfo(new(Source)) assert.NoError(t, err) - RegisterLoginTypeConfig(LoginOAuth2, new(TestSource)) + RegisterTypeConfig(OAuth2, new(TestSource)) - CreateLoginSource(&LoginSource{ - Type: LoginOAuth2, + CreateSource(&Source{ + Type: OAuth2, Name: "TestSource", IsActive: false, Cfg: &TestSource{ diff --git a/models/migrations/migrations_test.go b/models/migrations/migrations_test.go index fffc44be12..78624f1e27 100644 --- a/models/migrations/migrations_test.go +++ b/models/migrations/migrations_test.go @@ -241,7 +241,10 @@ func prepareTestEnv(t *testing.T, skip int, syncModels ...interface{}) (*xorm.En if _, err := os.Stat(fixturesDir); err == nil { t.Logf("initializing fixtures from: %s", fixturesDir) - if err := db.InitFixtures(fixturesDir, x); err != nil { + if err := db.InitFixtures( + db.FixturesOptions{ + Dir: fixturesDir, + }, x); err != nil { t.Errorf("error whilst initializing fixtures from %s: %v", fixturesDir, err) return x, deferFn } diff --git a/models/notification.go b/models/notification.go index af24a6cf5a..bcbe8b0988 100644 --- a/models/notification.go +++ b/models/notification.go @@ -74,7 +74,7 @@ func init() { // FindNotificationOptions represent the filters for notifications. If an ID is 0 it will be ignored. type FindNotificationOptions struct { - ListOptions + db.ListOptions UserID int64 RepoID int64 IssueID int64 @@ -115,7 +115,7 @@ func (opts *FindNotificationOptions) ToCond() builder.Cond { func (opts *FindNotificationOptions) ToSession(e db.Engine) *xorm.Session { sess := e.Where(opts.ToCond()) if opts.Page != 0 { - sess = setSessionPagination(sess, opts) + sess = db.SetSessionPagination(sess, opts) } return sess } diff --git a/models/oauth2.go b/models/oauth2.go deleted file mode 100644 index 7fdd5309fb..0000000000 --- a/models/oauth2.go +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2017 The Gitea Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. - -package models - -import "code.gitea.io/gitea/models/db" - -// GetActiveOAuth2ProviderLoginSources returns all actived LoginOAuth2 sources -func GetActiveOAuth2ProviderLoginSources() ([]*LoginSource, error) { - sources := make([]*LoginSource, 0, 1) - if err := db.GetEngine(db.DefaultContext).Where("is_active = ? and type = ?", true, LoginOAuth2).Find(&sources); err != nil { - return nil, err - } - return sources, nil -} - -// GetActiveOAuth2LoginSourceByName returns a OAuth2 LoginSource based on the given name -func GetActiveOAuth2LoginSourceByName(name string) (*LoginSource, error) { - loginSource := new(LoginSource) - has, err := db.GetEngine(db.DefaultContext).Where("name = ? and type = ? and is_active = ?", name, LoginOAuth2, true).Get(loginSource) - if !has || err != nil { - return nil, err - } - - return loginSource, nil -} diff --git a/models/org.go b/models/org.go index bc6c47fd45..94939d2c74 100644 --- a/models/org.go +++ b/models/org.go @@ -78,7 +78,7 @@ func (org *User) GetMembers() (err error) { // FindOrgMembersOpts represensts find org members conditions type FindOrgMembersOpts struct { - ListOptions + db.ListOptions OrgID int64 PublicOnly bool } @@ -574,7 +574,7 @@ func GetOrgUsersByUserID(uid int64, opts *SearchOrganizationsOptions) ([]*OrgUse } if opts.PageSize != 0 { - sess = setSessionPagination(sess, opts) + sess = db.SetSessionPagination(sess, opts) } err := sess. @@ -594,7 +594,7 @@ func getOrgUsersByOrgID(e db.Engine, opts *FindOrgMembersOpts) ([]*OrgUser, erro sess.And("is_public = ?", true) } if opts.ListOptions.PageSize > 0 { - sess = setSessionPagination(sess, opts) + sess = db.SetSessionPagination(sess, opts) ous := make([]*OrgUser, 0, opts.PageSize) return ous, sess.Find(&ous) diff --git a/models/org_team.go b/models/org_team.go index 7ca715bb78..fc6a5f2c3b 100644 --- a/models/org_team.go +++ b/models/org_team.go @@ -47,7 +47,7 @@ func init() { // SearchTeamOptions holds the search options type SearchTeamOptions struct { - ListOptions + db.ListOptions UserID int64 Keyword string OrgID int64 @@ -56,7 +56,7 @@ type SearchTeamOptions struct { // SearchMembersOptions holds the search options type SearchMembersOptions struct { - ListOptions + db.ListOptions } // SearchTeam search for teams. Caller is responsible to check permissions. @@ -176,7 +176,7 @@ func (t *Team) GetRepositories(opts *SearchTeamOptions) error { return t.getRepositories(db.GetEngine(db.DefaultContext)) } - return t.getRepositories(getPaginatedSession(opts)) + return t.getRepositories(db.GetPaginatedSession(opts)) } func (t *Team) getMembers(e db.Engine) (err error) { @@ -190,7 +190,7 @@ func (t *Team) GetMembers(opts *SearchMembersOptions) (err error) { return t.getMembers(db.GetEngine(db.DefaultContext)) } - return t.getMembers(getPaginatedSession(opts)) + return t.getMembers(db.GetPaginatedSession(opts)) } // AddMember adds new membership of the team to the organization, diff --git a/models/org_test.go b/models/org_test.go index 75dfc4262d..2df89b2afc 100644 --- a/models/org_test.go +++ b/models/org_test.go @@ -399,7 +399,7 @@ func TestGetOrgUsersByOrgID(t *testing.T) { assert.NoError(t, db.PrepareTestDatabase()) orgUsers, err := GetOrgUsersByOrgID(&FindOrgMembersOpts{ - ListOptions: ListOptions{}, + ListOptions: db.ListOptions{}, OrgID: 3, PublicOnly: false, }) @@ -420,7 +420,7 @@ func TestGetOrgUsersByOrgID(t *testing.T) { } orgUsers, err = GetOrgUsersByOrgID(&FindOrgMembersOpts{ - ListOptions: ListOptions{}, + ListOptions: db.ListOptions{}, OrgID: db.NonexistentID, PublicOnly: false, }) diff --git a/models/pull_list.go b/models/pull_list.go index 57e2f9c85f..57ef210213 100644 --- a/models/pull_list.go +++ b/models/pull_list.go @@ -17,7 +17,7 @@ import ( // PullRequestsOptions holds the options for PRs type PullRequestsOptions struct { - ListOptions + db.ListOptions State string SortType string Labels []string @@ -101,7 +101,7 @@ func PullRequests(baseRepoID int64, opts *PullRequestsOptions) ([]*PullRequest, log.Error("listPullRequestStatement: %v", err) return nil, maxResults, err } - findSession = setSessionPagination(findSession, opts) + findSession = db.SetSessionPagination(findSession, opts) prs := make([]*PullRequest, 0, opts.PageSize) return prs, maxResults, findSession.Find(&prs) } diff --git a/models/pull_sign.go b/models/pull_sign.go index e7cf4ab666..2e7cbff48b 100644 --- a/models/pull_sign.go +++ b/models/pull_sign.go @@ -5,6 +5,7 @@ package models import ( + "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" @@ -35,7 +36,7 @@ Loop: case always: break Loop case pubkey: - keys, err := ListGPGKeys(u.ID, ListOptions{}) + keys, err := ListGPGKeys(u.ID, db.ListOptions{}) if err != nil { return false, "", nil, err } diff --git a/models/pull_test.go b/models/pull_test.go index 6543d0ec96..2b7ef2f664 100644 --- a/models/pull_test.go +++ b/models/pull_test.go @@ -56,7 +56,7 @@ func TestPullRequest_LoadHeadRepo(t *testing.T) { func TestPullRequestsNewest(t *testing.T) { assert.NoError(t, db.PrepareTestDatabase()) prs, count, err := PullRequests(1, &PullRequestsOptions{ - ListOptions: ListOptions{ + ListOptions: db.ListOptions{ Page: 1, }, State: "open", @@ -75,7 +75,7 @@ func TestPullRequestsNewest(t *testing.T) { func TestPullRequestsOldest(t *testing.T) { assert.NoError(t, db.PrepareTestDatabase()) prs, count, err := PullRequests(1, &PullRequestsOptions{ - ListOptions: ListOptions{ + ListOptions: db.ListOptions{ Page: 1, }, State: "open", diff --git a/models/release.go b/models/release.go index d6b629cfe8..4624791b8f 100644 --- a/models/release.go +++ b/models/release.go @@ -177,7 +177,7 @@ func GetReleaseByID(id int64) (*Release, error) { // FindReleasesOptions describes the conditions to Find releases type FindReleasesOptions struct { - ListOptions + db.ListOptions IncludeDrafts bool IncludeTags bool IsPreRelease util.OptionalBool @@ -214,7 +214,7 @@ func GetReleasesByRepoID(repoID int64, opts FindReleasesOptions) ([]*Release, er Where(opts.toConds(repoID)) if opts.PageSize != 0 { - sess = setSessionPagination(sess, &opts.ListOptions) + sess = db.SetSessionPagination(sess, &opts.ListOptions) } rels := make([]*Release, 0, opts.PageSize) diff --git a/models/repo.go b/models/repo.go index ae149f467d..efd78c6042 100644 --- a/models/repo.go +++ b/models/repo.go @@ -1772,7 +1772,7 @@ func GetUserRepositories(opts *SearchRepoOptions) ([]*Repository, int64, error) sess.Where(cond).OrderBy(opts.OrderBy.String()) repos := make([]*Repository, 0, opts.PageSize) - return repos, count, setSessionPagination(sess, opts).Find(&repos) + return repos, count, db.SetSessionPagination(sess, opts).Find(&repos) } // GetUserMirrorRepositories returns a list of mirror repositories of given user. @@ -2057,13 +2057,13 @@ func CopyLFS(ctx context.Context, newRepo, oldRepo *Repository) error { } // GetForks returns all the forks of the repository -func (repo *Repository) GetForks(listOptions ListOptions) ([]*Repository, error) { +func (repo *Repository) GetForks(listOptions db.ListOptions) ([]*Repository, error) { if listOptions.Page == 0 { forks := make([]*Repository, 0, repo.NumForks) return forks, db.GetEngine(db.DefaultContext).Find(&forks, &Repository{ForkID: repo.ID}) } - sess := getPaginatedSession(&listOptions) + sess := db.GetPaginatedSession(&listOptions) forks := make([]*Repository, 0, listOptions.PageSize) return forks, sess.Find(&forks, &Repository{ForkID: repo.ID}) } diff --git a/models/repo_collaboration.go b/models/repo_collaboration.go index 08d2062dbb..08360c102d 100644 --- a/models/repo_collaboration.go +++ b/models/repo_collaboration.go @@ -64,13 +64,13 @@ func (repo *Repository) AddCollaborator(u *User) error { return sess.Commit() } -func (repo *Repository) getCollaborations(e db.Engine, listOptions ListOptions) ([]*Collaboration, error) { +func (repo *Repository) getCollaborations(e db.Engine, listOptions db.ListOptions) ([]*Collaboration, error) { if listOptions.Page == 0 { collaborations := make([]*Collaboration, 0, 8) return collaborations, e.Find(&collaborations, &Collaboration{RepoID: repo.ID}) } - e = setEnginePagination(e, &listOptions) + e = db.SetEnginePagination(e, &listOptions) collaborations := make([]*Collaboration, 0, listOptions.PageSize) return collaborations, e.Find(&collaborations, &Collaboration{RepoID: repo.ID}) @@ -82,7 +82,7 @@ type Collaborator struct { Collaboration *Collaboration } -func (repo *Repository) getCollaborators(e db.Engine, listOptions ListOptions) ([]*Collaborator, error) { +func (repo *Repository) getCollaborators(e db.Engine, listOptions db.ListOptions) ([]*Collaborator, error) { collaborations, err := repo.getCollaborations(e, listOptions) if err != nil { return nil, fmt.Errorf("getCollaborations: %v", err) @@ -103,7 +103,7 @@ func (repo *Repository) getCollaborators(e db.Engine, listOptions ListOptions) ( } // GetCollaborators returns the collaborators for a repository -func (repo *Repository) GetCollaborators(listOptions ListOptions) ([]*Collaborator, error) { +func (repo *Repository) GetCollaborators(listOptions db.ListOptions) ([]*Collaborator, error) { return repo.getCollaborators(db.GetEngine(db.DefaultContext), listOptions) } diff --git a/models/repo_collaboration_test.go b/models/repo_collaboration_test.go index 5a3ffef5fa..326fb4dbf7 100644 --- a/models/repo_collaboration_test.go +++ b/models/repo_collaboration_test.go @@ -30,7 +30,7 @@ func TestRepository_GetCollaborators(t *testing.T) { assert.NoError(t, db.PrepareTestDatabase()) test := func(repoID int64) { repo := db.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository) - collaborators, err := repo.GetCollaborators(ListOptions{}) + collaborators, err := repo.GetCollaborators(db.ListOptions{}) assert.NoError(t, err) expectedLen, err := db.GetEngine(db.DefaultContext).Count(&Collaboration{RepoID: repoID}) assert.NoError(t, err) diff --git a/models/repo_generate.go b/models/repo_generate.go index cb8bf45184..650da711a3 100644 --- a/models/repo_generate.go +++ b/models/repo_generate.go @@ -151,7 +151,7 @@ func GenerateAvatar(ctx context.Context, templateRepo, generateRepo *Repository) // GenerateIssueLabels generates issue labels from a template repository func GenerateIssueLabels(ctx context.Context, templateRepo, generateRepo *Repository) error { - templateLabels, err := getLabelsByRepoID(db.GetEngine(ctx), templateRepo.ID, "", ListOptions{}) + templateLabels, err := getLabelsByRepoID(db.GetEngine(ctx), templateRepo.ID, "", db.ListOptions{}) if err != nil { return err } diff --git a/models/repo_list.go b/models/repo_list.go index 7179114f46..6804a997c8 100644 --- a/models/repo_list.go +++ b/models/repo_list.go @@ -135,7 +135,7 @@ func (repos MirrorRepositoryList) LoadAttributes() error { // SearchRepoOptions holds the search options type SearchRepoOptions struct { - ListOptions + db.ListOptions Actor *User Keyword string OwnerID int64 diff --git a/models/repo_list_test.go b/models/repo_list_test.go index a1fd454c10..3c30cad564 100644 --- a/models/repo_list_test.go +++ b/models/repo_list_test.go @@ -18,7 +18,7 @@ func TestSearchRepository(t *testing.T) { // test search public repository on explore page repos, count, err := SearchRepositoryByName(&SearchRepoOptions{ - ListOptions: ListOptions{ + ListOptions: db.ListOptions{ Page: 1, PageSize: 10, }, @@ -33,7 +33,7 @@ func TestSearchRepository(t *testing.T) { assert.Equal(t, int64(1), count) repos, count, err = SearchRepositoryByName(&SearchRepoOptions{ - ListOptions: ListOptions{ + ListOptions: db.ListOptions{ Page: 1, PageSize: 10, }, @@ -47,7 +47,7 @@ func TestSearchRepository(t *testing.T) { // test search private repository on explore page repos, count, err = SearchRepositoryByName(&SearchRepoOptions{ - ListOptions: ListOptions{ + ListOptions: db.ListOptions{ Page: 1, PageSize: 10, }, @@ -63,7 +63,7 @@ func TestSearchRepository(t *testing.T) { assert.Equal(t, int64(1), count) repos, count, err = SearchRepositoryByName(&SearchRepoOptions{ - ListOptions: ListOptions{ + ListOptions: db.ListOptions{ Page: 1, PageSize: 10, }, @@ -85,7 +85,7 @@ func TestSearchRepository(t *testing.T) { // Test search within description repos, count, err = SearchRepository(&SearchRepoOptions{ - ListOptions: ListOptions{ + ListOptions: db.ListOptions{ Page: 1, PageSize: 10, }, @@ -102,7 +102,7 @@ func TestSearchRepository(t *testing.T) { // Test NOT search within description repos, count, err = SearchRepository(&SearchRepoOptions{ - ListOptions: ListOptions{ + ListOptions: db.ListOptions{ Page: 1, PageSize: 10, }, @@ -122,142 +122,142 @@ func TestSearchRepository(t *testing.T) { }{ { name: "PublicRepositoriesByName", - opts: &SearchRepoOptions{Keyword: "big_test_", ListOptions: ListOptions{PageSize: 10}, Collaborate: util.OptionalBoolFalse}, + opts: &SearchRepoOptions{Keyword: "big_test_", ListOptions: db.ListOptions{PageSize: 10}, Collaborate: util.OptionalBoolFalse}, count: 7, }, { name: "PublicAndPrivateRepositoriesByName", - opts: &SearchRepoOptions{Keyword: "big_test_", ListOptions: ListOptions{Page: 1, PageSize: 10}, Private: true, Collaborate: util.OptionalBoolFalse}, + opts: &SearchRepoOptions{Keyword: "big_test_", ListOptions: db.ListOptions{Page: 1, PageSize: 10}, Private: true, Collaborate: util.OptionalBoolFalse}, count: 14, }, { name: "PublicAndPrivateRepositoriesByNameWithPagesizeLimitFirstPage", - opts: &SearchRepoOptions{Keyword: "big_test_", ListOptions: ListOptions{Page: 1, PageSize: 5}, Private: true, Collaborate: util.OptionalBoolFalse}, + opts: &SearchRepoOptions{Keyword: "big_test_", ListOptions: db.ListOptions{Page: 1, PageSize: 5}, Private: true, Collaborate: util.OptionalBoolFalse}, count: 14, }, { name: "PublicAndPrivateRepositoriesByNameWithPagesizeLimitSecondPage", - opts: &SearchRepoOptions{Keyword: "big_test_", ListOptions: ListOptions{Page: 2, PageSize: 5}, Private: true, Collaborate: util.OptionalBoolFalse}, + opts: &SearchRepoOptions{Keyword: "big_test_", ListOptions: db.ListOptions{Page: 2, PageSize: 5}, Private: true, Collaborate: util.OptionalBoolFalse}, count: 14, }, { name: "PublicAndPrivateRepositoriesByNameWithPagesizeLimitThirdPage", - opts: &SearchRepoOptions{Keyword: "big_test_", ListOptions: ListOptions{Page: 3, PageSize: 5}, Private: true, Collaborate: util.OptionalBoolFalse}, + opts: &SearchRepoOptions{Keyword: "big_test_", ListOptions: db.ListOptions{Page: 3, PageSize: 5}, Private: true, Collaborate: util.OptionalBoolFalse}, count: 14, }, { name: "PublicAndPrivateRepositoriesByNameWithPagesizeLimitFourthPage", - opts: &SearchRepoOptions{Keyword: "big_test_", ListOptions: ListOptions{Page: 3, PageSize: 5}, Private: true, Collaborate: util.OptionalBoolFalse}, + opts: &SearchRepoOptions{Keyword: "big_test_", ListOptions: db.ListOptions{Page: 3, PageSize: 5}, Private: true, Collaborate: util.OptionalBoolFalse}, count: 14, }, { name: "PublicRepositoriesOfUser", - opts: &SearchRepoOptions{ListOptions: ListOptions{Page: 1, PageSize: 10}, OwnerID: 15, Collaborate: util.OptionalBoolFalse}, + opts: &SearchRepoOptions{ListOptions: db.ListOptions{Page: 1, PageSize: 10}, OwnerID: 15, Collaborate: util.OptionalBoolFalse}, count: 2, }, { name: "PublicRepositoriesOfUser2", - opts: &SearchRepoOptions{ListOptions: ListOptions{Page: 1, PageSize: 10}, OwnerID: 18, Collaborate: util.OptionalBoolFalse}, + opts: &SearchRepoOptions{ListOptions: db.ListOptions{Page: 1, PageSize: 10}, OwnerID: 18, Collaborate: util.OptionalBoolFalse}, count: 0, }, { name: "PublicRepositoriesOfUser3", - opts: &SearchRepoOptions{ListOptions: ListOptions{Page: 1, PageSize: 10}, OwnerID: 20, Collaborate: util.OptionalBoolFalse}, + opts: &SearchRepoOptions{ListOptions: db.ListOptions{Page: 1, PageSize: 10}, OwnerID: 20, Collaborate: util.OptionalBoolFalse}, count: 2, }, { name: "PublicAndPrivateRepositoriesOfUser", - opts: &SearchRepoOptions{ListOptions: ListOptions{Page: 1, PageSize: 10}, OwnerID: 15, Private: true, Collaborate: util.OptionalBoolFalse}, + opts: &SearchRepoOptions{ListOptions: db.ListOptions{Page: 1, PageSize: 10}, OwnerID: 15, Private: true, Collaborate: util.OptionalBoolFalse}, count: 4, }, { name: "PublicAndPrivateRepositoriesOfUser2", - opts: &SearchRepoOptions{ListOptions: ListOptions{Page: 1, PageSize: 10}, OwnerID: 18, Private: true, Collaborate: util.OptionalBoolFalse}, + opts: &SearchRepoOptions{ListOptions: db.ListOptions{Page: 1, PageSize: 10}, OwnerID: 18, Private: true, Collaborate: util.OptionalBoolFalse}, count: 0, }, { name: "PublicAndPrivateRepositoriesOfUser3", - opts: &SearchRepoOptions{ListOptions: ListOptions{Page: 1, PageSize: 10}, OwnerID: 20, Private: true, Collaborate: util.OptionalBoolFalse}, + opts: &SearchRepoOptions{ListOptions: db.ListOptions{Page: 1, PageSize: 10}, OwnerID: 20, Private: true, Collaborate: util.OptionalBoolFalse}, count: 4, }, { name: "PublicRepositoriesOfUserIncludingCollaborative", - opts: &SearchRepoOptions{ListOptions: ListOptions{Page: 1, PageSize: 10}, OwnerID: 15}, + opts: &SearchRepoOptions{ListOptions: db.ListOptions{Page: 1, PageSize: 10}, OwnerID: 15}, count: 5, }, { name: "PublicRepositoriesOfUser2IncludingCollaborative", - opts: &SearchRepoOptions{ListOptions: ListOptions{Page: 1, PageSize: 10}, OwnerID: 18}, + opts: &SearchRepoOptions{ListOptions: db.ListOptions{Page: 1, PageSize: 10}, OwnerID: 18}, count: 1, }, { name: "PublicRepositoriesOfUser3IncludingCollaborative", - opts: &SearchRepoOptions{ListOptions: ListOptions{Page: 1, PageSize: 10}, OwnerID: 20}, + opts: &SearchRepoOptions{ListOptions: db.ListOptions{Page: 1, PageSize: 10}, OwnerID: 20}, count: 3, }, { name: "PublicAndPrivateRepositoriesOfUserIncludingCollaborative", - opts: &SearchRepoOptions{ListOptions: ListOptions{Page: 1, PageSize: 10}, OwnerID: 15, Private: true}, + opts: &SearchRepoOptions{ListOptions: db.ListOptions{Page: 1, PageSize: 10}, OwnerID: 15, Private: true}, count: 9, }, { name: "PublicAndPrivateRepositoriesOfUser2IncludingCollaborative", - opts: &SearchRepoOptions{ListOptions: ListOptions{Page: 1, PageSize: 10}, OwnerID: 18, Private: true}, + opts: &SearchRepoOptions{ListOptions: db.ListOptions{Page: 1, PageSize: 10}, OwnerID: 18, Private: true}, count: 4, }, { name: "PublicAndPrivateRepositoriesOfUser3IncludingCollaborative", - opts: &SearchRepoOptions{ListOptions: ListOptions{Page: 1, PageSize: 10}, OwnerID: 20, Private: true}, + opts: &SearchRepoOptions{ListOptions: db.ListOptions{Page: 1, PageSize: 10}, OwnerID: 20, Private: true}, count: 7, }, { name: "PublicRepositoriesOfOrganization", - opts: &SearchRepoOptions{ListOptions: ListOptions{Page: 1, PageSize: 10}, OwnerID: 17, Collaborate: util.OptionalBoolFalse}, + opts: &SearchRepoOptions{ListOptions: db.ListOptions{Page: 1, PageSize: 10}, OwnerID: 17, Collaborate: util.OptionalBoolFalse}, count: 1, }, { name: "PublicAndPrivateRepositoriesOfOrganization", - opts: &SearchRepoOptions{ListOptions: ListOptions{Page: 1, PageSize: 10}, OwnerID: 17, Private: true, Collaborate: util.OptionalBoolFalse}, + opts: &SearchRepoOptions{ListOptions: db.ListOptions{Page: 1, PageSize: 10}, OwnerID: 17, Private: true, Collaborate: util.OptionalBoolFalse}, count: 2, }, { name: "AllPublic/PublicRepositoriesByName", - opts: &SearchRepoOptions{Keyword: "big_test_", ListOptions: ListOptions{PageSize: 10}, AllPublic: true, Collaborate: util.OptionalBoolFalse}, + opts: &SearchRepoOptions{Keyword: "big_test_", ListOptions: db.ListOptions{PageSize: 10}, AllPublic: true, Collaborate: util.OptionalBoolFalse}, count: 7, }, { name: "AllPublic/PublicAndPrivateRepositoriesByName", - opts: &SearchRepoOptions{Keyword: "big_test_", ListOptions: ListOptions{Page: 1, PageSize: 10}, Private: true, AllPublic: true, Collaborate: util.OptionalBoolFalse}, + opts: &SearchRepoOptions{Keyword: "big_test_", ListOptions: db.ListOptions{Page: 1, PageSize: 10}, Private: true, AllPublic: true, Collaborate: util.OptionalBoolFalse}, count: 14, }, { name: "AllPublic/PublicRepositoriesOfUserIncludingCollaborative", - opts: &SearchRepoOptions{ListOptions: ListOptions{Page: 1, PageSize: 10}, OwnerID: 15, AllPublic: true, Template: util.OptionalBoolFalse}, + opts: &SearchRepoOptions{ListOptions: db.ListOptions{Page: 1, PageSize: 10}, OwnerID: 15, AllPublic: true, Template: util.OptionalBoolFalse}, count: 28, }, { name: "AllPublic/PublicAndPrivateRepositoriesOfUserIncludingCollaborative", - opts: &SearchRepoOptions{ListOptions: ListOptions{Page: 1, PageSize: 10}, OwnerID: 15, Private: true, AllPublic: true, AllLimited: true, Template: util.OptionalBoolFalse}, + opts: &SearchRepoOptions{ListOptions: db.ListOptions{Page: 1, PageSize: 10}, OwnerID: 15, Private: true, AllPublic: true, AllLimited: true, Template: util.OptionalBoolFalse}, count: 33, }, { name: "AllPublic/PublicAndPrivateRepositoriesOfUserIncludingCollaborativeByName", - opts: &SearchRepoOptions{Keyword: "test", ListOptions: ListOptions{Page: 1, PageSize: 10}, OwnerID: 15, Private: true, AllPublic: true}, + opts: &SearchRepoOptions{Keyword: "test", ListOptions: db.ListOptions{Page: 1, PageSize: 10}, OwnerID: 15, Private: true, AllPublic: true}, count: 15, }, { name: "AllPublic/PublicAndPrivateRepositoriesOfUser2IncludingCollaborativeByName", - opts: &SearchRepoOptions{Keyword: "test", ListOptions: ListOptions{Page: 1, PageSize: 10}, OwnerID: 18, Private: true, AllPublic: true}, + opts: &SearchRepoOptions{Keyword: "test", ListOptions: db.ListOptions{Page: 1, PageSize: 10}, OwnerID: 18, Private: true, AllPublic: true}, count: 13, }, { name: "AllPublic/PublicRepositoriesOfOrganization", - opts: &SearchRepoOptions{ListOptions: ListOptions{Page: 1, PageSize: 10}, OwnerID: 17, AllPublic: true, Collaborate: util.OptionalBoolFalse, Template: util.OptionalBoolFalse}, + opts: &SearchRepoOptions{ListOptions: db.ListOptions{Page: 1, PageSize: 10}, OwnerID: 17, AllPublic: true, Collaborate: util.OptionalBoolFalse, Template: util.OptionalBoolFalse}, count: 28, }, { name: "AllTemplates", - opts: &SearchRepoOptions{ListOptions: ListOptions{Page: 1, PageSize: 10}, Template: util.OptionalBoolTrue}, + opts: &SearchRepoOptions{ListOptions: db.ListOptions{Page: 1, PageSize: 10}, Template: util.OptionalBoolTrue}, count: 2, }, } diff --git a/models/repo_sign.go b/models/repo_sign.go index be9309ed4e..ae0895df76 100644 --- a/models/repo_sign.go +++ b/models/repo_sign.go @@ -7,6 +7,7 @@ package models import ( "strings" + "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/process" @@ -120,7 +121,7 @@ Loop: case always: break Loop case pubkey: - keys, err := ListGPGKeys(u.ID, ListOptions{}) + keys, err := ListGPGKeys(u.ID, db.ListOptions{}) if err != nil { return false, "", nil, err } @@ -156,7 +157,7 @@ Loop: case always: break Loop case pubkey: - keys, err := ListGPGKeys(u.ID, ListOptions{}) + keys, err := ListGPGKeys(u.ID, db.ListOptions{}) if err != nil { return false, "", nil, err } @@ -209,7 +210,7 @@ Loop: case always: break Loop case pubkey: - keys, err := ListGPGKeys(u.ID, ListOptions{}) + keys, err := ListGPGKeys(u.ID, db.ListOptions{}) if err != nil { return false, "", nil, err } diff --git a/models/repo_transfer.go b/models/repo_transfer.go index e3eb756eb4..fe50c1cc04 100644 --- a/models/repo_transfer.go +++ b/models/repo_transfer.go @@ -266,7 +266,7 @@ func TransferOwnership(doer *User, newOwnerName string, repo *Repository) (err e } // Remove redundant collaborators. - collaborators, err := repo.getCollaborators(sess, ListOptions{}) + collaborators, err := repo.getCollaborators(sess, db.ListOptions{}) if err != nil { return fmt.Errorf("getCollaborators: %v", err) } diff --git a/models/repo_unit.go b/models/repo_unit.go index c35312be60..7061119bd8 100644 --- a/models/repo_unit.go +++ b/models/repo_unit.go @@ -8,6 +8,7 @@ import ( "fmt" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/login" "code.gitea.io/gitea/modules/json" "code.gitea.io/gitea/modules/timeutil" @@ -153,7 +154,7 @@ func (cfg *PullRequestsConfig) AllowedMergeStyleCount() int { func (r *RepoUnit) BeforeSet(colName string, val xorm.Cell) { switch colName { case "type": - switch UnitType(Cell2Int64(val)) { + switch UnitType(login.Cell2Int64(val)) { case UnitTypeCode, UnitTypeReleases, UnitTypeWiki, UnitTypeProjects: r.Config = new(UnitConfig) case UnitTypeExternalWiki: diff --git a/models/repo_watch.go b/models/repo_watch.go index d3720fe857..b37d47874e 100644 --- a/models/repo_watch.go +++ b/models/repo_watch.go @@ -165,12 +165,12 @@ func getRepoWatchersIDs(e db.Engine, repoID int64) ([]int64, error) { } // GetWatchers returns range of users watching given repository. -func (repo *Repository) GetWatchers(opts ListOptions) ([]*User, error) { +func (repo *Repository) GetWatchers(opts db.ListOptions) ([]*User, error) { sess := db.GetEngine(db.DefaultContext).Where("watch.repo_id=?", repo.ID). Join("LEFT", "watch", "`user`.id=`watch`.user_id"). And("`watch`.mode<>?", RepoWatchModeDont) if opts.Page > 0 { - sess = setSessionPagination(sess, &opts) + sess = db.SetSessionPagination(sess, &opts) users := make([]*User, 0, opts.PageSize) return users, sess.Find(&users) diff --git a/models/repo_watch_test.go b/models/repo_watch_test.go index 1a94b8ad30..52222af2ca 100644 --- a/models/repo_watch_test.go +++ b/models/repo_watch_test.go @@ -60,7 +60,7 @@ func TestRepository_GetWatchers(t *testing.T) { assert.NoError(t, db.PrepareTestDatabase()) repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) - watchers, err := repo.GetWatchers(ListOptions{Page: 1}) + watchers, err := repo.GetWatchers(db.ListOptions{Page: 1}) assert.NoError(t, err) assert.Len(t, watchers, repo.NumWatches) for _, watcher := range watchers { @@ -68,7 +68,7 @@ func TestRepository_GetWatchers(t *testing.T) { } repo = db.AssertExistsAndLoadBean(t, &Repository{ID: 9}).(*Repository) - watchers, err = repo.GetWatchers(ListOptions{Page: 1}) + watchers, err = repo.GetWatchers(db.ListOptions{Page: 1}) assert.NoError(t, err) assert.Len(t, watchers, 0) } @@ -114,7 +114,7 @@ func TestWatchIfAuto(t *testing.T) { assert.NoError(t, db.PrepareTestDatabase()) repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) - watchers, err := repo.GetWatchers(ListOptions{Page: 1}) + watchers, err := repo.GetWatchers(db.ListOptions{Page: 1}) assert.NoError(t, err) assert.Len(t, watchers, repo.NumWatches) @@ -124,13 +124,13 @@ func TestWatchIfAuto(t *testing.T) { // Must not add watch assert.NoError(t, WatchIfAuto(8, 1, true)) - watchers, err = repo.GetWatchers(ListOptions{Page: 1}) + watchers, err = repo.GetWatchers(db.ListOptions{Page: 1}) assert.NoError(t, err) assert.Len(t, watchers, prevCount) // Should not add watch assert.NoError(t, WatchIfAuto(10, 1, true)) - watchers, err = repo.GetWatchers(ListOptions{Page: 1}) + watchers, err = repo.GetWatchers(db.ListOptions{Page: 1}) assert.NoError(t, err) assert.Len(t, watchers, prevCount) @@ -138,31 +138,31 @@ func TestWatchIfAuto(t *testing.T) { // Must not add watch assert.NoError(t, WatchIfAuto(8, 1, true)) - watchers, err = repo.GetWatchers(ListOptions{Page: 1}) + watchers, err = repo.GetWatchers(db.ListOptions{Page: 1}) assert.NoError(t, err) assert.Len(t, watchers, prevCount) // Should not add watch assert.NoError(t, WatchIfAuto(12, 1, false)) - watchers, err = repo.GetWatchers(ListOptions{Page: 1}) + watchers, err = repo.GetWatchers(db.ListOptions{Page: 1}) assert.NoError(t, err) assert.Len(t, watchers, prevCount) // Should add watch assert.NoError(t, WatchIfAuto(12, 1, true)) - watchers, err = repo.GetWatchers(ListOptions{Page: 1}) + watchers, err = repo.GetWatchers(db.ListOptions{Page: 1}) assert.NoError(t, err) assert.Len(t, watchers, prevCount+1) // Should remove watch, inhibit from adding auto assert.NoError(t, WatchRepo(12, 1, false)) - watchers, err = repo.GetWatchers(ListOptions{Page: 1}) + watchers, err = repo.GetWatchers(db.ListOptions{Page: 1}) assert.NoError(t, err) assert.Len(t, watchers, prevCount) // Must not add watch assert.NoError(t, WatchIfAuto(12, 1, true)) - watchers, err = repo.GetWatchers(ListOptions{Page: 1}) + watchers, err = repo.GetWatchers(db.ListOptions{Page: 1}) assert.NoError(t, err) assert.Len(t, watchers, prevCount) } diff --git a/models/review.go b/models/review.go index 3f81c39b2f..5b12e6ffa2 100644 --- a/models/review.go +++ b/models/review.go @@ -172,7 +172,7 @@ func GetReviewByID(id int64) (*Review, error) { // FindReviewOptions represent possible filters to find reviews type FindReviewOptions struct { - ListOptions + db.ListOptions Type ReviewType IssueID int64 ReviewerID int64 @@ -200,7 +200,7 @@ func findReviews(e db.Engine, opts FindReviewOptions) ([]*Review, error) { reviews := make([]*Review, 0, 10) sess := e.Where(opts.toCond()) if opts.Page > 0 { - sess = setSessionPagination(sess, &opts) + sess = db.SetSessionPagination(sess, &opts) } return reviews, sess. Asc("created_unix"). diff --git a/models/ssh_key.go b/models/ssh_key.go index 41016537eb..c08fb72e75 100644 --- a/models/ssh_key.go +++ b/models/ssh_key.go @@ -11,6 +11,7 @@ import ( "time" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/login" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/util" @@ -197,10 +198,10 @@ func SearchPublicKey(uid int64, fingerprint string) ([]*PublicKey, error) { } // ListPublicKeys returns a list of public keys belongs to given user. -func ListPublicKeys(uid int64, listOptions ListOptions) ([]*PublicKey, error) { +func ListPublicKeys(uid int64, listOptions db.ListOptions) ([]*PublicKey, error) { sess := db.GetEngine(db.DefaultContext).Where("owner_id = ? AND type != ?", uid, KeyTypePrincipal) if listOptions.Page != 0 { - sess = setSessionPagination(sess, &listOptions) + sess = db.SetSessionPagination(sess, &listOptions) keys := make([]*PublicKey, 0, listOptions.PageSize) return keys, sess.Find(&keys) @@ -255,7 +256,7 @@ func deletePublicKeys(e db.Engine, keyIDs ...int64) error { // PublicKeysAreExternallyManaged returns whether the provided KeyID represents an externally managed Key func PublicKeysAreExternallyManaged(keys []*PublicKey) ([]bool, error) { - sources := make([]*LoginSource, 0, 5) + sources := make([]*login.Source, 0, 5) externals := make([]bool, len(keys)) keyloop: for i, key := range keys { @@ -264,7 +265,7 @@ keyloop: continue keyloop } - var source *LoginSource + var source *login.Source sourceloop: for _, s := range sources { @@ -276,11 +277,11 @@ keyloop: if source == nil { var err error - source, err = GetLoginSourceByID(key.LoginSourceID) + source, err = login.GetSourceByID(key.LoginSourceID) if err != nil { - if IsErrLoginSourceNotExist(err) { + if login.IsErrSourceNotExist(err) { externals[i] = false - sources[i] = &LoginSource{ + sources[i] = &login.Source{ ID: key.LoginSourceID, } continue keyloop @@ -289,7 +290,7 @@ keyloop: } } - if sshKeyProvider, ok := source.Cfg.(SSHKeyProvider); ok && sshKeyProvider.ProvidesSSHKeys() { + if sshKeyProvider, ok := source.Cfg.(login.SSHKeyProvider); ok && sshKeyProvider.ProvidesSSHKeys() { // Disable setting SSH keys for this user externals[i] = true } @@ -307,14 +308,14 @@ func PublicKeyIsExternallyManaged(id int64) (bool, error) { if key.LoginSourceID == 0 { return false, nil } - source, err := GetLoginSourceByID(key.LoginSourceID) + source, err := login.GetSourceByID(key.LoginSourceID) if err != nil { - if IsErrLoginSourceNotExist(err) { + if login.IsErrSourceNotExist(err) { return false, nil } return false, err } - if sshKeyProvider, ok := source.Cfg.(SSHKeyProvider); ok && sshKeyProvider.ProvidesSSHKeys() { + if sshKeyProvider, ok := source.Cfg.(login.SSHKeyProvider); ok && sshKeyProvider.ProvidesSSHKeys() { // Disable setting SSH keys for this user return true, nil } @@ -387,7 +388,7 @@ func deleteKeysMarkedForDeletion(keys []string) (bool, error) { } // AddPublicKeysBySource add a users public keys. Returns true if there are changes. -func AddPublicKeysBySource(usr *User, s *LoginSource, sshPublicKeys []string) bool { +func AddPublicKeysBySource(usr *User, s *login.Source, sshPublicKeys []string) bool { var sshKeysNeedUpdate bool for _, sshKey := range sshPublicKeys { var err error @@ -425,7 +426,7 @@ func AddPublicKeysBySource(usr *User, s *LoginSource, sshPublicKeys []string) bo } // SynchronizePublicKeys updates a users public keys. Returns true if there are changes. -func SynchronizePublicKeys(usr *User, s *LoginSource, sshPublicKeys []string) bool { +func SynchronizePublicKeys(usr *User, s *login.Source, sshPublicKeys []string) bool { var sshKeysNeedUpdate bool log.Trace("synchronizePublicKeys[%s]: Handling Public SSH Key synchronization for user %s", s.Name, usr.Name) diff --git a/models/ssh_key_deploy.go b/models/ssh_key_deploy.go index 3b9a168280..34cf03e925 100644 --- a/models/ssh_key_deploy.go +++ b/models/ssh_key_deploy.go @@ -271,7 +271,7 @@ func deleteDeployKey(sess db.Engine, doer *User, id int64) error { // ListDeployKeysOptions are options for ListDeployKeys type ListDeployKeysOptions struct { - ListOptions + db.ListOptions RepoID int64 KeyID int64 Fingerprint string @@ -300,7 +300,7 @@ func listDeployKeys(e db.Engine, opts *ListDeployKeysOptions) ([]*DeployKey, err sess := e.Where(opts.toCond()) if opts.Page != 0 { - sess = setSessionPagination(sess, opts) + sess = db.SetSessionPagination(sess, opts) keys := make([]*DeployKey, 0, opts.PageSize) return keys, sess.Find(&keys) diff --git a/models/ssh_key_principals.go b/models/ssh_key_principals.go index 383693e14e..44b2ee0bb4 100644 --- a/models/ssh_key_principals.go +++ b/models/ssh_key_principals.go @@ -112,10 +112,10 @@ func CheckPrincipalKeyString(user *User, content string) (_ string, err error) { } // ListPrincipalKeys returns a list of principals belongs to given user. -func ListPrincipalKeys(uid int64, listOptions ListOptions) ([]*PublicKey, error) { +func ListPrincipalKeys(uid int64, listOptions db.ListOptions) ([]*PublicKey, error) { sess := db.GetEngine(db.DefaultContext).Where("owner_id = ? AND type = ?", uid, KeyTypePrincipal) if listOptions.Page != 0 { - sess = setSessionPagination(sess, &listOptions) + sess = db.SetSessionPagination(sess, &listOptions) keys := make([]*PublicKey, 0, listOptions.PageSize) return keys, sess.Find(&keys) diff --git a/models/star.go b/models/star.go index ad583f1998..ee7791513d 100644 --- a/models/star.go +++ b/models/star.go @@ -74,11 +74,11 @@ func isStaring(e db.Engine, userID, repoID int64) bool { } // GetStargazers returns the users that starred the repo. -func (repo *Repository) GetStargazers(opts ListOptions) ([]*User, error) { +func (repo *Repository) GetStargazers(opts db.ListOptions) ([]*User, error) { sess := db.GetEngine(db.DefaultContext).Where("star.repo_id = ?", repo.ID). Join("LEFT", "star", "`user`.id = star.uid") if opts.Page > 0 { - sess = setSessionPagination(sess, &opts) + sess = db.SetSessionPagination(sess, &opts) users := make([]*User, 0, opts.PageSize) return users, sess.Find(&users) diff --git a/models/star_test.go b/models/star_test.go index c0c0a607be..326da8a861 100644 --- a/models/star_test.go +++ b/models/star_test.go @@ -34,7 +34,7 @@ func TestRepository_GetStargazers(t *testing.T) { // repo with stargazers assert.NoError(t, db.PrepareTestDatabase()) repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 4}).(*Repository) - gazers, err := repo.GetStargazers(ListOptions{Page: 0}) + gazers, err := repo.GetStargazers(db.ListOptions{Page: 0}) assert.NoError(t, err) if assert.Len(t, gazers, 1) { assert.Equal(t, int64(2), gazers[0].ID) @@ -45,7 +45,7 @@ func TestRepository_GetStargazers2(t *testing.T) { // repo with stargazers assert.NoError(t, db.PrepareTestDatabase()) repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 3}).(*Repository) - gazers, err := repo.GetStargazers(ListOptions{Page: 0}) + gazers, err := repo.GetStargazers(db.ListOptions{Page: 0}) assert.NoError(t, err) assert.Len(t, gazers, 0) } diff --git a/models/statistic.go b/models/statistic.go index d192a971f5..43b1afbc48 100644 --- a/models/statistic.go +++ b/models/statistic.go @@ -4,7 +4,10 @@ package models -import "code.gitea.io/gitea/models/db" +import ( + "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/login" +) // Statistic contains the database statistics type Statistic struct { @@ -52,7 +55,7 @@ func GetStatistic() (stats Statistic) { stats.Counter.Follow, _ = db.GetEngine(db.DefaultContext).Count(new(Follow)) stats.Counter.Mirror, _ = db.GetEngine(db.DefaultContext).Count(new(Mirror)) stats.Counter.Release, _ = db.GetEngine(db.DefaultContext).Count(new(Release)) - stats.Counter.LoginSource = CountLoginSources() + stats.Counter.LoginSource = login.CountSources() stats.Counter.Webhook, _ = db.GetEngine(db.DefaultContext).Count(new(Webhook)) stats.Counter.Milestone, _ = db.GetEngine(db.DefaultContext).Count(new(Milestone)) stats.Counter.Label, _ = db.GetEngine(db.DefaultContext).Count(new(Label)) diff --git a/models/token.go b/models/token.go index 48ae795424..07d013ac8e 100644 --- a/models/token.go +++ b/models/token.go @@ -147,7 +147,7 @@ func AccessTokenByNameExists(token *AccessToken) (bool, error) { // ListAccessTokensOptions contain filter options type ListAccessTokensOptions struct { - ListOptions + db.ListOptions Name string UserID int64 } @@ -163,7 +163,7 @@ func ListAccessTokens(opts ListAccessTokensOptions) ([]*AccessToken, error) { sess = sess.Desc("id") if opts.Page != 0 { - sess = setSessionPagination(sess, &opts) + sess = db.SetSessionPagination(sess, &opts) tokens := make([]*AccessToken, 0, opts.PageSize) return tokens, sess.Find(&tokens) diff --git a/models/topic.go b/models/topic.go index cf563e9b11..6eb8c67b8d 100644 --- a/models/topic.go +++ b/models/topic.go @@ -164,7 +164,7 @@ func removeTopicsFromRepo(e db.Engine, repoID int64) error { // FindTopicOptions represents the options when fdin topics type FindTopicOptions struct { - ListOptions + db.ListOptions RepoID int64 Keyword string } @@ -189,7 +189,7 @@ func FindTopics(opts *FindTopicOptions) ([]*Topic, int64, error) { sess.Join("INNER", "repo_topic", "repo_topic.topic_id = topic.id") } if opts.PageSize != 0 && opts.Page != 0 { - sess = setSessionPagination(sess, opts) + sess = db.SetSessionPagination(sess, opts) } topics := make([]*Topic, 0, 10) total, err := sess.Desc("topic.repo_count").FindAndCount(&topics) diff --git a/models/topic_test.go b/models/topic_test.go index 9f6352e7e7..b069deaba3 100644 --- a/models/topic_test.go +++ b/models/topic_test.go @@ -23,7 +23,7 @@ func TestAddTopic(t *testing.T) { assert.Len(t, topics, totalNrOfTopics) topics, total, err := FindTopics(&FindTopicOptions{ - ListOptions: ListOptions{Page: 1, PageSize: 2}, + ListOptions: db.ListOptions{Page: 1, PageSize: 2}, }) assert.NoError(t, err) assert.Len(t, topics, 2) diff --git a/models/user.go b/models/user.go index fc5d417d36..fb40a0acc8 100644 --- a/models/user.go +++ b/models/user.go @@ -21,6 +21,7 @@ import ( "unicode/utf8" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/login" "code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/log" @@ -106,7 +107,7 @@ type User struct { // is to change his/her password after registration. MustChangePassword bool `xorm:"NOT NULL DEFAULT false"` - LoginType LoginType + LoginType login.Type LoginSource int64 `xorm:"NOT NULL DEFAULT 0"` LoginName string Type UserType @@ -169,7 +170,7 @@ func init() { // SearchOrganizationsOptions options to filter organizations type SearchOrganizationsOptions struct { - ListOptions + db.ListOptions All bool } @@ -241,12 +242,12 @@ func GetAllUsers() ([]*User, error) { // IsLocal returns true if user login type is LoginPlain. func (u *User) IsLocal() bool { - return u.LoginType <= LoginPlain + return u.LoginType <= login.Plain } // IsOAuth2 returns true if user login type is LoginOAuth2. func (u *User) IsOAuth2() bool { - return u.LoginType == LoginOAuth2 + return u.LoginType == login.OAuth2 } // HasForkedRepo checks if user has already forked a repository with given ID. @@ -331,13 +332,13 @@ func (u *User) GenerateEmailActivateCode(email string) string { } // GetFollowers returns range of user's followers. -func (u *User) GetFollowers(listOptions ListOptions) ([]*User, error) { +func (u *User) GetFollowers(listOptions db.ListOptions) ([]*User, error) { sess := db.GetEngine(db.DefaultContext). Where("follow.follow_id=?", u.ID). Join("LEFT", "follow", "`user`.id=follow.user_id") if listOptions.Page != 0 { - sess = setSessionPagination(sess, &listOptions) + sess = db.SetSessionPagination(sess, &listOptions) users := make([]*User, 0, listOptions.PageSize) return users, sess.Find(&users) @@ -353,13 +354,13 @@ func (u *User) IsFollowing(followID int64) bool { } // GetFollowing returns range of user's following. -func (u *User) GetFollowing(listOptions ListOptions) ([]*User, error) { +func (u *User) GetFollowing(listOptions db.ListOptions) ([]*User, error) { sess := db.GetEngine(db.DefaultContext). Where("follow.user_id=?", u.ID). Join("LEFT", "follow", "`user`.id=follow.follow_id") if listOptions.Page != 0 { - sess = setSessionPagination(sess, &listOptions) + sess = db.SetSessionPagination(sess, &listOptions) users := make([]*User, 0, listOptions.PageSize) return users, sess.Find(&users) @@ -542,7 +543,7 @@ func (u *User) GetOrganizationCount() (int64, error) { } // GetRepositories returns repositories that user owns, including private repositories. -func (u *User) GetRepositories(listOpts ListOptions, names ...string) (err error) { +func (u *User) GetRepositories(listOpts db.ListOptions, names ...string) (err error) { u.Repos, _, err = GetUserRepositories(&SearchRepoOptions{Actor: u, Private: true, ListOptions: listOpts, LowerNames: names}) return err } @@ -1252,7 +1253,7 @@ func deleteUser(e db.Engine, u *User) error { // ***** END: PublicKey ***** // ***** START: GPGPublicKey ***** - keys, err := listGPGKeys(e, u.ID, ListOptions{}) + keys, err := listGPGKeys(e, u.ID, db.ListOptions{}) if err != nil { return fmt.Errorf("ListGPGKeys: %v", err) } @@ -1488,7 +1489,7 @@ func GetUserIDsByNames(names []string, ignoreNonExistent bool) ([]int64, error) } // GetUsersBySource returns a list of Users for a login source -func GetUsersBySource(s *LoginSource) ([]*User, error) { +func GetUsersBySource(s *login.Source) ([]*User, error) { var users []*User err := db.GetEngine(db.DefaultContext).Where("login_type = ? AND login_source = ?", s.Type, s.ID).Find(&users) return users, err @@ -1592,7 +1593,7 @@ func GetUser(user *User) (bool, error) { // SearchUserOptions contains the options for searching type SearchUserOptions struct { - ListOptions + db.ListOptions Keyword string Type UserType UID int64 @@ -1675,7 +1676,7 @@ func SearchUsers(opts *SearchUserOptions) (users []*User, _ int64, _ error) { sess := db.GetEngine(db.DefaultContext).Where(cond).OrderBy(opts.OrderBy.String()) if opts.Page != 0 { - sess = setSessionPagination(sess, opts) + sess = db.SetSessionPagination(sess, opts) } users = make([]*User, 0, opts.PageSize) @@ -1683,7 +1684,7 @@ func SearchUsers(opts *SearchUserOptions) (users []*User, _ int64, _ error) { } // GetStarredRepos returns the repos starred by a particular user -func GetStarredRepos(userID int64, private bool, listOptions ListOptions) ([]*Repository, error) { +func GetStarredRepos(userID int64, private bool, listOptions db.ListOptions) ([]*Repository, error) { sess := db.GetEngine(db.DefaultContext).Where("star.uid=?", userID). Join("LEFT", "star", "`repository`.id=`star`.repo_id") if !private { @@ -1691,7 +1692,7 @@ func GetStarredRepos(userID int64, private bool, listOptions ListOptions) ([]*Re } if listOptions.Page != 0 { - sess = setSessionPagination(sess, &listOptions) + sess = db.SetSessionPagination(sess, &listOptions) repos := make([]*Repository, 0, listOptions.PageSize) return repos, sess.Find(&repos) @@ -1702,7 +1703,7 @@ func GetStarredRepos(userID int64, private bool, listOptions ListOptions) ([]*Re } // GetWatchedRepos returns the repos watched by a particular user -func GetWatchedRepos(userID int64, private bool, listOptions ListOptions) ([]*Repository, int64, error) { +func GetWatchedRepos(userID int64, private bool, listOptions db.ListOptions) ([]*Repository, int64, error) { sess := db.GetEngine(db.DefaultContext).Where("watch.user_id=?", userID). And("`watch`.mode<>?", RepoWatchModeDont). Join("LEFT", "watch", "`repository`.id=`watch`.repo_id") @@ -1711,7 +1712,7 @@ func GetWatchedRepos(userID int64, private bool, listOptions ListOptions) ([]*Re } if listOptions.Page != 0 { - sess = setSessionPagination(sess, &listOptions) + sess = db.SetSessionPagination(sess, &listOptions) repos := make([]*Repository, 0, listOptions.PageSize) total, err := sess.FindAndCount(&repos) diff --git a/models/user_mail.go b/models/user_mail.go index 51d34d2682..caa931788d 100644 --- a/models/user_mail.go +++ b/models/user_mail.go @@ -301,7 +301,7 @@ const ( // SearchEmailOptions are options to search e-mail addresses for the admin panel type SearchEmailOptions struct { - ListOptions + db.ListOptions Keyword string SortType SearchEmailOrderBy IsPrimary util.OptionalBool @@ -357,7 +357,7 @@ func SearchEmails(opts *SearchEmailOptions) ([]*SearchEmailResult, int64, error) orderby = SearchEmailOrderByEmail.String() } - opts.setDefaultValues() + opts.SetDefaultValues() emails := make([]*SearchEmailResult, 0, opts.PageSize) err = db.GetEngine(db.DefaultContext).Table("email_address"). diff --git a/models/user_mail_test.go b/models/user_mail_test.go index 22e5f786bf..384f28b7bf 100644 --- a/models/user_mail_test.go +++ b/models/user_mail_test.go @@ -189,7 +189,7 @@ func TestListEmails(t *testing.T) { // Must find all users and their emails opts := &SearchEmailOptions{ - ListOptions: ListOptions{ + ListOptions: db.ListOptions{ PageSize: 10000, }, } @@ -241,7 +241,7 @@ func TestListEmails(t *testing.T) { // Must find more than one page, but retrieve only one opts = &SearchEmailOptions{ - ListOptions: ListOptions{ + ListOptions: db.ListOptions{ PageSize: 5, Page: 1, }, diff --git a/models/user_test.go b/models/user_test.go index 6c616a60a9..bf796a8c62 100644 --- a/models/user_test.go +++ b/models/user_test.go @@ -11,6 +11,7 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/login" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/modules/util" @@ -18,6 +19,14 @@ import ( "github.com/stretchr/testify/assert" ) +func TestOAuth2Application_LoadUser(t *testing.T) { + assert.NoError(t, db.PrepareTestDatabase()) + app := db.AssertExistsAndLoadBean(t, &login.OAuth2Application{ID: 1}).(*login.OAuth2Application) + user, err := GetUserByID(app.UID) + assert.NoError(t, err) + assert.NotNil(t, user) +} + func TestUserIsPublicMember(t *testing.T) { assert.NoError(t, db.PrepareTestDatabase()) @@ -116,19 +125,19 @@ func TestSearchUsers(t *testing.T) { testSuccess(opts, expectedOrgIDs) } - testOrgSuccess(&SearchUserOptions{OrderBy: "id ASC", ListOptions: ListOptions{Page: 1, PageSize: 2}}, + testOrgSuccess(&SearchUserOptions{OrderBy: "id ASC", ListOptions: db.ListOptions{Page: 1, PageSize: 2}}, []int64{3, 6}) - testOrgSuccess(&SearchUserOptions{OrderBy: "id ASC", ListOptions: ListOptions{Page: 2, PageSize: 2}}, + testOrgSuccess(&SearchUserOptions{OrderBy: "id ASC", ListOptions: db.ListOptions{Page: 2, PageSize: 2}}, []int64{7, 17}) - testOrgSuccess(&SearchUserOptions{OrderBy: "id ASC", ListOptions: ListOptions{Page: 3, PageSize: 2}}, + testOrgSuccess(&SearchUserOptions{OrderBy: "id ASC", ListOptions: db.ListOptions{Page: 3, PageSize: 2}}, []int64{19, 25}) - testOrgSuccess(&SearchUserOptions{OrderBy: "id ASC", ListOptions: ListOptions{Page: 4, PageSize: 2}}, + testOrgSuccess(&SearchUserOptions{OrderBy: "id ASC", ListOptions: db.ListOptions{Page: 4, PageSize: 2}}, []int64{26}) - testOrgSuccess(&SearchUserOptions{ListOptions: ListOptions{Page: 5, PageSize: 2}}, + testOrgSuccess(&SearchUserOptions{ListOptions: db.ListOptions{Page: 5, PageSize: 2}}, []int64{}) // test users @@ -137,20 +146,20 @@ func TestSearchUsers(t *testing.T) { testSuccess(opts, expectedUserIDs) } - testUserSuccess(&SearchUserOptions{OrderBy: "id ASC", ListOptions: ListOptions{Page: 1}}, + testUserSuccess(&SearchUserOptions{OrderBy: "id ASC", ListOptions: db.ListOptions{Page: 1}}, []int64{1, 2, 4, 5, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 20, 21, 24, 27, 28, 29, 30}) - testUserSuccess(&SearchUserOptions{ListOptions: ListOptions{Page: 1}, IsActive: util.OptionalBoolFalse}, + testUserSuccess(&SearchUserOptions{ListOptions: db.ListOptions{Page: 1}, IsActive: util.OptionalBoolFalse}, []int64{9}) - testUserSuccess(&SearchUserOptions{OrderBy: "id ASC", ListOptions: ListOptions{Page: 1}, IsActive: util.OptionalBoolTrue}, + testUserSuccess(&SearchUserOptions{OrderBy: "id ASC", ListOptions: db.ListOptions{Page: 1}, IsActive: util.OptionalBoolTrue}, []int64{1, 2, 4, 5, 8, 10, 11, 12, 13, 14, 15, 16, 18, 20, 21, 24, 28, 29, 30}) - testUserSuccess(&SearchUserOptions{Keyword: "user1", OrderBy: "id ASC", ListOptions: ListOptions{Page: 1}, IsActive: util.OptionalBoolTrue}, + testUserSuccess(&SearchUserOptions{Keyword: "user1", OrderBy: "id ASC", ListOptions: db.ListOptions{Page: 1}, IsActive: util.OptionalBoolTrue}, []int64{1, 10, 11, 12, 13, 14, 15, 16, 18}) // order by name asc default - testUserSuccess(&SearchUserOptions{Keyword: "user1", ListOptions: ListOptions{Page: 1}, IsActive: util.OptionalBoolTrue}, + testUserSuccess(&SearchUserOptions{Keyword: "user1", ListOptions: db.ListOptions{Page: 1}, IsActive: util.OptionalBoolTrue}, []int64{1, 10, 11, 12, 13, 14, 15, 16, 18}) } @@ -407,7 +416,7 @@ func TestAddLdapSSHPublicKeys(t *testing.T) { assert.NoError(t, db.PrepareTestDatabase()) user := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) - s := &LoginSource{ID: 1} + s := &login.Source{ID: 1} testCases := []struct { keyString string diff --git a/models/webhook.go b/models/webhook.go index 034b37263a..9d04f8f5e4 100644 --- a/models/webhook.go +++ b/models/webhook.go @@ -397,7 +397,7 @@ func GetWebhookByOrgID(orgID, id int64) (*Webhook, error) { // ListWebhookOptions are options to filter webhooks on ListWebhooksByOpts type ListWebhookOptions struct { - ListOptions + db.ListOptions RepoID int64 OrgID int64 IsActive util.OptionalBool @@ -421,7 +421,7 @@ func listWebhooksByOpts(e db.Engine, opts *ListWebhookOptions) ([]*Webhook, erro sess := e.Where(opts.toCond()) if opts.Page != 0 { - sess = setSessionPagination(sess, opts) + sess = db.SetSessionPagination(sess, opts) webhooks := make([]*Webhook, 0, opts.PageSize) err := sess.Find(&webhooks) return webhooks, err |