From c548dde205244a39a26ba98377c0f5cc11da7041 Mon Sep 17 00:00:00 2001 From: JakobDev Date: Fri, 15 Sep 2023 08:13:19 +0200 Subject: [PATCH] More refactoring of `db.DefaultContext` (#27083) Next step of #27065 --- cmd/admin_user_create.go | 2 +- cmd/admin_user_generate_access_token.go | 4 +-- models/auth/token.go | 31 ++++++++-------- models/auth/token_test.go | 35 ++++++++++--------- models/auth/twofactor.go | 21 +++++------ models/issues/comment.go | 4 +-- models/issues/pull_list.go | 14 ++++---- models/issues/pull_test.go | 4 +-- models/repo/attachment.go | 20 +++++------ models/repo/attachment_test.go | 8 ++--- models/repo/star.go | 8 ++--- models/repo/star_test.go | 16 ++++----- models/repo/upload.go | 23 ++++++------ models/repo/watch.go | 8 ++--- models/repo/watch_test.go | 32 ++++++++--------- models/user/openid.go | 14 ++++---- models/user/openid_test.go | 15 ++++---- models/user/setting.go | 32 ++++++++--------- models/user/setting_test.go | 19 +++++----- modules/activitypub/client.go | 5 +-- modules/activitypub/client_test.go | 3 +- modules/activitypub/user_settings.go | 18 +++++----- modules/activitypub/user_settings_test.go | 7 ++-- modules/context/api.go | 2 +- modules/context/repo.go | 2 +- routers/api/packages/alpine/alpine.go | 2 +- routers/api/packages/chef/auth.go | 7 ++-- routers/api/packages/debian/debian.go | 2 +- routers/api/packages/nuget/auth.go | 4 +-- routers/api/packages/rpm/rpm.go | 2 +- routers/api/v1/activitypub/person.go | 2 +- routers/api/v1/api.go | 2 +- routers/api/v1/org/team.go | 2 +- routers/api/v1/repo/issue_attachment.go | 4 +-- .../api/v1/repo/issue_comment_attachment.go | 2 +- routers/api/v1/repo/pull.go | 2 +- routers/api/v1/repo/release_attachment.go | 2 +- routers/api/v1/repo/star.go | 2 +- routers/api/v1/repo/subscriber.go | 2 +- routers/api/v1/repo/teams.go | 6 ++-- routers/api/v1/user/app.go | 12 +++---- routers/api/v1/user/star.go | 4 +-- routers/api/v1/user/watch.go | 2 +- routers/web/admin/users.go | 6 ++-- routers/web/auth/2fa.go | 8 ++--- routers/web/auth/auth.go | 2 +- routers/web/auth/linkaccount.go | 2 +- routers/web/auth/oauth.go | 2 +- routers/web/auth/password.go | 6 ++-- routers/web/org/teams.go | 2 +- routers/web/repo/attachment.go | 4 +-- routers/web/repo/editor.go | 4 +-- routers/web/repo/http.go | 2 +- routers/web/repo/issue.go | 6 ++-- routers/web/repo/middlewares.go | 8 ++--- routers/web/repo/repo.go | 4 +-- routers/web/repo/setting/collaboration.go | 2 +- routers/web/repo/setting/settings_test.go | 9 ++--- routers/web/repo/view.go | 4 +-- routers/web/shared/user/header.go | 2 +- routers/web/user/setting/applications.go | 8 ++--- routers/web/user/setting/packages.go | 2 +- routers/web/user/setting/profile.go | 4 +-- routers/web/user/setting/security/2fa.go | 14 ++++---- routers/web/user/setting/security/openid.go | 6 ++-- routers/web/user/setting/security/security.go | 6 ++-- services/asymkey/sign.go | 8 ++--- services/auth/basic.go | 6 ++-- services/auth/oauth2.go | 18 +++++----- services/issue/content.go | 7 ++-- services/migrations/gitea_uploader_test.go | 2 +- services/org/repo.go | 6 ++-- services/org/repo_test.go | 5 +-- services/packages/alpine/repository.go | 12 +++---- services/packages/debian/repository.go | 12 +++---- services/packages/rpm/repository.go | 15 ++++---- services/pull/check.go | 2 +- services/repository/create_test.go | 2 +- services/repository/delete.go | 20 +++++------ services/repository/delete_test.go | 2 +- services/repository/files/upload.go | 13 ++++--- .../api_activitypub_person_test.go | 3 +- tests/integration/api_packages_chef_test.go | 2 +- 83 files changed, 336 insertions(+), 320 deletions(-) diff --git a/cmd/admin_user_create.go b/cmd/admin_user_create.go index 73afcdcf32..fefe18d39c 100644 --- a/cmd/admin_user_create.go +++ b/cmd/admin_user_create.go @@ -156,7 +156,7 @@ func runCreateUser(c *cli.Context) error { UID: u.ID, } - if err := auth_model.NewAccessToken(t); err != nil { + if err := auth_model.NewAccessToken(ctx, t); err != nil { return err } diff --git a/cmd/admin_user_generate_access_token.go b/cmd/admin_user_generate_access_token.go index 0febb91661..6e78939680 100644 --- a/cmd/admin_user_generate_access_token.go +++ b/cmd/admin_user_generate_access_token.go @@ -63,7 +63,7 @@ func runGenerateAccessToken(c *cli.Context) error { UID: user.ID, } - exist, err := auth_model.AccessTokenByNameExists(t) + exist, err := auth_model.AccessTokenByNameExists(ctx, t) if err != nil { return err } @@ -79,7 +79,7 @@ func runGenerateAccessToken(c *cli.Context) error { t.Scope = accessTokenScope // create the token - if err := auth_model.NewAccessToken(t); err != nil { + if err := auth_model.NewAccessToken(ctx, t); err != nil { return err } diff --git a/models/auth/token.go b/models/auth/token.go index fed03803d5..8abcc622bc 100644 --- a/models/auth/token.go +++ b/models/auth/token.go @@ -5,6 +5,7 @@ package auth import ( + "context" "crypto/subtle" "encoding/hex" "fmt" @@ -95,7 +96,7 @@ func init() { } // NewAccessToken creates new access token. -func NewAccessToken(t *AccessToken) error { +func NewAccessToken(ctx context.Context, t *AccessToken) error { salt, err := util.CryptoRandomString(10) if err != nil { return err @@ -108,7 +109,7 @@ func NewAccessToken(t *AccessToken) error { t.Token = hex.EncodeToString(token) t.TokenHash = HashToken(t.Token, t.TokenSalt) t.TokenLastEight = t.Token[len(t.Token)-8:] - _, err = db.GetEngine(db.DefaultContext).Insert(t) + _, err = db.GetEngine(ctx).Insert(t) return err } @@ -137,7 +138,7 @@ func getAccessTokenIDFromCache(token string) int64 { } // GetAccessTokenBySHA returns access token by given token value -func GetAccessTokenBySHA(token string) (*AccessToken, error) { +func GetAccessTokenBySHA(ctx context.Context, token string) (*AccessToken, error) { if token == "" { return nil, ErrAccessTokenEmpty{} } @@ -158,7 +159,7 @@ func GetAccessTokenBySHA(token string) (*AccessToken, error) { TokenLastEight: lastEight, } // Re-get the token from the db in case it has been deleted in the intervening period - has, err := db.GetEngine(db.DefaultContext).ID(id).Get(accessToken) + has, err := db.GetEngine(ctx).ID(id).Get(accessToken) if err != nil { return nil, err } @@ -169,7 +170,7 @@ func GetAccessTokenBySHA(token string) (*AccessToken, error) { } var tokens []AccessToken - err := db.GetEngine(db.DefaultContext).Table(&AccessToken{}).Where("token_last_eight = ?", lastEight).Find(&tokens) + err := db.GetEngine(ctx).Table(&AccessToken{}).Where("token_last_eight = ?", lastEight).Find(&tokens) if err != nil { return nil, err } else if len(tokens) == 0 { @@ -189,8 +190,8 @@ func GetAccessTokenBySHA(token string) (*AccessToken, error) { } // AccessTokenByNameExists checks if a token name has been used already by a user. -func AccessTokenByNameExists(token *AccessToken) (bool, error) { - return db.GetEngine(db.DefaultContext).Table("access_token").Where("name = ?", token.Name).And("uid = ?", token.UID).Exist() +func AccessTokenByNameExists(ctx context.Context, token *AccessToken) (bool, error) { + return db.GetEngine(ctx).Table("access_token").Where("name = ?", token.Name).And("uid = ?", token.UID).Exist() } // ListAccessTokensOptions contain filter options @@ -201,8 +202,8 @@ type ListAccessTokensOptions struct { } // ListAccessTokens returns a list of access tokens belongs to given user. -func ListAccessTokens(opts ListAccessTokensOptions) ([]*AccessToken, error) { - sess := db.GetEngine(db.DefaultContext).Where("uid=?", opts.UserID) +func ListAccessTokens(ctx context.Context, opts ListAccessTokensOptions) ([]*AccessToken, error) { + sess := db.GetEngine(ctx).Where("uid=?", opts.UserID) if len(opts.Name) != 0 { sess = sess.Where("name=?", opts.Name) @@ -222,14 +223,14 @@ func ListAccessTokens(opts ListAccessTokensOptions) ([]*AccessToken, error) { } // UpdateAccessToken updates information of access token. -func UpdateAccessToken(t *AccessToken) error { - _, err := db.GetEngine(db.DefaultContext).ID(t.ID).AllCols().Update(t) +func UpdateAccessToken(ctx context.Context, t *AccessToken) error { + _, err := db.GetEngine(ctx).ID(t.ID).AllCols().Update(t) return err } // CountAccessTokens count access tokens belongs to given user by options -func CountAccessTokens(opts ListAccessTokensOptions) (int64, error) { - sess := db.GetEngine(db.DefaultContext).Where("uid=?", opts.UserID) +func CountAccessTokens(ctx context.Context, opts ListAccessTokensOptions) (int64, error) { + sess := db.GetEngine(ctx).Where("uid=?", opts.UserID) if len(opts.Name) != 0 { sess = sess.Where("name=?", opts.Name) } @@ -237,8 +238,8 @@ func CountAccessTokens(opts ListAccessTokensOptions) (int64, error) { } // DeleteAccessTokenByID deletes access token by given ID. -func DeleteAccessTokenByID(id, userID int64) error { - cnt, err := db.GetEngine(db.DefaultContext).ID(id).Delete(&AccessToken{ +func DeleteAccessTokenByID(ctx context.Context, id, userID int64) error { + cnt, err := db.GetEngine(ctx).ID(id).Delete(&AccessToken{ UID: userID, }) if err != nil { diff --git a/models/auth/token_test.go b/models/auth/token_test.go index 8a1e664950..72c937ffd6 100644 --- a/models/auth/token_test.go +++ b/models/auth/token_test.go @@ -7,6 +7,7 @@ import ( "testing" auth_model "code.gitea.io/gitea/models/auth" + "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" @@ -18,7 +19,7 @@ func TestNewAccessToken(t *testing.T) { UID: 3, Name: "Token C", } - assert.NoError(t, auth_model.NewAccessToken(token)) + assert.NoError(t, auth_model.NewAccessToken(db.DefaultContext, token)) unittest.AssertExistsAndLoadBean(t, token) invalidToken := &auth_model.AccessToken{ @@ -26,7 +27,7 @@ func TestNewAccessToken(t *testing.T) { UID: 2, Name: "Token F", } - assert.Error(t, auth_model.NewAccessToken(invalidToken)) + assert.Error(t, auth_model.NewAccessToken(db.DefaultContext, invalidToken)) } func TestAccessTokenByNameExists(t *testing.T) { @@ -39,16 +40,16 @@ func TestAccessTokenByNameExists(t *testing.T) { } // Check to make sure it doesn't exists already - exist, err := auth_model.AccessTokenByNameExists(token) + exist, err := auth_model.AccessTokenByNameExists(db.DefaultContext, token) assert.NoError(t, err) assert.False(t, exist) // Save it to the database - assert.NoError(t, auth_model.NewAccessToken(token)) + assert.NoError(t, auth_model.NewAccessToken(db.DefaultContext, token)) unittest.AssertExistsAndLoadBean(t, token) // This token must be found by name in the DB now - exist, err = auth_model.AccessTokenByNameExists(token) + exist, err = auth_model.AccessTokenByNameExists(db.DefaultContext, token) assert.NoError(t, err) assert.True(t, exist) @@ -59,32 +60,32 @@ func TestAccessTokenByNameExists(t *testing.T) { // Name matches but different user ID, this shouldn't exists in the // database - exist, err = auth_model.AccessTokenByNameExists(user4Token) + exist, err = auth_model.AccessTokenByNameExists(db.DefaultContext, user4Token) assert.NoError(t, err) assert.False(t, exist) } func TestGetAccessTokenBySHA(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - token, err := auth_model.GetAccessTokenBySHA("d2c6c1ba3890b309189a8e618c72a162e4efbf36") + token, err := auth_model.GetAccessTokenBySHA(db.DefaultContext, "d2c6c1ba3890b309189a8e618c72a162e4efbf36") assert.NoError(t, err) assert.Equal(t, int64(1), token.UID) assert.Equal(t, "Token A", token.Name) assert.Equal(t, "2b3668e11cb82d3af8c6e4524fc7841297668f5008d1626f0ad3417e9fa39af84c268248b78c481daa7e5dc437784003494f", token.TokenHash) assert.Equal(t, "e4efbf36", token.TokenLastEight) - _, err = auth_model.GetAccessTokenBySHA("notahash") + _, err = auth_model.GetAccessTokenBySHA(db.DefaultContext, "notahash") assert.Error(t, err) assert.True(t, auth_model.IsErrAccessTokenNotExist(err)) - _, err = auth_model.GetAccessTokenBySHA("") + _, err = auth_model.GetAccessTokenBySHA(db.DefaultContext, "") assert.Error(t, err) assert.True(t, auth_model.IsErrAccessTokenEmpty(err)) } func TestListAccessTokens(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - tokens, err := auth_model.ListAccessTokens(auth_model.ListAccessTokensOptions{UserID: 1}) + tokens, err := auth_model.ListAccessTokens(db.DefaultContext, auth_model.ListAccessTokensOptions{UserID: 1}) assert.NoError(t, err) if assert.Len(t, tokens, 2) { assert.Equal(t, int64(1), tokens[0].UID) @@ -93,39 +94,39 @@ func TestListAccessTokens(t *testing.T) { assert.Contains(t, []string{tokens[0].Name, tokens[1].Name}, "Token B") } - tokens, err = auth_model.ListAccessTokens(auth_model.ListAccessTokensOptions{UserID: 2}) + tokens, err = auth_model.ListAccessTokens(db.DefaultContext, auth_model.ListAccessTokensOptions{UserID: 2}) assert.NoError(t, err) if assert.Len(t, tokens, 1) { assert.Equal(t, int64(2), tokens[0].UID) assert.Equal(t, "Token A", tokens[0].Name) } - tokens, err = auth_model.ListAccessTokens(auth_model.ListAccessTokensOptions{UserID: 100}) + tokens, err = auth_model.ListAccessTokens(db.DefaultContext, auth_model.ListAccessTokensOptions{UserID: 100}) assert.NoError(t, err) assert.Empty(t, tokens) } func TestUpdateAccessToken(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - token, err := auth_model.GetAccessTokenBySHA("4c6f36e6cf498e2a448662f915d932c09c5a146c") + token, err := auth_model.GetAccessTokenBySHA(db.DefaultContext, "4c6f36e6cf498e2a448662f915d932c09c5a146c") assert.NoError(t, err) token.Name = "Token Z" - assert.NoError(t, auth_model.UpdateAccessToken(token)) + assert.NoError(t, auth_model.UpdateAccessToken(db.DefaultContext, token)) unittest.AssertExistsAndLoadBean(t, token) } func TestDeleteAccessTokenByID(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - token, err := auth_model.GetAccessTokenBySHA("4c6f36e6cf498e2a448662f915d932c09c5a146c") + token, err := auth_model.GetAccessTokenBySHA(db.DefaultContext, "4c6f36e6cf498e2a448662f915d932c09c5a146c") assert.NoError(t, err) assert.Equal(t, int64(1), token.UID) - assert.NoError(t, auth_model.DeleteAccessTokenByID(token.ID, 1)) + assert.NoError(t, auth_model.DeleteAccessTokenByID(db.DefaultContext, token.ID, 1)) unittest.AssertNotExistsBean(t, token) - err = auth_model.DeleteAccessTokenByID(100, 100) + err = auth_model.DeleteAccessTokenByID(db.DefaultContext, 100, 100) assert.Error(t, err) assert.True(t, auth_model.IsErrAccessTokenNotExist(err)) } diff --git a/models/auth/twofactor.go b/models/auth/twofactor.go index 751a281f7e..51061e5205 100644 --- a/models/auth/twofactor.go +++ b/models/auth/twofactor.go @@ -4,6 +4,7 @@ package auth import ( + "context" "crypto/md5" "crypto/subtle" "encoding/base32" @@ -121,22 +122,22 @@ func (t *TwoFactor) ValidateTOTP(passcode string) (bool, error) { } // NewTwoFactor creates a new two-factor authentication token. -func NewTwoFactor(t *TwoFactor) error { - _, err := db.GetEngine(db.DefaultContext).Insert(t) +func NewTwoFactor(ctx context.Context, t *TwoFactor) error { + _, err := db.GetEngine(ctx).Insert(t) return err } // UpdateTwoFactor updates a two-factor authentication token. -func UpdateTwoFactor(t *TwoFactor) error { - _, err := db.GetEngine(db.DefaultContext).ID(t.ID).AllCols().Update(t) +func UpdateTwoFactor(ctx context.Context, t *TwoFactor) error { + _, err := db.GetEngine(ctx).ID(t.ID).AllCols().Update(t) return err } // GetTwoFactorByUID returns the two-factor authentication token associated with // the user, if any. -func GetTwoFactorByUID(uid int64) (*TwoFactor, error) { +func GetTwoFactorByUID(ctx context.Context, uid int64) (*TwoFactor, error) { twofa := &TwoFactor{} - has, err := db.GetEngine(db.DefaultContext).Where("uid=?", uid).Get(twofa) + has, err := db.GetEngine(ctx).Where("uid=?", uid).Get(twofa) if err != nil { return nil, err } else if !has { @@ -147,13 +148,13 @@ func GetTwoFactorByUID(uid int64) (*TwoFactor, error) { // HasTwoFactorByUID returns the two-factor authentication token associated with // the user, if any. -func HasTwoFactorByUID(uid int64) (bool, error) { - return db.GetEngine(db.DefaultContext).Where("uid=?", uid).Exist(&TwoFactor{}) +func HasTwoFactorByUID(ctx context.Context, uid int64) (bool, error) { + return db.GetEngine(ctx).Where("uid=?", uid).Exist(&TwoFactor{}) } // DeleteTwoFactorByID deletes two-factor authentication token by given ID. -func DeleteTwoFactorByID(id, userID int64) error { - cnt, err := db.GetEngine(db.DefaultContext).ID(id).Delete(&TwoFactor{ +func DeleteTwoFactorByID(ctx context.Context, id, userID int64) error { + cnt, err := db.GetEngine(ctx).ID(id).Delete(&TwoFactor{ UID: userID, }) if err != nil { diff --git a/models/issues/comment.go b/models/issues/comment.go index e045b71d23..66b3a8527f 100644 --- a/models/issues/comment.go +++ b/models/issues/comment.go @@ -359,12 +359,12 @@ func (c *Comment) LoadPoster(ctx context.Context) (err error) { } // AfterDelete is invoked from XORM after the object is deleted. -func (c *Comment) AfterDelete() { +func (c *Comment) AfterDelete(ctx context.Context) { if c.ID <= 0 { return } - _, err := repo_model.DeleteAttachmentsByComment(c.ID, true) + _, err := repo_model.DeleteAttachmentsByComment(ctx, c.ID, true) if err != nil { log.Info("Could not delete files for comment %d on issue #%d: %s", c.ID, c.IssueID, err) } diff --git a/models/issues/pull_list.go b/models/issues/pull_list.go index c4506ef150..c209386e2e 100644 --- a/models/issues/pull_list.go +++ b/models/issues/pull_list.go @@ -27,8 +27,8 @@ type PullRequestsOptions struct { MilestoneID int64 } -func listPullRequestStatement(baseRepoID int64, opts *PullRequestsOptions) (*xorm.Session, error) { - sess := db.GetEngine(db.DefaultContext).Where("pull_request.base_repo_id=?", baseRepoID) +func listPullRequestStatement(ctx context.Context, baseRepoID int64, opts *PullRequestsOptions) (*xorm.Session, error) { + sess := db.GetEngine(ctx).Where("pull_request.base_repo_id=?", baseRepoID) sess.Join("INNER", "issue", "pull_request.issue_id = issue.id") switch opts.State { @@ -115,21 +115,21 @@ func GetUnmergedPullRequestsByBaseInfo(ctx context.Context, repoID int64, branch } // GetPullRequestIDsByCheckStatus returns all pull requests according the special checking status. -func GetPullRequestIDsByCheckStatus(status PullRequestStatus) ([]int64, error) { +func GetPullRequestIDsByCheckStatus(ctx context.Context, status PullRequestStatus) ([]int64, error) { prs := make([]int64, 0, 10) - return prs, db.GetEngine(db.DefaultContext).Table("pull_request"). + return prs, db.GetEngine(ctx).Table("pull_request"). Where("status=?", status). Cols("pull_request.id"). Find(&prs) } // PullRequests returns all pull requests for a base Repo by the given conditions -func PullRequests(baseRepoID int64, opts *PullRequestsOptions) ([]*PullRequest, int64, error) { +func PullRequests(ctx context.Context, baseRepoID int64, opts *PullRequestsOptions) ([]*PullRequest, int64, error) { if opts.Page <= 0 { opts.Page = 1 } - countSession, err := listPullRequestStatement(baseRepoID, opts) + countSession, err := listPullRequestStatement(ctx, baseRepoID, opts) if err != nil { log.Error("listPullRequestStatement: %v", err) return nil, 0, err @@ -140,7 +140,7 @@ func PullRequests(baseRepoID int64, opts *PullRequestsOptions) ([]*PullRequest, return nil, maxResults, err } - findSession, err := listPullRequestStatement(baseRepoID, opts) + findSession, err := listPullRequestStatement(ctx, baseRepoID, opts) applySorts(findSession, opts.SortType, 0) if err != nil { log.Error("listPullRequestStatement: %v", err) diff --git a/models/issues/pull_test.go b/models/issues/pull_test.go index 1105608858..3636263c46 100644 --- a/models/issues/pull_test.go +++ b/models/issues/pull_test.go @@ -60,7 +60,7 @@ func TestPullRequest_LoadHeadRepo(t *testing.T) { func TestPullRequestsNewest(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - prs, count, err := issues_model.PullRequests(1, &issues_model.PullRequestsOptions{ + prs, count, err := issues_model.PullRequests(db.DefaultContext, 1, &issues_model.PullRequestsOptions{ ListOptions: db.ListOptions{ Page: 1, }, @@ -107,7 +107,7 @@ func TestLoadRequestedReviewers(t *testing.T) { func TestPullRequestsOldest(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - prs, count, err := issues_model.PullRequests(1, &issues_model.PullRequestsOptions{ + prs, count, err := issues_model.PullRequests(db.DefaultContext, 1, &issues_model.PullRequestsOptions{ ListOptions: db.ListOptions{ Page: 1, }, diff --git a/models/repo/attachment.go b/models/repo/attachment.go index df3b9cd213..1a588398c1 100644 --- a/models/repo/attachment.go +++ b/models/repo/attachment.go @@ -37,9 +37,9 @@ func init() { } // IncreaseDownloadCount is update download count + 1 -func (a *Attachment) IncreaseDownloadCount() error { +func (a *Attachment) IncreaseDownloadCount(ctx context.Context) error { // Update download count. - if _, err := db.GetEngine(db.DefaultContext).Exec("UPDATE `attachment` SET download_count=download_count+1 WHERE id=?", a.ID); err != nil { + if _, err := db.GetEngine(ctx).Exec("UPDATE `attachment` SET download_count=download_count+1 WHERE id=?", a.ID); err != nil { return fmt.Errorf("increase attachment count: %w", err) } @@ -164,8 +164,8 @@ func GetAttachmentByReleaseIDFileName(ctx context.Context, releaseID int64, file } // DeleteAttachment deletes the given attachment and optionally the associated file. -func DeleteAttachment(a *Attachment, remove bool) error { - _, err := DeleteAttachments(db.DefaultContext, []*Attachment{a}, remove) +func DeleteAttachment(ctx context.Context, a *Attachment, remove bool) error { + _, err := DeleteAttachments(ctx, []*Attachment{a}, remove) return err } @@ -196,23 +196,23 @@ func DeleteAttachments(ctx context.Context, attachments []*Attachment, remove bo } // DeleteAttachmentsByIssue deletes all attachments associated with the given issue. -func DeleteAttachmentsByIssue(issueID int64, remove bool) (int, error) { - attachments, err := GetAttachmentsByIssueID(db.DefaultContext, issueID) +func DeleteAttachmentsByIssue(ctx context.Context, issueID int64, remove bool) (int, error) { + attachments, err := GetAttachmentsByIssueID(ctx, issueID) if err != nil { return 0, err } - return DeleteAttachments(db.DefaultContext, attachments, remove) + return DeleteAttachments(ctx, attachments, remove) } // DeleteAttachmentsByComment deletes all attachments associated with the given comment. -func DeleteAttachmentsByComment(commentID int64, remove bool) (int, error) { - attachments, err := GetAttachmentsByCommentID(db.DefaultContext, commentID) +func DeleteAttachmentsByComment(ctx context.Context, commentID int64, remove bool) (int, error) { + attachments, err := GetAttachmentsByCommentID(ctx, commentID) if err != nil { return 0, err } - return DeleteAttachments(db.DefaultContext, attachments, remove) + return DeleteAttachments(ctx, attachments, remove) } // UpdateAttachmentByUUID Updates attachment via uuid diff --git a/models/repo/attachment_test.go b/models/repo/attachment_test.go index 21fba227a5..c059ffd39a 100644 --- a/models/repo/attachment_test.go +++ b/models/repo/attachment_test.go @@ -21,7 +21,7 @@ func TestIncreaseDownloadCount(t *testing.T) { assert.Equal(t, int64(0), attachment.DownloadCount) // increase download count - err = attachment.IncreaseDownloadCount() + err = attachment.IncreaseDownloadCount(db.DefaultContext) assert.NoError(t, err) attachment, err = repo_model.GetAttachmentByUUID(db.DefaultContext, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11") @@ -45,15 +45,15 @@ func TestGetByCommentOrIssueID(t *testing.T) { func TestDeleteAttachments(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - count, err := repo_model.DeleteAttachmentsByIssue(4, false) + count, err := repo_model.DeleteAttachmentsByIssue(db.DefaultContext, 4, false) assert.NoError(t, err) assert.Equal(t, 2, count) - count, err = repo_model.DeleteAttachmentsByComment(2, false) + count, err = repo_model.DeleteAttachmentsByComment(db.DefaultContext, 2, false) assert.NoError(t, err) assert.Equal(t, 2, count) - err = repo_model.DeleteAttachment(&repo_model.Attachment{ID: 8}, false) + err = repo_model.DeleteAttachment(db.DefaultContext, &repo_model.Attachment{ID: 8}, false) assert.NoError(t, err) attachment, err := repo_model.GetAttachmentByUUID(db.DefaultContext, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a18") diff --git a/models/repo/star.go b/models/repo/star.go index 89bdb7ac05..60737149da 100644 --- a/models/repo/star.go +++ b/models/repo/star.go @@ -24,8 +24,8 @@ func init() { } // StarRepo or unstar repository. -func StarRepo(userID, repoID int64, star bool) error { - ctx, committer, err := db.TxContext(db.DefaultContext) +func StarRepo(ctx context.Context, userID, repoID int64, star bool) error { + ctx, committer, err := db.TxContext(ctx) if err != nil { return err } @@ -72,8 +72,8 @@ func IsStaring(ctx context.Context, userID, repoID int64) bool { } // GetStargazers returns the users that starred the repo. -func GetStargazers(repo *Repository, opts db.ListOptions) ([]*user_model.User, error) { - sess := db.GetEngine(db.DefaultContext).Where("star.repo_id = ?", repo.ID). +func GetStargazers(ctx context.Context, repo *Repository, opts db.ListOptions) ([]*user_model.User, error) { + sess := db.GetEngine(ctx).Where("star.repo_id = ?", repo.ID). Join("LEFT", "star", "`user`.id = star.uid") if opts.Page > 0 { sess = db.SetSessionPagination(sess, &opts) diff --git a/models/repo/star_test.go b/models/repo/star_test.go index f15ac12ebe..62eac4e29a 100644 --- a/models/repo/star_test.go +++ b/models/repo/star_test.go @@ -18,11 +18,11 @@ func TestStarRepo(t *testing.T) { const userID = 2 const repoID = 1 unittest.AssertNotExistsBean(t, &repo_model.Star{UID: userID, RepoID: repoID}) - assert.NoError(t, repo_model.StarRepo(userID, repoID, true)) + assert.NoError(t, repo_model.StarRepo(db.DefaultContext, userID, repoID, true)) unittest.AssertExistsAndLoadBean(t, &repo_model.Star{UID: userID, RepoID: repoID}) - assert.NoError(t, repo_model.StarRepo(userID, repoID, true)) + assert.NoError(t, repo_model.StarRepo(db.DefaultContext, userID, repoID, true)) unittest.AssertExistsAndLoadBean(t, &repo_model.Star{UID: userID, RepoID: repoID}) - assert.NoError(t, repo_model.StarRepo(userID, repoID, false)) + assert.NoError(t, repo_model.StarRepo(db.DefaultContext, userID, repoID, false)) unittest.AssertNotExistsBean(t, &repo_model.Star{UID: userID, RepoID: repoID}) } @@ -36,7 +36,7 @@ func TestRepository_GetStargazers(t *testing.T) { // repo with stargazers assert.NoError(t, unittest.PrepareTestDatabase()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4}) - gazers, err := repo_model.GetStargazers(repo, db.ListOptions{Page: 0}) + gazers, err := repo_model.GetStargazers(db.DefaultContext, repo, db.ListOptions{Page: 0}) assert.NoError(t, err) if assert.Len(t, gazers, 1) { assert.Equal(t, int64(2), gazers[0].ID) @@ -47,7 +47,7 @@ func TestRepository_GetStargazers2(t *testing.T) { // repo with stargazers assert.NoError(t, unittest.PrepareTestDatabase()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}) - gazers, err := repo_model.GetStargazers(repo, db.ListOptions{Page: 0}) + gazers, err := repo_model.GetStargazers(db.DefaultContext, repo, db.ListOptions{Page: 0}) assert.NoError(t, err) assert.Len(t, gazers, 0) } @@ -57,15 +57,15 @@ func TestClearRepoStars(t *testing.T) { const userID = 2 const repoID = 1 unittest.AssertNotExistsBean(t, &repo_model.Star{UID: userID, RepoID: repoID}) - assert.NoError(t, repo_model.StarRepo(userID, repoID, true)) + assert.NoError(t, repo_model.StarRepo(db.DefaultContext, userID, repoID, true)) unittest.AssertExistsAndLoadBean(t, &repo_model.Star{UID: userID, RepoID: repoID}) - assert.NoError(t, repo_model.StarRepo(userID, repoID, false)) + assert.NoError(t, repo_model.StarRepo(db.DefaultContext, userID, repoID, false)) unittest.AssertNotExistsBean(t, &repo_model.Star{UID: userID, RepoID: repoID}) assert.NoError(t, repo_model.ClearRepoStars(db.DefaultContext, repoID)) unittest.AssertNotExistsBean(t, &repo_model.Star{UID: userID, RepoID: repoID}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) - gazers, err := repo_model.GetStargazers(repo, db.ListOptions{Page: 0}) + gazers, err := repo_model.GetStargazers(db.DefaultContext, repo, db.ListOptions{Page: 0}) assert.NoError(t, err) assert.Len(t, gazers, 0) } diff --git a/models/repo/upload.go b/models/repo/upload.go index 3b1b97c6d6..d96ab21bcd 100644 --- a/models/repo/upload.go +++ b/models/repo/upload.go @@ -5,6 +5,7 @@ package repo import ( + "context" "fmt" "io" "mime/multipart" @@ -61,7 +62,7 @@ func (upload *Upload) LocalPath() string { } // NewUpload creates a new upload object. -func NewUpload(name string, buf []byte, file multipart.File) (_ *Upload, err error) { +func NewUpload(ctx context.Context, name string, buf []byte, file multipart.File) (_ *Upload, err error) { upload := &Upload{ UUID: gouuid.New().String(), Name: name, @@ -84,7 +85,7 @@ func NewUpload(name string, buf []byte, file multipart.File) (_ *Upload, err err return nil, fmt.Errorf("Copy: %w", err) } - if _, err := db.GetEngine(db.DefaultContext).Insert(upload); err != nil { + if _, err := db.GetEngine(ctx).Insert(upload); err != nil { return nil, err } @@ -92,9 +93,9 @@ func NewUpload(name string, buf []byte, file multipart.File) (_ *Upload, err err } // GetUploadByUUID returns the Upload by UUID -func GetUploadByUUID(uuid string) (*Upload, error) { +func GetUploadByUUID(ctx context.Context, uuid string) (*Upload, error) { upload := &Upload{} - has, err := db.GetEngine(db.DefaultContext).Where("uuid=?", uuid).Get(upload) + has, err := db.GetEngine(ctx).Where("uuid=?", uuid).Get(upload) if err != nil { return nil, err } else if !has { @@ -104,23 +105,23 @@ func GetUploadByUUID(uuid string) (*Upload, error) { } // GetUploadsByUUIDs returns multiple uploads by UUIDS -func GetUploadsByUUIDs(uuids []string) ([]*Upload, error) { +func GetUploadsByUUIDs(ctx context.Context, uuids []string) ([]*Upload, error) { if len(uuids) == 0 { return []*Upload{}, nil } // Silently drop invalid uuids. uploads := make([]*Upload, 0, len(uuids)) - return uploads, db.GetEngine(db.DefaultContext).In("uuid", uuids).Find(&uploads) + return uploads, db.GetEngine(ctx).In("uuid", uuids).Find(&uploads) } // DeleteUploads deletes multiple uploads -func DeleteUploads(uploads ...*Upload) (err error) { +func DeleteUploads(ctx context.Context, uploads ...*Upload) (err error) { if len(uploads) == 0 { return nil } - ctx, committer, err := db.TxContext(db.DefaultContext) + ctx, committer, err := db.TxContext(ctx) if err != nil { return err } @@ -159,8 +160,8 @@ func DeleteUploads(uploads ...*Upload) (err error) { } // DeleteUploadByUUID deletes a upload by UUID -func DeleteUploadByUUID(uuid string) error { - upload, err := GetUploadByUUID(uuid) +func DeleteUploadByUUID(ctx context.Context, uuid string) error { + upload, err := GetUploadByUUID(ctx, uuid) if err != nil { if IsErrUploadNotExist(err) { return nil @@ -168,7 +169,7 @@ func DeleteUploadByUUID(uuid string) error { return fmt.Errorf("GetUploadByUUID: %w", err) } - if err := DeleteUploads(upload); err != nil { + if err := DeleteUploads(ctx, upload); err != nil { return fmt.Errorf("DeleteUpload: %w", err) } diff --git a/models/repo/watch.go b/models/repo/watch.go index 00f313ca7c..02a94ecac0 100644 --- a/models/repo/watch.go +++ b/models/repo/watch.go @@ -59,8 +59,8 @@ func IsWatchMode(mode WatchMode) bool { } // IsWatching checks if user has watched given repository. -func IsWatching(userID, repoID int64) bool { - watch, err := GetWatch(db.DefaultContext, userID, repoID) +func IsWatching(ctx context.Context, userID, repoID int64) bool { + watch, err := GetWatch(ctx, userID, repoID) return err == nil && IsWatchMode(watch.Mode) } @@ -155,8 +155,8 @@ func GetRepoWatchersIDs(ctx context.Context, repoID int64) ([]int64, error) { } // GetRepoWatchers returns range of users watching given repository. -func GetRepoWatchers(repoID int64, opts db.ListOptions) ([]*user_model.User, error) { - sess := db.GetEngine(db.DefaultContext).Where("watch.repo_id=?", repoID). +func GetRepoWatchers(ctx context.Context, repoID int64, opts db.ListOptions) ([]*user_model.User, error) { + sess := db.GetEngine(ctx).Where("watch.repo_id=?", repoID). Join("LEFT", "watch", "`user`.id=`watch`.user_id"). And("`watch`.mode<>?", WatchModeDont) if opts.Page > 0 { diff --git a/models/repo/watch_test.go b/models/repo/watch_test.go index 8b8c6d6250..1384d1e157 100644 --- a/models/repo/watch_test.go +++ b/models/repo/watch_test.go @@ -17,13 +17,13 @@ import ( func TestIsWatching(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - assert.True(t, repo_model.IsWatching(1, 1)) - assert.True(t, repo_model.IsWatching(4, 1)) - assert.True(t, repo_model.IsWatching(11, 1)) + assert.True(t, repo_model.IsWatching(db.DefaultContext, 1, 1)) + assert.True(t, repo_model.IsWatching(db.DefaultContext, 4, 1)) + assert.True(t, repo_model.IsWatching(db.DefaultContext, 11, 1)) - assert.False(t, repo_model.IsWatching(1, 5)) - assert.False(t, repo_model.IsWatching(8, 1)) - assert.False(t, repo_model.IsWatching(unittest.NonexistentID, unittest.NonexistentID)) + assert.False(t, repo_model.IsWatching(db.DefaultContext, 1, 5)) + assert.False(t, repo_model.IsWatching(db.DefaultContext, 8, 1)) + assert.False(t, repo_model.IsWatching(db.DefaultContext, unittest.NonexistentID, unittest.NonexistentID)) } func TestGetWatchers(t *testing.T) { @@ -47,7 +47,7 @@ func TestRepository_GetWatchers(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) - watchers, err := repo_model.GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) + watchers, err := repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1}) assert.NoError(t, err) assert.Len(t, watchers, repo.NumWatches) for _, watcher := range watchers { @@ -55,7 +55,7 @@ func TestRepository_GetWatchers(t *testing.T) { } repo = unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 9}) - watchers, err = repo_model.GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) + watchers, err = repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1}) assert.NoError(t, err) assert.Len(t, watchers, 0) } @@ -64,7 +64,7 @@ func TestWatchIfAuto(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) - watchers, err := repo_model.GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) + watchers, err := repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1}) assert.NoError(t, err) assert.Len(t, watchers, repo.NumWatches) @@ -74,13 +74,13 @@ func TestWatchIfAuto(t *testing.T) { // Must not add watch assert.NoError(t, repo_model.WatchIfAuto(db.DefaultContext, 8, 1, true)) - watchers, err = repo_model.GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) + watchers, err = repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1}) assert.NoError(t, err) assert.Len(t, watchers, prevCount) // Should not add watch assert.NoError(t, repo_model.WatchIfAuto(db.DefaultContext, 10, 1, true)) - watchers, err = repo_model.GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) + watchers, err = repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1}) assert.NoError(t, err) assert.Len(t, watchers, prevCount) @@ -88,31 +88,31 @@ func TestWatchIfAuto(t *testing.T) { // Must not add watch assert.NoError(t, repo_model.WatchIfAuto(db.DefaultContext, 8, 1, true)) - watchers, err = repo_model.GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) + watchers, err = repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1}) assert.NoError(t, err) assert.Len(t, watchers, prevCount) // Should not add watch assert.NoError(t, repo_model.WatchIfAuto(db.DefaultContext, 12, 1, false)) - watchers, err = repo_model.GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) + watchers, err = repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1}) assert.NoError(t, err) assert.Len(t, watchers, prevCount) // Should add watch assert.NoError(t, repo_model.WatchIfAuto(db.DefaultContext, 12, 1, true)) - watchers, err = repo_model.GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) + watchers, err = repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1}) assert.NoError(t, err) assert.Len(t, watchers, prevCount+1) // Should remove watch, inhibit from adding auto assert.NoError(t, repo_model.WatchRepo(db.DefaultContext, 12, 1, false)) - watchers, err = repo_model.GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) + watchers, err = repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1}) assert.NoError(t, err) assert.Len(t, watchers, prevCount) // Must not add watch assert.NoError(t, repo_model.WatchIfAuto(db.DefaultContext, 12, 1, true)) - watchers, err = repo_model.GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) + watchers, err = repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1}) assert.NoError(t, err) assert.Len(t, watchers, prevCount) } diff --git a/models/user/openid.go b/models/user/openid.go index 596ff182bc..ee4ecabae0 100644 --- a/models/user/openid.go +++ b/models/user/openid.go @@ -28,9 +28,9 @@ func init() { } // GetUserOpenIDs returns all openid addresses that belongs to given user. -func GetUserOpenIDs(uid int64) ([]*UserOpenID, error) { +func GetUserOpenIDs(ctx context.Context, uid int64) ([]*UserOpenID, error) { openids := make([]*UserOpenID, 0, 5) - if err := db.GetEngine(db.DefaultContext). + if err := db.GetEngine(ctx). Where("uid=?", uid). Asc("id"). Find(&openids); err != nil { @@ -82,16 +82,16 @@ func AddUserOpenID(ctx context.Context, openid *UserOpenID) error { } // DeleteUserOpenID deletes an openid address of given user. -func DeleteUserOpenID(openid *UserOpenID) (err error) { +func DeleteUserOpenID(ctx context.Context, openid *UserOpenID) (err error) { var deleted int64 // ask to check UID address := UserOpenID{ UID: openid.UID, } if openid.ID > 0 { - deleted, err = db.GetEngine(db.DefaultContext).ID(openid.ID).Delete(&address) + deleted, err = db.GetEngine(ctx).ID(openid.ID).Delete(&address) } else { - deleted, err = db.GetEngine(db.DefaultContext). + deleted, err = db.GetEngine(ctx). Where("openid=?", openid.URI). Delete(&address) } @@ -105,7 +105,7 @@ func DeleteUserOpenID(openid *UserOpenID) (err error) { } // ToggleUserOpenIDVisibility toggles visibility of an openid address of given user. -func ToggleUserOpenIDVisibility(id int64) (err error) { - _, err = db.GetEngine(db.DefaultContext).Exec("update `user_open_id` set `show` = not `show` where `id` = ?", id) +func ToggleUserOpenIDVisibility(ctx context.Context, id int64) (err error) { + _, err = db.GetEngine(ctx).Exec("update `user_open_id` set `show` = not `show` where `id` = ?", id) return err } diff --git a/models/user/openid_test.go b/models/user/openid_test.go index 6f0eae55e7..27e6edd1e0 100644 --- a/models/user/openid_test.go +++ b/models/user/openid_test.go @@ -6,6 +6,7 @@ package user_test import ( "testing" + "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" @@ -15,7 +16,7 @@ import ( func TestGetUserOpenIDs(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - oids, err := user_model.GetUserOpenIDs(int64(1)) + oids, err := user_model.GetUserOpenIDs(db.DefaultContext, int64(1)) if assert.NoError(t, err) && assert.Len(t, oids, 2) { assert.Equal(t, "https://user1.domain1.tld/", oids[0].URI) assert.False(t, oids[0].Show) @@ -23,7 +24,7 @@ func TestGetUserOpenIDs(t *testing.T) { assert.True(t, oids[1].Show) } - oids, err = user_model.GetUserOpenIDs(int64(2)) + oids, err = user_model.GetUserOpenIDs(db.DefaultContext, int64(2)) if assert.NoError(t, err) && assert.Len(t, oids, 1) { assert.Equal(t, "https://domain1.tld/user2/", oids[0].URI) assert.True(t, oids[0].Show) @@ -32,28 +33,28 @@ func TestGetUserOpenIDs(t *testing.T) { func TestToggleUserOpenIDVisibility(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - oids, err := user_model.GetUserOpenIDs(int64(2)) + oids, err := user_model.GetUserOpenIDs(db.DefaultContext, int64(2)) if !assert.NoError(t, err) || !assert.Len(t, oids, 1) { return } assert.True(t, oids[0].Show) - err = user_model.ToggleUserOpenIDVisibility(oids[0].ID) + err = user_model.ToggleUserOpenIDVisibility(db.DefaultContext, oids[0].ID) if !assert.NoError(t, err) { return } - oids, err = user_model.GetUserOpenIDs(int64(2)) + oids, err = user_model.GetUserOpenIDs(db.DefaultContext, int64(2)) if !assert.NoError(t, err) || !assert.Len(t, oids, 1) { return } assert.False(t, oids[0].Show) - err = user_model.ToggleUserOpenIDVisibility(oids[0].ID) + err = user_model.ToggleUserOpenIDVisibility(db.DefaultContext, oids[0].ID) if !assert.NoError(t, err) { return } - oids, err = user_model.GetUserOpenIDs(int64(2)) + oids, err = user_model.GetUserOpenIDs(db.DefaultContext, int64(2)) if !assert.NoError(t, err) { return } diff --git a/models/user/setting.go b/models/user/setting.go index a41e494db9..b4af0e5ccd 100644 --- a/models/user/setting.go +++ b/models/user/setting.go @@ -59,9 +59,9 @@ func genSettingCacheKey(userID int64, key string) string { } // GetSetting returns the setting value via the key -func GetSetting(uid int64, key string) (string, error) { +func GetSetting(ctx context.Context, uid int64, key string) (string, error) { return cache.GetString(genSettingCacheKey(uid, key), func() (string, error) { - res, err := GetSettingNoCache(uid, key) + res, err := GetSettingNoCache(ctx, uid, key) if err != nil { return "", err } @@ -70,8 +70,8 @@ func GetSetting(uid int64, key string) (string, error) { } // GetSettingNoCache returns specific setting without using the cache -func GetSettingNoCache(uid int64, key string) (*Setting, error) { - v, err := GetSettings(uid, []string{key}) +func GetSettingNoCache(ctx context.Context, uid int64, key string) (*Setting, error) { + v, err := GetSettings(ctx, uid, []string{key}) if err != nil { return nil, err } @@ -82,9 +82,9 @@ func GetSettingNoCache(uid int64, key string) (*Setting, error) { } // GetSettings returns specific settings from user -func GetSettings(uid int64, keys []string) (map[string]*Setting, error) { +func GetSettings(ctx context.Context, uid int64, keys []string) (map[string]*Setting, error) { settings := make([]*Setting, 0, len(keys)) - if err := db.GetEngine(db.DefaultContext). + if err := db.GetEngine(ctx). Where("user_id=?", uid). And(builder.In("setting_key", keys)). Find(&settings); err != nil { @@ -98,9 +98,9 @@ func GetSettings(uid int64, keys []string) (map[string]*Setting, error) { } // GetUserAllSettings returns all settings from user -func GetUserAllSettings(uid int64) (map[string]*Setting, error) { +func GetUserAllSettings(ctx context.Context, uid int64) (map[string]*Setting, error) { settings := make([]*Setting, 0, 5) - if err := db.GetEngine(db.DefaultContext). + if err := db.GetEngine(ctx). Where("user_id=?", uid). Find(&settings); err != nil { return nil, err @@ -123,13 +123,13 @@ func validateUserSettingKey(key string) error { } // GetUserSetting gets a specific setting for a user -func GetUserSetting(userID int64, key string, def ...string) (string, error) { +func GetUserSetting(ctx context.Context, userID int64, key string, def ...string) (string, error) { if err := validateUserSettingKey(key); err != nil { return "", err } setting := &Setting{UserID: userID, SettingKey: key} - has, err := db.GetEngine(db.DefaultContext).Get(setting) + has, err := db.GetEngine(ctx).Get(setting) if err != nil { return "", err } @@ -143,24 +143,24 @@ func GetUserSetting(userID int64, key string, def ...string) (string, error) { } // DeleteUserSetting deletes a specific setting for a user -func DeleteUserSetting(userID int64, key string) error { +func DeleteUserSetting(ctx context.Context, userID int64, key string) error { if err := validateUserSettingKey(key); err != nil { return err } cache.Remove(genSettingCacheKey(userID, key)) - _, err := db.GetEngine(db.DefaultContext).Delete(&Setting{UserID: userID, SettingKey: key}) + _, err := db.GetEngine(ctx).Delete(&Setting{UserID: userID, SettingKey: key}) return err } // SetUserSetting updates a users' setting for a specific key -func SetUserSetting(userID int64, key, value string) error { +func SetUserSetting(ctx context.Context, userID int64, key, value string) error { if err := validateUserSettingKey(key); err != nil { return err } - if err := upsertUserSettingValue(userID, key, value); err != nil { + if err := upsertUserSettingValue(ctx, userID, key, value); err != nil { return err } @@ -172,8 +172,8 @@ func SetUserSetting(userID int64, key, value string) error { return nil } -func upsertUserSettingValue(userID int64, key, value string) error { - return db.WithTx(db.DefaultContext, func(ctx context.Context) error { +func upsertUserSettingValue(ctx context.Context, userID int64, key, value string) error { + return db.WithTx(ctx, func(ctx context.Context) error { e := db.GetEngine(ctx) // here we use a general method to do a safe upsert for different databases (and most transaction levels) diff --git a/models/user/setting_test.go b/models/user/setting_test.go index d0d612d25d..c56fe93075 100644 --- a/models/user/setting_test.go +++ b/models/user/setting_test.go @@ -6,6 +6,7 @@ package user_test import ( "testing" + "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" @@ -19,41 +20,41 @@ func TestSettings(t *testing.T) { newSetting := &user_model.Setting{UserID: 99, SettingKey: keyName, SettingValue: "Gitea User Setting Test"} // create setting - err := user_model.SetUserSetting(newSetting.UserID, newSetting.SettingKey, newSetting.SettingValue) + err := user_model.SetUserSetting(db.DefaultContext, newSetting.UserID, newSetting.SettingKey, newSetting.SettingValue) assert.NoError(t, err) // test about saving unchanged values - err = user_model.SetUserSetting(newSetting.UserID, newSetting.SettingKey, newSetting.SettingValue) + err = user_model.SetUserSetting(db.DefaultContext, newSetting.UserID, newSetting.SettingKey, newSetting.SettingValue) assert.NoError(t, err) // get specific setting - settings, err := user_model.GetSettings(99, []string{keyName}) + settings, err := user_model.GetSettings(db.DefaultContext, 99, []string{keyName}) assert.NoError(t, err) assert.Len(t, settings, 1) assert.EqualValues(t, newSetting.SettingValue, settings[keyName].SettingValue) - settingValue, err := user_model.GetUserSetting(99, keyName) + settingValue, err := user_model.GetUserSetting(db.DefaultContext, 99, keyName) assert.NoError(t, err) assert.EqualValues(t, newSetting.SettingValue, settingValue) - settingValue, err = user_model.GetUserSetting(99, "no_such") + settingValue, err = user_model.GetUserSetting(db.DefaultContext, 99, "no_such") assert.NoError(t, err) assert.EqualValues(t, "", settingValue) // updated setting updatedSetting := &user_model.Setting{UserID: 99, SettingKey: keyName, SettingValue: "Updated"} - err = user_model.SetUserSetting(updatedSetting.UserID, updatedSetting.SettingKey, updatedSetting.SettingValue) + err = user_model.SetUserSetting(db.DefaultContext, updatedSetting.UserID, updatedSetting.SettingKey, updatedSetting.SettingValue) assert.NoError(t, err) // get all settings - settings, err = user_model.GetUserAllSettings(99) + settings, err = user_model.GetUserAllSettings(db.DefaultContext, 99) assert.NoError(t, err) assert.Len(t, settings, 1) assert.EqualValues(t, updatedSetting.SettingValue, settings[updatedSetting.SettingKey].SettingValue) // delete setting - err = user_model.DeleteUserSetting(99, keyName) + err = user_model.DeleteUserSetting(db.DefaultContext, 99, keyName) assert.NoError(t, err) - settings, err = user_model.GetUserAllSettings(99) + settings, err = user_model.GetUserAllSettings(db.DefaultContext, 99) assert.NoError(t, err) assert.Len(t, settings, 0) } diff --git a/modules/activitypub/client.go b/modules/activitypub/client.go index fa1b57638f..66b977c01f 100644 --- a/modules/activitypub/client.go +++ b/modules/activitypub/client.go @@ -5,6 +5,7 @@ package activitypub import ( "bytes" + "context" "crypto/rsa" "crypto/x509" "encoding/pem" @@ -61,14 +62,14 @@ type Client struct { } // NewClient function -func NewClient(user *user_model.User, pubID string) (c *Client, err error) { +func NewClient(ctx context.Context, user *user_model.User, pubID string) (c *Client, err error) { if err = containsRequiredHTTPHeaders(http.MethodGet, setting.Federation.GetHeaders); err != nil { return nil, err } else if err = containsRequiredHTTPHeaders(http.MethodPost, setting.Federation.PostHeaders); err != nil { return nil, err } - priv, err := GetPrivateKey(user) + priv, err := GetPrivateKey(ctx, user) if err != nil { return nil, err } diff --git a/modules/activitypub/client_test.go b/modules/activitypub/client_test.go index 83000b96d5..65ea8d4d5b 100644 --- a/modules/activitypub/client_test.go +++ b/modules/activitypub/client_test.go @@ -11,6 +11,7 @@ import ( "regexp" "testing" + "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/setting" @@ -22,7 +23,7 @@ func TestActivityPubSignedPost(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) pubID := "https://example.com/pubID" - c, err := NewClient(user, pubID) + c, err := NewClient(db.DefaultContext, user, pubID) assert.NoError(t, err) expected := "BODY" diff --git a/modules/activitypub/user_settings.go b/modules/activitypub/user_settings.go index ef9bc0a864..d196a3806e 100644 --- a/modules/activitypub/user_settings.go +++ b/modules/activitypub/user_settings.go @@ -4,6 +4,8 @@ package activitypub import ( + "context" + user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/util" ) @@ -11,19 +13,19 @@ import ( const rsaBits = 3072 // GetKeyPair function returns a user's private and public keys -func GetKeyPair(user *user_model.User) (pub, priv string, err error) { +func GetKeyPair(ctx context.Context, user *user_model.User) (pub, priv string, err error) { var settings map[string]*user_model.Setting - settings, err = user_model.GetSettings(user.ID, []string{user_model.UserActivityPubPrivPem, user_model.UserActivityPubPubPem}) + settings, err = user_model.GetSettings(ctx, user.ID, []string{user_model.UserActivityPubPrivPem, user_model.UserActivityPubPubPem}) if err != nil { return pub, priv, err } else if len(settings) == 0 { if priv, pub, err = util.GenerateKeyPair(rsaBits); err != nil { return pub, priv, err } - if err = user_model.SetUserSetting(user.ID, user_model.UserActivityPubPrivPem, priv); err != nil { + if err = user_model.SetUserSetting(ctx, user.ID, user_model.UserActivityPubPrivPem, priv); err != nil { return pub, priv, err } - if err = user_model.SetUserSetting(user.ID, user_model.UserActivityPubPubPem, pub); err != nil { + if err = user_model.SetUserSetting(ctx, user.ID, user_model.UserActivityPubPubPem, pub); err != nil { return pub, priv, err } return pub, priv, err @@ -35,13 +37,13 @@ func GetKeyPair(user *user_model.User) (pub, priv string, err error) { } // GetPublicKey function returns a user's public key -func GetPublicKey(user *user_model.User) (pub string, err error) { - pub, _, err = GetKeyPair(user) +func GetPublicKey(ctx context.Context, user *user_model.User) (pub string, err error) { + pub, _, err = GetKeyPair(ctx, user) return pub, err } // GetPrivateKey function returns a user's private key -func GetPrivateKey(user *user_model.User) (priv string, err error) { - _, priv, err = GetKeyPair(user) +func GetPrivateKey(ctx context.Context, user *user_model.User) (priv string, err error) { + _, priv, err = GetKeyPair(ctx, user) return priv, err } diff --git a/modules/activitypub/user_settings_test.go b/modules/activitypub/user_settings_test.go index 78ebf8e824..2d77906521 100644 --- a/modules/activitypub/user_settings_test.go +++ b/modules/activitypub/user_settings_test.go @@ -6,6 +6,7 @@ package activitypub import ( "testing" + "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" @@ -17,12 +18,12 @@ import ( func TestUserSettings(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) - pub, priv, err := GetKeyPair(user1) + pub, priv, err := GetKeyPair(db.DefaultContext, user1) assert.NoError(t, err) - pub1, err := GetPublicKey(user1) + pub1, err := GetPublicKey(db.DefaultContext, user1) assert.NoError(t, err) assert.Equal(t, pub, pub1) - priv1, err := GetPrivateKey(user1) + priv1, err := GetPrivateKey(db.DefaultContext, user1) assert.NoError(t, err) assert.Equal(t, priv, priv1) } diff --git a/modules/context/api.go b/modules/context/api.go index 58532b883d..044ec51b56 100644 --- a/modules/context/api.go +++ b/modules/context/api.go @@ -212,7 +212,7 @@ func (ctx *APIContext) CheckForOTP() { } otpHeader := ctx.Req.Header.Get("X-Gitea-OTP") - twofa, err := auth.GetTwoFactorByUID(ctx.Doer.ID) + twofa, err := auth.GetTwoFactorByUID(ctx, ctx.Doer.ID) if err != nil { if auth.IsErrTwoFactorNotEnrolled(err) { return // No 2FA enrollment for this user diff --git a/modules/context/repo.go b/modules/context/repo.go index 126196b0d3..f9c966d5be 100644 --- a/modules/context/repo.go +++ b/modules/context/repo.go @@ -598,7 +598,7 @@ func RepoAssignment(ctx *Context) context.CancelFunc { } if ctx.IsSigned { - ctx.Data["IsWatchingRepo"] = repo_model.IsWatching(ctx.Doer.ID, repo.ID) + ctx.Data["IsWatchingRepo"] = repo_model.IsWatching(ctx, ctx.Doer.ID, repo.ID) ctx.Data["IsStaringRepo"] = repo_model.IsStaring(ctx, ctx.Doer.ID, repo.ID) } diff --git a/routers/api/packages/alpine/alpine.go b/routers/api/packages/alpine/alpine.go index 51a5c784e0..d499244dc3 100644 --- a/routers/api/packages/alpine/alpine.go +++ b/routers/api/packages/alpine/alpine.go @@ -31,7 +31,7 @@ func apiError(ctx *context.Context, status int, obj any) { } func GetRepositoryKey(ctx *context.Context) { - _, pub, err := alpine_service.GetOrCreateKeyPair(ctx.Package.Owner.ID) + _, pub, err := alpine_service.GetOrCreateKeyPair(ctx, ctx.Package.Owner.ID) if err != nil { apiError(ctx, http.StatusInternalServerError, err) return diff --git a/routers/api/packages/chef/auth.go b/routers/api/packages/chef/auth.go index 53055bb682..3aef8281a4 100644 --- a/routers/api/packages/chef/auth.go +++ b/routers/api/packages/chef/auth.go @@ -4,6 +4,7 @@ package chef import ( + "context" "crypto" "crypto/rsa" "crypto/sha1" @@ -63,7 +64,7 @@ func (a *Auth) Verify(req *http.Request, w http.ResponseWriter, store auth.DataS return nil, nil } - pub, err := getUserPublicKey(u) + pub, err := getUserPublicKey(req.Context(), u) if err != nil { return nil, err } @@ -93,8 +94,8 @@ func getUserFromRequest(req *http.Request) (*user_model.User, error) { return user_model.GetUserByName(req.Context(), username) } -func getUserPublicKey(u *user_model.User) (crypto.PublicKey, error) { - pubKey, err := user_model.GetSetting(u.ID, chef_module.SettingPublicPem) +func getUserPublicKey(ctx context.Context, u *user_model.User) (crypto.PublicKey, error) { + pubKey, err := user_model.GetSetting(ctx, u.ID, chef_module.SettingPublicPem) if err != nil { return nil, err } diff --git a/routers/api/packages/debian/debian.go b/routers/api/packages/debian/debian.go index 04ca2ed977..869bc1e901 100644 --- a/routers/api/packages/debian/debian.go +++ b/routers/api/packages/debian/debian.go @@ -30,7 +30,7 @@ func apiError(ctx *context.Context, status int, obj any) { } func GetRepositoryKey(ctx *context.Context) { - _, pub, err := debian_service.GetOrCreateKeyPair(ctx.Package.Owner.ID) + _, pub, err := debian_service.GetOrCreateKeyPair(ctx, ctx.Package.Owner.ID) if err != nil { apiError(ctx, http.StatusInternalServerError, err) return diff --git a/routers/api/packages/nuget/auth.go b/routers/api/packages/nuget/auth.go index 60b81b8d4b..1bb68d059b 100644 --- a/routers/api/packages/nuget/auth.go +++ b/routers/api/packages/nuget/auth.go @@ -23,7 +23,7 @@ func (a *Auth) Name() string { // https://docs.microsoft.com/en-us/nuget/api/package-publish-resource#request-parameters func (a *Auth) Verify(req *http.Request, w http.ResponseWriter, store auth.DataStore, sess auth.SessionStore) (*user_model.User, error) { - token, err := auth_model.GetAccessTokenBySHA(req.Header.Get("X-NuGet-ApiKey")) + token, err := auth_model.GetAccessTokenBySHA(req.Context(), req.Header.Get("X-NuGet-ApiKey")) if err != nil { if !(auth_model.IsErrAccessTokenNotExist(err) || auth_model.IsErrAccessTokenEmpty(err)) { log.Error("GetAccessTokenBySHA: %v", err) @@ -39,7 +39,7 @@ func (a *Auth) Verify(req *http.Request, w http.ResponseWriter, store auth.DataS } token.UpdatedUnix = timeutil.TimeStampNow() - if err := auth_model.UpdateAccessToken(token); err != nil { + if err := auth_model.UpdateAccessToken(req.Context(), token); err != nil { log.Error("UpdateAccessToken: %v", err) } diff --git a/routers/api/packages/rpm/rpm.go b/routers/api/packages/rpm/rpm.go index 1e462bb908..65b7c74bdd 100644 --- a/routers/api/packages/rpm/rpm.go +++ b/routers/api/packages/rpm/rpm.go @@ -45,7 +45,7 @@ gpgkey=`+url+`/repository.key`) // Gets or creates the PGP public key used to sign repository metadata files func GetRepositoryKey(ctx *context.Context) { - _, pub, err := rpm_service.GetOrCreateKeyPair(ctx.Package.Owner.ID) + _, pub, err := rpm_service.GetOrCreateKeyPair(ctx, ctx.Package.Owner.ID) if err != nil { apiError(ctx, http.StatusInternalServerError, err) return diff --git a/routers/api/v1/activitypub/person.go b/routers/api/v1/activitypub/person.go index bc6b82b179..cad5032d10 100644 --- a/routers/api/v1/activitypub/person.go +++ b/routers/api/v1/activitypub/person.go @@ -66,7 +66,7 @@ func Person(ctx *context.APIContext) { person.PublicKey.ID = ap.IRI(link + "#main-key") person.PublicKey.Owner = ap.IRI(link) - publicKeyPem, err := activitypub.GetPublicKey(ctx.ContextUser) + publicKeyPem, err := activitypub.GetPublicKey(ctx, ctx.ContextUser) if err != nil { ctx.ServerError("GetPublicKey", err) return diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index fd7d3687ac..ca74a23a4b 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -776,7 +776,7 @@ func verifyAuthWithOptions(options *common.VerifyOptions) func(ctx *context.APIC if skip, ok := ctx.Data["SkipLocalTwoFA"]; ok && skip.(bool) { return // Skip 2FA } - twofa, err := auth_model.GetTwoFactorByUID(ctx.Doer.ID) + twofa, err := auth_model.GetTwoFactorByUID(ctx, ctx.Doer.ID) if err != nil { if auth_model.IsErrTwoFactorNotEnrolled(err) { return // No 2FA enrollment for this user diff --git a/routers/api/v1/org/team.go b/routers/api/v1/org/team.go index 944fd763ca..519572ee51 100644 --- a/routers/api/v1/org/team.go +++ b/routers/api/v1/org/team.go @@ -693,7 +693,7 @@ func AddTeamRepository(ctx *context.APIContext) { ctx.Error(http.StatusForbidden, "", "Must have admin-level access to the repository") return } - if err := org_service.TeamAddRepository(ctx.Org.Team, repo); err != nil { + if err := org_service.TeamAddRepository(ctx, ctx.Org.Team, repo); err != nil { ctx.Error(http.StatusInternalServerError, "TeamAddRepository", err) return } diff --git a/routers/api/v1/repo/issue_attachment.go b/routers/api/v1/repo/issue_attachment.go index c689e70a08..60e554990f 100644 --- a/routers/api/v1/repo/issue_attachment.go +++ b/routers/api/v1/repo/issue_attachment.go @@ -189,7 +189,7 @@ func CreateIssueAttachment(ctx *context.APIContext) { issue.Attachments = append(issue.Attachments, attachment) - if err := issue_service.ChangeContent(issue, ctx.Doer, issue.Content); err != nil { + if err := issue_service.ChangeContent(ctx, issue, ctx.Doer, issue.Content); err != nil { ctx.Error(http.StatusInternalServerError, "ChangeContent", err) return } @@ -298,7 +298,7 @@ func DeleteIssueAttachment(ctx *context.APIContext) { return } - if err := repo_model.DeleteAttachment(attachment, true); err != nil { + if err := repo_model.DeleteAttachment(ctx, attachment, true); err != nil { ctx.Error(http.StatusInternalServerError, "DeleteAttachment", err) return } diff --git a/routers/api/v1/repo/issue_comment_attachment.go b/routers/api/v1/repo/issue_comment_attachment.go index 121e3f10e0..c30e8278db 100644 --- a/routers/api/v1/repo/issue_comment_attachment.go +++ b/routers/api/v1/repo/issue_comment_attachment.go @@ -303,7 +303,7 @@ func DeleteIssueCommentAttachment(ctx *context.APIContext) { return } - if err := repo_model.DeleteAttachment(attach, true); err != nil { + if err := repo_model.DeleteAttachment(ctx, attach, true); err != nil { ctx.Error(http.StatusInternalServerError, "DeleteAttachment", err) return } diff --git a/routers/api/v1/repo/pull.go b/routers/api/v1/repo/pull.go index 0fe657d245..4f22a059a1 100644 --- a/routers/api/v1/repo/pull.go +++ b/routers/api/v1/repo/pull.go @@ -97,7 +97,7 @@ func ListPullRequests(ctx *context.APIContext) { listOptions := utils.GetListOptions(ctx) - prs, maxResults, err := issues_model.PullRequests(ctx.Repo.Repository.ID, &issues_model.PullRequestsOptions{ + prs, maxResults, err := issues_model.PullRequests(ctx, ctx.Repo.Repository.ID, &issues_model.PullRequestsOptions{ ListOptions: listOptions, State: ctx.FormTrim("state"), SortType: ctx.FormTrim("sort"), diff --git a/routers/api/v1/repo/release_attachment.go b/routers/api/v1/repo/release_attachment.go index 9571c8ebb9..e142183128 100644 --- a/routers/api/v1/repo/release_attachment.go +++ b/routers/api/v1/repo/release_attachment.go @@ -345,7 +345,7 @@ func DeleteReleaseAttachment(ctx *context.APIContext) { } // FIXME Should prove the existence of the given repo, but results in unnecessary database requests - if err := repo_model.DeleteAttachment(attach, true); err != nil { + if err := repo_model.DeleteAttachment(ctx, attach, true); err != nil { ctx.Error(http.StatusInternalServerError, "DeleteAttachment", err) return } diff --git a/routers/api/v1/repo/star.go b/routers/api/v1/repo/star.go index fccc76b518..05227e33a0 100644 --- a/routers/api/v1/repo/star.go +++ b/routers/api/v1/repo/star.go @@ -45,7 +45,7 @@ func ListStargazers(ctx *context.APIContext) { // "404": // "$ref": "#/responses/notFound" - stargazers, err := repo_model.GetStargazers(ctx.Repo.Repository, utils.GetListOptions(ctx)) + stargazers, err := repo_model.GetStargazers(ctx, ctx.Repo.Repository, utils.GetListOptions(ctx)) if err != nil { ctx.Error(http.StatusInternalServerError, "GetStargazers", err) return diff --git a/routers/api/v1/repo/subscriber.go b/routers/api/v1/repo/subscriber.go index 61d9470707..05509fc443 100644 --- a/routers/api/v1/repo/subscriber.go +++ b/routers/api/v1/repo/subscriber.go @@ -45,7 +45,7 @@ func ListSubscribers(ctx *context.APIContext) { // "404": // "$ref": "#/responses/notFound" - subscribers, err := repo_model.GetRepoWatchers(ctx.Repo.Repository.ID, utils.GetListOptions(ctx)) + subscribers, err := repo_model.GetRepoWatchers(ctx, ctx.Repo.Repository.ID, utils.GetListOptions(ctx)) if err != nil { ctx.Error(http.StatusInternalServerError, "GetRepoWatchers", err) return diff --git a/routers/api/v1/repo/teams.go b/routers/api/v1/repo/teams.go index 2887e89603..1bacc71211 100644 --- a/routers/api/v1/repo/teams.go +++ b/routers/api/v1/repo/teams.go @@ -99,7 +99,7 @@ func IsTeam(ctx *context.APIContext) { return } - if repo_service.HasRepository(team, ctx.Repo.Repository.ID) { + if repo_service.HasRepository(ctx, team, ctx.Repo.Repository.ID) { apiTeam, err := convert.ToTeam(ctx, team) if err != nil { ctx.InternalServerError(err) @@ -198,14 +198,14 @@ func changeRepoTeam(ctx *context.APIContext, add bool) { return } - repoHasTeam := repo_service.HasRepository(team, ctx.Repo.Repository.ID) + repoHasTeam := repo_service.HasRepository(ctx, team, ctx.Repo.Repository.ID) var err error if add { if repoHasTeam { ctx.Error(http.StatusUnprocessableEntity, "alreadyAdded", fmt.Errorf("team '%s' is already added to repo", team.Name)) return } - err = org_service.TeamAddRepository(team, ctx.Repo.Repository) + err = org_service.TeamAddRepository(ctx, team, ctx.Repo.Repository) } else { if !repoHasTeam { ctx.Error(http.StatusUnprocessableEntity, "notAdded", fmt.Errorf("team '%s' was not added to repo", team.Name)) diff --git a/routers/api/v1/user/app.go b/routers/api/v1/user/app.go index f89d53945f..e512ba9e4b 100644 --- a/routers/api/v1/user/app.go +++ b/routers/api/v1/user/app.go @@ -46,12 +46,12 @@ func ListAccessTokens(ctx *context.APIContext) { opts := auth_model.ListAccessTokensOptions{UserID: ctx.Doer.ID, ListOptions: utils.GetListOptions(ctx)} - count, err := auth_model.CountAccessTokens(opts) + count, err := auth_model.CountAccessTokens(ctx, opts) if err != nil { ctx.InternalServerError(err) return } - tokens, err := auth_model.ListAccessTokens(opts) + tokens, err := auth_model.ListAccessTokens(ctx, opts) if err != nil { ctx.InternalServerError(err) return @@ -103,7 +103,7 @@ func CreateAccessToken(ctx *context.APIContext) { Name: form.Name, } - exist, err := auth_model.AccessTokenByNameExists(t) + exist, err := auth_model.AccessTokenByNameExists(ctx, t) if err != nil { ctx.InternalServerError(err) return @@ -120,7 +120,7 @@ func CreateAccessToken(ctx *context.APIContext) { } t.Scope = scope - if err := auth_model.NewAccessToken(t); err != nil { + if err := auth_model.NewAccessToken(ctx, t); err != nil { ctx.Error(http.StatusInternalServerError, "NewAccessToken", err) return } @@ -162,7 +162,7 @@ func DeleteAccessToken(ctx *context.APIContext) { tokenID, _ := strconv.ParseInt(token, 0, 64) if tokenID == 0 { - tokens, err := auth_model.ListAccessTokens(auth_model.ListAccessTokensOptions{ + tokens, err := auth_model.ListAccessTokens(ctx, auth_model.ListAccessTokensOptions{ Name: token, UserID: ctx.Doer.ID, }) @@ -187,7 +187,7 @@ func DeleteAccessToken(ctx *context.APIContext) { return } - if err := auth_model.DeleteAccessTokenByID(tokenID, ctx.Doer.ID); err != nil { + if err := auth_model.DeleteAccessTokenByID(ctx, tokenID, ctx.Doer.ID); err != nil { if auth_model.IsErrAccessTokenNotExist(err) { ctx.NotFound() } else { diff --git a/routers/api/v1/user/star.go b/routers/api/v1/user/star.go index 09f799cc6a..2659789ddd 100644 --- a/routers/api/v1/user/star.go +++ b/routers/api/v1/user/star.go @@ -155,7 +155,7 @@ func Star(ctx *context.APIContext) { // "404": // "$ref": "#/responses/notFound" - err := repo_model.StarRepo(ctx.Doer.ID, ctx.Repo.Repository.ID, true) + err := repo_model.StarRepo(ctx, ctx.Doer.ID, ctx.Repo.Repository.ID, true) if err != nil { ctx.Error(http.StatusInternalServerError, "StarRepo", err) return @@ -185,7 +185,7 @@ func Unstar(ctx *context.APIContext) { // "404": // "$ref": "#/responses/notFound" - err := repo_model.StarRepo(ctx.Doer.ID, ctx.Repo.Repository.ID, false) + err := repo_model.StarRepo(ctx, ctx.Doer.ID, ctx.Repo.Repository.ID, false) if err != nil { ctx.Error(http.StatusInternalServerError, "StarRepo", err) return diff --git a/routers/api/v1/user/watch.go b/routers/api/v1/user/watch.go index b5899baa93..7f531eafaa 100644 --- a/routers/api/v1/user/watch.go +++ b/routers/api/v1/user/watch.go @@ -124,7 +124,7 @@ func IsWatching(ctx *context.APIContext) { // "404": // description: User is not watching this repo or repo do not exist - if repo_model.IsWatching(ctx.Doer.ID, ctx.Repo.Repository.ID) { + if repo_model.IsWatching(ctx, ctx.Doer.ID, ctx.Repo.Repository.ID) { ctx.JSON(http.StatusOK, api.WatchInfo{ Subscribed: true, Ignored: false, diff --git a/routers/web/admin/users.go b/routers/web/admin/users.go index 0414a60e18..5562cc390c 100644 --- a/routers/web/admin/users.go +++ b/routers/web/admin/users.go @@ -238,7 +238,7 @@ func prepareUserInfo(ctx *context.Context) *user_model.User { } ctx.Data["Sources"] = sources - hasTOTP, err := auth.HasTwoFactorByUID(u.ID) + hasTOTP, err := auth.HasTwoFactorByUID(ctx, u.ID) if err != nil { ctx.ServerError("auth.HasTwoFactorByUID", err) return nil @@ -410,12 +410,12 @@ func EditUserPost(ctx *context.Context) { } if form.Reset2FA { - tf, err := auth.GetTwoFactorByUID(u.ID) + tf, err := auth.GetTwoFactorByUID(ctx, u.ID) if err != nil && !auth.IsErrTwoFactorNotEnrolled(err) { ctx.ServerError("auth.GetTwoFactorByUID", err) return } else if tf != nil { - if err := auth.DeleteTwoFactorByID(tf.ID, u.ID); err != nil { + if err := auth.DeleteTwoFactorByID(ctx, tf.ID, u.ID); err != nil { ctx.ServerError("auth.DeleteTwoFactorByID", err) return } diff --git a/routers/web/auth/2fa.go b/routers/web/auth/2fa.go index 4791b04313..31ede82f01 100644 --- a/routers/web/auth/2fa.go +++ b/routers/web/auth/2fa.go @@ -53,7 +53,7 @@ func TwoFactorPost(ctx *context.Context) { } id := idSess.(int64) - twofa, err := auth.GetTwoFactorByUID(id) + twofa, err := auth.GetTwoFactorByUID(ctx, id) if err != nil { ctx.ServerError("UserSignIn", err) return @@ -83,7 +83,7 @@ func TwoFactorPost(ctx *context.Context) { } twofa.LastUsedPasscode = form.Passcode - if err = auth.UpdateTwoFactor(twofa); err != nil { + if err = auth.UpdateTwoFactor(ctx, twofa); err != nil { ctx.ServerError("UserSignIn", err) return } @@ -126,7 +126,7 @@ func TwoFactorScratchPost(ctx *context.Context) { } id := idSess.(int64) - twofa, err := auth.GetTwoFactorByUID(id) + twofa, err := auth.GetTwoFactorByUID(ctx, id) if err != nil { ctx.ServerError("UserSignIn", err) return @@ -140,7 +140,7 @@ func TwoFactorScratchPost(ctx *context.Context) { ctx.ServerError("UserSignIn", err) return } - if err = auth.UpdateTwoFactor(twofa); err != nil { + if err = auth.UpdateTwoFactor(ctx, twofa); err != nil { ctx.ServerError("UserSignIn", err) return } diff --git a/routers/web/auth/auth.go b/routers/web/auth/auth.go index f8549f68f6..b7a73e4379 100644 --- a/routers/web/auth/auth.go +++ b/routers/web/auth/auth.go @@ -236,7 +236,7 @@ func SignInPost(ctx *context.Context) { // If this user is enrolled in 2FA TOTP, we can't sign the user in just yet. // Instead, redirect them to the 2FA authentication page. - hasTOTPtwofa, err := auth.HasTwoFactorByUID(u.ID) + hasTOTPtwofa, err := auth.HasTwoFactorByUID(ctx, u.ID) if err != nil { ctx.ServerError("UserSignIn", err) return diff --git a/routers/web/auth/linkaccount.go b/routers/web/auth/linkaccount.go index e6791cafce..745b4e818c 100644 --- a/routers/web/auth/linkaccount.go +++ b/routers/web/auth/linkaccount.go @@ -157,7 +157,7 @@ func linkAccount(ctx *context.Context, u *user_model.User, gothUser goth.User, r // If this user is enrolled in 2FA, we can't sign the user in just yet. // Instead, redirect them to the 2FA authentication page. // We deliberately ignore the skip local 2fa setting here because we are linking to a previous user here - _, err := auth.GetTwoFactorByUID(u.ID) + _, err := auth.GetTwoFactorByUID(ctx, u.ID) if err != nil { if !auth.IsErrTwoFactorNotEnrolled(err) { ctx.ServerError("UserLinkAccount", err) diff --git a/routers/web/auth/oauth.go b/routers/web/auth/oauth.go index 178ae84366..640c01e203 100644 --- a/routers/web/auth/oauth.go +++ b/routers/web/auth/oauth.go @@ -1097,7 +1097,7 @@ func handleOAuth2SignIn(ctx *context.Context, source *auth.Source, u *user_model needs2FA := false if !source.Cfg.(*oauth2.Source).SkipLocalTwoFA { - _, err := auth.GetTwoFactorByUID(u.ID) + _, err := auth.GetTwoFactorByUID(ctx, u.ID) if err != nil && !auth.IsErrTwoFactorNotEnrolled(err) { ctx.ServerError("UserSignIn", err) return diff --git a/routers/web/auth/password.go b/routers/web/auth/password.go index 970d316300..bdfa8c4025 100644 --- a/routers/web/auth/password.go +++ b/routers/web/auth/password.go @@ -120,7 +120,7 @@ func commonResetPassword(ctx *context.Context) (*user_model.User, *auth.TwoFacto return nil, nil } - twofa, err := auth.GetTwoFactorByUID(u.ID) + twofa, err := auth.GetTwoFactorByUID(ctx, u.ID) if err != nil { if !auth.IsErrTwoFactorNotEnrolled(err) { ctx.Error(http.StatusInternalServerError, "CommonResetPassword", err.Error()) @@ -217,7 +217,7 @@ func ResetPasswdPost(ctx *context.Context) { } twofa.LastUsedPasscode = passcode - if err = auth.UpdateTwoFactor(twofa); err != nil { + if err = auth.UpdateTwoFactor(ctx, twofa); err != nil { ctx.ServerError("ResetPasswdPost: UpdateTwoFactor", err) return } @@ -249,7 +249,7 @@ func ResetPasswdPost(ctx *context.Context) { ctx.ServerError("UserSignIn", err) return } - if err = auth.UpdateTwoFactor(twofa); err != nil { + if err = auth.UpdateTwoFactor(ctx, twofa); err != nil { ctx.ServerError("UserSignIn", err) return } diff --git a/routers/web/org/teams.go b/routers/web/org/teams.go index 46ca68b612..dfb87b28f8 100644 --- a/routers/web/org/teams.go +++ b/routers/web/org/teams.go @@ -247,7 +247,7 @@ func TeamsRepoAction(ctx *context.Context) { ctx.ServerError("GetRepositoryByName", err) return } - err = org_service.TeamAddRepository(ctx.Org.Team, repo) + err = org_service.TeamAddRepository(ctx, ctx.Org.Team, repo) case "remove": err = repo_service.RemoveRepositoryFromTeam(ctx, ctx.Org.Team, ctx.FormInt64("repoid")) case "addall": diff --git a/routers/web/repo/attachment.go b/routers/web/repo/attachment.go index b7be77914f..7b7fa9e994 100644 --- a/routers/web/repo/attachment.go +++ b/routers/web/repo/attachment.go @@ -77,7 +77,7 @@ func DeleteAttachment(ctx *context.Context) { ctx.Error(http.StatusForbidden) return } - err = repo_model.DeleteAttachment(attach, true) + err = repo_model.DeleteAttachment(ctx, attach, true) if err != nil { ctx.Error(http.StatusInternalServerError, fmt.Sprintf("DeleteAttachment: %v", err)) return @@ -122,7 +122,7 @@ func ServeAttachment(ctx *context.Context, uuid string) { } } - if err := attach.IncreaseDownloadCount(); err != nil { + if err := attach.IncreaseDownloadCount(ctx); err != nil { ctx.ServerError("IncreaseDownloadCount", err) return } diff --git a/routers/web/repo/editor.go b/routers/web/repo/editor.go index b053e3c63f..0a606582e5 100644 --- a/routers/web/repo/editor.go +++ b/routers/web/repo/editor.go @@ -812,7 +812,7 @@ func UploadFileToServer(ctx *context.Context) { return } - upload, err := repo_model.NewUpload(name, buf, file) + upload, err := repo_model.NewUpload(ctx, name, buf, file) if err != nil { ctx.Error(http.StatusInternalServerError, fmt.Sprintf("NewUpload: %v", err)) return @@ -832,7 +832,7 @@ func RemoveUploadFileFromServer(ctx *context.Context) { return } - if err := repo_model.DeleteUploadByUUID(form.File); err != nil { + if err := repo_model.DeleteUploadByUUID(ctx, form.File); err != nil { ctx.Error(http.StatusInternalServerError, fmt.Sprintf("DeleteUploadByUUID: %v", err)) return } diff --git a/routers/web/repo/http.go b/routers/web/repo/http.go index c8ecb3b1d8..1fd784a40a 100644 --- a/routers/web/repo/http.go +++ b/routers/web/repo/http.go @@ -158,7 +158,7 @@ func httpBase(ctx *context.Context) *serviceHandler { } if ctx.IsBasicAuth && ctx.Data["IsApiToken"] != true && ctx.Data["IsActionsToken"] != true { - _, err = auth_model.GetTwoFactorByUID(ctx.Doer.ID) + _, err = auth_model.GetTwoFactorByUID(ctx, ctx.Doer.ID) if err == nil { // TODO: This response should be changed to "invalid credentials" for security reasons once the expectation behind it (creating an app token to authenticate) is properly documented ctx.PlainText(http.StatusUnauthorized, "Users with two-factor authentication enabled cannot perform HTTP/HTTPS operations via plain username and password. Please create and use a personal access token on the user settings page") diff --git a/routers/web/repo/issue.go b/routers/web/repo/issue.go index 820c5d7233..94c9382f23 100644 --- a/routers/web/repo/issue.go +++ b/routers/web/repo/issue.go @@ -1975,7 +1975,7 @@ func ViewIssue(ctx *context.Context) { var hiddenCommentTypes *big.Int if ctx.IsSigned { - val, err := user_model.GetUserSetting(ctx.Doer.ID, user_model.SettingsKeyHiddenCommentTypes) + val, err := user_model.GetUserSetting(ctx, ctx.Doer.ID, user_model.SettingsKeyHiddenCommentTypes) if err != nil { ctx.ServerError("GetUserSetting", err) return @@ -2205,7 +2205,7 @@ func UpdateIssueContent(ctx *context.Context) { return } - if err := issue_service.ChangeContent(issue, ctx.Doer, ctx.Req.FormValue("content")); err != nil { + if err := issue_service.ChangeContent(ctx, issue, ctx.Doer, ctx.Req.FormValue("content")); err != nil { ctx.ServerError("ChangeContent", err) return } @@ -3451,7 +3451,7 @@ func updateAttachments(ctx *context.Context, item any, files []string) error { if util.SliceContainsString(files, attachments[i].UUID) { continue } - if err := repo_model.DeleteAttachment(attachments[i], true); err != nil { + if err := repo_model.DeleteAttachment(ctx, attachments[i], true); err != nil { return err } } diff --git a/routers/web/repo/middlewares.go b/routers/web/repo/middlewares.go index 5efc1a82b3..b50e96be3c 100644 --- a/routers/web/repo/middlewares.go +++ b/routers/web/repo/middlewares.go @@ -72,12 +72,12 @@ func SetWhitespaceBehavior(ctx *context.Context) { whitespaceBehavior = defaultWhitespaceBehavior } if ctx.IsSigned { - userWhitespaceBehavior, err := user_model.GetUserSetting(ctx.Doer.ID, user_model.SettingsKeyDiffWhitespaceBehavior, defaultWhitespaceBehavior) + userWhitespaceBehavior, err := user_model.GetUserSetting(ctx, ctx.Doer.ID, user_model.SettingsKeyDiffWhitespaceBehavior, defaultWhitespaceBehavior) if err == nil { if whitespaceBehavior == "" { whitespaceBehavior = userWhitespaceBehavior } else if whitespaceBehavior != userWhitespaceBehavior { - _ = user_model.SetUserSetting(ctx.Doer.ID, user_model.SettingsKeyDiffWhitespaceBehavior, whitespaceBehavior) + _ = user_model.SetUserSetting(ctx, ctx.Doer.ID, user_model.SettingsKeyDiffWhitespaceBehavior, whitespaceBehavior) } } // else: we can ignore the error safely } @@ -98,7 +98,7 @@ func SetShowOutdatedComments(ctx *context.Context) { if showOutdatedCommentsValue != "true" && showOutdatedCommentsValue != "false" { // invalid or no value for this form string -> use default or stored user setting if ctx.IsSigned { - showOutdatedCommentsValue, _ = user_model.GetUserSetting(ctx.Doer.ID, user_model.SettingsKeyShowOutdatedComments, "false") + showOutdatedCommentsValue, _ = user_model.GetUserSetting(ctx, ctx.Doer.ID, user_model.SettingsKeyShowOutdatedComments, "false") } else { // not logged in user -> use the default value showOutdatedCommentsValue = "false" @@ -106,7 +106,7 @@ func SetShowOutdatedComments(ctx *context.Context) { } else { // valid value -> update user setting if user is logged in if ctx.IsSigned { - _ = user_model.SetUserSetting(ctx.Doer.ID, user_model.SettingsKeyShowOutdatedComments, showOutdatedCommentsValue) + _ = user_model.SetUserSetting(ctx, ctx.Doer.ID, user_model.SettingsKeyShowOutdatedComments, showOutdatedCommentsValue) } } diff --git a/routers/web/repo/repo.go b/routers/web/repo/repo.go index 7772799557..799c2268de 100644 --- a/routers/web/repo/repo.go +++ b/routers/web/repo/repo.go @@ -308,9 +308,9 @@ func Action(ctx *context.Context) { case "unwatch": err = repo_model.WatchRepo(ctx, ctx.Doer.ID, ctx.Repo.Repository.ID, false) case "star": - err = repo_model.StarRepo(ctx.Doer.ID, ctx.Repo.Repository.ID, true) + err = repo_model.StarRepo(ctx, ctx.Doer.ID, ctx.Repo.Repository.ID, true) case "unstar": - err = repo_model.StarRepo(ctx.Doer.ID, ctx.Repo.Repository.ID, false) + err = repo_model.StarRepo(ctx, ctx.Doer.ID, ctx.Repo.Repository.ID, false) case "accept_transfer": err = acceptOrRejectRepoTransfer(ctx, true) case "reject_transfer": diff --git a/routers/web/repo/setting/collaboration.go b/routers/web/repo/setting/collaboration.go index 212b0346bc..1e71d33c08 100644 --- a/routers/web/repo/setting/collaboration.go +++ b/routers/web/repo/setting/collaboration.go @@ -173,7 +173,7 @@ func AddTeamPost(ctx *context.Context) { return } - if err = org_service.TeamAddRepository(team, ctx.Repo.Repository); err != nil { + if err = org_service.TeamAddRepository(ctx, team, ctx.Repo.Repository); err != nil { ctx.ServerError("TeamAddRepository", err) return } diff --git a/routers/web/repo/setting/settings_test.go b/routers/web/repo/setting/settings_test.go index 55f292f143..066d2ef2a9 100644 --- a/routers/web/repo/setting/settings_test.go +++ b/routers/web/repo/setting/settings_test.go @@ -8,6 +8,7 @@ import ( "testing" asymkey_model "code.gitea.io/gitea/models/asymkey" + "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/organization" "code.gitea.io/gitea/models/perm" repo_model "code.gitea.io/gitea/models/repo" @@ -248,7 +249,7 @@ func TestAddTeamPost(t *testing.T) { AddTeamPost(ctx) - assert.True(t, repo_service.HasRepository(team, re.ID)) + assert.True(t, repo_service.HasRepository(db.DefaultContext, team, re.ID)) assert.EqualValues(t, http.StatusSeeOther, ctx.Resp.Status()) assert.Empty(t, ctx.Flash.ErrorMsg) } @@ -288,7 +289,7 @@ func TestAddTeamPost_NotAllowed(t *testing.T) { AddTeamPost(ctx) - assert.False(t, repo_service.HasRepository(team, re.ID)) + assert.False(t, repo_service.HasRepository(db.DefaultContext, team, re.ID)) assert.EqualValues(t, http.StatusSeeOther, ctx.Resp.Status()) assert.NotEmpty(t, ctx.Flash.ErrorMsg) } @@ -329,7 +330,7 @@ func TestAddTeamPost_AddTeamTwice(t *testing.T) { AddTeamPost(ctx) AddTeamPost(ctx) - assert.True(t, repo_service.HasRepository(team, re.ID)) + assert.True(t, repo_service.HasRepository(db.DefaultContext, team, re.ID)) assert.EqualValues(t, http.StatusSeeOther, ctx.Resp.Status()) assert.NotEmpty(t, ctx.Flash.ErrorMsg) } @@ -402,5 +403,5 @@ func TestDeleteTeam(t *testing.T) { DeleteTeam(ctx) - assert.False(t, repo_service.HasRepository(team, re.ID)) + assert.False(t, repo_service.HasRepository(db.DefaultContext, team, re.ID)) } diff --git a/routers/web/repo/view.go b/routers/web/repo/view.go index 540a82e865..26e9cedd3a 100644 --- a/routers/web/repo/view.go +++ b/routers/web/repo/view.go @@ -1065,7 +1065,7 @@ func Watchers(ctx *context.Context) { ctx.Data["PageIsWatchers"] = true RenderUserCards(ctx, ctx.Repo.Repository.NumWatches, func(opts db.ListOptions) ([]*user_model.User, error) { - return repo_model.GetRepoWatchers(ctx.Repo.Repository.ID, opts) + return repo_model.GetRepoWatchers(ctx, ctx.Repo.Repository.ID, opts) }, tplWatchers) } @@ -1075,7 +1075,7 @@ func Stars(ctx *context.Context) { ctx.Data["CardsTitle"] = ctx.Tr("repo.stargazers") ctx.Data["PageIsStargazers"] = true RenderUserCards(ctx, ctx.Repo.Repository.NumStars, func(opts db.ListOptions) ([]*user_model.User, error) { - return repo_model.GetStargazers(ctx.Repo.Repository, opts) + return repo_model.GetStargazers(ctx, ctx.Repo.Repository, opts) }, tplWatchers) } diff --git a/routers/web/shared/user/header.go b/routers/web/shared/user/header.go index 6273e11fc5..649537ec63 100644 --- a/routers/web/shared/user/header.go +++ b/routers/web/shared/user/header.go @@ -34,7 +34,7 @@ func PrepareContextForProfileBigAvatar(ctx *context.Context) { ctx.Data["ShowUserEmail"] = setting.UI.ShowUserEmail && ctx.ContextUser.Email != "" && ctx.IsSigned && !ctx.ContextUser.KeepEmailPrivate // Show OpenID URIs - openIDs, err := user_model.GetUserOpenIDs(ctx.ContextUser.ID) + openIDs, err := user_model.GetUserOpenIDs(ctx, ctx.ContextUser.ID) if err != nil { ctx.ServerError("GetUserOpenIDs", err) return diff --git a/routers/web/user/setting/applications.go b/routers/web/user/setting/applications.go index 088aba38b6..ee44d48dce 100644 --- a/routers/web/user/setting/applications.go +++ b/routers/web/user/setting/applications.go @@ -53,7 +53,7 @@ func ApplicationsPost(ctx *context.Context) { Scope: scope, } - exist, err := auth_model.AccessTokenByNameExists(t) + exist, err := auth_model.AccessTokenByNameExists(ctx, t) if err != nil { ctx.ServerError("AccessTokenByNameExists", err) return @@ -64,7 +64,7 @@ func ApplicationsPost(ctx *context.Context) { return } - if err := auth_model.NewAccessToken(t); err != nil { + if err := auth_model.NewAccessToken(ctx, t); err != nil { ctx.ServerError("NewAccessToken", err) return } @@ -77,7 +77,7 @@ func ApplicationsPost(ctx *context.Context) { // DeleteApplication response for delete user access token func DeleteApplication(ctx *context.Context) { - if err := auth_model.DeleteAccessTokenByID(ctx.FormInt64("id"), ctx.Doer.ID); err != nil { + if err := auth_model.DeleteAccessTokenByID(ctx, ctx.FormInt64("id"), ctx.Doer.ID); err != nil { ctx.Flash.Error("DeleteAccessTokenByID: " + err.Error()) } else { ctx.Flash.Success(ctx.Tr("settings.delete_token_success")) @@ -88,7 +88,7 @@ func DeleteApplication(ctx *context.Context) { func loadApplicationsData(ctx *context.Context) { ctx.Data["AccessTokenScopePublicOnly"] = auth_model.AccessTokenScopePublicOnly - tokens, err := auth_model.ListAccessTokens(auth_model.ListAccessTokensOptions{UserID: ctx.Doer.ID}) + tokens, err := auth_model.ListAccessTokens(ctx, auth_model.ListAccessTokensOptions{UserID: ctx.Doer.ID}) if err != nil { ctx.ServerError("ListAccessTokens", err) return diff --git a/routers/web/user/setting/packages.go b/routers/web/user/setting/packages.go index 0d2eb14c20..34d18f999e 100644 --- a/routers/web/user/setting/packages.go +++ b/routers/web/user/setting/packages.go @@ -107,7 +107,7 @@ func RegenerateChefKeyPair(ctx *context.Context) { return } - if err := user_model.SetUserSetting(ctx.Doer.ID, chef_module.SettingPublicPem, pub); err != nil { + if err := user_model.SetUserSetting(ctx, ctx.Doer.ID, chef_module.SettingPublicPem, pub); err != nil { ctx.ServerError("SetUserSetting", err) return } diff --git a/routers/web/user/setting/profile.go b/routers/web/user/setting/profile.go index 13c9f08098..2aa6619a49 100644 --- a/routers/web/user/setting/profile.go +++ b/routers/web/user/setting/profile.go @@ -348,7 +348,7 @@ func Appearance(ctx *context.Context) { ctx.Data["PageIsSettingsAppearance"] = true var hiddenCommentTypes *big.Int - val, err := user_model.GetUserSetting(ctx.Doer.ID, user_model.SettingsKeyHiddenCommentTypes) + val, err := user_model.GetUserSetting(ctx, ctx.Doer.ID, user_model.SettingsKeyHiddenCommentTypes) if err != nil { ctx.ServerError("GetUserSetting", err) return @@ -420,7 +420,7 @@ func UpdateUserLang(ctx *context.Context) { // UpdateUserHiddenComments update a user's shown comment types func UpdateUserHiddenComments(ctx *context.Context) { - err := user_model.SetUserSetting(ctx.Doer.ID, user_model.SettingsKeyHiddenCommentTypes, forms.UserHiddenCommentTypesFromRequest(ctx).String()) + err := user_model.SetUserSetting(ctx, ctx.Doer.ID, user_model.SettingsKeyHiddenCommentTypes, forms.UserHiddenCommentTypesFromRequest(ctx).String()) if err != nil { ctx.ServerError("SetUserSetting", err) return diff --git a/routers/web/user/setting/security/2fa.go b/routers/web/user/setting/security/2fa.go index 0cecb1aa37..7858b634ce 100644 --- a/routers/web/user/setting/security/2fa.go +++ b/routers/web/user/setting/security/2fa.go @@ -28,7 +28,7 @@ func RegenerateScratchTwoFactor(ctx *context.Context) { ctx.Data["Title"] = ctx.Tr("settings") ctx.Data["PageIsSettingsSecurity"] = true - t, err := auth.GetTwoFactorByUID(ctx.Doer.ID) + t, err := auth.GetTwoFactorByUID(ctx, ctx.Doer.ID) if err != nil { if auth.IsErrTwoFactorNotEnrolled(err) { ctx.Flash.Error(ctx.Tr("settings.twofa_not_enrolled")) @@ -44,7 +44,7 @@ func RegenerateScratchTwoFactor(ctx *context.Context) { return } - if err = auth.UpdateTwoFactor(t); err != nil { + if err = auth.UpdateTwoFactor(ctx, t); err != nil { ctx.ServerError("SettingsTwoFactor: Failed to UpdateTwoFactor", err) return } @@ -58,7 +58,7 @@ func DisableTwoFactor(ctx *context.Context) { ctx.Data["Title"] = ctx.Tr("settings") ctx.Data["PageIsSettingsSecurity"] = true - t, err := auth.GetTwoFactorByUID(ctx.Doer.ID) + t, err := auth.GetTwoFactorByUID(ctx, ctx.Doer.ID) if err != nil { if auth.IsErrTwoFactorNotEnrolled(err) { ctx.Flash.Error(ctx.Tr("settings.twofa_not_enrolled")) @@ -68,7 +68,7 @@ func DisableTwoFactor(ctx *context.Context) { return } - if err = auth.DeleteTwoFactorByID(t.ID, ctx.Doer.ID); err != nil { + if err = auth.DeleteTwoFactorByID(ctx, t.ID, ctx.Doer.ID); err != nil { if auth.IsErrTwoFactorNotEnrolled(err) { // There is a potential DB race here - we must have been disabled by another request in the intervening period ctx.Flash.Success(ctx.Tr("settings.twofa_disabled")) @@ -145,7 +145,7 @@ func EnrollTwoFactor(ctx *context.Context) { ctx.Data["Title"] = ctx.Tr("settings") ctx.Data["PageIsSettingsSecurity"] = true - t, err := auth.GetTwoFactorByUID(ctx.Doer.ID) + t, err := auth.GetTwoFactorByUID(ctx, ctx.Doer.ID) if t != nil { // already enrolled - we should redirect back! log.Warn("Trying to re-enroll %-v in twofa when already enrolled", ctx.Doer) @@ -171,7 +171,7 @@ func EnrollTwoFactorPost(ctx *context.Context) { ctx.Data["Title"] = ctx.Tr("settings") ctx.Data["PageIsSettingsSecurity"] = true - t, err := auth.GetTwoFactorByUID(ctx.Doer.ID) + t, err := auth.GetTwoFactorByUID(ctx, ctx.Doer.ID) if t != nil { // already enrolled ctx.Flash.Error(ctx.Tr("settings.twofa_is_enrolled")) @@ -237,7 +237,7 @@ func EnrollTwoFactorPost(ctx *context.Context) { log.Error("Unable to save changes to the session: %v", err) } - if err = auth.NewTwoFactor(t); err != nil { + if err = auth.NewTwoFactor(ctx, t); err != nil { // FIXME: We need to handle a unique constraint fail here it's entirely possible that another request has beaten us. // If there is a unique constraint fail we should just tolerate the error ctx.ServerError("SettingsTwoFactor: Failed to save two factor", err) diff --git a/routers/web/user/setting/security/openid.go b/routers/web/user/setting/security/openid.go index b5509f570f..9a207e149d 100644 --- a/routers/web/user/setting/security/openid.go +++ b/routers/web/user/setting/security/openid.go @@ -44,7 +44,7 @@ func OpenIDPost(ctx *context.Context) { form.Openid = id log.Trace("Normalized id: " + id) - oids, err := user_model.GetUserOpenIDs(ctx.Doer.ID) + oids, err := user_model.GetUserOpenIDs(ctx, ctx.Doer.ID) if err != nil { ctx.ServerError("GetUserOpenIDs", err) return @@ -105,7 +105,7 @@ func settingsOpenIDVerify(ctx *context.Context) { // DeleteOpenID response for delete user's openid func DeleteOpenID(ctx *context.Context) { - if err := user_model.DeleteUserOpenID(&user_model.UserOpenID{ID: ctx.FormInt64("id"), UID: ctx.Doer.ID}); err != nil { + if err := user_model.DeleteUserOpenID(ctx, &user_model.UserOpenID{ID: ctx.FormInt64("id"), UID: ctx.Doer.ID}); err != nil { ctx.ServerError("DeleteUserOpenID", err) return } @@ -117,7 +117,7 @@ func DeleteOpenID(ctx *context.Context) { // ToggleOpenIDVisibility response for toggle visibility of user's openid func ToggleOpenIDVisibility(ctx *context.Context) { - if err := user_model.ToggleUserOpenIDVisibility(ctx.FormInt64("id")); err != nil { + if err := user_model.ToggleUserOpenIDVisibility(ctx, ctx.FormInt64("id")); err != nil { ctx.ServerError("ToggleUserOpenIDVisibility", err) return } diff --git a/routers/web/user/setting/security/security.go b/routers/web/user/setting/security/security.go index dae9bf950d..1ce59fef09 100644 --- a/routers/web/user/setting/security/security.go +++ b/routers/web/user/setting/security/security.go @@ -52,7 +52,7 @@ func DeleteAccountLink(ctx *context.Context) { } func loadSecurityData(ctx *context.Context) { - enrolled, err := auth_model.HasTwoFactorByUID(ctx.Doer.ID) + enrolled, err := auth_model.HasTwoFactorByUID(ctx, ctx.Doer.ID) if err != nil { ctx.ServerError("SettingsTwoFactor", err) return @@ -66,7 +66,7 @@ func loadSecurityData(ctx *context.Context) { } ctx.Data["WebAuthnCredentials"] = credentials - tokens, err := auth_model.ListAccessTokens(auth_model.ListAccessTokensOptions{UserID: ctx.Doer.ID}) + tokens, err := auth_model.ListAccessTokens(ctx, auth_model.ListAccessTokensOptions{UserID: ctx.Doer.ID}) if err != nil { ctx.ServerError("ListAccessTokens", err) return @@ -113,7 +113,7 @@ func loadSecurityData(ctx *context.Context) { ctx.Data["OrderedOAuth2Names"] = orderedOAuth2Names ctx.Data["OAuth2Providers"] = oauth2Providers - openid, err := user_model.GetUserOpenIDs(ctx.Doer.ID) + openid, err := user_model.GetUserOpenIDs(ctx, ctx.Doer.ID) if err != nil { ctx.ServerError("GetUserOpenIDs", err) return diff --git a/services/asymkey/sign.go b/services/asymkey/sign.go index 252277e1bc..1598f32165 100644 --- a/services/asymkey/sign.go +++ b/services/asymkey/sign.go @@ -151,7 +151,7 @@ Loop: return false, "", nil, &ErrWontSign{pubkey} } case twofa: - twofaModel, err := auth.GetTwoFactorByUID(u.ID) + twofaModel, err := auth.GetTwoFactorByUID(ctx, u.ID) if err != nil && !auth.IsErrTwoFactorNotEnrolled(err) { return false, "", nil, err } @@ -187,7 +187,7 @@ Loop: return false, "", nil, &ErrWontSign{pubkey} } case twofa: - twofaModel, err := auth.GetTwoFactorByUID(u.ID) + twofaModel, err := auth.GetTwoFactorByUID(ctx, u.ID) if err != nil && !auth.IsErrTwoFactorNotEnrolled(err) { return false, "", nil, err } @@ -240,7 +240,7 @@ Loop: return false, "", nil, &ErrWontSign{pubkey} } case twofa: - twofaModel, err := auth.GetTwoFactorByUID(u.ID) + twofaModel, err := auth.GetTwoFactorByUID(ctx, u.ID) if err != nil && !auth.IsErrTwoFactorNotEnrolled(err) { return false, "", nil, err } @@ -302,7 +302,7 @@ Loop: return false, "", nil, &ErrWontSign{pubkey} } case twofa: - twofaModel, err := auth.GetTwoFactorByUID(u.ID) + twofaModel, err := auth.GetTwoFactorByUID(ctx, u.ID) if err != nil && !auth.IsErrTwoFactorNotEnrolled(err) { return false, "", nil, err } diff --git a/services/auth/basic.go b/services/auth/basic.go index f3a9a8abce..bb9eb7a321 100644 --- a/services/auth/basic.go +++ b/services/auth/basic.go @@ -71,7 +71,7 @@ func (b *Basic) Verify(req *http.Request, w http.ResponseWriter, store DataStore } // check oauth2 token - uid := CheckOAuthAccessToken(authToken) + uid := CheckOAuthAccessToken(req.Context(), authToken) if uid != 0 { log.Trace("Basic Authorization: Valid OAuthAccessToken for user[%d]", uid) @@ -86,7 +86,7 @@ func (b *Basic) Verify(req *http.Request, w http.ResponseWriter, store DataStore } // check personal access token - token, err := auth_model.GetAccessTokenBySHA(authToken) + token, err := auth_model.GetAccessTokenBySHA(req.Context(), authToken) if err == nil { log.Trace("Basic Authorization: Valid AccessToken for user[%d]", uid) u, err := user_model.GetUserByID(req.Context(), token.UID) @@ -96,7 +96,7 @@ func (b *Basic) Verify(req *http.Request, w http.ResponseWriter, store DataStore } token.UpdatedUnix = timeutil.TimeStampNow() - if err = auth_model.UpdateAccessToken(token); err != nil { + if err = auth_model.UpdateAccessToken(req.Context(), token); err != nil { log.Error("UpdateAccessToken: %v", err) } diff --git a/services/auth/oauth2.go b/services/auth/oauth2.go index e621b5ffad..6572d661e8 100644 --- a/services/auth/oauth2.go +++ b/services/auth/oauth2.go @@ -5,13 +5,13 @@ package auth import ( + "context" "net/http" "strings" "time" actions_model "code.gitea.io/gitea/models/actions" auth_model "code.gitea.io/gitea/models/auth" - "code.gitea.io/gitea/models/db" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/timeutil" @@ -25,7 +25,7 @@ var ( ) // CheckOAuthAccessToken returns uid of user from oauth token -func CheckOAuthAccessToken(accessToken string) int64 { +func CheckOAuthAccessToken(ctx context.Context, accessToken string) int64 { // JWT tokens require a "." if !strings.Contains(accessToken, ".") { return 0 @@ -36,7 +36,7 @@ func CheckOAuthAccessToken(accessToken string) int64 { return 0 } var grant *auth_model.OAuth2Grant - if grant, err = auth_model.GetOAuth2GrantByID(db.DefaultContext, token.GrantID); err != nil || grant == nil { + if grant, err = auth_model.GetOAuth2GrantByID(ctx, token.GrantID); err != nil || grant == nil { return 0 } if token.Type != oauth2.TypeAccessToken { @@ -83,21 +83,21 @@ func parseToken(req *http.Request) (string, bool) { // userIDFromToken returns the user id corresponding to the OAuth token. // It will set 'IsApiToken' to true if the token is an API token and // set 'ApiTokenScope' to the scope of the access token -func (o *OAuth2) userIDFromToken(tokenSHA string, store DataStore) int64 { +func (o *OAuth2) userIDFromToken(ctx context.Context, tokenSHA string, store DataStore) int64 { // Let's see if token is valid. if strings.Contains(tokenSHA, ".") { - uid := CheckOAuthAccessToken(tokenSHA) + uid := CheckOAuthAccessToken(ctx, tokenSHA) if uid != 0 { store.GetData()["IsApiToken"] = true store.GetData()["ApiTokenScope"] = auth_model.AccessTokenScopeAll // fallback to all } return uid } - t, err := auth_model.GetAccessTokenBySHA(tokenSHA) + t, err := auth_model.GetAccessTokenBySHA(ctx, tokenSHA) if err != nil { if auth_model.IsErrAccessTokenNotExist(err) { // check task token - task, err := actions_model.GetRunningTaskByToken(db.DefaultContext, tokenSHA) + task, err := actions_model.GetRunningTaskByToken(ctx, tokenSHA) if err == nil && task != nil { log.Trace("Basic Authorization: Valid AccessToken for task[%d]", task.ID) @@ -112,7 +112,7 @@ func (o *OAuth2) userIDFromToken(tokenSHA string, store DataStore) int64 { return 0 } t.UpdatedUnix = timeutil.TimeStampNow() - if err = auth_model.UpdateAccessToken(t); err != nil { + if err = auth_model.UpdateAccessToken(ctx, t); err != nil { log.Error("UpdateAccessToken: %v", err) } store.GetData()["IsApiToken"] = true @@ -134,7 +134,7 @@ func (o *OAuth2) Verify(req *http.Request, w http.ResponseWriter, store DataStor return nil, nil } - id := o.userIDFromToken(token, store) + id := o.userIDFromToken(req.Context(), token, store) if id <= 0 && id != -2 { // -2 means actions, so we need to allow it. return nil, user_model.ErrUserNotExist{} diff --git a/services/issue/content.go b/services/issue/content.go index cda11dbb18..41f1bfefe8 100644 --- a/services/issue/content.go +++ b/services/issue/content.go @@ -4,21 +4,22 @@ package issue import ( - "code.gitea.io/gitea/models/db" + "context" + issues_model "code.gitea.io/gitea/models/issues" user_model "code.gitea.io/gitea/models/user" notify_service "code.gitea.io/gitea/services/notify" ) // ChangeContent changes issue content, as the given user. -func ChangeContent(issue *issues_model.Issue, doer *user_model.User, content string) (err error) { +func ChangeContent(ctx context.Context, issue *issues_model.Issue, doer *user_model.User, content string) (err error) { oldContent := issue.Content if err := issues_model.ChangeIssueContent(issue, doer, content); err != nil { return err } - notify_service.IssueChangeContent(db.DefaultContext, doer, issue, oldContent) + notify_service.IssueChangeContent(ctx, doer, issue, oldContent) return nil } diff --git a/services/migrations/gitea_uploader_test.go b/services/migrations/gitea_uploader_test.go index 878b6d6b84..e42d9e9286 100644 --- a/services/migrations/gitea_uploader_test.go +++ b/services/migrations/gitea_uploader_test.go @@ -113,7 +113,7 @@ func TestGiteaUploadRepo(t *testing.T) { assert.NoError(t, issues[0].LoadDiscussComments(db.DefaultContext)) assert.Empty(t, issues[0].Comments) - pulls, _, err := issues_model.PullRequests(repo.ID, &issues_model.PullRequestsOptions{ + pulls, _, err := issues_model.PullRequests(db.DefaultContext, repo.ID, &issues_model.PullRequestsOptions{ SortType: "oldest", }) assert.NoError(t, err) diff --git a/services/org/repo.go b/services/org/repo.go index 0edbf2d464..78a829ef25 100644 --- a/services/org/repo.go +++ b/services/org/repo.go @@ -14,14 +14,14 @@ import ( ) // TeamAddRepository adds new repository to team of organization. -func TeamAddRepository(t *organization.Team, repo *repo_model.Repository) (err error) { +func TeamAddRepository(ctx context.Context, t *organization.Team, repo *repo_model.Repository) (err error) { if repo.OwnerID != t.OrgID { return errors.New("repository does not belong to organization") - } else if organization.HasTeamRepo(db.DefaultContext, t.OrgID, t.ID, repo.ID) { + } else if organization.HasTeamRepo(ctx, t.OrgID, t.ID, repo.ID) { return nil } - return db.WithTx(db.DefaultContext, func(ctx context.Context) error { + return db.WithTx(ctx, func(ctx context.Context) error { return models.AddRepository(ctx, t, repo) }) } diff --git a/services/org/repo_test.go b/services/org/repo_test.go index 40b0d17077..68c64a01ab 100644 --- a/services/org/repo_test.go +++ b/services/org/repo_test.go @@ -6,6 +6,7 @@ package org import ( "testing" + "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/organization" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" @@ -19,7 +20,7 @@ func TestTeam_AddRepository(t *testing.T) { testSuccess := func(teamID, repoID int64) { team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID}) - assert.NoError(t, TeamAddRepository(team, repo)) + assert.NoError(t, TeamAddRepository(db.DefaultContext, team, repo)) unittest.AssertExistsAndLoadBean(t, &organization.TeamRepo{TeamID: teamID, RepoID: repoID}) unittest.CheckConsistencyFor(t, &organization.Team{ID: teamID}, &repo_model.Repository{ID: repoID}) } @@ -28,6 +29,6 @@ func TestTeam_AddRepository(t *testing.T) { team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 1}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) - assert.Error(t, TeamAddRepository(team, repo)) + assert.Error(t, TeamAddRepository(db.DefaultContext, team, repo)) unittest.CheckConsistencyFor(t, &organization.Team{ID: 1}, &repo_model.Repository{ID: 1}) } diff --git a/services/packages/alpine/repository.go b/services/packages/alpine/repository.go index 5264bd6c4a..24e673289a 100644 --- a/services/packages/alpine/repository.go +++ b/services/packages/alpine/repository.go @@ -39,13 +39,13 @@ func GetOrCreateRepositoryVersion(ownerID int64) (*packages_model.PackageVersion } // GetOrCreateKeyPair gets or creates the RSA keys used to sign repository files -func GetOrCreateKeyPair(ownerID int64) (string, string, error) { - priv, err := user_model.GetSetting(ownerID, alpine_module.SettingKeyPrivate) +func GetOrCreateKeyPair(ctx context.Context, ownerID int64) (string, string, error) { + priv, err := user_model.GetSetting(ctx, ownerID, alpine_module.SettingKeyPrivate) if err != nil && !errors.Is(err, util.ErrNotExist) { return "", "", err } - pub, err := user_model.GetSetting(ownerID, alpine_module.SettingKeyPublic) + pub, err := user_model.GetSetting(ctx, ownerID, alpine_module.SettingKeyPublic) if err != nil && !errors.Is(err, util.ErrNotExist) { return "", "", err } @@ -56,11 +56,11 @@ func GetOrCreateKeyPair(ownerID int64) (string, string, error) { return "", "", err } - if err := user_model.SetUserSetting(ownerID, alpine_module.SettingKeyPrivate, priv); err != nil { + if err := user_model.SetUserSetting(ctx, ownerID, alpine_module.SettingKeyPrivate, priv); err != nil { return "", "", err } - if err := user_model.SetUserSetting(ownerID, alpine_module.SettingKeyPublic, pub); err != nil { + if err := user_model.SetUserSetting(ctx, ownerID, alpine_module.SettingKeyPublic, pub); err != nil { return "", "", err } } @@ -244,7 +244,7 @@ func buildPackagesIndex(ctx context.Context, ownerID int64, repoVersion *package return err } - priv, _, err := GetOrCreateKeyPair(ownerID) + priv, _, err := GetOrCreateKeyPair(ctx, ownerID) if err != nil { return err } diff --git a/services/packages/debian/repository.go b/services/packages/debian/repository.go index be82fbed6e..46b1a94b81 100644 --- a/services/packages/debian/repository.go +++ b/services/packages/debian/repository.go @@ -37,13 +37,13 @@ func GetOrCreateRepositoryVersion(ownerID int64) (*packages_model.PackageVersion } // GetOrCreateKeyPair gets or creates the PGP keys used to sign repository files -func GetOrCreateKeyPair(ownerID int64) (string, string, error) { - priv, err := user_model.GetSetting(ownerID, debian_module.SettingKeyPrivate) +func GetOrCreateKeyPair(ctx context.Context, ownerID int64) (string, string, error) { + priv, err := user_model.GetSetting(ctx, ownerID, debian_module.SettingKeyPrivate) if err != nil && !errors.Is(err, util.ErrNotExist) { return "", "", err } - pub, err := user_model.GetSetting(ownerID, debian_module.SettingKeyPublic) + pub, err := user_model.GetSetting(ctx, ownerID, debian_module.SettingKeyPublic) if err != nil && !errors.Is(err, util.ErrNotExist) { return "", "", err } @@ -54,11 +54,11 @@ func GetOrCreateKeyPair(ownerID int64) (string, string, error) { return "", "", err } - if err := user_model.SetUserSetting(ownerID, debian_module.SettingKeyPrivate, priv); err != nil { + if err := user_model.SetUserSetting(ctx, ownerID, debian_module.SettingKeyPrivate, priv); err != nil { return "", "", err } - if err := user_model.SetUserSetting(ownerID, debian_module.SettingKeyPublic, pub); err != nil { + if err := user_model.SetUserSetting(ctx, ownerID, debian_module.SettingKeyPublic, pub); err != nil { return "", "", err } } @@ -306,7 +306,7 @@ func buildReleaseFiles(ctx context.Context, ownerID int64, repoVersion *packages sort.Strings(architectures) - priv, _, err := GetOrCreateKeyPair(ownerID) + priv, _, err := GetOrCreateKeyPair(ctx, ownerID) if err != nil { return err } diff --git a/services/packages/rpm/repository.go b/services/packages/rpm/repository.go index cfd70ec23e..d115197197 100644 --- a/services/packages/rpm/repository.go +++ b/services/packages/rpm/repository.go @@ -38,13 +38,13 @@ func GetOrCreateRepositoryVersion(ownerID int64) (*packages_model.PackageVersion } // GetOrCreateKeyPair gets or creates the PGP keys used to sign repository metadata files -func GetOrCreateKeyPair(ownerID int64) (string, string, error) { - priv, err := user_model.GetSetting(ownerID, rpm_module.SettingKeyPrivate) +func GetOrCreateKeyPair(ctx context.Context, ownerID int64) (string, string, error) { + priv, err := user_model.GetSetting(ctx, ownerID, rpm_module.SettingKeyPrivate) if err != nil && !errors.Is(err, util.ErrNotExist) { return "", "", err } - pub, err := user_model.GetSetting(ownerID, rpm_module.SettingKeyPublic) + pub, err := user_model.GetSetting(ctx, ownerID, rpm_module.SettingKeyPublic) if err != nil && !errors.Is(err, util.ErrNotExist) { return "", "", err } @@ -55,11 +55,11 @@ func GetOrCreateKeyPair(ownerID int64) (string, string, error) { return "", "", err } - if err := user_model.SetUserSetting(ownerID, rpm_module.SettingKeyPrivate, priv); err != nil { + if err := user_model.SetUserSetting(ctx, ownerID, rpm_module.SettingKeyPrivate, priv); err != nil { return "", "", err } - if err := user_model.SetUserSetting(ownerID, rpm_module.SettingKeyPublic, pub); err != nil { + if err := user_model.SetUserSetting(ctx, ownerID, rpm_module.SettingKeyPublic, pub); err != nil { return "", "", err } } @@ -212,6 +212,7 @@ func BuildRepositoryFiles(ctx context.Context, ownerID int64) error { } return buildRepomd( + ctx, pv, ownerID, []*repoData{ @@ -223,7 +224,7 @@ func BuildRepositoryFiles(ctx context.Context, ownerID int64) error { } // https://docs.pulpproject.org/en/2.19/plugins/pulp_rpm/tech-reference/rpm.html#repomd-xml -func buildRepomd(pv *packages_model.PackageVersion, ownerID int64, data []*repoData) error { +func buildRepomd(ctx context.Context, pv *packages_model.PackageVersion, ownerID int64, data []*repoData) error { type Repomd struct { XMLName xml.Name `xml:"repomd"` Xmlns string `xml:"xmlns,attr"` @@ -241,7 +242,7 @@ func buildRepomd(pv *packages_model.PackageVersion, ownerID int64, data []*repoD return err } - priv, _, err := GetOrCreateKeyPair(ownerID) + priv, _, err := GetOrCreateKeyPair(ctx, ownerID) if err != nil { return err } diff --git a/services/pull/check.go b/services/pull/check.go index dcb488c309..e4a0f6b27b 100644 --- a/services/pull/check.go +++ b/services/pull/check.go @@ -303,7 +303,7 @@ func manuallyMerged(ctx context.Context, pr *issues_model.PullRequest) bool { // InitializePullRequests checks and tests untested patches of pull requests. func InitializePullRequests(ctx context.Context) { - prs, err := issues_model.GetPullRequestIDsByCheckStatus(issues_model.PullRequestStatusChecking) + prs, err := issues_model.GetPullRequestIDsByCheckStatus(ctx, issues_model.PullRequestStatusChecking) if err != nil { log.Error("Find Checking PRs: %v", err) return diff --git a/services/repository/create_test.go b/services/repository/create_test.go index 7ffdcc38fb..36065cafff 100644 --- a/services/repository/create_test.go +++ b/services/repository/create_test.go @@ -28,7 +28,7 @@ func TestIncludesAllRepositoriesTeams(t *testing.T) { assert.Len(t, team.Repos, len(repoIds), "%s: repo count", team.Name) for i, rid := range repoIds { if rid > 0 { - assert.True(t, HasRepository(team, rid), "%s: HasRepository(%d) %d", rid, i) + assert.True(t, HasRepository(db.DefaultContext, team, rid), "%s: HasRepository(%d) %d", rid, i) } } } diff --git a/services/repository/delete.go b/services/repository/delete.go index 8e28c9b255..f2b4781458 100644 --- a/services/repository/delete.go +++ b/services/repository/delete.go @@ -286,36 +286,36 @@ func DeleteRepositoryDirectly(ctx context.Context, doer *user_model.User, uid, r // Remove repository files. repoPath := repo.RepoPath() - system_model.RemoveAllWithNotice(db.DefaultContext, "Delete repository files", repoPath) + system_model.RemoveAllWithNotice(ctx, "Delete repository files", repoPath) // Remove wiki files if repo.HasWiki() { - system_model.RemoveAllWithNotice(db.DefaultContext, "Delete repository wiki", repo.WikiPath()) + system_model.RemoveAllWithNotice(ctx, "Delete repository wiki", repo.WikiPath()) } // Remove archives for _, archive := range archivePaths { - system_model.RemoveStorageWithNotice(db.DefaultContext, storage.RepoArchives, "Delete repo archive file", archive) + system_model.RemoveStorageWithNotice(ctx, storage.RepoArchives, "Delete repo archive file", archive) } // Remove lfs objects for _, lfsObj := range lfsPaths { - system_model.RemoveStorageWithNotice(db.DefaultContext, storage.LFS, "Delete orphaned LFS file", lfsObj) + system_model.RemoveStorageWithNotice(ctx, storage.LFS, "Delete orphaned LFS file", lfsObj) } // Remove issue attachment files. for _, attachment := range attachmentPaths { - system_model.RemoveStorageWithNotice(db.DefaultContext, storage.Attachments, "Delete issue attachment", attachment) + system_model.RemoveStorageWithNotice(ctx, storage.Attachments, "Delete issue attachment", attachment) } // Remove release attachment files. for _, releaseAttachment := range releaseAttachments { - system_model.RemoveStorageWithNotice(db.DefaultContext, storage.Attachments, "Delete release attachment", releaseAttachment) + system_model.RemoveStorageWithNotice(ctx, storage.Attachments, "Delete release attachment", releaseAttachment) } // Remove attachment with no issue_id and release_id. for _, newAttachment := range newAttachmentPaths { - system_model.RemoveStorageWithNotice(db.DefaultContext, storage.Attachments, "Delete issue attachment", newAttachment) + system_model.RemoveStorageWithNotice(ctx, storage.Attachments, "Delete issue attachment", newAttachment) } if len(repo.Avatar) > 0 { @@ -390,14 +390,14 @@ func removeRepositoryFromTeam(ctx context.Context, t *organization.Team, repo *r } // HasRepository returns true if given repository belong to team. -func HasRepository(t *organization.Team, repoID int64) bool { - return organization.HasTeamRepo(db.DefaultContext, t.OrgID, t.ID, repoID) +func HasRepository(ctx context.Context, t *organization.Team, repoID int64) bool { + return organization.HasTeamRepo(ctx, t.OrgID, t.ID, repoID) } // RemoveRepositoryFromTeam removes repository from team of organization. // If the team shall include all repositories the request is ignored. func RemoveRepositoryFromTeam(ctx context.Context, t *organization.Team, repoID int64) error { - if !HasRepository(t, repoID) { + if !HasRepository(ctx, t, repoID) { return nil } diff --git a/services/repository/delete_test.go b/services/repository/delete_test.go index 2905c01868..ae5fd53962 100644 --- a/services/repository/delete_test.go +++ b/services/repository/delete_test.go @@ -19,7 +19,7 @@ func TestTeam_HasRepository(t *testing.T) { test := func(teamID, repoID int64, expected bool) { team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) - assert.Equal(t, expected, HasRepository(team, repoID)) + assert.Equal(t, expected, HasRepository(db.DefaultContext, team, repoID)) } test(1, 1, false) test(1, 3, true) diff --git a/services/repository/files/upload.go b/services/repository/files/upload.go index 338811f0f1..f4e1da7bb1 100644 --- a/services/repository/files/upload.go +++ b/services/repository/files/upload.go @@ -10,7 +10,6 @@ import ( "path" "strings" - "code.gitea.io/gitea/models/db" git_model "code.gitea.io/gitea/models/git" repo_model "code.gitea.io/gitea/models/repo" user_model "code.gitea.io/gitea/models/user" @@ -35,13 +34,13 @@ type uploadInfo struct { lfsMetaObject *git_model.LFSMetaObject } -func cleanUpAfterFailure(infos *[]uploadInfo, t *TemporaryUploadRepository, original error) error { +func cleanUpAfterFailure(ctx context.Context, infos *[]uploadInfo, t *TemporaryUploadRepository, original error) error { for _, info := range *infos { if info.lfsMetaObject == nil { continue } if !info.lfsMetaObject.Existing { - if _, err := git_model.RemoveLFSMetaObjectByOid(db.DefaultContext, t.repo.ID, info.lfsMetaObject.Oid); err != nil { + if _, err := git_model.RemoveLFSMetaObjectByOid(ctx, t.repo.ID, info.lfsMetaObject.Oid); err != nil { original = fmt.Errorf("%w, %v", original, err) // We wrap the original error - as this is the underlying error that required the fallback } } @@ -55,7 +54,7 @@ func UploadRepoFiles(ctx context.Context, repo *repo_model.Repository, doer *use return nil } - uploads, err := repo_model.GetUploadsByUUIDs(opts.Files) + uploads, err := repo_model.GetUploadsByUUIDs(ctx, opts.Files) if err != nil { return fmt.Errorf("GetUploadsByUUIDs [uuids: %v]: %w", opts.Files, err) } @@ -147,7 +146,7 @@ func UploadRepoFiles(ctx context.Context, repo *repo_model.Repository, doer *use infos[i].lfsMetaObject, err = git_model.NewLFSMetaObject(ctx, infos[i].lfsMetaObject) if err != nil { // OK Now we need to cleanup - return cleanUpAfterFailure(&infos, t, err) + return cleanUpAfterFailure(ctx, &infos, t, err) } // Don't move the files yet - we need to ensure that // everything can be inserted first @@ -158,7 +157,7 @@ func UploadRepoFiles(ctx context.Context, repo *repo_model.Repository, doer *use contentStore := lfs.NewContentStore() for _, info := range infos { if err := uploadToLFSContentStore(info, contentStore); err != nil { - return cleanUpAfterFailure(&infos, t, err) + return cleanUpAfterFailure(ctx, &infos, t, err) } } @@ -167,7 +166,7 @@ func UploadRepoFiles(ctx context.Context, repo *repo_model.Repository, doer *use return err } - return repo_model.DeleteUploads(uploads...) + return repo_model.DeleteUploads(ctx, uploads...) } func copyUploadedLFSFileIntoRepository(info *uploadInfo, filename2attribute2info map[string]map[string]string, t *TemporaryUploadRepository, treePath string) error { diff --git a/tests/integration/api_activitypub_person_test.go b/tests/integration/api_activitypub_person_test.go index 1a8a38ce56..3222dfc807 100644 --- a/tests/integration/api_activitypub_person_test.go +++ b/tests/integration/api_activitypub_person_test.go @@ -11,6 +11,7 @@ import ( "net/url" "testing" + "code.gitea.io/gitea/models/db" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/activitypub" "code.gitea.io/gitea/modules/setting" @@ -96,7 +97,7 @@ func TestActivityPubPersonInbox(t *testing.T) { user1, err := user_model.GetUserByName(ctx, username1) assert.NoError(t, err) user1url := fmt.Sprintf("%s/api/v1/activitypub/user-id/1#main-key", srv.URL) - c, err := activitypub.NewClient(user1, user1url) + c, err := activitypub.NewClient(db.DefaultContext, user1, user1url) assert.NoError(t, err) user2inboxurl := fmt.Sprintf("%s/api/v1/activitypub/user-id/2/inbox", srv.URL) diff --git a/tests/integration/api_packages_chef_test.go b/tests/integration/api_packages_chef_test.go index 0ee43e1741..4a1fe2607e 100644 --- a/tests/integration/api_packages_chef_test.go +++ b/tests/integration/api_packages_chef_test.go @@ -83,7 +83,7 @@ kPuCu6vH9brvOuYo0q8hLVNkBeXcimRpsDjLhQYzEJjoMTbaiVGnjBky+PWNiofJ nwIDAQAB -----END PUBLIC KEY-----` - err := user_model.SetUserSetting(user.ID, chef_module.SettingPublicPem, pubPem) + err := user_model.SetUserSetting(db.DefaultContext, user.ID, chef_module.SettingPublicPem, pubPem) assert.NoError(t, err) t.Run("Authenticate", func(t *testing.T) {