Final round of db.DefaultContext refactor (#27587)

Last part of #27065
This commit is contained in:
JakobDev 2023-10-14 10:37:24 +02:00 committed by GitHub
parent ae419fa494
commit 76a85a4ce9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
64 changed files with 250 additions and 242 deletions

View File

@ -105,5 +105,5 @@ func runDeleteAuth(c *cli.Context) error {
return err
}
return auth_service.DeleteSource(source)
return auth_service.DeleteSource(ctx, source)
}

View File

@ -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
}

View File

@ -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 {

View File

@ -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
}

View File

@ -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{})
}

View File

@ -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)

View File

@ -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
}

View File

@ -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
}

View File

@ -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")))

View File

@ -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

View File

@ -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}

View File

@ -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))
}

View File

@ -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)

View File

@ -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
}

View File

@ -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,
})

View File

@ -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)
}

View File

@ -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) {

View File

@ -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)

View File

@ -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) {

View File

@ -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 {

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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 {

View File

@ -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 {

View File

@ -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)

View File

@ -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(),
})

View File

@ -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 {

Some files were not shown because too many files have changed in this diff Show More