From 76a85a4ce90fead1eb2b743a42b41617b4592889 Mon Sep 17 00:00:00 2001 From: JakobDev Date: Sat, 14 Oct 2023 10:37:24 +0200 Subject: [PATCH] Final round of `db.DefaultContext` refactor (#27587) Last part of #27065 --- cmd/admin_auth.go | 2 +- models/asymkey/gpg_key.go | 4 +- models/asymkey/gpg_key_import.go | 10 +++-- models/asymkey/gpg_key_verify.go | 5 ++- models/asymkey/ssh_key_deploy.go | 16 +++---- models/asymkey/ssh_key_principals.go | 14 +++--- models/asymkey/ssh_key_verify.go | 5 ++- models/auth/oauth2.go | 24 +++++----- models/auth/oauth2_test.go | 6 +-- models/avatars/avatar.go | 10 ++--- models/repo/redirect.go | 4 +- models/repo/redirect_test.go | 4 +- models/user/external_login_user.go | 32 +++++++------- models/webhook/hooktask.go | 8 ++-- models/webhook/webhook.go | 44 +++++++++---------- models/webhook/webhook_test.go | 28 ++++++------ modules/context/repo.go | 12 ++--- modules/eventsource/manager_run.go | 2 +- routers/api/v1/api.go | 2 +- routers/api/v1/repo/hook.go | 4 +- routers/api/v1/repo/issue_stopwatch.go | 4 +- routers/api/v1/repo/issue_tracked_time.go | 6 +-- routers/api/v1/repo/key.go | 4 +- routers/api/v1/repo/pull.go | 2 +- routers/api/v1/user/app.go | 10 ++--- routers/api/v1/user/gpg_key.go | 4 +- routers/api/v1/utils/hook.go | 10 ++--- routers/init.go | 2 +- routers/private/key.go | 2 +- routers/web/admin/auths.go | 2 +- routers/web/auth/auth.go | 10 ++--- routers/web/auth/linkaccount.go | 2 +- routers/web/auth/oauth.go | 10 ++--- routers/web/org/setting.go | 2 +- routers/web/repo/http.go | 2 +- routers/web/repo/issue.go | 6 +-- routers/web/repo/issue_dependency.go | 4 +- routers/web/repo/issue_stopwatch.go | 4 +- routers/web/repo/issue_timetrack.go | 4 +- routers/web/repo/pull.go | 2 +- routers/web/repo/setting/deploy_key.go | 2 +- routers/web/repo/setting/webhook.go | 12 ++--- routers/web/user/avatar.go | 2 +- routers/web/user/home.go | 2 +- routers/web/user/setting/keys.go | 12 ++--- routers/web/user/setting/oauth2_common.go | 8 ++-- routers/web/user/setting/security/security.go | 6 +-- routers/web/user/setting/webhooks.go | 2 +- routers/web/user/stop_watch.go | 2 +- services/actions/notifier.go | 15 +++---- services/auth/source.go | 10 +++-- services/auth/source/oauth2/init.go | 13 +++--- services/auth/source/oauth2/providers.go | 5 ++- services/convert/issue.go | 7 ++- services/externalaccount/user.go | 14 +++--- services/migrations/gitea_uploader.go | 2 +- services/migrations/gitea_uploader_test.go | 2 +- services/migrations/update.go | 2 +- services/pull/lfs.go | 8 ++-- services/pull/merge.go | 4 +- services/pull/pull.go | 6 +-- services/webhook/deliver.go | 6 +-- tests/integration/api_private_serv_test.go | 6 +-- tests/integration/pull_merge_test.go | 16 +++---- 64 files changed, 250 insertions(+), 242 deletions(-) diff --git a/cmd/admin_auth.go b/cmd/admin_auth.go index 0c931e74e..3b308d77f 100644 --- a/cmd/admin_auth.go +++ b/cmd/admin_auth.go @@ -105,5 +105,5 @@ func runDeleteAuth(c *cli.Context) error { return err } - return auth_service.DeleteSource(source) + return auth_service.DeleteSource(ctx, source) } diff --git a/models/asymkey/gpg_key.go b/models/asymkey/gpg_key.go index 21d271bed..1da7c346d 100644 --- a/models/asymkey/gpg_key.go +++ b/models/asymkey/gpg_key.go @@ -111,8 +111,8 @@ func GetGPGKeysByKeyID(ctx context.Context, keyID string) ([]*GPGKey, error) { } // GPGKeyToEntity retrieve the imported key and the traducted entity -func GPGKeyToEntity(k *GPGKey) (*openpgp.Entity, error) { - impKey, err := GetGPGImportByKeyID(k.KeyID) +func GPGKeyToEntity(ctx context.Context, k *GPGKey) (*openpgp.Entity, error) { + impKey, err := GetGPGImportByKeyID(ctx, k.KeyID) if err != nil { return nil, err } diff --git a/models/asymkey/gpg_key_import.go b/models/asymkey/gpg_key_import.go index 83881b5c2..c9d46d29e 100644 --- a/models/asymkey/gpg_key_import.go +++ b/models/asymkey/gpg_key_import.go @@ -3,7 +3,11 @@ package asymkey -import "code.gitea.io/gitea/models/db" +import ( + "context" + + "code.gitea.io/gitea/models/db" +) // __________________ ________ ____ __. // / _____/\______ \/ _____/ | |/ _|____ ___.__. @@ -31,9 +35,9 @@ func init() { } // GetGPGImportByKeyID returns the import public armored key by given KeyID. -func GetGPGImportByKeyID(keyID string) (*GPGKeyImport, error) { +func GetGPGImportByKeyID(ctx context.Context, keyID string) (*GPGKeyImport, error) { key := new(GPGKeyImport) - has, err := db.GetEngine(db.DefaultContext).ID(keyID).Get(key) + has, err := db.GetEngine(ctx).ID(keyID).Get(key) if err != nil { return nil, err } else if !has { diff --git a/models/asymkey/gpg_key_verify.go b/models/asymkey/gpg_key_verify.go index cb5eb7c85..be36482c7 100644 --- a/models/asymkey/gpg_key_verify.go +++ b/models/asymkey/gpg_key_verify.go @@ -4,6 +4,7 @@ package asymkey import ( + "context" "strconv" "time" @@ -29,8 +30,8 @@ import ( // This file provides functions relating verifying gpg keys // VerifyGPGKey marks a GPG key as verified -func VerifyGPGKey(ownerID int64, keyID, token, signature string) (string, error) { - ctx, committer, err := db.TxContext(db.DefaultContext) +func VerifyGPGKey(ctx context.Context, ownerID int64, keyID, token, signature string) (string, error) { + ctx, committer, err := db.TxContext(ctx) if err != nil { return "", err } diff --git a/models/asymkey/ssh_key_deploy.go b/models/asymkey/ssh_key_deploy.go index 25d95291f..e347604bc 100644 --- a/models/asymkey/ssh_key_deploy.go +++ b/models/asymkey/ssh_key_deploy.go @@ -106,15 +106,15 @@ func addDeployKey(ctx context.Context, keyID, repoID int64, name, fingerprint st } // HasDeployKey returns true if public key is a deploy key of given repository. -func HasDeployKey(keyID, repoID int64) bool { - has, _ := db.GetEngine(db.DefaultContext). +func HasDeployKey(ctx context.Context, keyID, repoID int64) bool { + has, _ := db.GetEngine(ctx). Where("key_id = ? AND repo_id = ?", keyID, repoID). Get(new(DeployKey)) return has } // AddDeployKey add new deploy key to database and authorized_keys file. -func AddDeployKey(repoID int64, name, content string, readOnly bool) (*DeployKey, error) { +func AddDeployKey(ctx context.Context, repoID int64, name, content string, readOnly bool) (*DeployKey, error) { fingerprint, err := CalcFingerprint(content) if err != nil { return nil, err @@ -125,7 +125,7 @@ func AddDeployKey(repoID int64, name, content string, readOnly bool) (*DeployKey accessMode = perm.AccessModeWrite } - ctx, committer, err := db.TxContext(db.DefaultContext) + ctx, committer, err := db.TxContext(ctx) if err != nil { return nil, err } @@ -197,8 +197,8 @@ func IsDeployKeyExistByKeyID(ctx context.Context, keyID int64) (bool, error) { } // UpdateDeployKeyCols updates deploy key information in the specified columns. -func UpdateDeployKeyCols(key *DeployKey, cols ...string) error { - _, err := db.GetEngine(db.DefaultContext).ID(key.ID).Cols(cols...).Update(key) +func UpdateDeployKeyCols(ctx context.Context, key *DeployKey, cols ...string) error { + _, err := db.GetEngine(ctx).ID(key.ID).Cols(cols...).Update(key) return err } @@ -240,6 +240,6 @@ func ListDeployKeys(ctx context.Context, opts *ListDeployKeysOptions) ([]*Deploy } // CountDeployKeys returns count deploy keys matching the provided arguments. -func CountDeployKeys(opts *ListDeployKeysOptions) (int64, error) { - return db.GetEngine(db.DefaultContext).Where(opts.toCond()).Count(&DeployKey{}) +func CountDeployKeys(ctx context.Context, opts *ListDeployKeysOptions) (int64, error) { + return db.GetEngine(ctx).Where(opts.toCond()).Count(&DeployKey{}) } diff --git a/models/asymkey/ssh_key_principals.go b/models/asymkey/ssh_key_principals.go index 150b77c7b..92789e26f 100644 --- a/models/asymkey/ssh_key_principals.go +++ b/models/asymkey/ssh_key_principals.go @@ -25,15 +25,15 @@ import ( // This file contains functions related to principals // AddPrincipalKey adds new principal to database and authorized_principals file. -func AddPrincipalKey(ownerID int64, content string, authSourceID int64) (*PublicKey, error) { - ctx, committer, err := db.TxContext(db.DefaultContext) +func AddPrincipalKey(ctx context.Context, ownerID int64, content string, authSourceID int64) (*PublicKey, error) { + dbCtx, committer, err := db.TxContext(ctx) if err != nil { return nil, err } defer committer.Close() // Principals cannot be duplicated. - has, err := db.GetEngine(ctx). + has, err := db.GetEngine(dbCtx). Where("content = ? AND type = ?", content, KeyTypePrincipal). Get(new(PublicKey)) if err != nil { @@ -50,7 +50,7 @@ func AddPrincipalKey(ownerID int64, content string, authSourceID int64) (*Public Type: KeyTypePrincipal, LoginSourceID: authSourceID, } - if err = db.Insert(ctx, key); err != nil { + if err = db.Insert(dbCtx, key); err != nil { return nil, fmt.Errorf("addKey: %w", err) } @@ -60,7 +60,7 @@ func AddPrincipalKey(ownerID int64, content string, authSourceID int64) (*Public committer.Close() - return key, RewriteAllPrincipalKeys(db.DefaultContext) + return key, RewriteAllPrincipalKeys(ctx) } // CheckPrincipalKeyString strips spaces and returns an error if the given principal contains newlines @@ -105,8 +105,8 @@ func CheckPrincipalKeyString(ctx context.Context, user *user_model.User, content } // ListPrincipalKeys returns a list of principals belongs to given user. -func ListPrincipalKeys(uid int64, listOptions db.ListOptions) ([]*PublicKey, error) { - sess := db.GetEngine(db.DefaultContext).Where("owner_id = ? AND type = ?", uid, KeyTypePrincipal) +func ListPrincipalKeys(ctx context.Context, uid int64, listOptions db.ListOptions) ([]*PublicKey, error) { + sess := db.GetEngine(ctx).Where("owner_id = ? AND type = ?", uid, KeyTypePrincipal) if listOptions.Page != 0 { sess = db.SetSessionPagination(sess, &listOptions) diff --git a/models/asymkey/ssh_key_verify.go b/models/asymkey/ssh_key_verify.go index d6c16eb46..e9f433248 100644 --- a/models/asymkey/ssh_key_verify.go +++ b/models/asymkey/ssh_key_verify.go @@ -5,6 +5,7 @@ package asymkey import ( "bytes" + "context" "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/modules/log" @@ -13,8 +14,8 @@ import ( ) // VerifySSHKey marks a SSH key as verified -func VerifySSHKey(ownerID int64, fingerprint, token, signature string) (string, error) { - ctx, committer, err := db.TxContext(db.DefaultContext) +func VerifySSHKey(ctx context.Context, ownerID int64, fingerprint, token, signature string) (string, error) { + ctx, committer, err := db.TxContext(ctx) if err != nil { return "", err } diff --git a/models/auth/oauth2.go b/models/auth/oauth2.go index 7ac1d3a5f..d73ad6965 100644 --- a/models/auth/oauth2.go +++ b/models/auth/oauth2.go @@ -170,7 +170,7 @@ const lowerBase32Chars = "abcdefghijklmnopqrstuvwxyz234567" var base32Lower = base32.NewEncoding(lowerBase32Chars).WithPadding(base32.NoPadding) // GenerateClientSecret will generate the client secret and returns the plaintext and saves the hash at the database -func (app *OAuth2Application) GenerateClientSecret() (string, error) { +func (app *OAuth2Application) GenerateClientSecret(ctx context.Context) (string, error) { rBytes, err := util.CryptoRandomBytes(32) if err != nil { return "", err @@ -184,7 +184,7 @@ func (app *OAuth2Application) GenerateClientSecret() (string, error) { return "", err } app.ClientSecret = string(hashedSecret) - if _, err := db.GetEngine(db.DefaultContext).ID(app.ID).Cols("client_secret").Update(app); err != nil { + if _, err := db.GetEngine(ctx).ID(app.ID).Cols("client_secret").Update(app); err != nil { return "", err } return clientSecret, nil @@ -284,8 +284,8 @@ type UpdateOAuth2ApplicationOptions struct { } // UpdateOAuth2Application updates an oauth2 application -func UpdateOAuth2Application(opts UpdateOAuth2ApplicationOptions) (*OAuth2Application, error) { - ctx, committer, err := db.TxContext(db.DefaultContext) +func UpdateOAuth2Application(ctx context.Context, opts UpdateOAuth2ApplicationOptions) (*OAuth2Application, error) { + ctx, committer, err := db.TxContext(ctx) if err != nil { return nil, err } @@ -352,8 +352,8 @@ func deleteOAuth2Application(ctx context.Context, id, userid int64) error { } // DeleteOAuth2Application deletes the application with the given id and the grants and auth codes related to it. It checks if the userid was the creator of the app. -func DeleteOAuth2Application(id, userid int64) error { - ctx, committer, err := db.TxContext(db.DefaultContext) +func DeleteOAuth2Application(ctx context.Context, id, userid int64) error { + ctx, committer, err := db.TxContext(ctx) if err != nil { return err } @@ -373,8 +373,8 @@ func DeleteOAuth2Application(id, userid int64) error { } // ListOAuth2Applications returns a list of oauth2 applications belongs to given user. -func ListOAuth2Applications(uid int64, listOptions db.ListOptions) ([]*OAuth2Application, int64, error) { - sess := db.GetEngine(db.DefaultContext). +func ListOAuth2Applications(ctx context.Context, uid int64, listOptions db.ListOptions) ([]*OAuth2Application, int64, error) { + sess := db.GetEngine(ctx). Where("uid=?", uid). Desc("id") @@ -632,18 +632,18 @@ func (err ErrOAuthApplicationNotFound) Unwrap() error { } // GetActiveOAuth2ProviderSources returns all actived LoginOAuth2 sources -func GetActiveOAuth2ProviderSources() ([]*Source, error) { +func GetActiveOAuth2ProviderSources(ctx context.Context) ([]*Source, error) { sources := make([]*Source, 0, 1) - if err := db.GetEngine(db.DefaultContext).Where("is_active = ? and type = ?", true, OAuth2).Find(&sources); err != nil { + if err := db.GetEngine(ctx).Where("is_active = ? and type = ?", true, OAuth2).Find(&sources); err != nil { return nil, err } return sources, nil } // GetActiveOAuth2SourceByName returns a OAuth2 AuthSource based on the given name -func GetActiveOAuth2SourceByName(name string) (*Source, error) { +func GetActiveOAuth2SourceByName(ctx context.Context, name string) (*Source, error) { authSource := new(Source) - has, err := db.GetEngine(db.DefaultContext).Where("name = ? and type = ? and is_active = ?", name, OAuth2, true).Get(authSource) + has, err := db.GetEngine(ctx).Where("name = ? and type = ? and is_active = ?", name, OAuth2, true).Get(authSource) if err != nil { return nil, err } diff --git a/models/auth/oauth2_test.go b/models/auth/oauth2_test.go index b8f0bc12c..122d43098 100644 --- a/models/auth/oauth2_test.go +++ b/models/auth/oauth2_test.go @@ -18,7 +18,7 @@ import ( func TestOAuth2Application_GenerateClientSecret(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) app := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{ID: 1}) - secret, err := app.GenerateClientSecret() + secret, err := app.GenerateClientSecret(db.DefaultContext) assert.NoError(t, err) assert.True(t, len(secret) > 0) unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{ID: 1, ClientSecret: app.ClientSecret}) @@ -28,7 +28,7 @@ func BenchmarkOAuth2Application_GenerateClientSecret(b *testing.B) { assert.NoError(b, unittest.PrepareTestDatabase()) app := unittest.AssertExistsAndLoadBean(b, &auth_model.OAuth2Application{ID: 1}) for i := 0; i < b.N; i++ { - _, _ = app.GenerateClientSecret() + _, _ = app.GenerateClientSecret(db.DefaultContext) } } @@ -78,7 +78,7 @@ func TestOAuth2Application_ContainsRedirect_Slash(t *testing.T) { func TestOAuth2Application_ValidateClientSecret(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) app := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{ID: 1}) - secret, err := app.GenerateClientSecret() + secret, err := app.GenerateClientSecret(db.DefaultContext) assert.NoError(t, err) assert.True(t, app.ValidateClientSecret([]byte(secret))) assert.False(t, app.ValidateClientSecret([]byte("fewijfowejgfiowjeoifew"))) diff --git a/models/avatars/avatar.go b/models/avatars/avatar.go index b0bfa4408..c197a22dc 100644 --- a/models/avatars/avatar.go +++ b/models/avatars/avatar.go @@ -94,13 +94,13 @@ func HashEmail(email string) string { } // GetEmailForHash converts a provided md5sum to the email -func GetEmailForHash(md5Sum string) (string, error) { +func GetEmailForHash(ctx context.Context, md5Sum string) (string, error) { return cache.GetString("Avatar:"+md5Sum, func() (string, error) { emailHash := EmailHash{ Hash: strings.ToLower(strings.TrimSpace(md5Sum)), } - _, err := db.GetEngine(db.DefaultContext).Get(&emailHash) + _, err := db.GetEngine(ctx).Get(&emailHash) return emailHash.Email, err }) } @@ -127,7 +127,7 @@ func LibravatarURL(email string) (*url.URL, error) { // saveEmailHash returns an avatar link for a provided email, // the email and hash are saved into database, which will be used by GetEmailForHash later -func saveEmailHash(email string) string { +func saveEmailHash(ctx context.Context, email string) string { lowerEmail := strings.ToLower(strings.TrimSpace(email)) emailHash := HashEmail(lowerEmail) _, _ = cache.GetString("Avatar:"+emailHash, func() (string, error) { @@ -136,7 +136,7 @@ func saveEmailHash(email string) string { Hash: emailHash, } // OK we're going to open a session just because I think that that might hide away any problems with postgres reporting errors - if err := db.WithTx(db.DefaultContext, func(ctx context.Context) error { + if err := db.WithTx(ctx, func(ctx context.Context) error { has, err := db.GetEngine(ctx).Where("email = ? AND hash = ?", emailHash.Email, emailHash.Hash).Get(new(EmailHash)) if has || err != nil { // Seriously we don't care about any DB problems just return the lowerEmail - we expect the transaction to fail most of the time @@ -196,7 +196,7 @@ func generateEmailAvatarLink(ctx context.Context, email string, size int, final enableFederatedAvatar := setting.Config().Picture.EnableFederatedAvatar.Value(ctx) if enableFederatedAvatar { - emailHash := saveEmailHash(email) + emailHash := saveEmailHash(ctx, email) if final { // for final link, we can spend more time on slow external query var avatarURL *url.URL diff --git a/models/repo/redirect.go b/models/repo/redirect.go index 92a011a45..61789ebef 100644 --- a/models/repo/redirect.go +++ b/models/repo/redirect.go @@ -50,10 +50,10 @@ func init() { } // LookupRedirect look up if a repository has a redirect name -func LookupRedirect(ownerID int64, repoName string) (int64, error) { +func LookupRedirect(ctx context.Context, ownerID int64, repoName string) (int64, error) { repoName = strings.ToLower(repoName) redirect := &Redirect{OwnerID: ownerID, LowerName: repoName} - if has, err := db.GetEngine(db.DefaultContext).Get(redirect); err != nil { + if has, err := db.GetEngine(ctx).Get(redirect); err != nil { return 0, err } else if !has { return 0, ErrRedirectNotExist{OwnerID: ownerID, RepoName: repoName} diff --git a/models/repo/redirect_test.go b/models/repo/redirect_test.go index 8255704d5..24cf7e89f 100644 --- a/models/repo/redirect_test.go +++ b/models/repo/redirect_test.go @@ -16,11 +16,11 @@ import ( func TestLookupRedirect(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - repoID, err := repo_model.LookupRedirect(2, "oldrepo1") + repoID, err := repo_model.LookupRedirect(db.DefaultContext, 2, "oldrepo1") assert.NoError(t, err) assert.EqualValues(t, 1, repoID) - _, err = repo_model.LookupRedirect(unittest.NonexistentID, "doesnotexist") + _, err = repo_model.LookupRedirect(db.DefaultContext, unittest.NonexistentID, "doesnotexist") assert.True(t, repo_model.IsErrRedirectNotExist(err)) } diff --git a/models/user/external_login_user.go b/models/user/external_login_user.go index 3a5624043..4121c5d89 100644 --- a/models/user/external_login_user.go +++ b/models/user/external_login_user.go @@ -92,14 +92,14 @@ func init() { } // GetExternalLogin checks if a externalID in loginSourceID scope already exists -func GetExternalLogin(externalLoginUser *ExternalLoginUser) (bool, error) { - return db.GetEngine(db.DefaultContext).Get(externalLoginUser) +func GetExternalLogin(ctx context.Context, externalLoginUser *ExternalLoginUser) (bool, error) { + return db.GetEngine(ctx).Get(externalLoginUser) } // ListAccountLinks returns a map with the ExternalLoginUser and its LoginSource -func ListAccountLinks(user *User) ([]*ExternalLoginUser, error) { +func ListAccountLinks(ctx context.Context, user *User) ([]*ExternalLoginUser, error) { externalAccounts := make([]*ExternalLoginUser, 0, 5) - err := db.GetEngine(db.DefaultContext).Where("user_id=?", user.ID). + err := db.GetEngine(ctx).Where("user_id=?", user.ID). Desc("login_source_id"). Find(&externalAccounts) if err != nil { @@ -110,8 +110,8 @@ func ListAccountLinks(user *User) ([]*ExternalLoginUser, error) { } // LinkExternalToUser link the external user to the user -func LinkExternalToUser(user *User, externalLoginUser *ExternalLoginUser) error { - has, err := db.GetEngine(db.DefaultContext).Where("external_id=? AND login_source_id=?", externalLoginUser.ExternalID, externalLoginUser.LoginSourceID). +func LinkExternalToUser(ctx context.Context, user *User, externalLoginUser *ExternalLoginUser) error { + has, err := db.GetEngine(ctx).Where("external_id=? AND login_source_id=?", externalLoginUser.ExternalID, externalLoginUser.LoginSourceID). NoAutoCondition(). Exist(externalLoginUser) if err != nil { @@ -120,13 +120,13 @@ func LinkExternalToUser(user *User, externalLoginUser *ExternalLoginUser) error return ErrExternalLoginUserAlreadyExist{externalLoginUser.ExternalID, user.ID, externalLoginUser.LoginSourceID} } - _, err = db.GetEngine(db.DefaultContext).Insert(externalLoginUser) + _, err = db.GetEngine(ctx).Insert(externalLoginUser) return err } // RemoveAccountLink will remove all external login sources for the given user -func RemoveAccountLink(user *User, loginSourceID int64) (int64, error) { - deleted, err := db.GetEngine(db.DefaultContext).Delete(&ExternalLoginUser{UserID: user.ID, LoginSourceID: loginSourceID}) +func RemoveAccountLink(ctx context.Context, user *User, loginSourceID int64) (int64, error) { + deleted, err := db.GetEngine(ctx).Delete(&ExternalLoginUser{UserID: user.ID, LoginSourceID: loginSourceID}) if err != nil { return deleted, err } @@ -143,9 +143,9 @@ func RemoveAllAccountLinks(ctx context.Context, user *User) error { } // GetUserIDByExternalUserID get user id according to provider and userID -func GetUserIDByExternalUserID(provider, userID string) (int64, error) { +func GetUserIDByExternalUserID(ctx context.Context, provider, userID string) (int64, error) { var id int64 - _, err := db.GetEngine(db.DefaultContext).Table("external_login_user"). + _, err := db.GetEngine(ctx).Table("external_login_user"). Select("user_id"). Where("provider=?", provider). And("external_id=?", userID). @@ -157,8 +157,8 @@ func GetUserIDByExternalUserID(provider, userID string) (int64, error) { } // UpdateExternalUserByExternalID updates an external user's information -func UpdateExternalUserByExternalID(external *ExternalLoginUser) error { - has, err := db.GetEngine(db.DefaultContext).Where("external_id=? AND login_source_id=?", external.ExternalID, external.LoginSourceID). +func UpdateExternalUserByExternalID(ctx context.Context, external *ExternalLoginUser) error { + has, err := db.GetEngine(ctx).Where("external_id=? AND login_source_id=?", external.ExternalID, external.LoginSourceID). NoAutoCondition(). Exist(external) if err != nil { @@ -167,7 +167,7 @@ func UpdateExternalUserByExternalID(external *ExternalLoginUser) error { return ErrExternalLoginUserNotExist{external.UserID, external.LoginSourceID} } - _, err = db.GetEngine(db.DefaultContext).Where("external_id=? AND login_source_id=?", external.ExternalID, external.LoginSourceID).AllCols().Update(external) + _, err = db.GetEngine(ctx).Where("external_id=? AND login_source_id=?", external.ExternalID, external.LoginSourceID).AllCols().Update(external) return err } @@ -187,9 +187,9 @@ func (opts FindExternalUserOptions) toConds() builder.Cond { } // FindExternalUsersByProvider represents external users via provider -func FindExternalUsersByProvider(opts FindExternalUserOptions) ([]ExternalLoginUser, error) { +func FindExternalUsersByProvider(ctx context.Context, opts FindExternalUserOptions) ([]ExternalLoginUser, error) { var users []ExternalLoginUser - err := db.GetEngine(db.DefaultContext).Where(opts.toConds()). + err := db.GetEngine(ctx).Where(opts.toConds()). Limit(opts.Limit, opts.Start). OrderBy("login_source_id ASC, external_id ASC"). Find(&users) diff --git a/models/webhook/hooktask.go b/models/webhook/hooktask.go index 3ece5f062..3ff27b93a 100644 --- a/models/webhook/hooktask.go +++ b/models/webhook/hooktask.go @@ -101,9 +101,9 @@ func (t *HookTask) simpleMarshalJSON(v any) string { } // HookTasks returns a list of hook tasks by given conditions. -func HookTasks(hookID int64, page int) ([]*HookTask, error) { +func HookTasks(ctx context.Context, hookID int64, page int) ([]*HookTask, error) { tasks := make([]*HookTask, 0, setting.Webhook.PagingNum) - return tasks, db.GetEngine(db.DefaultContext). + return tasks, db.GetEngine(ctx). Limit(setting.Webhook.PagingNum, (page-1)*setting.Webhook.PagingNum). Where("hook_id=?", hookID). Desc("id"). @@ -143,8 +143,8 @@ func GetHookTaskByID(ctx context.Context, id int64) (*HookTask, error) { } // UpdateHookTask updates information of hook task. -func UpdateHookTask(t *HookTask) error { - _, err := db.GetEngine(db.DefaultContext).ID(t.ID).AllCols().Update(t) +func UpdateHookTask(ctx context.Context, t *HookTask) error { + _, err := db.GetEngine(ctx).ID(t.ID).AllCols().Update(t) return err } diff --git a/models/webhook/webhook.go b/models/webhook/webhook.go index fc2bbed08..b28cea6a9 100644 --- a/models/webhook/webhook.go +++ b/models/webhook/webhook.go @@ -155,8 +155,8 @@ func (w *Webhook) AfterLoad() { } // History returns history of webhook by given conditions. -func (w *Webhook) History(page int) ([]*HookTask, error) { - return HookTasks(w.ID, page) +func (w *Webhook) History(ctx context.Context, page int) ([]*HookTask, error) { + return HookTasks(ctx, w.ID, page) } // UpdateEvent handles conversion from HookEvent to Events. @@ -394,8 +394,8 @@ func CreateWebhooks(ctx context.Context, ws []*Webhook) error { // getWebhook uses argument bean as query condition, // ID must be specified and do not assign unnecessary fields. -func getWebhook(bean *Webhook) (*Webhook, error) { - has, err := db.GetEngine(db.DefaultContext).Get(bean) +func getWebhook(ctx context.Context, bean *Webhook) (*Webhook, error) { + has, err := db.GetEngine(ctx).Get(bean) if err != nil { return nil, err } else if !has { @@ -405,23 +405,23 @@ func getWebhook(bean *Webhook) (*Webhook, error) { } // GetWebhookByID returns webhook of repository by given ID. -func GetWebhookByID(id int64) (*Webhook, error) { - return getWebhook(&Webhook{ +func GetWebhookByID(ctx context.Context, id int64) (*Webhook, error) { + return getWebhook(ctx, &Webhook{ ID: id, }) } // GetWebhookByRepoID returns webhook of repository by given ID. -func GetWebhookByRepoID(repoID, id int64) (*Webhook, error) { - return getWebhook(&Webhook{ +func GetWebhookByRepoID(ctx context.Context, repoID, id int64) (*Webhook, error) { + return getWebhook(ctx, &Webhook{ ID: id, RepoID: repoID, }) } // GetWebhookByOwnerID returns webhook of a user or organization by given ID. -func GetWebhookByOwnerID(ownerID, id int64) (*Webhook, error) { - return getWebhook(&Webhook{ +func GetWebhookByOwnerID(ctx context.Context, ownerID, id int64) (*Webhook, error) { + return getWebhook(ctx, &Webhook{ ID: id, OwnerID: ownerID, }) @@ -466,26 +466,26 @@ func ListWebhooksByOpts(ctx context.Context, opts *ListWebhookOptions) ([]*Webho } // CountWebhooksByOpts count webhooks based on options and ignore pagination -func CountWebhooksByOpts(opts *ListWebhookOptions) (int64, error) { - return db.GetEngine(db.DefaultContext).Where(opts.toCond()).Count(&Webhook{}) +func CountWebhooksByOpts(ctx context.Context, opts *ListWebhookOptions) (int64, error) { + return db.GetEngine(ctx).Where(opts.toCond()).Count(&Webhook{}) } // UpdateWebhook updates information of webhook. -func UpdateWebhook(w *Webhook) error { - _, err := db.GetEngine(db.DefaultContext).ID(w.ID).AllCols().Update(w) +func UpdateWebhook(ctx context.Context, w *Webhook) error { + _, err := db.GetEngine(ctx).ID(w.ID).AllCols().Update(w) return err } // UpdateWebhookLastStatus updates last status of webhook. -func UpdateWebhookLastStatus(w *Webhook) error { - _, err := db.GetEngine(db.DefaultContext).ID(w.ID).Cols("last_status").Update(w) +func UpdateWebhookLastStatus(ctx context.Context, w *Webhook) error { + _, err := db.GetEngine(ctx).ID(w.ID).Cols("last_status").Update(w) return err } // deleteWebhook uses argument bean as query condition, // ID must be specified and do not assign unnecessary fields. -func deleteWebhook(bean *Webhook) (err error) { - ctx, committer, err := db.TxContext(db.DefaultContext) +func deleteWebhook(ctx context.Context, bean *Webhook) (err error) { + ctx, committer, err := db.TxContext(ctx) if err != nil { return err } @@ -503,16 +503,16 @@ func deleteWebhook(bean *Webhook) (err error) { } // DeleteWebhookByRepoID deletes webhook of repository by given ID. -func DeleteWebhookByRepoID(repoID, id int64) error { - return deleteWebhook(&Webhook{ +func DeleteWebhookByRepoID(ctx context.Context, repoID, id int64) error { + return deleteWebhook(ctx, &Webhook{ ID: id, RepoID: repoID, }) } // DeleteWebhookByOwnerID deletes webhook of a user or organization by given ID. -func DeleteWebhookByOwnerID(ownerID, id int64) error { - return deleteWebhook(&Webhook{ +func DeleteWebhookByOwnerID(ctx context.Context, ownerID, id int64) error { + return deleteWebhook(ctx, &Webhook{ ID: id, OwnerID: ownerID, }) diff --git a/models/webhook/webhook_test.go b/models/webhook/webhook_test.go index de6568c32..6a01fdd75 100644 --- a/models/webhook/webhook_test.go +++ b/models/webhook/webhook_test.go @@ -33,14 +33,14 @@ func TestIsValidHookContentType(t *testing.T) { func TestWebhook_History(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) webhook := unittest.AssertExistsAndLoadBean(t, &Webhook{ID: 1}) - tasks, err := webhook.History(0) + tasks, err := webhook.History(db.DefaultContext, 0) assert.NoError(t, err) if assert.Len(t, tasks, 1) { assert.Equal(t, int64(1), tasks[0].ID) } webhook = unittest.AssertExistsAndLoadBean(t, &Webhook{ID: 2}) - tasks, err = webhook.History(0) + tasks, err = webhook.History(db.DefaultContext, 0) assert.NoError(t, err) assert.Len(t, tasks, 0) } @@ -101,22 +101,22 @@ func TestCreateWebhook(t *testing.T) { func TestGetWebhookByRepoID(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - hook, err := GetWebhookByRepoID(1, 1) + hook, err := GetWebhookByRepoID(db.DefaultContext, 1, 1) assert.NoError(t, err) assert.Equal(t, int64(1), hook.ID) - _, err = GetWebhookByRepoID(unittest.NonexistentID, unittest.NonexistentID) + _, err = GetWebhookByRepoID(db.DefaultContext, unittest.NonexistentID, unittest.NonexistentID) assert.Error(t, err) assert.True(t, IsErrWebhookNotExist(err)) } func TestGetWebhookByOwnerID(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - hook, err := GetWebhookByOwnerID(3, 3) + hook, err := GetWebhookByOwnerID(db.DefaultContext, 3, 3) assert.NoError(t, err) assert.Equal(t, int64(3), hook.ID) - _, err = GetWebhookByOwnerID(unittest.NonexistentID, unittest.NonexistentID) + _, err = GetWebhookByOwnerID(db.DefaultContext, unittest.NonexistentID, unittest.NonexistentID) assert.Error(t, err) assert.True(t, IsErrWebhookNotExist(err)) } @@ -167,17 +167,17 @@ func TestUpdateWebhook(t *testing.T) { hook.IsActive = true hook.ContentType = ContentTypeForm unittest.AssertNotExistsBean(t, hook) - assert.NoError(t, UpdateWebhook(hook)) + assert.NoError(t, UpdateWebhook(db.DefaultContext, hook)) unittest.AssertExistsAndLoadBean(t, hook) } func TestDeleteWebhookByRepoID(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) unittest.AssertExistsAndLoadBean(t, &Webhook{ID: 2, RepoID: 1}) - assert.NoError(t, DeleteWebhookByRepoID(1, 2)) + assert.NoError(t, DeleteWebhookByRepoID(db.DefaultContext, 1, 2)) unittest.AssertNotExistsBean(t, &Webhook{ID: 2, RepoID: 1}) - err := DeleteWebhookByRepoID(unittest.NonexistentID, unittest.NonexistentID) + err := DeleteWebhookByRepoID(db.DefaultContext, unittest.NonexistentID, unittest.NonexistentID) assert.Error(t, err) assert.True(t, IsErrWebhookNotExist(err)) } @@ -185,23 +185,23 @@ func TestDeleteWebhookByRepoID(t *testing.T) { func TestDeleteWebhookByOwnerID(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) unittest.AssertExistsAndLoadBean(t, &Webhook{ID: 3, OwnerID: 3}) - assert.NoError(t, DeleteWebhookByOwnerID(3, 3)) + assert.NoError(t, DeleteWebhookByOwnerID(db.DefaultContext, 3, 3)) unittest.AssertNotExistsBean(t, &Webhook{ID: 3, OwnerID: 3}) - err := DeleteWebhookByOwnerID(unittest.NonexistentID, unittest.NonexistentID) + err := DeleteWebhookByOwnerID(db.DefaultContext, unittest.NonexistentID, unittest.NonexistentID) assert.Error(t, err) assert.True(t, IsErrWebhookNotExist(err)) } func TestHookTasks(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - hookTasks, err := HookTasks(1, 1) + hookTasks, err := HookTasks(db.DefaultContext, 1, 1) assert.NoError(t, err) if assert.Len(t, hookTasks, 1) { assert.Equal(t, int64(1), hookTasks[0].ID) } - hookTasks, err = HookTasks(unittest.NonexistentID, 1) + hookTasks, err = HookTasks(db.DefaultContext, unittest.NonexistentID, 1) assert.NoError(t, err) assert.Len(t, hookTasks, 0) } @@ -225,7 +225,7 @@ func TestUpdateHookTask(t *testing.T) { hook.PayloadContent = "new payload content" hook.IsDelivered = true unittest.AssertNotExistsBean(t, hook) - assert.NoError(t, UpdateHookTask(hook)) + assert.NoError(t, UpdateHookTask(db.DefaultContext, hook)) unittest.AssertExistsAndLoadBean(t, hook) } diff --git a/modules/context/repo.go b/modules/context/repo.go index b340a6e23..9efa2ab3c 100644 --- a/modules/context/repo.go +++ b/modules/context/repo.go @@ -144,18 +144,18 @@ func (r *Repository) CanCommitToBranch(ctx context.Context, doer *user_model.Use } // CanUseTimetracker returns whether or not a user can use the timetracker. -func (r *Repository) CanUseTimetracker(issue *issues_model.Issue, user *user_model.User) bool { +func (r *Repository) CanUseTimetracker(ctx context.Context, issue *issues_model.Issue, user *user_model.User) bool { // Checking for following: // 1. Is timetracker enabled // 2. Is the user a contributor, admin, poster or assignee and do the repository policies require this? - isAssigned, _ := issues_model.IsUserAssignedToIssue(db.DefaultContext, issue, user) - return r.Repository.IsTimetrackerEnabled(db.DefaultContext) && (!r.Repository.AllowOnlyContributorsToTrackTime(db.DefaultContext) || + isAssigned, _ := issues_model.IsUserAssignedToIssue(ctx, issue, user) + return r.Repository.IsTimetrackerEnabled(ctx) && (!r.Repository.AllowOnlyContributorsToTrackTime(ctx) || r.Permission.CanWriteIssuesOrPulls(issue.IsPull) || issue.IsPoster(user.ID) || isAssigned) } // CanCreateIssueDependencies returns whether or not a user can create dependencies. -func (r *Repository) CanCreateIssueDependencies(user *user_model.User, isPull bool) bool { - return r.Repository.IsDependenciesEnabled(db.DefaultContext) && r.Permission.CanWriteIssuesOrPulls(isPull) +func (r *Repository) CanCreateIssueDependencies(ctx context.Context, user *user_model.User, isPull bool) bool { + return r.Repository.IsDependenciesEnabled(ctx) && r.Permission.CanWriteIssuesOrPulls(isPull) } // GetCommitsCount returns cached commit count for current view @@ -498,7 +498,7 @@ func RepoAssignment(ctx *Context) context.CancelFunc { repo, err := repo_model.GetRepositoryByName(ctx, owner.ID, repoName) if err != nil { if repo_model.IsErrRepoNotExist(err) { - redirectRepoID, err := repo_model.LookupRedirect(owner.ID, repoName) + redirectRepoID, err := repo_model.LookupRedirect(ctx, owner.ID, repoName) if err == nil { RedirectToRepo(ctx.Base, redirectRepoID) } else if repo_model.IsErrRedirectNotExist(err) { diff --git a/modules/eventsource/manager_run.go b/modules/eventsource/manager_run.go index bef1a00c5..f66dc78c7 100644 --- a/modules/eventsource/manager_run.go +++ b/modules/eventsource/manager_run.go @@ -91,7 +91,7 @@ loop: } for _, userStopwatches := range usersStopwatches { - apiSWs, err := convert.ToStopWatches(userStopwatches.StopWatches) + apiSWs, err := convert.ToStopWatches(ctx, userStopwatches.StopWatches) if err != nil { if !issues_model.IsErrIssueNotExist(err) { log.Error("Unable to APIFormat stopwatches: %v", err) diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index 8abe51ea4..8d8373f0a 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -169,7 +169,7 @@ func repoAssignment() func(ctx *context.APIContext) { repo, err := repo_model.GetRepositoryByName(ctx, owner.ID, repoName) if err != nil { if repo_model.IsErrRepoNotExist(err) { - redirectRepoID, err := repo_model.LookupRedirect(owner.ID, repoName) + redirectRepoID, err := repo_model.LookupRedirect(ctx, owner.ID, repoName) if err == nil { context.RedirectToRepo(ctx.Base, redirectRepoID) } else if repo_model.IsErrRedirectNotExist(err) { diff --git a/routers/api/v1/repo/hook.go b/routers/api/v1/repo/hook.go index e0f99b48f..7d0142748 100644 --- a/routers/api/v1/repo/hook.go +++ b/routers/api/v1/repo/hook.go @@ -58,7 +58,7 @@ func ListHooks(ctx *context.APIContext) { RepoID: ctx.Repo.Repository.ID, } - count, err := webhook.CountWebhooksByOpts(opts) + count, err := webhook.CountWebhooksByOpts(ctx, opts) if err != nil { ctx.InternalServerError(err) return @@ -301,7 +301,7 @@ func DeleteHook(ctx *context.APIContext) { // "$ref": "#/responses/empty" // "404": // "$ref": "#/responses/notFound" - if err := webhook.DeleteWebhookByRepoID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id")); err != nil { + if err := webhook.DeleteWebhookByRepoID(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":id")); err != nil { if webhook.IsErrWebhookNotExist(err) { ctx.NotFound() } else { diff --git a/routers/api/v1/repo/issue_stopwatch.go b/routers/api/v1/repo/issue_stopwatch.go index 384532ab8..52bf8b5c7 100644 --- a/routers/api/v1/repo/issue_stopwatch.go +++ b/routers/api/v1/repo/issue_stopwatch.go @@ -177,7 +177,7 @@ func prepareIssueStopwatch(ctx *context.APIContext, shouldExist bool) (*issues_m return nil, errors.New("Unable to write to PRs") } - if !ctx.Repo.CanUseTimetracker(issue, ctx.Doer) { + if !ctx.Repo.CanUseTimetracker(ctx, issue, ctx.Doer) { ctx.Status(http.StatusForbidden) return nil, errors.New("Cannot use time tracker") } @@ -230,7 +230,7 @@ func GetStopwatches(ctx *context.APIContext) { return } - apiSWs, err := convert.ToStopWatches(sws) + apiSWs, err := convert.ToStopWatches(ctx, sws) if err != nil { ctx.Error(http.StatusInternalServerError, "APIFormat", err) return diff --git a/routers/api/v1/repo/issue_tracked_time.go b/routers/api/v1/repo/issue_tracked_time.go index 06cd411ea..cf03e72aa 100644 --- a/routers/api/v1/repo/issue_tracked_time.go +++ b/routers/api/v1/repo/issue_tracked_time.go @@ -191,7 +191,7 @@ func AddTime(ctx *context.APIContext) { return } - if !ctx.Repo.CanUseTimetracker(issue, ctx.Doer) { + if !ctx.Repo.CanUseTimetracker(ctx, issue, ctx.Doer) { if !ctx.Repo.Repository.IsTimetrackerEnabled(ctx) { ctx.Error(http.StatusBadRequest, "", "time tracking disabled") return @@ -274,7 +274,7 @@ func ResetIssueTime(ctx *context.APIContext) { return } - if !ctx.Repo.CanUseTimetracker(issue, ctx.Doer) { + if !ctx.Repo.CanUseTimetracker(ctx, issue, ctx.Doer) { if !ctx.Repo.Repository.IsTimetrackerEnabled(ctx) { ctx.JSON(http.StatusBadRequest, struct{ Message string }{Message: "time tracking disabled"}) return @@ -347,7 +347,7 @@ func DeleteTime(ctx *context.APIContext) { return } - if !ctx.Repo.CanUseTimetracker(issue, ctx.Doer) { + if !ctx.Repo.CanUseTimetracker(ctx, issue, ctx.Doer) { if !ctx.Repo.Repository.IsTimetrackerEnabled(ctx) { ctx.JSON(http.StatusBadRequest, struct{ Message string }{Message: "time tracking disabled"}) return diff --git a/routers/api/v1/repo/key.go b/routers/api/v1/repo/key.go index e2b7b4943..47a4d1484 100644 --- a/routers/api/v1/repo/key.go +++ b/routers/api/v1/repo/key.go @@ -96,7 +96,7 @@ func ListDeployKeys(ctx *context.APIContext) { return } - count, err := asymkey_model.CountDeployKeys(opts) + count, err := asymkey_model.CountDeployKeys(ctx, opts) if err != nil { ctx.InternalServerError(err) return @@ -238,7 +238,7 @@ func CreateDeployKey(ctx *context.APIContext) { return } - key, err := asymkey_model.AddDeployKey(ctx.Repo.Repository.ID, form.Title, content, form.ReadOnly) + key, err := asymkey_model.AddDeployKey(ctx, ctx.Repo.Repository.ID, form.Title, content, form.ReadOnly) if err != nil { HandleAddKeyError(ctx, err) return diff --git a/routers/api/v1/repo/pull.go b/routers/api/v1/repo/pull.go index df9e7217b..a7faaf6fc 100644 --- a/routers/api/v1/repo/pull.go +++ b/routers/api/v1/repo/pull.go @@ -811,7 +811,7 @@ func MergePullRequest(ctx *context.APIContext) { // handle manually-merged mark if manuallyMerged { - if err := pull_service.MergedManually(pr, ctx.Doer, ctx.Repo.GitRepo, form.MergeCommitID); err != nil { + if err := pull_service.MergedManually(ctx, pr, ctx.Doer, ctx.Repo.GitRepo, form.MergeCommitID); err != nil { if models.IsErrInvalidMergeStyle(err) { ctx.Error(http.StatusMethodNotAllowed, "Invalid merge style", fmt.Errorf("%s is not allowed an allowed merge style for this repository", repo_model.MergeStyle(form.Do))) return diff --git a/routers/api/v1/user/app.go b/routers/api/v1/user/app.go index cdec69be5..fef0240b0 100644 --- a/routers/api/v1/user/app.go +++ b/routers/api/v1/user/app.go @@ -236,7 +236,7 @@ func CreateOauth2Application(ctx *context.APIContext) { ctx.Error(http.StatusBadRequest, "", "error creating oauth2 application") return } - secret, err := app.GenerateClientSecret() + secret, err := app.GenerateClientSecret(ctx) if err != nil { ctx.Error(http.StatusBadRequest, "", "error creating application secret") return @@ -266,7 +266,7 @@ func ListOauth2Applications(ctx *context.APIContext) { // "200": // "$ref": "#/responses/OAuth2ApplicationList" - apps, total, err := auth_model.ListOAuth2Applications(ctx.Doer.ID, utils.GetListOptions(ctx)) + apps, total, err := auth_model.ListOAuth2Applications(ctx, ctx.Doer.ID, utils.GetListOptions(ctx)) if err != nil { ctx.Error(http.StatusInternalServerError, "ListOAuth2Applications", err) return @@ -302,7 +302,7 @@ func DeleteOauth2Application(ctx *context.APIContext) { // "404": // "$ref": "#/responses/notFound" appID := ctx.ParamsInt64(":id") - if err := auth_model.DeleteOAuth2Application(appID, ctx.Doer.ID); err != nil { + if err := auth_model.DeleteOAuth2Application(ctx, appID, ctx.Doer.ID); err != nil { if auth_model.IsErrOAuthApplicationNotFound(err) { ctx.NotFound() } else { @@ -377,7 +377,7 @@ func UpdateOauth2Application(ctx *context.APIContext) { data := web.GetForm(ctx).(*api.CreateOAuth2ApplicationOptions) - app, err := auth_model.UpdateOAuth2Application(auth_model.UpdateOAuth2ApplicationOptions{ + app, err := auth_model.UpdateOAuth2Application(ctx, auth_model.UpdateOAuth2ApplicationOptions{ Name: data.Name, UserID: ctx.Doer.ID, ID: appID, @@ -392,7 +392,7 @@ func UpdateOauth2Application(ctx *context.APIContext) { } return } - app.ClientSecret, err = app.GenerateClientSecret() + app.ClientSecret, err = app.GenerateClientSecret(ctx) if err != nil { ctx.Error(http.StatusBadRequest, "", "error updating application secret") return diff --git a/routers/api/v1/user/gpg_key.go b/routers/api/v1/user/gpg_key.go index 8578e0905..404b1d221 100644 --- a/routers/api/v1/user/gpg_key.go +++ b/routers/api/v1/user/gpg_key.go @@ -185,9 +185,9 @@ func VerifyUserGPGKey(ctx *context.APIContext) { return } - _, err := asymkey_model.VerifyGPGKey(ctx.Doer.ID, form.KeyID, token, form.Signature) + _, err := asymkey_model.VerifyGPGKey(ctx, ctx.Doer.ID, form.KeyID, token, form.Signature) if err != nil && asymkey_model.IsErrGPGInvalidTokenSignature(err) { - _, err = asymkey_model.VerifyGPGKey(ctx.Doer.ID, form.KeyID, lastToken, form.Signature) + _, err = asymkey_model.VerifyGPGKey(ctx, ctx.Doer.ID, form.KeyID, lastToken, form.Signature) } if err != nil { diff --git a/routers/api/v1/utils/hook.go b/routers/api/v1/utils/hook.go index b62d20a18..362f4bfc4 100644 --- a/routers/api/v1/utils/hook.go +++ b/routers/api/v1/utils/hook.go @@ -26,7 +26,7 @@ func ListOwnerHooks(ctx *context.APIContext, owner *user_model.User) { OwnerID: owner.ID, } - count, err := webhook.CountWebhooksByOpts(opts) + count, err := webhook.CountWebhooksByOpts(ctx, opts) if err != nil { ctx.InternalServerError(err) return @@ -53,7 +53,7 @@ func ListOwnerHooks(ctx *context.APIContext, owner *user_model.User) { // GetOwnerHook gets an user or organization webhook. Errors are written to ctx. func GetOwnerHook(ctx *context.APIContext, ownerID, hookID int64) (*webhook.Webhook, error) { - w, err := webhook.GetWebhookByOwnerID(ownerID, hookID) + w, err := webhook.GetWebhookByOwnerID(ctx, ownerID, hookID) if err != nil { if webhook.IsErrWebhookNotExist(err) { ctx.NotFound() @@ -68,7 +68,7 @@ func GetOwnerHook(ctx *context.APIContext, ownerID, hookID int64) (*webhook.Webh // GetRepoHook get a repo's webhook. If there is an error, write to `ctx` // accordingly and return the error func GetRepoHook(ctx *context.APIContext, repoID, hookID int64) (*webhook.Webhook, error) { - w, err := webhook.GetWebhookByRepoID(repoID, hookID) + w, err := webhook.GetWebhookByRepoID(ctx, repoID, hookID) if err != nil { if webhook.IsErrWebhookNotExist(err) { ctx.NotFound() @@ -392,7 +392,7 @@ func editHook(ctx *context.APIContext, form *api.EditHookOption, w *webhook.Webh w.IsActive = *form.Active } - if err := webhook.UpdateWebhook(w); err != nil { + if err := webhook.UpdateWebhook(ctx, w); err != nil { ctx.Error(http.StatusInternalServerError, "UpdateWebhook", err) return false } @@ -401,7 +401,7 @@ func editHook(ctx *context.APIContext, form *api.EditHookOption, w *webhook.Webh // DeleteOwnerHook deletes the hook owned by the owner. func DeleteOwnerHook(ctx *context.APIContext, owner *user_model.User, hookID int64) { - if err := webhook.DeleteWebhookByOwnerID(owner.ID, hookID); err != nil { + if err := webhook.DeleteWebhookByOwnerID(ctx, owner.ID, hookID); err != nil { if webhook.IsErrWebhookNotExist(err) { ctx.NotFound() } else { diff --git a/routers/init.go b/routers/init.go index 0da510cc5..015b61a08 100644 --- a/routers/init.go +++ b/routers/init.go @@ -136,7 +136,7 @@ func InitWebInstalled(ctx context.Context) { mustInitCtx(ctx, common.InitDBEngine) log.Info("ORM engine initialization successful!") mustInit(system.Init) - mustInit(oauth2.Init) + mustInitCtx(ctx, oauth2.Init) mustInitCtx(ctx, models.Init) mustInitCtx(ctx, authmodel.Init) diff --git a/routers/private/key.go b/routers/private/key.go index 176e5ffcc..0096480d6 100644 --- a/routers/private/key.go +++ b/routers/private/key.go @@ -35,7 +35,7 @@ func UpdatePublicKeyInRepo(ctx *context.PrivateContext) { return } deployKey.UpdatedUnix = timeutil.TimeStampNow() - if err = asymkey_model.UpdateDeployKeyCols(deployKey, "updated_unix"); err != nil { + if err = asymkey_model.UpdateDeployKeyCols(ctx, deployKey, "updated_unix"); err != nil { ctx.JSON(http.StatusInternalServerError, private.Response{ Err: err.Error(), }) diff --git a/routers/web/admin/auths.go b/routers/web/admin/auths.go index 22de15036..da91e31ef 100644 --- a/routers/web/admin/auths.go +++ b/routers/web/admin/auths.go @@ -448,7 +448,7 @@ func DeleteAuthSource(ctx *context.Context) { return } - if err = auth_service.DeleteSource(source); err != nil { + if err = auth_service.DeleteSource(ctx, source); err != nil { if auth.IsErrSourceInUse(err) { ctx.Flash.Error(ctx.Tr("admin.auths.still_in_used")) } else { diff --git a/routers/web/auth/auth.go b/routers/web/auth/auth.go index 1238e5275..e27307ef1 100644 --- a/routers/web/auth/auth.go +++ b/routers/web/auth/auth.go @@ -160,7 +160,7 @@ func SignIn(ctx *context.Context) { return } - orderedOAuth2Names, oauth2Providers, err := oauth2.GetActiveOAuth2Providers() + orderedOAuth2Names, oauth2Providers, err := oauth2.GetActiveOAuth2Providers(ctx) if err != nil { ctx.ServerError("UserSignIn", err) return @@ -184,7 +184,7 @@ func SignIn(ctx *context.Context) { func SignInPost(ctx *context.Context) { ctx.Data["Title"] = ctx.Tr("sign_in") - orderedOAuth2Names, oauth2Providers, err := oauth2.GetActiveOAuth2Providers() + orderedOAuth2Names, oauth2Providers, err := oauth2.GetActiveOAuth2Providers(ctx) if err != nil { ctx.ServerError("UserSignIn", err) return @@ -408,7 +408,7 @@ func SignUp(ctx *context.Context) { ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/sign_up" - orderedOAuth2Names, oauth2Providers, err := oauth2.GetActiveOAuth2Providers() + orderedOAuth2Names, oauth2Providers, err := oauth2.GetActiveOAuth2Providers(ctx) if err != nil { ctx.ServerError("UserSignUp", err) return @@ -438,7 +438,7 @@ func SignUpPost(ctx *context.Context) { ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/sign_up" - orderedOAuth2Names, oauth2Providers, err := oauth2.GetActiveOAuth2Providers() + orderedOAuth2Names, oauth2Providers, err := oauth2.GetActiveOAuth2Providers(ctx) if err != nil { ctx.ServerError("UserSignUp", err) return @@ -604,7 +604,7 @@ func handleUserCreated(ctx *context.Context, u *user_model.User, gothUser *goth. // update external user information if gothUser != nil { - if err := externalaccount.UpdateExternalUser(u, *gothUser); err != nil { + if err := externalaccount.UpdateExternalUser(ctx, u, *gothUser); err != nil { if !errors.Is(err, util.ErrNotExist) { log.Error("UpdateExternalUser failed: %v", err) } diff --git a/routers/web/auth/linkaccount.go b/routers/web/auth/linkaccount.go index 1e70d85ce..f41590dc1 100644 --- a/routers/web/auth/linkaccount.go +++ b/routers/web/auth/linkaccount.go @@ -271,7 +271,7 @@ func LinkAccountPostRegister(ctx *context.Context) { } } - authSource, err := auth.GetActiveOAuth2SourceByName(gothUser.Provider) + authSource, err := auth.GetActiveOAuth2SourceByName(ctx, gothUser.Provider) if err != nil { ctx.ServerError("CreateUser", err) return diff --git a/routers/web/auth/oauth.go b/routers/web/auth/oauth.go index 64106e1ab..21d82cea4 100644 --- a/routers/web/auth/oauth.go +++ b/routers/web/auth/oauth.go @@ -847,7 +847,7 @@ func handleAuthorizeError(ctx *context.Context, authErr AuthorizeError, redirect func SignInOAuth(ctx *context.Context) { provider := ctx.Params(":provider") - authSource, err := auth.GetActiveOAuth2SourceByName(provider) + authSource, err := auth.GetActiveOAuth2SourceByName(ctx, provider) if err != nil { ctx.ServerError("SignIn", err) return @@ -868,7 +868,7 @@ func SignInOAuth(ctx *context.Context) { if err = authSource.Cfg.(*oauth2.Source).Callout(ctx.Req, ctx.Resp); err != nil { if strings.Contains(err.Error(), "no provider for ") { - if err = oauth2.ResetOAuth2(); err != nil { + if err = oauth2.ResetOAuth2(ctx); err != nil { ctx.ServerError("SignIn", err) return } @@ -898,7 +898,7 @@ func SignInOAuthCallback(ctx *context.Context) { } // first look if the provider is still active - authSource, err := auth.GetActiveOAuth2SourceByName(provider) + authSource, err := auth.GetActiveOAuth2SourceByName(ctx, provider) if err != nil { ctx.ServerError("SignIn", err) return @@ -1151,7 +1151,7 @@ func handleOAuth2SignIn(ctx *context.Context, source *auth.Source, u *user_model } // update external user information - if err := externalaccount.UpdateExternalUser(u, gothUser); err != nil { + if err := externalaccount.UpdateExternalUser(ctx, u, gothUser); err != nil { if !errors.Is(err, util.ErrNotExist) { log.Error("UpdateExternalUser failed: %v", err) } @@ -1274,7 +1274,7 @@ func oAuth2UserLoginCallback(ctx *context.Context, authSource *auth.Source, requ ExternalID: gothUser.UserID, LoginSourceID: authSource.ID, } - hasUser, err = user_model.GetExternalLogin(externalLoginUser) + hasUser, err = user_model.GetExternalLogin(request.Context(), externalLoginUser) if err != nil { return nil, goth.User{}, err } diff --git a/routers/web/org/setting.go b/routers/web/org/setting.go index a8e1bc1c8..c3eb7ff55 100644 --- a/routers/web/org/setting.go +++ b/routers/web/org/setting.go @@ -233,7 +233,7 @@ func Webhooks(ctx *context.Context) { // DeleteWebhook response for delete webhook func DeleteWebhook(ctx *context.Context) { - if err := webhook.DeleteWebhookByOwnerID(ctx.Org.Organization.ID, ctx.FormInt64("id")); err != nil { + if err := webhook.DeleteWebhookByOwnerID(ctx, ctx.Org.Organization.ID, ctx.FormInt64("id")); err != nil { ctx.Flash.Error("DeleteWebhookByOwnerID: " + err.Error()) } else { ctx.Flash.Success(ctx.Tr("repo.settings.webhook_deletion_success")) diff --git a/routers/web/repo/http.go b/routers/web/repo/http.go index 9e11d7a8c..6ff385f98 100644 --- a/routers/web/repo/http.go +++ b/routers/web/repo/http.go @@ -108,7 +108,7 @@ func httpBase(ctx *context.Context) *serviceHandler { repo, err := repo_model.GetRepositoryByName(ctx, owner.ID, reponame) if err != nil { if repo_model.IsErrRepoNotExist(err) { - if redirectRepoID, err := repo_model.LookupRedirect(owner.ID, reponame); err == nil { + if redirectRepoID, err := repo_model.LookupRedirect(ctx, owner.ID, reponame); err == nil { context.RedirectToRepo(ctx.Base, redirectRepoID) return nil } diff --git a/routers/web/repo/issue.go b/routers/web/repo/issue.go index bb5f6e7ef..279214bcf 100644 --- a/routers/web/repo/issue.go +++ b/routers/web/repo/issue.go @@ -830,7 +830,7 @@ func RetrieveRepoMetas(ctx *context.Context, repo *repo_model.Repository, isPull } // Contains true if the user can create issue dependencies - ctx.Data["CanCreateIssueDependencies"] = ctx.Repo.CanCreateIssueDependencies(ctx.Doer, isPull) + ctx.Data["CanCreateIssueDependencies"] = ctx.Repo.CanCreateIssueDependencies(ctx, ctx.Doer, isPull) return labels } @@ -1548,7 +1548,7 @@ func ViewIssue(ctx *context.Context) { ctx.Data["OtherStopwatchURL"] = swIssue.Link() } } - ctx.Data["CanUseTimetracker"] = ctx.Repo.CanUseTimetracker(issue, ctx.Doer) + ctx.Data["CanUseTimetracker"] = ctx.Repo.CanUseTimetracker(ctx, issue, ctx.Doer) } else { ctx.Data["CanUseTimetracker"] = false } @@ -1559,7 +1559,7 @@ func ViewIssue(ctx *context.Context) { } // Check if the user can use the dependencies - ctx.Data["CanCreateIssueDependencies"] = ctx.Repo.CanCreateIssueDependencies(ctx.Doer, issue.IsPull) + ctx.Data["CanCreateIssueDependencies"] = ctx.Repo.CanCreateIssueDependencies(ctx, ctx.Doer, issue.IsPull) // check if dependencies can be created across repositories ctx.Data["AllowCrossRepositoryDependencies"] = setting.Service.AllowCrossRepositoryDependencies diff --git a/routers/web/repo/issue_dependency.go b/routers/web/repo/issue_dependency.go index 716a02ab6..781c16671 100644 --- a/routers/web/repo/issue_dependency.go +++ b/routers/web/repo/issue_dependency.go @@ -22,7 +22,7 @@ func AddDependency(ctx *context.Context) { } // Check if the Repo is allowed to have dependencies - if !ctx.Repo.CanCreateIssueDependencies(ctx.Doer, issue.IsPull) { + if !ctx.Repo.CanCreateIssueDependencies(ctx, ctx.Doer, issue.IsPull) { ctx.Error(http.StatusForbidden, "CanCreateIssueDependencies") return } @@ -97,7 +97,7 @@ func RemoveDependency(ctx *context.Context) { } // Check if the Repo is allowed to have dependencies - if !ctx.Repo.CanCreateIssueDependencies(ctx.Doer, issue.IsPull) { + if !ctx.Repo.CanCreateIssueDependencies(ctx, ctx.Doer, issue.IsPull) { ctx.Error(http.StatusForbidden, "CanCreateIssueDependencies") return } diff --git a/routers/web/repo/issue_stopwatch.go b/routers/web/repo/issue_stopwatch.go index d42af5732..ab9fe3e69 100644 --- a/routers/web/repo/issue_stopwatch.go +++ b/routers/web/repo/issue_stopwatch.go @@ -26,7 +26,7 @@ func IssueStopwatch(c *context.Context) { showSuccessMessage = true } - if !c.Repo.CanUseTimetracker(issue, c.Doer) { + if !c.Repo.CanUseTimetracker(c, issue, c.Doer) { c.NotFound("CanUseTimetracker", nil) return } @@ -50,7 +50,7 @@ func CancelStopwatch(c *context.Context) { if c.Written() { return } - if !c.Repo.CanUseTimetracker(issue, c.Doer) { + if !c.Repo.CanUseTimetracker(c, issue, c.Doer) { c.NotFound("CanUseTimetracker", nil) return } diff --git a/routers/web/repo/issue_timetrack.go b/routers/web/repo/issue_timetrack.go index 82d8d8fae..c9bf861b8 100644 --- a/routers/web/repo/issue_timetrack.go +++ b/routers/web/repo/issue_timetrack.go @@ -22,7 +22,7 @@ func AddTimeManually(c *context.Context) { if c.Written() { return } - if !c.Repo.CanUseTimetracker(issue, c.Doer) { + if !c.Repo.CanUseTimetracker(c, issue, c.Doer) { c.NotFound("CanUseTimetracker", nil) return } @@ -56,7 +56,7 @@ func DeleteTime(c *context.Context) { if c.Written() { return } - if !c.Repo.CanUseTimetracker(issue, c.Doer) { + if !c.Repo.CanUseTimetracker(c, issue, c.Doer) { c.NotFound("CanUseTimetracker", nil) return } diff --git a/routers/web/repo/pull.go b/routers/web/repo/pull.go index c8a0a04fe..ec109ed66 100644 --- a/routers/web/repo/pull.go +++ b/routers/web/repo/pull.go @@ -1170,7 +1170,7 @@ func MergePullRequest(ctx *context.Context) { // handle manually-merged mark if manuallyMerged { - if err := pull_service.MergedManually(pr, ctx.Doer, ctx.Repo.GitRepo, form.MergeCommitID); err != nil { + if err := pull_service.MergedManually(ctx, pr, ctx.Doer, ctx.Repo.GitRepo, form.MergeCommitID); err != nil { switch { case models.IsErrInvalidMergeStyle(err): diff --git a/routers/web/repo/setting/deploy_key.go b/routers/web/repo/setting/deploy_key.go index 70e31e125..579743ef3 100644 --- a/routers/web/repo/setting/deploy_key.go +++ b/routers/web/repo/setting/deploy_key.go @@ -70,7 +70,7 @@ func DeployKeysPost(ctx *context.Context) { return } - key, err := asymkey_model.AddDeployKey(ctx.Repo.Repository.ID, form.Title, content, !form.IsWritable) + key, err := asymkey_model.AddDeployKey(ctx, ctx.Repo.Repository.ID, form.Title, content, !form.IsWritable) if err != nil { ctx.Data["HasError"] = true switch { diff --git a/routers/web/repo/setting/webhook.go b/routers/web/repo/setting/webhook.go index 33ea2c206..ea5abb057 100644 --- a/routers/web/repo/setting/webhook.go +++ b/routers/web/repo/setting/webhook.go @@ -300,7 +300,7 @@ func editWebhook(ctx *context.Context, params webhookParams) { if err := w.UpdateEvent(); err != nil { ctx.ServerError("UpdateEvent", err) return - } else if err := webhook.UpdateWebhook(w); err != nil { + } else if err := webhook.UpdateWebhook(ctx, w); err != nil { ctx.ServerError("UpdateWebhook", err) return } @@ -589,9 +589,9 @@ func checkWebhook(ctx *context.Context) (*ownerRepoCtx, *webhook.Webhook) { var w *webhook.Webhook if orCtx.RepoID > 0 { - w, err = webhook.GetWebhookByRepoID(orCtx.RepoID, ctx.ParamsInt64(":id")) + w, err = webhook.GetWebhookByRepoID(ctx, orCtx.RepoID, ctx.ParamsInt64(":id")) } else if orCtx.OwnerID > 0 { - w, err = webhook.GetWebhookByOwnerID(orCtx.OwnerID, ctx.ParamsInt64(":id")) + w, err = webhook.GetWebhookByOwnerID(ctx, orCtx.OwnerID, ctx.ParamsInt64(":id")) } else if orCtx.IsAdmin { w, err = webhook.GetSystemOrDefaultWebhook(ctx, ctx.ParamsInt64(":id")) } @@ -618,7 +618,7 @@ func checkWebhook(ctx *context.Context) (*ownerRepoCtx, *webhook.Webhook) { ctx.Data["PackagistHook"] = webhook_service.GetPackagistHook(w) } - ctx.Data["History"], err = w.History(1) + ctx.Data["History"], err = w.History(ctx, 1) if err != nil { ctx.ServerError("History", err) } @@ -643,7 +643,7 @@ func WebHooksEdit(ctx *context.Context) { // TestWebhook test if web hook is work fine func TestWebhook(ctx *context.Context) { hookID := ctx.ParamsInt64(":id") - w, err := webhook.GetWebhookByRepoID(ctx.Repo.Repository.ID, hookID) + w, err := webhook.GetWebhookByRepoID(ctx, ctx.Repo.Repository.ID, hookID) if err != nil { ctx.Flash.Error("GetWebhookByRepoID: " + err.Error()) ctx.Status(http.StatusInternalServerError) @@ -724,7 +724,7 @@ func ReplayWebhook(ctx *context.Context) { // DeleteWebhook delete a webhook func DeleteWebhook(ctx *context.Context) { - if err := webhook.DeleteWebhookByRepoID(ctx.Repo.Repository.ID, ctx.FormInt64("id")); err != nil { + if err := webhook.DeleteWebhookByRepoID(ctx, ctx.Repo.Repository.ID, ctx.FormInt64("id")); err != nil { ctx.Flash.Error("DeleteWebhookByRepoID: " + err.Error()) } else { ctx.Flash.Success(ctx.Tr("repo.settings.webhook_deletion_success")) diff --git a/routers/web/user/avatar.go b/routers/web/user/avatar.go index 7ad65cd51..01df2fd29 100644 --- a/routers/web/user/avatar.go +++ b/routers/web/user/avatar.go @@ -47,7 +47,7 @@ func AvatarByUserName(ctx *context.Context) { // AvatarByEmailHash redirects the browser to the email avatar link func AvatarByEmailHash(ctx *context.Context) { hash := ctx.Params(":hash") - email, err := avatars.GetEmailForHash(hash) + email, err := avatars.GetEmailForHash(ctx, hash) if err != nil { ctx.ServerError("invalid avatar hash: "+hash, err) return diff --git a/routers/web/user/home.go b/routers/web/user/home.go index 9364ce80d..8b9a4cd22 100644 --- a/routers/web/user/home.go +++ b/routers/web/user/home.go @@ -784,7 +784,7 @@ func ShowGPGKeys(ctx *context.Context) { entities := make([]*openpgp.Entity, 0) failedEntitiesID := make([]string, 0) for _, k := range keys { - e, err := asymkey_model.GPGKeyToEntity(k) + e, err := asymkey_model.GPGKeyToEntity(ctx, k) if err != nil { if asymkey_model.IsErrGPGKeyImportNotExist(err) { failedEntitiesID = append(failedEntitiesID, k.KeyID) diff --git a/routers/web/user/setting/keys.go b/routers/web/user/setting/keys.go index 227c1d3a7..440885bb0 100644 --- a/routers/web/user/setting/keys.go +++ b/routers/web/user/setting/keys.go @@ -61,7 +61,7 @@ func KeysPost(ctx *context.Context) { ctx.Redirect(setting.AppSubURL + "/user/settings/keys") return } - if _, err = asymkey_model.AddPrincipalKey(ctx.Doer.ID, content, 0); err != nil { + if _, err = asymkey_model.AddPrincipalKey(ctx, ctx.Doer.ID, content, 0); err != nil { ctx.Data["HasPrincipalError"] = true switch { case asymkey_model.IsErrKeyAlreadyExist(err), asymkey_model.IsErrKeyNameAlreadyUsed(err): @@ -131,9 +131,9 @@ func KeysPost(ctx *context.Context) { token := asymkey_model.VerificationToken(ctx.Doer, 1) lastToken := asymkey_model.VerificationToken(ctx.Doer, 0) - keyID, err := asymkey_model.VerifyGPGKey(ctx.Doer.ID, form.KeyID, token, form.Signature) + keyID, err := asymkey_model.VerifyGPGKey(ctx, ctx.Doer.ID, form.KeyID, token, form.Signature) if err != nil && asymkey_model.IsErrGPGInvalidTokenSignature(err) { - keyID, err = asymkey_model.VerifyGPGKey(ctx.Doer.ID, form.KeyID, lastToken, form.Signature) + keyID, err = asymkey_model.VerifyGPGKey(ctx, ctx.Doer.ID, form.KeyID, lastToken, form.Signature) } if err != nil { ctx.Data["HasGPGVerifyError"] = true @@ -195,9 +195,9 @@ func KeysPost(ctx *context.Context) { token := asymkey_model.VerificationToken(ctx.Doer, 1) lastToken := asymkey_model.VerificationToken(ctx.Doer, 0) - fingerprint, err := asymkey_model.VerifySSHKey(ctx.Doer.ID, form.Fingerprint, token, form.Signature) + fingerprint, err := asymkey_model.VerifySSHKey(ctx, ctx.Doer.ID, form.Fingerprint, token, form.Signature) if err != nil && asymkey_model.IsErrSSHInvalidTokenSignature(err) { - fingerprint, err = asymkey_model.VerifySSHKey(ctx.Doer.ID, form.Fingerprint, lastToken, form.Signature) + fingerprint, err = asymkey_model.VerifySSHKey(ctx, ctx.Doer.ID, form.Fingerprint, lastToken, form.Signature) } if err != nil { ctx.Data["HasSSHVerifyError"] = true @@ -285,7 +285,7 @@ func loadKeysData(ctx *context.Context) { // generate a new aes cipher using the csrfToken ctx.Data["TokenToSign"] = tokenToSign - principals, err := asymkey_model.ListPrincipalKeys(ctx.Doer.ID, db.ListOptions{}) + principals, err := asymkey_model.ListPrincipalKeys(ctx, ctx.Doer.ID, db.ListOptions{}) if err != nil { ctx.ServerError("ListPrincipalKeys", err) return diff --git a/routers/web/user/setting/oauth2_common.go b/routers/web/user/setting/oauth2_common.go index 5ac03e4a7..fecaa4b87 100644 --- a/routers/web/user/setting/oauth2_common.go +++ b/routers/web/user/setting/oauth2_common.go @@ -62,7 +62,7 @@ func (oa *OAuth2CommonHandlers) AddApp(ctx *context.Context) { // render the edit page with secret ctx.Flash.Success(ctx.Tr("settings.create_oauth2_application_success"), true) ctx.Data["App"] = app - ctx.Data["ClientSecret"], err = app.GenerateClientSecret() + ctx.Data["ClientSecret"], err = app.GenerateClientSecret(ctx) if err != nil { ctx.ServerError("GenerateClientSecret", err) return @@ -101,7 +101,7 @@ func (oa *OAuth2CommonHandlers) EditSave(ctx *context.Context) { // TODO validate redirect URI var err error - if ctx.Data["App"], err = auth.UpdateOAuth2Application(auth.UpdateOAuth2ApplicationOptions{ + if ctx.Data["App"], err = auth.UpdateOAuth2Application(ctx, auth.UpdateOAuth2ApplicationOptions{ ID: ctx.ParamsInt64("id"), Name: form.Name, RedirectURIs: util.SplitTrimSpace(form.RedirectURIs, "\n"), @@ -131,7 +131,7 @@ func (oa *OAuth2CommonHandlers) RegenerateSecret(ctx *context.Context) { return } ctx.Data["App"] = app - ctx.Data["ClientSecret"], err = app.GenerateClientSecret() + ctx.Data["ClientSecret"], err = app.GenerateClientSecret(ctx) if err != nil { ctx.ServerError("GenerateClientSecret", err) return @@ -142,7 +142,7 @@ func (oa *OAuth2CommonHandlers) RegenerateSecret(ctx *context.Context) { // DeleteApp deletes the given oauth2 application func (oa *OAuth2CommonHandlers) DeleteApp(ctx *context.Context) { - if err := auth.DeleteOAuth2Application(ctx.ParamsInt64("id"), oa.OwnerID); err != nil { + if err := auth.DeleteOAuth2Application(ctx, ctx.ParamsInt64("id"), oa.OwnerID); err != nil { ctx.ServerError("DeleteOAuth2Application", err) return } diff --git a/routers/web/user/setting/security/security.go b/routers/web/user/setting/security/security.go index 833940d92..c687f7314 100644 --- a/routers/web/user/setting/security/security.go +++ b/routers/web/user/setting/security/security.go @@ -41,7 +41,7 @@ func DeleteAccountLink(ctx *context.Context) { if id <= 0 { ctx.Flash.Error("Account link id is not given") } else { - if _, err := user_model.RemoveAccountLink(ctx.Doer, id); err != nil { + if _, err := user_model.RemoveAccountLink(ctx, ctx.Doer, id); err != nil { ctx.Flash.Error("RemoveAccountLink: " + err.Error()) } else { ctx.Flash.Success(ctx.Tr("settings.remove_account_link_success")) @@ -73,7 +73,7 @@ func loadSecurityData(ctx *context.Context) { } ctx.Data["Tokens"] = tokens - accountLinks, err := user_model.ListAccountLinks(ctx.Doer) + accountLinks, err := user_model.ListAccountLinks(ctx, ctx.Doer) if err != nil { ctx.ServerError("ListAccountLinks", err) return @@ -105,7 +105,7 @@ func loadSecurityData(ctx *context.Context) { } ctx.Data["AccountLinks"] = sources - orderedOAuth2Names, oauth2Providers, err := oauth2.GetActiveOAuth2Providers() + orderedOAuth2Names, oauth2Providers, err := oauth2.GetActiveOAuth2Providers(ctx) if err != nil { ctx.ServerError("GetActiveOAuth2Providers", err) return diff --git a/routers/web/user/setting/webhooks.go b/routers/web/user/setting/webhooks.go index 04092461f..50cebc2a3 100644 --- a/routers/web/user/setting/webhooks.go +++ b/routers/web/user/setting/webhooks.go @@ -36,7 +36,7 @@ func Webhooks(ctx *context.Context) { // DeleteWebhook response for delete webhook func DeleteWebhook(ctx *context.Context) { - if err := webhook.DeleteWebhookByOwnerID(ctx.Doer.ID, ctx.FormInt64("id")); err != nil { + if err := webhook.DeleteWebhookByOwnerID(ctx, ctx.Doer.ID, ctx.FormInt64("id")); err != nil { ctx.Flash.Error("DeleteWebhookByOwnerID: " + err.Error()) } else { ctx.Flash.Success(ctx.Tr("repo.settings.webhook_deletion_success")) diff --git a/routers/web/user/stop_watch.go b/routers/web/user/stop_watch.go index cac446d84..86f66e64a 100644 --- a/routers/web/user/stop_watch.go +++ b/routers/web/user/stop_watch.go @@ -29,7 +29,7 @@ func GetStopwatches(ctx *context.Context) { return } - apiSWs, err := convert.ToStopWatches(sws) + apiSWs, err := convert.ToStopWatches(ctx, sws) if err != nil { ctx.Error(http.StatusInternalServerError, err.Error()) return diff --git a/services/actions/notifier.go b/services/actions/notifier.go index 6dc44143b..5a71d1cd7 100644 --- a/services/actions/notifier.go +++ b/services/actions/notifier.go @@ -6,7 +6,6 @@ package actions import ( "context" - "code.gitea.io/gitea/models/db" issues_model "code.gitea.io/gitea/models/issues" packages_model "code.gitea.io/gitea/models/packages" perm_model "code.gitea.io/gitea/models/perm" @@ -68,7 +67,7 @@ func (n *actionsNotifier) IssueChangeStatus(ctx context.Context, doer *user_mode // Merge pull request calls issue.changeStatus so we need to handle separately. apiPullRequest := &api.PullRequestPayload{ Index: issue.Index, - PullRequest: convert.ToAPIPullRequest(db.DefaultContext, issue.PullRequest, nil), + PullRequest: convert.ToAPIPullRequest(ctx, issue.PullRequest, nil), Repository: convert.ToRepo(ctx, issue.Repo, permission), Sender: convert.ToUser(ctx, doer, nil), CommitID: commitID, @@ -296,7 +295,7 @@ func (n *actionsNotifier) PullRequestReview(ctx context.Context, pr *issues_mode WithPayload(&api.PullRequestPayload{ Action: api.HookIssueReviewed, Index: review.Issue.Index, - PullRequest: convert.ToAPIPullRequest(db.DefaultContext, pr, nil), + PullRequest: convert.ToAPIPullRequest(ctx, pr, nil), Repository: convert.ToRepo(ctx, review.Issue.Repo, permission), Sender: convert.ToUser(ctx, review.Reviewer, nil), Review: &api.ReviewPayload{ @@ -320,7 +319,7 @@ func (*actionsNotifier) MergePullRequest(ctx context.Context, doer *user_model.U return } - if err := pr.Issue.LoadRepo(db.DefaultContext); err != nil { + if err := pr.Issue.LoadRepo(ctx); err != nil { log.Error("pr.Issue.LoadRepo: %v", err) return } @@ -334,7 +333,7 @@ func (*actionsNotifier) MergePullRequest(ctx context.Context, doer *user_model.U // Merge pull request calls issue.changeStatus so we need to handle separately. apiPullRequest := &api.PullRequestPayload{ Index: pr.Issue.Index, - PullRequest: convert.ToAPIPullRequest(db.DefaultContext, pr, nil), + PullRequest: convert.ToAPIPullRequest(ctx, pr, nil), Repository: convert.ToRepo(ctx, pr.Issue.Repo, permission), Sender: convert.ToUser(ctx, doer, nil), Action: api.HookIssueClosed, @@ -413,7 +412,7 @@ func (n *actionsNotifier) SyncPushCommits(ctx context.Context, pusher *user_mode ctx = withMethod(ctx, "SyncPushCommits") apiPusher := convert.ToUser(ctx, pusher, nil) - apiCommits, apiHeadCommit, err := commits.ToAPIPayloadCommits(db.DefaultContext, repo.RepoPath(), repo.HTMLURL()) + apiCommits, apiHeadCommit, err := commits.ToAPIPayloadCommits(ctx, repo.RepoPath(), repo.HTMLURL()) if err != nil { log.Error("commits.ToAPIPayloadCommits failed: %v", err) return @@ -484,7 +483,7 @@ func (n *actionsNotifier) PullRequestSynchronized(ctx context.Context, doer *use return } - if err := pr.Issue.LoadRepo(db.DefaultContext); err != nil { + if err := pr.Issue.LoadRepo(ctx); err != nil { log.Error("pr.Issue.LoadRepo: %v", err) return } @@ -509,7 +508,7 @@ func (n *actionsNotifier) PullRequestChangeTargetBranch(ctx context.Context, doe return } - if err := pr.Issue.LoadRepo(db.DefaultContext); err != nil { + if err := pr.Issue.LoadRepo(ctx); err != nil { log.Error("pr.Issue.LoadRepo: %v", err) return } diff --git a/services/auth/source.go b/services/auth/source.go index aae3a7810..69b71a6de 100644 --- a/services/auth/source.go +++ b/services/auth/source.go @@ -4,14 +4,16 @@ package auth import ( + "context" + "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/models/db" user_model "code.gitea.io/gitea/models/user" ) // DeleteSource deletes a AuthSource record in DB. -func DeleteSource(source *auth.Source) error { - count, err := db.GetEngine(db.DefaultContext).Count(&user_model.User{LoginSource: source.ID}) +func DeleteSource(ctx context.Context, source *auth.Source) error { + count, err := db.GetEngine(ctx).Count(&user_model.User{LoginSource: source.ID}) if err != nil { return err } else if count > 0 { @@ -20,7 +22,7 @@ func DeleteSource(source *auth.Source) error { } } - count, err = db.GetEngine(db.DefaultContext).Count(&user_model.ExternalLoginUser{LoginSourceID: source.ID}) + count, err = db.GetEngine(ctx).Count(&user_model.ExternalLoginUser{LoginSourceID: source.ID}) if err != nil { return err } else if count > 0 { @@ -35,6 +37,6 @@ func DeleteSource(source *auth.Source) error { } } - _, err = db.GetEngine(db.DefaultContext).ID(source.ID).Delete(new(auth.Source)) + _, err = db.GetEngine(ctx).ID(source.ID).Delete(new(auth.Source)) return err } diff --git a/services/auth/source/oauth2/init.go b/services/auth/source/oauth2/init.go index 32fe545c9..cfaddaa35 100644 --- a/services/auth/source/oauth2/init.go +++ b/services/auth/source/oauth2/init.go @@ -4,6 +4,7 @@ package oauth2 import ( + "context" "encoding/gob" "net/http" "sync" @@ -26,7 +27,7 @@ const UsersStoreKey = "gitea-oauth2-sessions" const ProviderHeaderKey = "gitea-oauth2-provider" // Init initializes the oauth source -func Init() error { +func Init(ctx context.Context) error { if err := InitSigningKey(); err != nil { return err } @@ -51,18 +52,18 @@ func Init() error { // Unlock our mutex gothRWMutex.Unlock() - return initOAuth2Sources() + return initOAuth2Sources(ctx) } // ResetOAuth2 clears existing OAuth2 providers and loads them from DB -func ResetOAuth2() error { +func ResetOAuth2(ctx context.Context) error { ClearProviders() - return initOAuth2Sources() + return initOAuth2Sources(ctx) } // initOAuth2Sources is used to load and register all active OAuth2 providers -func initOAuth2Sources() error { - authSources, _ := auth.GetActiveOAuth2ProviderSources() +func initOAuth2Sources(ctx context.Context) error { + authSources, _ := auth.GetActiveOAuth2ProviderSources(ctx) for _, source := range authSources { oauth2Source, ok := source.Cfg.(*Source) if !ok { diff --git a/services/auth/source/oauth2/providers.go b/services/auth/source/oauth2/providers.go index e3a0cb033..cd158614a 100644 --- a/services/auth/source/oauth2/providers.go +++ b/services/auth/source/oauth2/providers.go @@ -4,6 +4,7 @@ package oauth2 import ( + "context" "errors" "fmt" "html" @@ -97,10 +98,10 @@ func GetOAuth2Providers() []Provider { // GetActiveOAuth2Providers returns the map of configured active OAuth2 providers // key is used as technical name (like in the callbackURL) // values to display -func GetActiveOAuth2Providers() ([]string, map[string]Provider, error) { +func GetActiveOAuth2Providers(ctx context.Context) ([]string, map[string]Provider, error) { // Maybe also separate used and unused providers so we can force the registration of only 1 active provider for each type - authSources, err := auth.GetActiveOAuth2ProviderSources() + authSources, err := auth.GetActiveOAuth2ProviderSources(ctx) if err != nil { return nil, nil, err } diff --git a/services/convert/issue.go b/services/convert/issue.go index 708eac36c..39d785e10 100644 --- a/services/convert/issue.go +++ b/services/convert/issue.go @@ -9,7 +9,6 @@ import ( "net/url" "strings" - "code.gitea.io/gitea/models/db" issues_model "code.gitea.io/gitea/models/issues" repo_model "code.gitea.io/gitea/models/repo" user_model "code.gitea.io/gitea/models/user" @@ -150,7 +149,7 @@ func ToTrackedTime(ctx context.Context, t *issues_model.TrackedTime) (apiT *api. } // ToStopWatches convert Stopwatch list to api.StopWatches -func ToStopWatches(sws []*issues_model.Stopwatch) (api.StopWatches, error) { +func ToStopWatches(ctx context.Context, sws []*issues_model.Stopwatch) (api.StopWatches, error) { result := api.StopWatches(make([]api.StopWatch, 0, len(sws))) issueCache := make(map[int64]*issues_model.Issue) @@ -165,14 +164,14 @@ func ToStopWatches(sws []*issues_model.Stopwatch) (api.StopWatches, error) { for _, sw := range sws { issue, ok = issueCache[sw.IssueID] if !ok { - issue, err = issues_model.GetIssueByID(db.DefaultContext, sw.IssueID) + issue, err = issues_model.GetIssueByID(ctx, sw.IssueID) if err != nil { return nil, err } } repo, ok = repoCache[issue.RepoID] if !ok { - repo, err = repo_model.GetRepositoryByID(db.DefaultContext, issue.RepoID) + repo, err = repo_model.GetRepositoryByID(ctx, issue.RepoID) if err != nil { return nil, err } diff --git a/services/externalaccount/user.go b/services/externalaccount/user.go index a80ba6fee..e2de41da1 100644 --- a/services/externalaccount/user.go +++ b/services/externalaccount/user.go @@ -16,8 +16,8 @@ import ( "github.com/markbates/goth" ) -func toExternalLoginUser(user *user_model.User, gothUser goth.User) (*user_model.ExternalLoginUser, error) { - authSource, err := auth.GetActiveOAuth2SourceByName(gothUser.Provider) +func toExternalLoginUser(ctx context.Context, user *user_model.User, gothUser goth.User) (*user_model.ExternalLoginUser, error) { + authSource, err := auth.GetActiveOAuth2SourceByName(ctx, gothUser.Provider) if err != nil { return nil, err } @@ -44,12 +44,12 @@ func toExternalLoginUser(user *user_model.User, gothUser goth.User) (*user_model // LinkAccountToUser link the gothUser to the user func LinkAccountToUser(ctx context.Context, user *user_model.User, gothUser goth.User) error { - externalLoginUser, err := toExternalLoginUser(user, gothUser) + externalLoginUser, err := toExternalLoginUser(ctx, user, gothUser) if err != nil { return err } - if err := user_model.LinkExternalToUser(user, externalLoginUser); err != nil { + if err := user_model.LinkExternalToUser(ctx, user, externalLoginUser); err != nil { return err } @@ -71,13 +71,13 @@ func LinkAccountToUser(ctx context.Context, user *user_model.User, gothUser goth } // UpdateExternalUser updates external user's information -func UpdateExternalUser(user *user_model.User, gothUser goth.User) error { - externalLoginUser, err := toExternalLoginUser(user, gothUser) +func UpdateExternalUser(ctx context.Context, user *user_model.User, gothUser goth.User) error { + externalLoginUser, err := toExternalLoginUser(ctx, user, gothUser) if err != nil { return err } - return user_model.UpdateExternalUserByExternalID(externalLoginUser) + return user_model.UpdateExternalUserByExternalID(ctx, externalLoginUser) } // UpdateMigrationsByType updates all migrated repositories' posterid from gitServiceType to replace originalAuthorID to posterID diff --git a/services/migrations/gitea_uploader.go b/services/migrations/gitea_uploader.go index 36b5e1529..ddc2cbd4e 100644 --- a/services/migrations/gitea_uploader.go +++ b/services/migrations/gitea_uploader.go @@ -989,7 +989,7 @@ func (g *GiteaLocalUploader) remapLocalUser(source user_model.ExternalUserMigrat func (g *GiteaLocalUploader) remapExternalUser(source user_model.ExternalUserMigrated, target user_model.ExternalUserRemappable) (userid int64, err error) { userid, ok := g.userMap[source.GetExternalID()] if !ok { - userid, err = user_model.GetUserIDByExternalUserID(g.gitServiceType.Name(), fmt.Sprintf("%d", source.GetExternalID())) + userid, err = user_model.GetUserIDByExternalUserID(g.ctx, g.gitServiceType.Name(), fmt.Sprintf("%d", source.GetExternalID())) if err != nil { log.Error("GetUserIDByExternalUserID: %v", err) return 0, err diff --git a/services/migrations/gitea_uploader_test.go b/services/migrations/gitea_uploader_test.go index 847e76d9b..84db83bc6 100644 --- a/services/migrations/gitea_uploader_test.go +++ b/services/migrations/gitea_uploader_test.go @@ -210,7 +210,7 @@ func TestGiteaUploadRemapExternalUser(t *testing.T) { LoginSourceID: 0, Provider: structs.GiteaService.Name(), } - err = user_model.LinkExternalToUser(linkedUser, externalLoginUser) + err = user_model.LinkExternalToUser(db.DefaultContext, linkedUser, externalLoginUser) assert.NoError(t, err) // diff --git a/services/migrations/update.go b/services/migrations/update.go index f14c07cc8..d46683236 100644 --- a/services/migrations/update.go +++ b/services/migrations/update.go @@ -45,7 +45,7 @@ func updateMigrationPosterIDByGitService(ctx context.Context, tp structs.GitServ default: } - users, err := user_model.FindExternalUsersByProvider(user_model.FindExternalUserOptions{ + users, err := user_model.FindExternalUsersByProvider(ctx, user_model.FindExternalUserOptions{ Provider: provider, Start: start, Limit: batchSize, diff --git a/services/pull/lfs.go b/services/pull/lfs.go index 394337246..2ca82b563 100644 --- a/services/pull/lfs.go +++ b/services/pull/lfs.go @@ -40,7 +40,7 @@ func LFSPush(ctx context.Context, tmpBasePath, mergeHeadSHA, mergeBaseSHA string // 6. Take the output of cat-file --batch and check if each file in turn // to see if they're pointers to files in the LFS store associated with // the head repo and add them to the base repo if so - go createLFSMetaObjectsFromCatFileBatch(catFileBatchReader, &wg, pr) + go createLFSMetaObjectsFromCatFileBatch(db.DefaultContext, catFileBatchReader, &wg, pr) // 5. Take the shas of the blobs and batch read them go pipeline.CatFileBatch(ctx, shasToBatchReader, catFileBatchWriter, &wg, tmpBasePath) @@ -68,7 +68,7 @@ func LFSPush(ctx context.Context, tmpBasePath, mergeHeadSHA, mergeBaseSHA string return nil } -func createLFSMetaObjectsFromCatFileBatch(catFileBatchReader *io.PipeReader, wg *sync.WaitGroup, pr *issues_model.PullRequest) { +func createLFSMetaObjectsFromCatFileBatch(ctx context.Context, catFileBatchReader *io.PipeReader, wg *sync.WaitGroup, pr *issues_model.PullRequest) { defer wg.Done() defer catFileBatchReader.Close() @@ -116,7 +116,7 @@ func createLFSMetaObjectsFromCatFileBatch(catFileBatchReader *io.PipeReader, wg } // Then we need to check that this pointer is in the db - if _, err := git_model.GetLFSMetaObjectByOid(db.DefaultContext, pr.HeadRepoID, pointer.Oid); err != nil { + if _, err := git_model.GetLFSMetaObjectByOid(ctx, pr.HeadRepoID, pointer.Oid); err != nil { if err == git_model.ErrLFSObjectNotExist { log.Warn("During merge of: %d in %-v, there is a pointer to LFS Oid: %s which although present in the LFS store is not associated with the head repo %-v", pr.Index, pr.BaseRepo, pointer.Oid, pr.HeadRepo) continue @@ -129,7 +129,7 @@ func createLFSMetaObjectsFromCatFileBatch(catFileBatchReader *io.PipeReader, wg // Therefore it should be associated with the base repo meta := &git_model.LFSMetaObject{Pointer: pointer} meta.RepositoryID = pr.BaseRepoID - if _, err := git_model.NewLFSMetaObject(db.DefaultContext, meta); err != nil { + if _, err := git_model.NewLFSMetaObject(ctx, meta); err != nil { _ = catFileBatchReader.CloseWithError(err) break } diff --git a/services/pull/merge.go b/services/pull/merge.go index 185060cba..e6f02e6e0 100644 --- a/services/pull/merge.go +++ b/services/pull/merge.go @@ -464,11 +464,11 @@ func CheckPullBranchProtections(ctx context.Context, pr *issues_model.PullReques } // MergedManually mark pr as merged manually -func MergedManually(pr *issues_model.PullRequest, doer *user_model.User, baseGitRepo *git.Repository, commitID string) error { +func MergedManually(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.User, baseGitRepo *git.Repository, commitID string) error { pullWorkingPool.CheckIn(fmt.Sprint(pr.ID)) defer pullWorkingPool.CheckOut(fmt.Sprint(pr.ID)) - if err := db.WithTx(db.DefaultContext, func(ctx context.Context) error { + if err := db.WithTx(ctx, func(ctx context.Context) error { if err := pr.LoadBaseRepo(ctx); err != nil { return err } diff --git a/services/pull/pull.go b/services/pull/pull.go index e4096f8ac..2f5143903 100644 --- a/services/pull/pull.go +++ b/services/pull/pull.go @@ -811,7 +811,7 @@ func GetIssuesAllCommitStatus(ctx context.Context, issues issues_model.IssueList gitRepos[issue.RepoID] = gitRepo } - statuses, lastStatus, err := getAllCommitStatus(gitRepo, issue.PullRequest) + statuses, lastStatus, err := getAllCommitStatus(ctx, gitRepo, issue.PullRequest) if err != nil { log.Error("getAllCommitStatus: cant get commit statuses of pull [%d]: %v", issue.PullRequest.ID, err) continue @@ -823,13 +823,13 @@ func GetIssuesAllCommitStatus(ctx context.Context, issues issues_model.IssueList } // getAllCommitStatus get pr's commit statuses. -func getAllCommitStatus(gitRepo *git.Repository, pr *issues_model.PullRequest) (statuses []*git_model.CommitStatus, lastStatus *git_model.CommitStatus, err error) { +func getAllCommitStatus(ctx context.Context, gitRepo *git.Repository, pr *issues_model.PullRequest) (statuses []*git_model.CommitStatus, lastStatus *git_model.CommitStatus, err error) { sha, shaErr := gitRepo.GetRefCommitID(pr.GetGitRefName()) if shaErr != nil { return nil, nil, shaErr } - statuses, _, err = git_model.GetLatestCommitStatus(db.DefaultContext, pr.BaseRepo.ID, sha, db.ListOptions{ListAll: true}) + statuses, _, err = git_model.GetLatestCommitStatus(ctx, pr.BaseRepo.ID, sha, db.ListOptions{ListAll: true}) lastStatus = git_model.CalcCommitStatus(statuses) return statuses, lastStatus, err } diff --git a/services/webhook/deliver.go b/services/webhook/deliver.go index fd7a3d7fb..19c34772c 100644 --- a/services/webhook/deliver.go +++ b/services/webhook/deliver.go @@ -34,7 +34,7 @@ import ( // Deliver deliver hook task func Deliver(ctx context.Context, t *webhook_model.HookTask) error { - w, err := webhook_model.GetWebhookByID(t.HookID) + w, err := webhook_model.GetWebhookByID(ctx, t.HookID) if err != nil { return err } @@ -185,7 +185,7 @@ func Deliver(ctx context.Context, t *webhook_model.HookTask) error { log.Trace("Hook delivery failed: %s", t.UUID) } - if err := webhook_model.UpdateHookTask(t); err != nil { + if err := webhook_model.UpdateHookTask(ctx, t); err != nil { log.Error("UpdateHookTask [%d]: %v", t.ID, err) } @@ -195,7 +195,7 @@ func Deliver(ctx context.Context, t *webhook_model.HookTask) error { } else { w.LastStatus = webhook_module.HookStatusFail } - if err = webhook_model.UpdateWebhookLastStatus(w); err != nil { + if err = webhook_model.UpdateWebhookLastStatus(ctx, w); err != nil { log.Error("UpdateWebhookLastStatus: %v", err) return } diff --git a/tests/integration/api_private_serv_test.go b/tests/integration/api_private_serv_test.go index 8beec6238..2001bb1fa 100644 --- a/tests/integration/api_private_serv_test.go +++ b/tests/integration/api_private_serv_test.go @@ -26,7 +26,7 @@ func TestAPIPrivateNoServ(t *testing.T) { assert.Equal(t, int64(1), key.ID) assert.Equal(t, "user2@localhost", key.Name) - deployKey, err := asymkey_model.AddDeployKey(1, "test-deploy", "sk-ecdsa-sha2-nistp256@openssh.com AAAAInNrLWVjZHNhLXNoYTItbmlzdHAyNTZAb3BlbnNzaC5jb20AAAAIbmlzdHAyNTYAAABBBGXEEzWmm1dxb+57RoK5KVCL0w2eNv9cqJX2AGGVlkFsVDhOXHzsadS3LTK4VlEbbrDMJdoti9yM8vclA8IeRacAAAAEc3NoOg== nocomment", false) + deployKey, err := asymkey_model.AddDeployKey(ctx, 1, "test-deploy", "sk-ecdsa-sha2-nistp256@openssh.com AAAAInNrLWVjZHNhLXNoYTItbmlzdHAyNTZAb3BlbnNzaC5jb20AAAAIbmlzdHAyNTYAAABBBGXEEzWmm1dxb+57RoK5KVCL0w2eNv9cqJX2AGGVlkFsVDhOXHzsadS3LTK4VlEbbrDMJdoti9yM8vclA8IeRacAAAAEc3NoOg== nocomment", false) assert.NoError(t, err) key, user, err = private.ServNoCommand(ctx, deployKey.KeyID) @@ -84,7 +84,7 @@ func TestAPIPrivateServ(t *testing.T) { assert.Empty(t, results) // Add reading deploy key - deployKey, err := asymkey_model.AddDeployKey(19, "test-deploy", "sk-ecdsa-sha2-nistp256@openssh.com AAAAInNrLWVjZHNhLXNoYTItbmlzdHAyNTZAb3BlbnNzaC5jb20AAAAIbmlzdHAyNTYAAABBBGXEEzWmm1dxb+57RoK5KVCL0w2eNv9cqJX2AGGVlkFsVDhOXHzsadS3LTK4VlEbbrDMJdoti9yM8vclA8IeRacAAAAEc3NoOg== nocomment", true) + deployKey, err := asymkey_model.AddDeployKey(ctx, 19, "test-deploy", "sk-ecdsa-sha2-nistp256@openssh.com AAAAInNrLWVjZHNhLXNoYTItbmlzdHAyNTZAb3BlbnNzaC5jb20AAAAIbmlzdHAyNTYAAABBBGXEEzWmm1dxb+57RoK5KVCL0w2eNv9cqJX2AGGVlkFsVDhOXHzsadS3LTK4VlEbbrDMJdoti9yM8vclA8IeRacAAAAEc3NoOg== nocomment", true) assert.NoError(t, err) // Can pull from repo we're a deploy key for @@ -116,7 +116,7 @@ func TestAPIPrivateServ(t *testing.T) { assert.Empty(t, results) // Add writing deploy key - deployKey, err = asymkey_model.AddDeployKey(20, "test-deploy", "sk-ecdsa-sha2-nistp256@openssh.com AAAAInNrLWVjZHNhLXNoYTItbmlzdHAyNTZAb3BlbnNzaC5jb20AAAAIbmlzdHAyNTYAAABBBGXEEzWmm1dxb+57RoK5KVCL0w2eNv9cqJX2AGGVlkFsVDhOXHzsadS3LTK4VlEbbrDMJdoti9yM8vclA8IeRacAAAAEc3NoOg== nocomment", false) + deployKey, err = asymkey_model.AddDeployKey(ctx, 20, "test-deploy", "sk-ecdsa-sha2-nistp256@openssh.com AAAAInNrLWVjZHNhLXNoYTItbmlzdHAyNTZAb3BlbnNzaC5jb20AAAAIbmlzdHAyNTYAAABBBGXEEzWmm1dxb+57RoK5KVCL0w2eNv9cqJX2AGGVlkFsVDhOXHzsadS3LTK4VlEbbrDMJdoti9yM8vclA8IeRacAAAAEc3NoOg== nocomment", false) assert.NoError(t, err) // Cannot push to a private repo with reading key diff --git a/tests/integration/pull_merge_test.go b/tests/integration/pull_merge_test.go index f94809e4b..a4cc3e76f 100644 --- a/tests/integration/pull_merge_test.go +++ b/tests/integration/pull_merge_test.go @@ -68,7 +68,7 @@ func testPullCleanUp(t *testing.T, session *TestSession, user, repo, pullnum str func TestPullMerge(t *testing.T) { onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) { - hookTasks, err := webhook.HookTasks(1, 1) // Retrieve previous hook number + hookTasks, err := webhook.HookTasks(db.DefaultContext, 1, 1) // Retrieve previous hook number assert.NoError(t, err) hookTasksLenBefore := len(hookTasks) @@ -82,7 +82,7 @@ func TestPullMerge(t *testing.T) { assert.EqualValues(t, "pulls", elem[3]) testPullMerge(t, session, elem[1], elem[2], elem[4], repo_model.MergeStyleMerge) - hookTasks, err = webhook.HookTasks(1, 1) + hookTasks, err = webhook.HookTasks(db.DefaultContext, 1, 1) assert.NoError(t, err) assert.Len(t, hookTasks, hookTasksLenBefore+1) }) @@ -90,7 +90,7 @@ func TestPullMerge(t *testing.T) { func TestPullRebase(t *testing.T) { onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) { - hookTasks, err := webhook.HookTasks(1, 1) // Retrieve previous hook number + hookTasks, err := webhook.HookTasks(db.DefaultContext, 1, 1) // Retrieve previous hook number assert.NoError(t, err) hookTasksLenBefore := len(hookTasks) @@ -104,7 +104,7 @@ func TestPullRebase(t *testing.T) { assert.EqualValues(t, "pulls", elem[3]) testPullMerge(t, session, elem[1], elem[2], elem[4], repo_model.MergeStyleRebase) - hookTasks, err = webhook.HookTasks(1, 1) + hookTasks, err = webhook.HookTasks(db.DefaultContext, 1, 1) assert.NoError(t, err) assert.Len(t, hookTasks, hookTasksLenBefore+1) }) @@ -112,7 +112,7 @@ func TestPullRebase(t *testing.T) { func TestPullRebaseMerge(t *testing.T) { onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) { - hookTasks, err := webhook.HookTasks(1, 1) // Retrieve previous hook number + hookTasks, err := webhook.HookTasks(db.DefaultContext, 1, 1) // Retrieve previous hook number assert.NoError(t, err) hookTasksLenBefore := len(hookTasks) @@ -126,7 +126,7 @@ func TestPullRebaseMerge(t *testing.T) { assert.EqualValues(t, "pulls", elem[3]) testPullMerge(t, session, elem[1], elem[2], elem[4], repo_model.MergeStyleRebaseMerge) - hookTasks, err = webhook.HookTasks(1, 1) + hookTasks, err = webhook.HookTasks(db.DefaultContext, 1, 1) assert.NoError(t, err) assert.Len(t, hookTasks, hookTasksLenBefore+1) }) @@ -134,7 +134,7 @@ func TestPullRebaseMerge(t *testing.T) { func TestPullSquash(t *testing.T) { onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) { - hookTasks, err := webhook.HookTasks(1, 1) // Retrieve previous hook number + hookTasks, err := webhook.HookTasks(db.DefaultContext, 1, 1) // Retrieve previous hook number assert.NoError(t, err) hookTasksLenBefore := len(hookTasks) @@ -149,7 +149,7 @@ func TestPullSquash(t *testing.T) { assert.EqualValues(t, "pulls", elem[3]) testPullMerge(t, session, elem[1], elem[2], elem[4], repo_model.MergeStyleSquash) - hookTasks, err = webhook.HookTasks(1, 1) + hookTasks, err = webhook.HookTasks(db.DefaultContext, 1, 1) assert.NoError(t, err) assert.Len(t, hookTasks, hookTasksLenBefore+1) })