1
1
mirror of https://github.com/go-gitea/gitea synced 2024-12-22 16:44:26 +00:00

More refactoring of db.DefaultContext (#27083)

Next step of #27065
This commit is contained in:
JakobDev 2023-09-15 08:13:19 +02:00 committed by GitHub
parent f8a1094406
commit c548dde205
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
83 changed files with 336 additions and 320 deletions

View File

@ -156,7 +156,7 @@ func runCreateUser(c *cli.Context) error {
UID: u.ID, UID: u.ID,
} }
if err := auth_model.NewAccessToken(t); err != nil { if err := auth_model.NewAccessToken(ctx, t); err != nil {
return err return err
} }

View File

@ -63,7 +63,7 @@ func runGenerateAccessToken(c *cli.Context) error {
UID: user.ID, UID: user.ID,
} }
exist, err := auth_model.AccessTokenByNameExists(t) exist, err := auth_model.AccessTokenByNameExists(ctx, t)
if err != nil { if err != nil {
return err return err
} }
@ -79,7 +79,7 @@ func runGenerateAccessToken(c *cli.Context) error {
t.Scope = accessTokenScope t.Scope = accessTokenScope
// create the token // create the token
if err := auth_model.NewAccessToken(t); err != nil { if err := auth_model.NewAccessToken(ctx, t); err != nil {
return err return err
} }

View File

@ -5,6 +5,7 @@
package auth package auth
import ( import (
"context"
"crypto/subtle" "crypto/subtle"
"encoding/hex" "encoding/hex"
"fmt" "fmt"
@ -95,7 +96,7 @@ func init() {
} }
// NewAccessToken creates new access token. // NewAccessToken creates new access token.
func NewAccessToken(t *AccessToken) error { func NewAccessToken(ctx context.Context, t *AccessToken) error {
salt, err := util.CryptoRandomString(10) salt, err := util.CryptoRandomString(10)
if err != nil { if err != nil {
return err return err
@ -108,7 +109,7 @@ func NewAccessToken(t *AccessToken) error {
t.Token = hex.EncodeToString(token) t.Token = hex.EncodeToString(token)
t.TokenHash = HashToken(t.Token, t.TokenSalt) t.TokenHash = HashToken(t.Token, t.TokenSalt)
t.TokenLastEight = t.Token[len(t.Token)-8:] t.TokenLastEight = t.Token[len(t.Token)-8:]
_, err = db.GetEngine(db.DefaultContext).Insert(t) _, err = db.GetEngine(ctx).Insert(t)
return err return err
} }
@ -137,7 +138,7 @@ func getAccessTokenIDFromCache(token string) int64 {
} }
// GetAccessTokenBySHA returns access token by given token value // GetAccessTokenBySHA returns access token by given token value
func GetAccessTokenBySHA(token string) (*AccessToken, error) { func GetAccessTokenBySHA(ctx context.Context, token string) (*AccessToken, error) {
if token == "" { if token == "" {
return nil, ErrAccessTokenEmpty{} return nil, ErrAccessTokenEmpty{}
} }
@ -158,7 +159,7 @@ func GetAccessTokenBySHA(token string) (*AccessToken, error) {
TokenLastEight: lastEight, TokenLastEight: lastEight,
} }
// Re-get the token from the db in case it has been deleted in the intervening period // Re-get the token from the db in case it has been deleted in the intervening period
has, err := db.GetEngine(db.DefaultContext).ID(id).Get(accessToken) has, err := db.GetEngine(ctx).ID(id).Get(accessToken)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -169,7 +170,7 @@ func GetAccessTokenBySHA(token string) (*AccessToken, error) {
} }
var tokens []AccessToken var tokens []AccessToken
err := db.GetEngine(db.DefaultContext).Table(&AccessToken{}).Where("token_last_eight = ?", lastEight).Find(&tokens) err := db.GetEngine(ctx).Table(&AccessToken{}).Where("token_last_eight = ?", lastEight).Find(&tokens)
if err != nil { if err != nil {
return nil, err return nil, err
} else if len(tokens) == 0 { } else if len(tokens) == 0 {
@ -189,8 +190,8 @@ func GetAccessTokenBySHA(token string) (*AccessToken, error) {
} }
// AccessTokenByNameExists checks if a token name has been used already by a user. // AccessTokenByNameExists checks if a token name has been used already by a user.
func AccessTokenByNameExists(token *AccessToken) (bool, error) { func AccessTokenByNameExists(ctx context.Context, token *AccessToken) (bool, error) {
return db.GetEngine(db.DefaultContext).Table("access_token").Where("name = ?", token.Name).And("uid = ?", token.UID).Exist() return db.GetEngine(ctx).Table("access_token").Where("name = ?", token.Name).And("uid = ?", token.UID).Exist()
} }
// ListAccessTokensOptions contain filter options // ListAccessTokensOptions contain filter options
@ -201,8 +202,8 @@ type ListAccessTokensOptions struct {
} }
// ListAccessTokens returns a list of access tokens belongs to given user. // ListAccessTokens returns a list of access tokens belongs to given user.
func ListAccessTokens(opts ListAccessTokensOptions) ([]*AccessToken, error) { func ListAccessTokens(ctx context.Context, opts ListAccessTokensOptions) ([]*AccessToken, error) {
sess := db.GetEngine(db.DefaultContext).Where("uid=?", opts.UserID) sess := db.GetEngine(ctx).Where("uid=?", opts.UserID)
if len(opts.Name) != 0 { if len(opts.Name) != 0 {
sess = sess.Where("name=?", opts.Name) sess = sess.Where("name=?", opts.Name)
@ -222,14 +223,14 @@ func ListAccessTokens(opts ListAccessTokensOptions) ([]*AccessToken, error) {
} }
// UpdateAccessToken updates information of access token. // UpdateAccessToken updates information of access token.
func UpdateAccessToken(t *AccessToken) error { func UpdateAccessToken(ctx context.Context, t *AccessToken) error {
_, err := db.GetEngine(db.DefaultContext).ID(t.ID).AllCols().Update(t) _, err := db.GetEngine(ctx).ID(t.ID).AllCols().Update(t)
return err return err
} }
// CountAccessTokens count access tokens belongs to given user by options // CountAccessTokens count access tokens belongs to given user by options
func CountAccessTokens(opts ListAccessTokensOptions) (int64, error) { func CountAccessTokens(ctx context.Context, opts ListAccessTokensOptions) (int64, error) {
sess := db.GetEngine(db.DefaultContext).Where("uid=?", opts.UserID) sess := db.GetEngine(ctx).Where("uid=?", opts.UserID)
if len(opts.Name) != 0 { if len(opts.Name) != 0 {
sess = sess.Where("name=?", opts.Name) sess = sess.Where("name=?", opts.Name)
} }
@ -237,8 +238,8 @@ func CountAccessTokens(opts ListAccessTokensOptions) (int64, error) {
} }
// DeleteAccessTokenByID deletes access token by given ID. // DeleteAccessTokenByID deletes access token by given ID.
func DeleteAccessTokenByID(id, userID int64) error { func DeleteAccessTokenByID(ctx context.Context, id, userID int64) error {
cnt, err := db.GetEngine(db.DefaultContext).ID(id).Delete(&AccessToken{ cnt, err := db.GetEngine(ctx).ID(id).Delete(&AccessToken{
UID: userID, UID: userID,
}) })
if err != nil { if err != nil {

View File

@ -7,6 +7,7 @@ import (
"testing" "testing"
auth_model "code.gitea.io/gitea/models/auth" auth_model "code.gitea.io/gitea/models/auth"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -18,7 +19,7 @@ func TestNewAccessToken(t *testing.T) {
UID: 3, UID: 3,
Name: "Token C", Name: "Token C",
} }
assert.NoError(t, auth_model.NewAccessToken(token)) assert.NoError(t, auth_model.NewAccessToken(db.DefaultContext, token))
unittest.AssertExistsAndLoadBean(t, token) unittest.AssertExistsAndLoadBean(t, token)
invalidToken := &auth_model.AccessToken{ invalidToken := &auth_model.AccessToken{
@ -26,7 +27,7 @@ func TestNewAccessToken(t *testing.T) {
UID: 2, UID: 2,
Name: "Token F", Name: "Token F",
} }
assert.Error(t, auth_model.NewAccessToken(invalidToken)) assert.Error(t, auth_model.NewAccessToken(db.DefaultContext, invalidToken))
} }
func TestAccessTokenByNameExists(t *testing.T) { func TestAccessTokenByNameExists(t *testing.T) {
@ -39,16 +40,16 @@ func TestAccessTokenByNameExists(t *testing.T) {
} }
// Check to make sure it doesn't exists already // Check to make sure it doesn't exists already
exist, err := auth_model.AccessTokenByNameExists(token) exist, err := auth_model.AccessTokenByNameExists(db.DefaultContext, token)
assert.NoError(t, err) assert.NoError(t, err)
assert.False(t, exist) assert.False(t, exist)
// Save it to the database // Save it to the database
assert.NoError(t, auth_model.NewAccessToken(token)) assert.NoError(t, auth_model.NewAccessToken(db.DefaultContext, token))
unittest.AssertExistsAndLoadBean(t, token) unittest.AssertExistsAndLoadBean(t, token)
// This token must be found by name in the DB now // This token must be found by name in the DB now
exist, err = auth_model.AccessTokenByNameExists(token) exist, err = auth_model.AccessTokenByNameExists(db.DefaultContext, token)
assert.NoError(t, err) assert.NoError(t, err)
assert.True(t, exist) assert.True(t, exist)
@ -59,32 +60,32 @@ func TestAccessTokenByNameExists(t *testing.T) {
// Name matches but different user ID, this shouldn't exists in the // Name matches but different user ID, this shouldn't exists in the
// database // database
exist, err = auth_model.AccessTokenByNameExists(user4Token) exist, err = auth_model.AccessTokenByNameExists(db.DefaultContext, user4Token)
assert.NoError(t, err) assert.NoError(t, err)
assert.False(t, exist) assert.False(t, exist)
} }
func TestGetAccessTokenBySHA(t *testing.T) { func TestGetAccessTokenBySHA(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
token, err := auth_model.GetAccessTokenBySHA("d2c6c1ba3890b309189a8e618c72a162e4efbf36") token, err := auth_model.GetAccessTokenBySHA(db.DefaultContext, "d2c6c1ba3890b309189a8e618c72a162e4efbf36")
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, int64(1), token.UID) assert.Equal(t, int64(1), token.UID)
assert.Equal(t, "Token A", token.Name) assert.Equal(t, "Token A", token.Name)
assert.Equal(t, "2b3668e11cb82d3af8c6e4524fc7841297668f5008d1626f0ad3417e9fa39af84c268248b78c481daa7e5dc437784003494f", token.TokenHash) assert.Equal(t, "2b3668e11cb82d3af8c6e4524fc7841297668f5008d1626f0ad3417e9fa39af84c268248b78c481daa7e5dc437784003494f", token.TokenHash)
assert.Equal(t, "e4efbf36", token.TokenLastEight) assert.Equal(t, "e4efbf36", token.TokenLastEight)
_, err = auth_model.GetAccessTokenBySHA("notahash") _, err = auth_model.GetAccessTokenBySHA(db.DefaultContext, "notahash")
assert.Error(t, err) assert.Error(t, err)
assert.True(t, auth_model.IsErrAccessTokenNotExist(err)) assert.True(t, auth_model.IsErrAccessTokenNotExist(err))
_, err = auth_model.GetAccessTokenBySHA("") _, err = auth_model.GetAccessTokenBySHA(db.DefaultContext, "")
assert.Error(t, err) assert.Error(t, err)
assert.True(t, auth_model.IsErrAccessTokenEmpty(err)) assert.True(t, auth_model.IsErrAccessTokenEmpty(err))
} }
func TestListAccessTokens(t *testing.T) { func TestListAccessTokens(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
tokens, err := auth_model.ListAccessTokens(auth_model.ListAccessTokensOptions{UserID: 1}) tokens, err := auth_model.ListAccessTokens(db.DefaultContext, auth_model.ListAccessTokensOptions{UserID: 1})
assert.NoError(t, err) assert.NoError(t, err)
if assert.Len(t, tokens, 2) { if assert.Len(t, tokens, 2) {
assert.Equal(t, int64(1), tokens[0].UID) assert.Equal(t, int64(1), tokens[0].UID)
@ -93,39 +94,39 @@ func TestListAccessTokens(t *testing.T) {
assert.Contains(t, []string{tokens[0].Name, tokens[1].Name}, "Token B") assert.Contains(t, []string{tokens[0].Name, tokens[1].Name}, "Token B")
} }
tokens, err = auth_model.ListAccessTokens(auth_model.ListAccessTokensOptions{UserID: 2}) tokens, err = auth_model.ListAccessTokens(db.DefaultContext, auth_model.ListAccessTokensOptions{UserID: 2})
assert.NoError(t, err) assert.NoError(t, err)
if assert.Len(t, tokens, 1) { if assert.Len(t, tokens, 1) {
assert.Equal(t, int64(2), tokens[0].UID) assert.Equal(t, int64(2), tokens[0].UID)
assert.Equal(t, "Token A", tokens[0].Name) assert.Equal(t, "Token A", tokens[0].Name)
} }
tokens, err = auth_model.ListAccessTokens(auth_model.ListAccessTokensOptions{UserID: 100}) tokens, err = auth_model.ListAccessTokens(db.DefaultContext, auth_model.ListAccessTokensOptions{UserID: 100})
assert.NoError(t, err) assert.NoError(t, err)
assert.Empty(t, tokens) assert.Empty(t, tokens)
} }
func TestUpdateAccessToken(t *testing.T) { func TestUpdateAccessToken(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
token, err := auth_model.GetAccessTokenBySHA("4c6f36e6cf498e2a448662f915d932c09c5a146c") token, err := auth_model.GetAccessTokenBySHA(db.DefaultContext, "4c6f36e6cf498e2a448662f915d932c09c5a146c")
assert.NoError(t, err) assert.NoError(t, err)
token.Name = "Token Z" token.Name = "Token Z"
assert.NoError(t, auth_model.UpdateAccessToken(token)) assert.NoError(t, auth_model.UpdateAccessToken(db.DefaultContext, token))
unittest.AssertExistsAndLoadBean(t, token) unittest.AssertExistsAndLoadBean(t, token)
} }
func TestDeleteAccessTokenByID(t *testing.T) { func TestDeleteAccessTokenByID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
token, err := auth_model.GetAccessTokenBySHA("4c6f36e6cf498e2a448662f915d932c09c5a146c") token, err := auth_model.GetAccessTokenBySHA(db.DefaultContext, "4c6f36e6cf498e2a448662f915d932c09c5a146c")
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, int64(1), token.UID) assert.Equal(t, int64(1), token.UID)
assert.NoError(t, auth_model.DeleteAccessTokenByID(token.ID, 1)) assert.NoError(t, auth_model.DeleteAccessTokenByID(db.DefaultContext, token.ID, 1))
unittest.AssertNotExistsBean(t, token) unittest.AssertNotExistsBean(t, token)
err = auth_model.DeleteAccessTokenByID(100, 100) err = auth_model.DeleteAccessTokenByID(db.DefaultContext, 100, 100)
assert.Error(t, err) assert.Error(t, err)
assert.True(t, auth_model.IsErrAccessTokenNotExist(err)) assert.True(t, auth_model.IsErrAccessTokenNotExist(err))
} }

View File

@ -4,6 +4,7 @@
package auth package auth
import ( import (
"context"
"crypto/md5" "crypto/md5"
"crypto/subtle" "crypto/subtle"
"encoding/base32" "encoding/base32"
@ -121,22 +122,22 @@ func (t *TwoFactor) ValidateTOTP(passcode string) (bool, error) {
} }
// NewTwoFactor creates a new two-factor authentication token. // NewTwoFactor creates a new two-factor authentication token.
func NewTwoFactor(t *TwoFactor) error { func NewTwoFactor(ctx context.Context, t *TwoFactor) error {
_, err := db.GetEngine(db.DefaultContext).Insert(t) _, err := db.GetEngine(ctx).Insert(t)
return err return err
} }
// UpdateTwoFactor updates a two-factor authentication token. // UpdateTwoFactor updates a two-factor authentication token.
func UpdateTwoFactor(t *TwoFactor) error { func UpdateTwoFactor(ctx context.Context, t *TwoFactor) error {
_, err := db.GetEngine(db.DefaultContext).ID(t.ID).AllCols().Update(t) _, err := db.GetEngine(ctx).ID(t.ID).AllCols().Update(t)
return err return err
} }
// GetTwoFactorByUID returns the two-factor authentication token associated with // GetTwoFactorByUID returns the two-factor authentication token associated with
// the user, if any. // the user, if any.
func GetTwoFactorByUID(uid int64) (*TwoFactor, error) { func GetTwoFactorByUID(ctx context.Context, uid int64) (*TwoFactor, error) {
twofa := &TwoFactor{} twofa := &TwoFactor{}
has, err := db.GetEngine(db.DefaultContext).Where("uid=?", uid).Get(twofa) has, err := db.GetEngine(ctx).Where("uid=?", uid).Get(twofa)
if err != nil { if err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
@ -147,13 +148,13 @@ func GetTwoFactorByUID(uid int64) (*TwoFactor, error) {
// HasTwoFactorByUID returns the two-factor authentication token associated with // HasTwoFactorByUID returns the two-factor authentication token associated with
// the user, if any. // the user, if any.
func HasTwoFactorByUID(uid int64) (bool, error) { func HasTwoFactorByUID(ctx context.Context, uid int64) (bool, error) {
return db.GetEngine(db.DefaultContext).Where("uid=?", uid).Exist(&TwoFactor{}) return db.GetEngine(ctx).Where("uid=?", uid).Exist(&TwoFactor{})
} }
// DeleteTwoFactorByID deletes two-factor authentication token by given ID. // DeleteTwoFactorByID deletes two-factor authentication token by given ID.
func DeleteTwoFactorByID(id, userID int64) error { func DeleteTwoFactorByID(ctx context.Context, id, userID int64) error {
cnt, err := db.GetEngine(db.DefaultContext).ID(id).Delete(&TwoFactor{ cnt, err := db.GetEngine(ctx).ID(id).Delete(&TwoFactor{
UID: userID, UID: userID,
}) })
if err != nil { if err != nil {

View File

@ -359,12 +359,12 @@ func (c *Comment) LoadPoster(ctx context.Context) (err error) {
} }
// AfterDelete is invoked from XORM after the object is deleted. // AfterDelete is invoked from XORM after the object is deleted.
func (c *Comment) AfterDelete() { func (c *Comment) AfterDelete(ctx context.Context) {
if c.ID <= 0 { if c.ID <= 0 {
return return
} }
_, err := repo_model.DeleteAttachmentsByComment(c.ID, true) _, err := repo_model.DeleteAttachmentsByComment(ctx, c.ID, true)
if err != nil { if err != nil {
log.Info("Could not delete files for comment %d on issue #%d: %s", c.ID, c.IssueID, err) log.Info("Could not delete files for comment %d on issue #%d: %s", c.ID, c.IssueID, err)
} }

View File

@ -27,8 +27,8 @@ type PullRequestsOptions struct {
MilestoneID int64 MilestoneID int64
} }
func listPullRequestStatement(baseRepoID int64, opts *PullRequestsOptions) (*xorm.Session, error) { func listPullRequestStatement(ctx context.Context, baseRepoID int64, opts *PullRequestsOptions) (*xorm.Session, error) {
sess := db.GetEngine(db.DefaultContext).Where("pull_request.base_repo_id=?", baseRepoID) sess := db.GetEngine(ctx).Where("pull_request.base_repo_id=?", baseRepoID)
sess.Join("INNER", "issue", "pull_request.issue_id = issue.id") sess.Join("INNER", "issue", "pull_request.issue_id = issue.id")
switch opts.State { switch opts.State {
@ -115,21 +115,21 @@ func GetUnmergedPullRequestsByBaseInfo(ctx context.Context, repoID int64, branch
} }
// GetPullRequestIDsByCheckStatus returns all pull requests according the special checking status. // GetPullRequestIDsByCheckStatus returns all pull requests according the special checking status.
func GetPullRequestIDsByCheckStatus(status PullRequestStatus) ([]int64, error) { func GetPullRequestIDsByCheckStatus(ctx context.Context, status PullRequestStatus) ([]int64, error) {
prs := make([]int64, 0, 10) prs := make([]int64, 0, 10)
return prs, db.GetEngine(db.DefaultContext).Table("pull_request"). return prs, db.GetEngine(ctx).Table("pull_request").
Where("status=?", status). Where("status=?", status).
Cols("pull_request.id"). Cols("pull_request.id").
Find(&prs) Find(&prs)
} }
// PullRequests returns all pull requests for a base Repo by the given conditions // PullRequests returns all pull requests for a base Repo by the given conditions
func PullRequests(baseRepoID int64, opts *PullRequestsOptions) ([]*PullRequest, int64, error) { func PullRequests(ctx context.Context, baseRepoID int64, opts *PullRequestsOptions) ([]*PullRequest, int64, error) {
if opts.Page <= 0 { if opts.Page <= 0 {
opts.Page = 1 opts.Page = 1
} }
countSession, err := listPullRequestStatement(baseRepoID, opts) countSession, err := listPullRequestStatement(ctx, baseRepoID, opts)
if err != nil { if err != nil {
log.Error("listPullRequestStatement: %v", err) log.Error("listPullRequestStatement: %v", err)
return nil, 0, err return nil, 0, err
@ -140,7 +140,7 @@ func PullRequests(baseRepoID int64, opts *PullRequestsOptions) ([]*PullRequest,
return nil, maxResults, err return nil, maxResults, err
} }
findSession, err := listPullRequestStatement(baseRepoID, opts) findSession, err := listPullRequestStatement(ctx, baseRepoID, opts)
applySorts(findSession, opts.SortType, 0) applySorts(findSession, opts.SortType, 0)
if err != nil { if err != nil {
log.Error("listPullRequestStatement: %v", err) log.Error("listPullRequestStatement: %v", err)

View File

@ -60,7 +60,7 @@ func TestPullRequest_LoadHeadRepo(t *testing.T) {
func TestPullRequestsNewest(t *testing.T) { func TestPullRequestsNewest(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
prs, count, err := issues_model.PullRequests(1, &issues_model.PullRequestsOptions{ prs, count, err := issues_model.PullRequests(db.DefaultContext, 1, &issues_model.PullRequestsOptions{
ListOptions: db.ListOptions{ ListOptions: db.ListOptions{
Page: 1, Page: 1,
}, },
@ -107,7 +107,7 @@ func TestLoadRequestedReviewers(t *testing.T) {
func TestPullRequestsOldest(t *testing.T) { func TestPullRequestsOldest(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
prs, count, err := issues_model.PullRequests(1, &issues_model.PullRequestsOptions{ prs, count, err := issues_model.PullRequests(db.DefaultContext, 1, &issues_model.PullRequestsOptions{
ListOptions: db.ListOptions{ ListOptions: db.ListOptions{
Page: 1, Page: 1,
}, },

View File

@ -37,9 +37,9 @@ func init() {
} }
// IncreaseDownloadCount is update download count + 1 // IncreaseDownloadCount is update download count + 1
func (a *Attachment) IncreaseDownloadCount() error { func (a *Attachment) IncreaseDownloadCount(ctx context.Context) error {
// Update download count. // Update download count.
if _, err := db.GetEngine(db.DefaultContext).Exec("UPDATE `attachment` SET download_count=download_count+1 WHERE id=?", a.ID); err != nil { if _, err := db.GetEngine(ctx).Exec("UPDATE `attachment` SET download_count=download_count+1 WHERE id=?", a.ID); err != nil {
return fmt.Errorf("increase attachment count: %w", err) return fmt.Errorf("increase attachment count: %w", err)
} }
@ -164,8 +164,8 @@ func GetAttachmentByReleaseIDFileName(ctx context.Context, releaseID int64, file
} }
// DeleteAttachment deletes the given attachment and optionally the associated file. // DeleteAttachment deletes the given attachment and optionally the associated file.
func DeleteAttachment(a *Attachment, remove bool) error { func DeleteAttachment(ctx context.Context, a *Attachment, remove bool) error {
_, err := DeleteAttachments(db.DefaultContext, []*Attachment{a}, remove) _, err := DeleteAttachments(ctx, []*Attachment{a}, remove)
return err return err
} }
@ -196,23 +196,23 @@ func DeleteAttachments(ctx context.Context, attachments []*Attachment, remove bo
} }
// DeleteAttachmentsByIssue deletes all attachments associated with the given issue. // DeleteAttachmentsByIssue deletes all attachments associated with the given issue.
func DeleteAttachmentsByIssue(issueID int64, remove bool) (int, error) { func DeleteAttachmentsByIssue(ctx context.Context, issueID int64, remove bool) (int, error) {
attachments, err := GetAttachmentsByIssueID(db.DefaultContext, issueID) attachments, err := GetAttachmentsByIssueID(ctx, issueID)
if err != nil { if err != nil {
return 0, err return 0, err
} }
return DeleteAttachments(db.DefaultContext, attachments, remove) return DeleteAttachments(ctx, attachments, remove)
} }
// DeleteAttachmentsByComment deletes all attachments associated with the given comment. // DeleteAttachmentsByComment deletes all attachments associated with the given comment.
func DeleteAttachmentsByComment(commentID int64, remove bool) (int, error) { func DeleteAttachmentsByComment(ctx context.Context, commentID int64, remove bool) (int, error) {
attachments, err := GetAttachmentsByCommentID(db.DefaultContext, commentID) attachments, err := GetAttachmentsByCommentID(ctx, commentID)
if err != nil { if err != nil {
return 0, err return 0, err
} }
return DeleteAttachments(db.DefaultContext, attachments, remove) return DeleteAttachments(ctx, attachments, remove)
} }
// UpdateAttachmentByUUID Updates attachment via uuid // UpdateAttachmentByUUID Updates attachment via uuid

View File

@ -21,7 +21,7 @@ func TestIncreaseDownloadCount(t *testing.T) {
assert.Equal(t, int64(0), attachment.DownloadCount) assert.Equal(t, int64(0), attachment.DownloadCount)
// increase download count // increase download count
err = attachment.IncreaseDownloadCount() err = attachment.IncreaseDownloadCount(db.DefaultContext)
assert.NoError(t, err) assert.NoError(t, err)
attachment, err = repo_model.GetAttachmentByUUID(db.DefaultContext, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11") attachment, err = repo_model.GetAttachmentByUUID(db.DefaultContext, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11")
@ -45,15 +45,15 @@ func TestGetByCommentOrIssueID(t *testing.T) {
func TestDeleteAttachments(t *testing.T) { func TestDeleteAttachments(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
count, err := repo_model.DeleteAttachmentsByIssue(4, false) count, err := repo_model.DeleteAttachmentsByIssue(db.DefaultContext, 4, false)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, 2, count) assert.Equal(t, 2, count)
count, err = repo_model.DeleteAttachmentsByComment(2, false) count, err = repo_model.DeleteAttachmentsByComment(db.DefaultContext, 2, false)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, 2, count) assert.Equal(t, 2, count)
err = repo_model.DeleteAttachment(&repo_model.Attachment{ID: 8}, false) err = repo_model.DeleteAttachment(db.DefaultContext, &repo_model.Attachment{ID: 8}, false)
assert.NoError(t, err) assert.NoError(t, err)
attachment, err := repo_model.GetAttachmentByUUID(db.DefaultContext, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a18") attachment, err := repo_model.GetAttachmentByUUID(db.DefaultContext, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a18")

View File

@ -24,8 +24,8 @@ func init() {
} }
// StarRepo or unstar repository. // StarRepo or unstar repository.
func StarRepo(userID, repoID int64, star bool) error { func StarRepo(ctx context.Context, userID, repoID int64, star bool) error {
ctx, committer, err := db.TxContext(db.DefaultContext) ctx, committer, err := db.TxContext(ctx)
if err != nil { if err != nil {
return err return err
} }
@ -72,8 +72,8 @@ func IsStaring(ctx context.Context, userID, repoID int64) bool {
} }
// GetStargazers returns the users that starred the repo. // GetStargazers returns the users that starred the repo.
func GetStargazers(repo *Repository, opts db.ListOptions) ([]*user_model.User, error) { func GetStargazers(ctx context.Context, repo *Repository, opts db.ListOptions) ([]*user_model.User, error) {
sess := db.GetEngine(db.DefaultContext).Where("star.repo_id = ?", repo.ID). sess := db.GetEngine(ctx).Where("star.repo_id = ?", repo.ID).
Join("LEFT", "star", "`user`.id = star.uid") Join("LEFT", "star", "`user`.id = star.uid")
if opts.Page > 0 { if opts.Page > 0 {
sess = db.SetSessionPagination(sess, &opts) sess = db.SetSessionPagination(sess, &opts)

View File

@ -18,11 +18,11 @@ func TestStarRepo(t *testing.T) {
const userID = 2 const userID = 2
const repoID = 1 const repoID = 1
unittest.AssertNotExistsBean(t, &repo_model.Star{UID: userID, RepoID: repoID}) unittest.AssertNotExistsBean(t, &repo_model.Star{UID: userID, RepoID: repoID})
assert.NoError(t, repo_model.StarRepo(userID, repoID, true)) assert.NoError(t, repo_model.StarRepo(db.DefaultContext, userID, repoID, true))
unittest.AssertExistsAndLoadBean(t, &repo_model.Star{UID: userID, RepoID: repoID}) unittest.AssertExistsAndLoadBean(t, &repo_model.Star{UID: userID, RepoID: repoID})
assert.NoError(t, repo_model.StarRepo(userID, repoID, true)) assert.NoError(t, repo_model.StarRepo(db.DefaultContext, userID, repoID, true))
unittest.AssertExistsAndLoadBean(t, &repo_model.Star{UID: userID, RepoID: repoID}) unittest.AssertExistsAndLoadBean(t, &repo_model.Star{UID: userID, RepoID: repoID})
assert.NoError(t, repo_model.StarRepo(userID, repoID, false)) assert.NoError(t, repo_model.StarRepo(db.DefaultContext, userID, repoID, false))
unittest.AssertNotExistsBean(t, &repo_model.Star{UID: userID, RepoID: repoID}) unittest.AssertNotExistsBean(t, &repo_model.Star{UID: userID, RepoID: repoID})
} }
@ -36,7 +36,7 @@ func TestRepository_GetStargazers(t *testing.T) {
// repo with stargazers // repo with stargazers
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4})
gazers, err := repo_model.GetStargazers(repo, db.ListOptions{Page: 0}) gazers, err := repo_model.GetStargazers(db.DefaultContext, repo, db.ListOptions{Page: 0})
assert.NoError(t, err) assert.NoError(t, err)
if assert.Len(t, gazers, 1) { if assert.Len(t, gazers, 1) {
assert.Equal(t, int64(2), gazers[0].ID) assert.Equal(t, int64(2), gazers[0].ID)
@ -47,7 +47,7 @@ func TestRepository_GetStargazers2(t *testing.T) {
// repo with stargazers // repo with stargazers
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3})
gazers, err := repo_model.GetStargazers(repo, db.ListOptions{Page: 0}) gazers, err := repo_model.GetStargazers(db.DefaultContext, repo, db.ListOptions{Page: 0})
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, gazers, 0) assert.Len(t, gazers, 0)
} }
@ -57,15 +57,15 @@ func TestClearRepoStars(t *testing.T) {
const userID = 2 const userID = 2
const repoID = 1 const repoID = 1
unittest.AssertNotExistsBean(t, &repo_model.Star{UID: userID, RepoID: repoID}) unittest.AssertNotExistsBean(t, &repo_model.Star{UID: userID, RepoID: repoID})
assert.NoError(t, repo_model.StarRepo(userID, repoID, true)) assert.NoError(t, repo_model.StarRepo(db.DefaultContext, userID, repoID, true))
unittest.AssertExistsAndLoadBean(t, &repo_model.Star{UID: userID, RepoID: repoID}) unittest.AssertExistsAndLoadBean(t, &repo_model.Star{UID: userID, RepoID: repoID})
assert.NoError(t, repo_model.StarRepo(userID, repoID, false)) assert.NoError(t, repo_model.StarRepo(db.DefaultContext, userID, repoID, false))
unittest.AssertNotExistsBean(t, &repo_model.Star{UID: userID, RepoID: repoID}) unittest.AssertNotExistsBean(t, &repo_model.Star{UID: userID, RepoID: repoID})
assert.NoError(t, repo_model.ClearRepoStars(db.DefaultContext, repoID)) assert.NoError(t, repo_model.ClearRepoStars(db.DefaultContext, repoID))
unittest.AssertNotExistsBean(t, &repo_model.Star{UID: userID, RepoID: repoID}) unittest.AssertNotExistsBean(t, &repo_model.Star{UID: userID, RepoID: repoID})
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
gazers, err := repo_model.GetStargazers(repo, db.ListOptions{Page: 0}) gazers, err := repo_model.GetStargazers(db.DefaultContext, repo, db.ListOptions{Page: 0})
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, gazers, 0) assert.Len(t, gazers, 0)
} }

View File

@ -5,6 +5,7 @@
package repo package repo
import ( import (
"context"
"fmt" "fmt"
"io" "io"
"mime/multipart" "mime/multipart"
@ -61,7 +62,7 @@ func (upload *Upload) LocalPath() string {
} }
// NewUpload creates a new upload object. // NewUpload creates a new upload object.
func NewUpload(name string, buf []byte, file multipart.File) (_ *Upload, err error) { func NewUpload(ctx context.Context, name string, buf []byte, file multipart.File) (_ *Upload, err error) {
upload := &Upload{ upload := &Upload{
UUID: gouuid.New().String(), UUID: gouuid.New().String(),
Name: name, Name: name,
@ -84,7 +85,7 @@ func NewUpload(name string, buf []byte, file multipart.File) (_ *Upload, err err
return nil, fmt.Errorf("Copy: %w", err) return nil, fmt.Errorf("Copy: %w", err)
} }
if _, err := db.GetEngine(db.DefaultContext).Insert(upload); err != nil { if _, err := db.GetEngine(ctx).Insert(upload); err != nil {
return nil, err return nil, err
} }
@ -92,9 +93,9 @@ func NewUpload(name string, buf []byte, file multipart.File) (_ *Upload, err err
} }
// GetUploadByUUID returns the Upload by UUID // GetUploadByUUID returns the Upload by UUID
func GetUploadByUUID(uuid string) (*Upload, error) { func GetUploadByUUID(ctx context.Context, uuid string) (*Upload, error) {
upload := &Upload{} upload := &Upload{}
has, err := db.GetEngine(db.DefaultContext).Where("uuid=?", uuid).Get(upload) has, err := db.GetEngine(ctx).Where("uuid=?", uuid).Get(upload)
if err != nil { if err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
@ -104,23 +105,23 @@ func GetUploadByUUID(uuid string) (*Upload, error) {
} }
// GetUploadsByUUIDs returns multiple uploads by UUIDS // GetUploadsByUUIDs returns multiple uploads by UUIDS
func GetUploadsByUUIDs(uuids []string) ([]*Upload, error) { func GetUploadsByUUIDs(ctx context.Context, uuids []string) ([]*Upload, error) {
if len(uuids) == 0 { if len(uuids) == 0 {
return []*Upload{}, nil return []*Upload{}, nil
} }
// Silently drop invalid uuids. // Silently drop invalid uuids.
uploads := make([]*Upload, 0, len(uuids)) uploads := make([]*Upload, 0, len(uuids))
return uploads, db.GetEngine(db.DefaultContext).In("uuid", uuids).Find(&uploads) return uploads, db.GetEngine(ctx).In("uuid", uuids).Find(&uploads)
} }
// DeleteUploads deletes multiple uploads // DeleteUploads deletes multiple uploads
func DeleteUploads(uploads ...*Upload) (err error) { func DeleteUploads(ctx context.Context, uploads ...*Upload) (err error) {
if len(uploads) == 0 { if len(uploads) == 0 {
return nil return nil
} }
ctx, committer, err := db.TxContext(db.DefaultContext) ctx, committer, err := db.TxContext(ctx)
if err != nil { if err != nil {
return err return err
} }
@ -159,8 +160,8 @@ func DeleteUploads(uploads ...*Upload) (err error) {
} }
// DeleteUploadByUUID deletes a upload by UUID // DeleteUploadByUUID deletes a upload by UUID
func DeleteUploadByUUID(uuid string) error { func DeleteUploadByUUID(ctx context.Context, uuid string) error {
upload, err := GetUploadByUUID(uuid) upload, err := GetUploadByUUID(ctx, uuid)
if err != nil { if err != nil {
if IsErrUploadNotExist(err) { if IsErrUploadNotExist(err) {
return nil return nil
@ -168,7 +169,7 @@ func DeleteUploadByUUID(uuid string) error {
return fmt.Errorf("GetUploadByUUID: %w", err) return fmt.Errorf("GetUploadByUUID: %w", err)
} }
if err := DeleteUploads(upload); err != nil { if err := DeleteUploads(ctx, upload); err != nil {
return fmt.Errorf("DeleteUpload: %w", err) return fmt.Errorf("DeleteUpload: %w", err)
} }

View File

@ -59,8 +59,8 @@ func IsWatchMode(mode WatchMode) bool {
} }
// IsWatching checks if user has watched given repository. // IsWatching checks if user has watched given repository.
func IsWatching(userID, repoID int64) bool { func IsWatching(ctx context.Context, userID, repoID int64) bool {
watch, err := GetWatch(db.DefaultContext, userID, repoID) watch, err := GetWatch(ctx, userID, repoID)
return err == nil && IsWatchMode(watch.Mode) return err == nil && IsWatchMode(watch.Mode)
} }
@ -155,8 +155,8 @@ func GetRepoWatchersIDs(ctx context.Context, repoID int64) ([]int64, error) {
} }
// GetRepoWatchers returns range of users watching given repository. // GetRepoWatchers returns range of users watching given repository.
func GetRepoWatchers(repoID int64, opts db.ListOptions) ([]*user_model.User, error) { func GetRepoWatchers(ctx context.Context, repoID int64, opts db.ListOptions) ([]*user_model.User, error) {
sess := db.GetEngine(db.DefaultContext).Where("watch.repo_id=?", repoID). sess := db.GetEngine(ctx).Where("watch.repo_id=?", repoID).
Join("LEFT", "watch", "`user`.id=`watch`.user_id"). Join("LEFT", "watch", "`user`.id=`watch`.user_id").
And("`watch`.mode<>?", WatchModeDont) And("`watch`.mode<>?", WatchModeDont)
if opts.Page > 0 { if opts.Page > 0 {

View File

@ -17,13 +17,13 @@ import (
func TestIsWatching(t *testing.T) { func TestIsWatching(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
assert.True(t, repo_model.IsWatching(1, 1)) assert.True(t, repo_model.IsWatching(db.DefaultContext, 1, 1))
assert.True(t, repo_model.IsWatching(4, 1)) assert.True(t, repo_model.IsWatching(db.DefaultContext, 4, 1))
assert.True(t, repo_model.IsWatching(11, 1)) assert.True(t, repo_model.IsWatching(db.DefaultContext, 11, 1))
assert.False(t, repo_model.IsWatching(1, 5)) assert.False(t, repo_model.IsWatching(db.DefaultContext, 1, 5))
assert.False(t, repo_model.IsWatching(8, 1)) assert.False(t, repo_model.IsWatching(db.DefaultContext, 8, 1))
assert.False(t, repo_model.IsWatching(unittest.NonexistentID, unittest.NonexistentID)) assert.False(t, repo_model.IsWatching(db.DefaultContext, unittest.NonexistentID, unittest.NonexistentID))
} }
func TestGetWatchers(t *testing.T) { func TestGetWatchers(t *testing.T) {
@ -47,7 +47,7 @@ func TestRepository_GetWatchers(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
watchers, err := repo_model.GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) watchers, err := repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1})
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, watchers, repo.NumWatches) assert.Len(t, watchers, repo.NumWatches)
for _, watcher := range watchers { for _, watcher := range watchers {
@ -55,7 +55,7 @@ func TestRepository_GetWatchers(t *testing.T) {
} }
repo = unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 9}) repo = unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 9})
watchers, err = repo_model.GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) watchers, err = repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1})
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, watchers, 0) assert.Len(t, watchers, 0)
} }
@ -64,7 +64,7 @@ func TestWatchIfAuto(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
watchers, err := repo_model.GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) watchers, err := repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1})
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, watchers, repo.NumWatches) assert.Len(t, watchers, repo.NumWatches)
@ -74,13 +74,13 @@ func TestWatchIfAuto(t *testing.T) {
// Must not add watch // Must not add watch
assert.NoError(t, repo_model.WatchIfAuto(db.DefaultContext, 8, 1, true)) assert.NoError(t, repo_model.WatchIfAuto(db.DefaultContext, 8, 1, true))
watchers, err = repo_model.GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) watchers, err = repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1})
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, watchers, prevCount) assert.Len(t, watchers, prevCount)
// Should not add watch // Should not add watch
assert.NoError(t, repo_model.WatchIfAuto(db.DefaultContext, 10, 1, true)) assert.NoError(t, repo_model.WatchIfAuto(db.DefaultContext, 10, 1, true))
watchers, err = repo_model.GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) watchers, err = repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1})
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, watchers, prevCount) assert.Len(t, watchers, prevCount)
@ -88,31 +88,31 @@ func TestWatchIfAuto(t *testing.T) {
// Must not add watch // Must not add watch
assert.NoError(t, repo_model.WatchIfAuto(db.DefaultContext, 8, 1, true)) assert.NoError(t, repo_model.WatchIfAuto(db.DefaultContext, 8, 1, true))
watchers, err = repo_model.GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) watchers, err = repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1})
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, watchers, prevCount) assert.Len(t, watchers, prevCount)
// Should not add watch // Should not add watch
assert.NoError(t, repo_model.WatchIfAuto(db.DefaultContext, 12, 1, false)) assert.NoError(t, repo_model.WatchIfAuto(db.DefaultContext, 12, 1, false))
watchers, err = repo_model.GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) watchers, err = repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1})
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, watchers, prevCount) assert.Len(t, watchers, prevCount)
// Should add watch // Should add watch
assert.NoError(t, repo_model.WatchIfAuto(db.DefaultContext, 12, 1, true)) assert.NoError(t, repo_model.WatchIfAuto(db.DefaultContext, 12, 1, true))
watchers, err = repo_model.GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) watchers, err = repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1})
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, watchers, prevCount+1) assert.Len(t, watchers, prevCount+1)
// Should remove watch, inhibit from adding auto // Should remove watch, inhibit from adding auto
assert.NoError(t, repo_model.WatchRepo(db.DefaultContext, 12, 1, false)) assert.NoError(t, repo_model.WatchRepo(db.DefaultContext, 12, 1, false))
watchers, err = repo_model.GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) watchers, err = repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1})
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, watchers, prevCount) assert.Len(t, watchers, prevCount)
// Must not add watch // Must not add watch
assert.NoError(t, repo_model.WatchIfAuto(db.DefaultContext, 12, 1, true)) assert.NoError(t, repo_model.WatchIfAuto(db.DefaultContext, 12, 1, true))
watchers, err = repo_model.GetRepoWatchers(repo.ID, db.ListOptions{Page: 1}) watchers, err = repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1})
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, watchers, prevCount) assert.Len(t, watchers, prevCount)
} }

View File

@ -28,9 +28,9 @@ func init() {
} }
// GetUserOpenIDs returns all openid addresses that belongs to given user. // GetUserOpenIDs returns all openid addresses that belongs to given user.
func GetUserOpenIDs(uid int64) ([]*UserOpenID, error) { func GetUserOpenIDs(ctx context.Context, uid int64) ([]*UserOpenID, error) {
openids := make([]*UserOpenID, 0, 5) openids := make([]*UserOpenID, 0, 5)
if err := db.GetEngine(db.DefaultContext). if err := db.GetEngine(ctx).
Where("uid=?", uid). Where("uid=?", uid).
Asc("id"). Asc("id").
Find(&openids); err != nil { Find(&openids); err != nil {
@ -82,16 +82,16 @@ func AddUserOpenID(ctx context.Context, openid *UserOpenID) error {
} }
// DeleteUserOpenID deletes an openid address of given user. // DeleteUserOpenID deletes an openid address of given user.
func DeleteUserOpenID(openid *UserOpenID) (err error) { func DeleteUserOpenID(ctx context.Context, openid *UserOpenID) (err error) {
var deleted int64 var deleted int64
// ask to check UID // ask to check UID
address := UserOpenID{ address := UserOpenID{
UID: openid.UID, UID: openid.UID,
} }
if openid.ID > 0 { if openid.ID > 0 {
deleted, err = db.GetEngine(db.DefaultContext).ID(openid.ID).Delete(&address) deleted, err = db.GetEngine(ctx).ID(openid.ID).Delete(&address)
} else { } else {
deleted, err = db.GetEngine(db.DefaultContext). deleted, err = db.GetEngine(ctx).
Where("openid=?", openid.URI). Where("openid=?", openid.URI).
Delete(&address) Delete(&address)
} }
@ -105,7 +105,7 @@ func DeleteUserOpenID(openid *UserOpenID) (err error) {
} }
// ToggleUserOpenIDVisibility toggles visibility of an openid address of given user. // ToggleUserOpenIDVisibility toggles visibility of an openid address of given user.
func ToggleUserOpenIDVisibility(id int64) (err error) { func ToggleUserOpenIDVisibility(ctx context.Context, id int64) (err error) {
_, err = db.GetEngine(db.DefaultContext).Exec("update `user_open_id` set `show` = not `show` where `id` = ?", id) _, err = db.GetEngine(ctx).Exec("update `user_open_id` set `show` = not `show` where `id` = ?", id)
return err return err
} }

View File

@ -6,6 +6,7 @@ package user_test
import ( import (
"testing" "testing"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
@ -15,7 +16,7 @@ import (
func TestGetUserOpenIDs(t *testing.T) { func TestGetUserOpenIDs(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
oids, err := user_model.GetUserOpenIDs(int64(1)) oids, err := user_model.GetUserOpenIDs(db.DefaultContext, int64(1))
if assert.NoError(t, err) && assert.Len(t, oids, 2) { if assert.NoError(t, err) && assert.Len(t, oids, 2) {
assert.Equal(t, "https://user1.domain1.tld/", oids[0].URI) assert.Equal(t, "https://user1.domain1.tld/", oids[0].URI)
assert.False(t, oids[0].Show) assert.False(t, oids[0].Show)
@ -23,7 +24,7 @@ func TestGetUserOpenIDs(t *testing.T) {
assert.True(t, oids[1].Show) assert.True(t, oids[1].Show)
} }
oids, err = user_model.GetUserOpenIDs(int64(2)) oids, err = user_model.GetUserOpenIDs(db.DefaultContext, int64(2))
if assert.NoError(t, err) && assert.Len(t, oids, 1) { if assert.NoError(t, err) && assert.Len(t, oids, 1) {
assert.Equal(t, "https://domain1.tld/user2/", oids[0].URI) assert.Equal(t, "https://domain1.tld/user2/", oids[0].URI)
assert.True(t, oids[0].Show) assert.True(t, oids[0].Show)
@ -32,28 +33,28 @@ func TestGetUserOpenIDs(t *testing.T) {
func TestToggleUserOpenIDVisibility(t *testing.T) { func TestToggleUserOpenIDVisibility(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
oids, err := user_model.GetUserOpenIDs(int64(2)) oids, err := user_model.GetUserOpenIDs(db.DefaultContext, int64(2))
if !assert.NoError(t, err) || !assert.Len(t, oids, 1) { if !assert.NoError(t, err) || !assert.Len(t, oids, 1) {
return return
} }
assert.True(t, oids[0].Show) assert.True(t, oids[0].Show)
err = user_model.ToggleUserOpenIDVisibility(oids[0].ID) err = user_model.ToggleUserOpenIDVisibility(db.DefaultContext, oids[0].ID)
if !assert.NoError(t, err) { if !assert.NoError(t, err) {
return return
} }
oids, err = user_model.GetUserOpenIDs(int64(2)) oids, err = user_model.GetUserOpenIDs(db.DefaultContext, int64(2))
if !assert.NoError(t, err) || !assert.Len(t, oids, 1) { if !assert.NoError(t, err) || !assert.Len(t, oids, 1) {
return return
} }
assert.False(t, oids[0].Show) assert.False(t, oids[0].Show)
err = user_model.ToggleUserOpenIDVisibility(oids[0].ID) err = user_model.ToggleUserOpenIDVisibility(db.DefaultContext, oids[0].ID)
if !assert.NoError(t, err) { if !assert.NoError(t, err) {
return return
} }
oids, err = user_model.GetUserOpenIDs(int64(2)) oids, err = user_model.GetUserOpenIDs(db.DefaultContext, int64(2))
if !assert.NoError(t, err) { if !assert.NoError(t, err) {
return return
} }

View File

@ -59,9 +59,9 @@ func genSettingCacheKey(userID int64, key string) string {
} }
// GetSetting returns the setting value via the key // GetSetting returns the setting value via the key
func GetSetting(uid int64, key string) (string, error) { func GetSetting(ctx context.Context, uid int64, key string) (string, error) {
return cache.GetString(genSettingCacheKey(uid, key), func() (string, error) { return cache.GetString(genSettingCacheKey(uid, key), func() (string, error) {
res, err := GetSettingNoCache(uid, key) res, err := GetSettingNoCache(ctx, uid, key)
if err != nil { if err != nil {
return "", err return "", err
} }
@ -70,8 +70,8 @@ func GetSetting(uid int64, key string) (string, error) {
} }
// GetSettingNoCache returns specific setting without using the cache // GetSettingNoCache returns specific setting without using the cache
func GetSettingNoCache(uid int64, key string) (*Setting, error) { func GetSettingNoCache(ctx context.Context, uid int64, key string) (*Setting, error) {
v, err := GetSettings(uid, []string{key}) v, err := GetSettings(ctx, uid, []string{key})
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -82,9 +82,9 @@ func GetSettingNoCache(uid int64, key string) (*Setting, error) {
} }
// GetSettings returns specific settings from user // GetSettings returns specific settings from user
func GetSettings(uid int64, keys []string) (map[string]*Setting, error) { func GetSettings(ctx context.Context, uid int64, keys []string) (map[string]*Setting, error) {
settings := make([]*Setting, 0, len(keys)) settings := make([]*Setting, 0, len(keys))
if err := db.GetEngine(db.DefaultContext). if err := db.GetEngine(ctx).
Where("user_id=?", uid). Where("user_id=?", uid).
And(builder.In("setting_key", keys)). And(builder.In("setting_key", keys)).
Find(&settings); err != nil { Find(&settings); err != nil {
@ -98,9 +98,9 @@ func GetSettings(uid int64, keys []string) (map[string]*Setting, error) {
} }
// GetUserAllSettings returns all settings from user // GetUserAllSettings returns all settings from user
func GetUserAllSettings(uid int64) (map[string]*Setting, error) { func GetUserAllSettings(ctx context.Context, uid int64) (map[string]*Setting, error) {
settings := make([]*Setting, 0, 5) settings := make([]*Setting, 0, 5)
if err := db.GetEngine(db.DefaultContext). if err := db.GetEngine(ctx).
Where("user_id=?", uid). Where("user_id=?", uid).
Find(&settings); err != nil { Find(&settings); err != nil {
return nil, err return nil, err
@ -123,13 +123,13 @@ func validateUserSettingKey(key string) error {
} }
// GetUserSetting gets a specific setting for a user // GetUserSetting gets a specific setting for a user
func GetUserSetting(userID int64, key string, def ...string) (string, error) { func GetUserSetting(ctx context.Context, userID int64, key string, def ...string) (string, error) {
if err := validateUserSettingKey(key); err != nil { if err := validateUserSettingKey(key); err != nil {
return "", err return "", err
} }
setting := &Setting{UserID: userID, SettingKey: key} setting := &Setting{UserID: userID, SettingKey: key}
has, err := db.GetEngine(db.DefaultContext).Get(setting) has, err := db.GetEngine(ctx).Get(setting)
if err != nil { if err != nil {
return "", err return "", err
} }
@ -143,24 +143,24 @@ func GetUserSetting(userID int64, key string, def ...string) (string, error) {
} }
// DeleteUserSetting deletes a specific setting for a user // DeleteUserSetting deletes a specific setting for a user
func DeleteUserSetting(userID int64, key string) error { func DeleteUserSetting(ctx context.Context, userID int64, key string) error {
if err := validateUserSettingKey(key); err != nil { if err := validateUserSettingKey(key); err != nil {
return err return err
} }
cache.Remove(genSettingCacheKey(userID, key)) cache.Remove(genSettingCacheKey(userID, key))
_, err := db.GetEngine(db.DefaultContext).Delete(&Setting{UserID: userID, SettingKey: key}) _, err := db.GetEngine(ctx).Delete(&Setting{UserID: userID, SettingKey: key})
return err return err
} }
// SetUserSetting updates a users' setting for a specific key // SetUserSetting updates a users' setting for a specific key
func SetUserSetting(userID int64, key, value string) error { func SetUserSetting(ctx context.Context, userID int64, key, value string) error {
if err := validateUserSettingKey(key); err != nil { if err := validateUserSettingKey(key); err != nil {
return err return err
} }
if err := upsertUserSettingValue(userID, key, value); err != nil { if err := upsertUserSettingValue(ctx, userID, key, value); err != nil {
return err return err
} }
@ -172,8 +172,8 @@ func SetUserSetting(userID int64, key, value string) error {
return nil return nil
} }
func upsertUserSettingValue(userID int64, key, value string) error { func upsertUserSettingValue(ctx context.Context, userID int64, key, value string) error {
return db.WithTx(db.DefaultContext, func(ctx context.Context) error { return db.WithTx(ctx, func(ctx context.Context) error {
e := db.GetEngine(ctx) e := db.GetEngine(ctx)
// here we use a general method to do a safe upsert for different databases (and most transaction levels) // here we use a general method to do a safe upsert for different databases (and most transaction levels)

View File

@ -6,6 +6,7 @@ package user_test
import ( import (
"testing" "testing"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
@ -19,41 +20,41 @@ func TestSettings(t *testing.T) {
newSetting := &user_model.Setting{UserID: 99, SettingKey: keyName, SettingValue: "Gitea User Setting Test"} newSetting := &user_model.Setting{UserID: 99, SettingKey: keyName, SettingValue: "Gitea User Setting Test"}
// create setting // create setting
err := user_model.SetUserSetting(newSetting.UserID, newSetting.SettingKey, newSetting.SettingValue) err := user_model.SetUserSetting(db.DefaultContext, newSetting.UserID, newSetting.SettingKey, newSetting.SettingValue)
assert.NoError(t, err) assert.NoError(t, err)
// test about saving unchanged values // test about saving unchanged values
err = user_model.SetUserSetting(newSetting.UserID, newSetting.SettingKey, newSetting.SettingValue) err = user_model.SetUserSetting(db.DefaultContext, newSetting.UserID, newSetting.SettingKey, newSetting.SettingValue)
assert.NoError(t, err) assert.NoError(t, err)
// get specific setting // get specific setting
settings, err := user_model.GetSettings(99, []string{keyName}) settings, err := user_model.GetSettings(db.DefaultContext, 99, []string{keyName})
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, settings, 1) assert.Len(t, settings, 1)
assert.EqualValues(t, newSetting.SettingValue, settings[keyName].SettingValue) assert.EqualValues(t, newSetting.SettingValue, settings[keyName].SettingValue)
settingValue, err := user_model.GetUserSetting(99, keyName) settingValue, err := user_model.GetUserSetting(db.DefaultContext, 99, keyName)
assert.NoError(t, err) assert.NoError(t, err)
assert.EqualValues(t, newSetting.SettingValue, settingValue) assert.EqualValues(t, newSetting.SettingValue, settingValue)
settingValue, err = user_model.GetUserSetting(99, "no_such") settingValue, err = user_model.GetUserSetting(db.DefaultContext, 99, "no_such")
assert.NoError(t, err) assert.NoError(t, err)
assert.EqualValues(t, "", settingValue) assert.EqualValues(t, "", settingValue)
// updated setting // updated setting
updatedSetting := &user_model.Setting{UserID: 99, SettingKey: keyName, SettingValue: "Updated"} updatedSetting := &user_model.Setting{UserID: 99, SettingKey: keyName, SettingValue: "Updated"}
err = user_model.SetUserSetting(updatedSetting.UserID, updatedSetting.SettingKey, updatedSetting.SettingValue) err = user_model.SetUserSetting(db.DefaultContext, updatedSetting.UserID, updatedSetting.SettingKey, updatedSetting.SettingValue)
assert.NoError(t, err) assert.NoError(t, err)
// get all settings // get all settings
settings, err = user_model.GetUserAllSettings(99) settings, err = user_model.GetUserAllSettings(db.DefaultContext, 99)
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, settings, 1) assert.Len(t, settings, 1)
assert.EqualValues(t, updatedSetting.SettingValue, settings[updatedSetting.SettingKey].SettingValue) assert.EqualValues(t, updatedSetting.SettingValue, settings[updatedSetting.SettingKey].SettingValue)
// delete setting // delete setting
err = user_model.DeleteUserSetting(99, keyName) err = user_model.DeleteUserSetting(db.DefaultContext, 99, keyName)
assert.NoError(t, err) assert.NoError(t, err)
settings, err = user_model.GetUserAllSettings(99) settings, err = user_model.GetUserAllSettings(db.DefaultContext, 99)
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, settings, 0) assert.Len(t, settings, 0)
} }

View File

@ -5,6 +5,7 @@ package activitypub
import ( import (
"bytes" "bytes"
"context"
"crypto/rsa" "crypto/rsa"
"crypto/x509" "crypto/x509"
"encoding/pem" "encoding/pem"
@ -61,14 +62,14 @@ type Client struct {
} }
// NewClient function // NewClient function
func NewClient(user *user_model.User, pubID string) (c *Client, err error) { func NewClient(ctx context.Context, user *user_model.User, pubID string) (c *Client, err error) {
if err = containsRequiredHTTPHeaders(http.MethodGet, setting.Federation.GetHeaders); err != nil { if err = containsRequiredHTTPHeaders(http.MethodGet, setting.Federation.GetHeaders); err != nil {
return nil, err return nil, err
} else if err = containsRequiredHTTPHeaders(http.MethodPost, setting.Federation.PostHeaders); err != nil { } else if err = containsRequiredHTTPHeaders(http.MethodPost, setting.Federation.PostHeaders); err != nil {
return nil, err return nil, err
} }
priv, err := GetPrivateKey(user) priv, err := GetPrivateKey(ctx, user)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -11,6 +11,7 @@ import (
"regexp" "regexp"
"testing" "testing"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
@ -22,7 +23,7 @@ func TestActivityPubSignedPost(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
pubID := "https://example.com/pubID" pubID := "https://example.com/pubID"
c, err := NewClient(user, pubID) c, err := NewClient(db.DefaultContext, user, pubID)
assert.NoError(t, err) assert.NoError(t, err)
expected := "BODY" expected := "BODY"

View File

@ -4,6 +4,8 @@
package activitypub package activitypub
import ( import (
"context"
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/util"
) )
@ -11,19 +13,19 @@ import (
const rsaBits = 3072 const rsaBits = 3072
// GetKeyPair function returns a user's private and public keys // GetKeyPair function returns a user's private and public keys
func GetKeyPair(user *user_model.User) (pub, priv string, err error) { func GetKeyPair(ctx context.Context, user *user_model.User) (pub, priv string, err error) {
var settings map[string]*user_model.Setting var settings map[string]*user_model.Setting
settings, err = user_model.GetSettings(user.ID, []string{user_model.UserActivityPubPrivPem, user_model.UserActivityPubPubPem}) settings, err = user_model.GetSettings(ctx, user.ID, []string{user_model.UserActivityPubPrivPem, user_model.UserActivityPubPubPem})
if err != nil { if err != nil {
return pub, priv, err return pub, priv, err
} else if len(settings) == 0 { } else if len(settings) == 0 {
if priv, pub, err = util.GenerateKeyPair(rsaBits); err != nil { if priv, pub, err = util.GenerateKeyPair(rsaBits); err != nil {
return pub, priv, err return pub, priv, err
} }
if err = user_model.SetUserSetting(user.ID, user_model.UserActivityPubPrivPem, priv); err != nil { if err = user_model.SetUserSetting(ctx, user.ID, user_model.UserActivityPubPrivPem, priv); err != nil {
return pub, priv, err return pub, priv, err
} }
if err = user_model.SetUserSetting(user.ID, user_model.UserActivityPubPubPem, pub); err != nil { if err = user_model.SetUserSetting(ctx, user.ID, user_model.UserActivityPubPubPem, pub); err != nil {
return pub, priv, err return pub, priv, err
} }
return pub, priv, err return pub, priv, err
@ -35,13 +37,13 @@ func GetKeyPair(user *user_model.User) (pub, priv string, err error) {
} }
// GetPublicKey function returns a user's public key // GetPublicKey function returns a user's public key
func GetPublicKey(user *user_model.User) (pub string, err error) { func GetPublicKey(ctx context.Context, user *user_model.User) (pub string, err error) {
pub, _, err = GetKeyPair(user) pub, _, err = GetKeyPair(ctx, user)
return pub, err return pub, err
} }
// GetPrivateKey function returns a user's private key // GetPrivateKey function returns a user's private key
func GetPrivateKey(user *user_model.User) (priv string, err error) { func GetPrivateKey(ctx context.Context, user *user_model.User) (priv string, err error) {
_, priv, err = GetKeyPair(user) _, priv, err = GetKeyPair(ctx, user)
return priv, err return priv, err
} }

View File

@ -6,6 +6,7 @@ package activitypub
import ( import (
"testing" "testing"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
@ -17,12 +18,12 @@ import (
func TestUserSettings(t *testing.T) { func TestUserSettings(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
pub, priv, err := GetKeyPair(user1) pub, priv, err := GetKeyPair(db.DefaultContext, user1)
assert.NoError(t, err) assert.NoError(t, err)
pub1, err := GetPublicKey(user1) pub1, err := GetPublicKey(db.DefaultContext, user1)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, pub, pub1) assert.Equal(t, pub, pub1)
priv1, err := GetPrivateKey(user1) priv1, err := GetPrivateKey(db.DefaultContext, user1)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, priv, priv1) assert.Equal(t, priv, priv1)
} }

View File

@ -212,7 +212,7 @@ func (ctx *APIContext) CheckForOTP() {
} }
otpHeader := ctx.Req.Header.Get("X-Gitea-OTP") otpHeader := ctx.Req.Header.Get("X-Gitea-OTP")
twofa, err := auth.GetTwoFactorByUID(ctx.Doer.ID) twofa, err := auth.GetTwoFactorByUID(ctx, ctx.Doer.ID)
if err != nil { if err != nil {
if auth.IsErrTwoFactorNotEnrolled(err) { if auth.IsErrTwoFactorNotEnrolled(err) {
return // No 2FA enrollment for this user return // No 2FA enrollment for this user

View File

@ -598,7 +598,7 @@ func RepoAssignment(ctx *Context) context.CancelFunc {
} }
if ctx.IsSigned { if ctx.IsSigned {
ctx.Data["IsWatchingRepo"] = repo_model.IsWatching(ctx.Doer.ID, repo.ID) ctx.Data["IsWatchingRepo"] = repo_model.IsWatching(ctx, ctx.Doer.ID, repo.ID)
ctx.Data["IsStaringRepo"] = repo_model.IsStaring(ctx, ctx.Doer.ID, repo.ID) ctx.Data["IsStaringRepo"] = repo_model.IsStaring(ctx, ctx.Doer.ID, repo.ID)
} }

View File

@ -31,7 +31,7 @@ func apiError(ctx *context.Context, status int, obj any) {
} }
func GetRepositoryKey(ctx *context.Context) { func GetRepositoryKey(ctx *context.Context) {
_, pub, err := alpine_service.GetOrCreateKeyPair(ctx.Package.Owner.ID) _, pub, err := alpine_service.GetOrCreateKeyPair(ctx, ctx.Package.Owner.ID)
if err != nil { if err != nil {
apiError(ctx, http.StatusInternalServerError, err) apiError(ctx, http.StatusInternalServerError, err)
return return

View File

@ -4,6 +4,7 @@
package chef package chef
import ( import (
"context"
"crypto" "crypto"
"crypto/rsa" "crypto/rsa"
"crypto/sha1" "crypto/sha1"
@ -63,7 +64,7 @@ func (a *Auth) Verify(req *http.Request, w http.ResponseWriter, store auth.DataS
return nil, nil return nil, nil
} }
pub, err := getUserPublicKey(u) pub, err := getUserPublicKey(req.Context(), u)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -93,8 +94,8 @@ func getUserFromRequest(req *http.Request) (*user_model.User, error) {
return user_model.GetUserByName(req.Context(), username) return user_model.GetUserByName(req.Context(), username)
} }
func getUserPublicKey(u *user_model.User) (crypto.PublicKey, error) { func getUserPublicKey(ctx context.Context, u *user_model.User) (crypto.PublicKey, error) {
pubKey, err := user_model.GetSetting(u.ID, chef_module.SettingPublicPem) pubKey, err := user_model.GetSetting(ctx, u.ID, chef_module.SettingPublicPem)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -30,7 +30,7 @@ func apiError(ctx *context.Context, status int, obj any) {
} }
func GetRepositoryKey(ctx *context.Context) { func GetRepositoryKey(ctx *context.Context) {
_, pub, err := debian_service.GetOrCreateKeyPair(ctx.Package.Owner.ID) _, pub, err := debian_service.GetOrCreateKeyPair(ctx, ctx.Package.Owner.ID)
if err != nil { if err != nil {
apiError(ctx, http.StatusInternalServerError, err) apiError(ctx, http.StatusInternalServerError, err)
return return

View File

@ -23,7 +23,7 @@ func (a *Auth) Name() string {
// https://docs.microsoft.com/en-us/nuget/api/package-publish-resource#request-parameters // https://docs.microsoft.com/en-us/nuget/api/package-publish-resource#request-parameters
func (a *Auth) Verify(req *http.Request, w http.ResponseWriter, store auth.DataStore, sess auth.SessionStore) (*user_model.User, error) { func (a *Auth) Verify(req *http.Request, w http.ResponseWriter, store auth.DataStore, sess auth.SessionStore) (*user_model.User, error) {
token, err := auth_model.GetAccessTokenBySHA(req.Header.Get("X-NuGet-ApiKey")) token, err := auth_model.GetAccessTokenBySHA(req.Context(), req.Header.Get("X-NuGet-ApiKey"))
if err != nil { if err != nil {
if !(auth_model.IsErrAccessTokenNotExist(err) || auth_model.IsErrAccessTokenEmpty(err)) { if !(auth_model.IsErrAccessTokenNotExist(err) || auth_model.IsErrAccessTokenEmpty(err)) {
log.Error("GetAccessTokenBySHA: %v", err) log.Error("GetAccessTokenBySHA: %v", err)
@ -39,7 +39,7 @@ func (a *Auth) Verify(req *http.Request, w http.ResponseWriter, store auth.DataS
} }
token.UpdatedUnix = timeutil.TimeStampNow() token.UpdatedUnix = timeutil.TimeStampNow()
if err := auth_model.UpdateAccessToken(token); err != nil { if err := auth_model.UpdateAccessToken(req.Context(), token); err != nil {
log.Error("UpdateAccessToken: %v", err) log.Error("UpdateAccessToken: %v", err)
} }

View File

@ -45,7 +45,7 @@ gpgkey=`+url+`/repository.key`)
// Gets or creates the PGP public key used to sign repository metadata files // Gets or creates the PGP public key used to sign repository metadata files
func GetRepositoryKey(ctx *context.Context) { func GetRepositoryKey(ctx *context.Context) {
_, pub, err := rpm_service.GetOrCreateKeyPair(ctx.Package.Owner.ID) _, pub, err := rpm_service.GetOrCreateKeyPair(ctx, ctx.Package.Owner.ID)
if err != nil { if err != nil {
apiError(ctx, http.StatusInternalServerError, err) apiError(ctx, http.StatusInternalServerError, err)
return return

View File

@ -66,7 +66,7 @@ func Person(ctx *context.APIContext) {
person.PublicKey.ID = ap.IRI(link + "#main-key") person.PublicKey.ID = ap.IRI(link + "#main-key")
person.PublicKey.Owner = ap.IRI(link) person.PublicKey.Owner = ap.IRI(link)
publicKeyPem, err := activitypub.GetPublicKey(ctx.ContextUser) publicKeyPem, err := activitypub.GetPublicKey(ctx, ctx.ContextUser)
if err != nil { if err != nil {
ctx.ServerError("GetPublicKey", err) ctx.ServerError("GetPublicKey", err)
return return

View File

@ -776,7 +776,7 @@ func verifyAuthWithOptions(options *common.VerifyOptions) func(ctx *context.APIC
if skip, ok := ctx.Data["SkipLocalTwoFA"]; ok && skip.(bool) { if skip, ok := ctx.Data["SkipLocalTwoFA"]; ok && skip.(bool) {
return // Skip 2FA return // Skip 2FA
} }
twofa, err := auth_model.GetTwoFactorByUID(ctx.Doer.ID) twofa, err := auth_model.GetTwoFactorByUID(ctx, ctx.Doer.ID)
if err != nil { if err != nil {
if auth_model.IsErrTwoFactorNotEnrolled(err) { if auth_model.IsErrTwoFactorNotEnrolled(err) {
return // No 2FA enrollment for this user return // No 2FA enrollment for this user

View File

@ -693,7 +693,7 @@ func AddTeamRepository(ctx *context.APIContext) {
ctx.Error(http.StatusForbidden, "", "Must have admin-level access to the repository") ctx.Error(http.StatusForbidden, "", "Must have admin-level access to the repository")
return return
} }
if err := org_service.TeamAddRepository(ctx.Org.Team, repo); err != nil { if err := org_service.TeamAddRepository(ctx, ctx.Org.Team, repo); err != nil {
ctx.Error(http.StatusInternalServerError, "TeamAddRepository", err) ctx.Error(http.StatusInternalServerError, "TeamAddRepository", err)
return return
} }

View File

@ -189,7 +189,7 @@ func CreateIssueAttachment(ctx *context.APIContext) {
issue.Attachments = append(issue.Attachments, attachment) issue.Attachments = append(issue.Attachments, attachment)
if err := issue_service.ChangeContent(issue, ctx.Doer, issue.Content); err != nil { if err := issue_service.ChangeContent(ctx, issue, ctx.Doer, issue.Content); err != nil {
ctx.Error(http.StatusInternalServerError, "ChangeContent", err) ctx.Error(http.StatusInternalServerError, "ChangeContent", err)
return return
} }
@ -298,7 +298,7 @@ func DeleteIssueAttachment(ctx *context.APIContext) {
return return
} }
if err := repo_model.DeleteAttachment(attachment, true); err != nil { if err := repo_model.DeleteAttachment(ctx, attachment, true); err != nil {
ctx.Error(http.StatusInternalServerError, "DeleteAttachment", err) ctx.Error(http.StatusInternalServerError, "DeleteAttachment", err)
return return
} }

View File

@ -303,7 +303,7 @@ func DeleteIssueCommentAttachment(ctx *context.APIContext) {
return return
} }
if err := repo_model.DeleteAttachment(attach, true); err != nil { if err := repo_model.DeleteAttachment(ctx, attach, true); err != nil {
ctx.Error(http.StatusInternalServerError, "DeleteAttachment", err) ctx.Error(http.StatusInternalServerError, "DeleteAttachment", err)
return return
} }

View File

@ -97,7 +97,7 @@ func ListPullRequests(ctx *context.APIContext) {
listOptions := utils.GetListOptions(ctx) listOptions := utils.GetListOptions(ctx)
prs, maxResults, err := issues_model.PullRequests(ctx.Repo.Repository.ID, &issues_model.PullRequestsOptions{ prs, maxResults, err := issues_model.PullRequests(ctx, ctx.Repo.Repository.ID, &issues_model.PullRequestsOptions{
ListOptions: listOptions, ListOptions: listOptions,
State: ctx.FormTrim("state"), State: ctx.FormTrim("state"),
SortType: ctx.FormTrim("sort"), SortType: ctx.FormTrim("sort"),

View File

@ -345,7 +345,7 @@ func DeleteReleaseAttachment(ctx *context.APIContext) {
} }
// FIXME Should prove the existence of the given repo, but results in unnecessary database requests // FIXME Should prove the existence of the given repo, but results in unnecessary database requests
if err := repo_model.DeleteAttachment(attach, true); err != nil { if err := repo_model.DeleteAttachment(ctx, attach, true); err != nil {
ctx.Error(http.StatusInternalServerError, "DeleteAttachment", err) ctx.Error(http.StatusInternalServerError, "DeleteAttachment", err)
return return
} }

View File

@ -45,7 +45,7 @@ func ListStargazers(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
stargazers, err := repo_model.GetStargazers(ctx.Repo.Repository, utils.GetListOptions(ctx)) stargazers, err := repo_model.GetStargazers(ctx, ctx.Repo.Repository, utils.GetListOptions(ctx))
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "GetStargazers", err) ctx.Error(http.StatusInternalServerError, "GetStargazers", err)
return return

View File

@ -45,7 +45,7 @@ func ListSubscribers(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
subscribers, err := repo_model.GetRepoWatchers(ctx.Repo.Repository.ID, utils.GetListOptions(ctx)) subscribers, err := repo_model.GetRepoWatchers(ctx, ctx.Repo.Repository.ID, utils.GetListOptions(ctx))
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "GetRepoWatchers", err) ctx.Error(http.StatusInternalServerError, "GetRepoWatchers", err)
return return

View File

@ -99,7 +99,7 @@ func IsTeam(ctx *context.APIContext) {
return return
} }
if repo_service.HasRepository(team, ctx.Repo.Repository.ID) { if repo_service.HasRepository(ctx, team, ctx.Repo.Repository.ID) {
apiTeam, err := convert.ToTeam(ctx, team) apiTeam, err := convert.ToTeam(ctx, team)
if err != nil { if err != nil {
ctx.InternalServerError(err) ctx.InternalServerError(err)
@ -198,14 +198,14 @@ func changeRepoTeam(ctx *context.APIContext, add bool) {
return return
} }
repoHasTeam := repo_service.HasRepository(team, ctx.Repo.Repository.ID) repoHasTeam := repo_service.HasRepository(ctx, team, ctx.Repo.Repository.ID)
var err error var err error
if add { if add {
if repoHasTeam { if repoHasTeam {
ctx.Error(http.StatusUnprocessableEntity, "alreadyAdded", fmt.Errorf("team '%s' is already added to repo", team.Name)) ctx.Error(http.StatusUnprocessableEntity, "alreadyAdded", fmt.Errorf("team '%s' is already added to repo", team.Name))
return return
} }
err = org_service.TeamAddRepository(team, ctx.Repo.Repository) err = org_service.TeamAddRepository(ctx, team, ctx.Repo.Repository)
} else { } else {
if !repoHasTeam { if !repoHasTeam {
ctx.Error(http.StatusUnprocessableEntity, "notAdded", fmt.Errorf("team '%s' was not added to repo", team.Name)) ctx.Error(http.StatusUnprocessableEntity, "notAdded", fmt.Errorf("team '%s' was not added to repo", team.Name))

View File

@ -46,12 +46,12 @@ func ListAccessTokens(ctx *context.APIContext) {
opts := auth_model.ListAccessTokensOptions{UserID: ctx.Doer.ID, ListOptions: utils.GetListOptions(ctx)} opts := auth_model.ListAccessTokensOptions{UserID: ctx.Doer.ID, ListOptions: utils.GetListOptions(ctx)}
count, err := auth_model.CountAccessTokens(opts) count, err := auth_model.CountAccessTokens(ctx, opts)
if err != nil { if err != nil {
ctx.InternalServerError(err) ctx.InternalServerError(err)
return return
} }
tokens, err := auth_model.ListAccessTokens(opts) tokens, err := auth_model.ListAccessTokens(ctx, opts)
if err != nil { if err != nil {
ctx.InternalServerError(err) ctx.InternalServerError(err)
return return
@ -103,7 +103,7 @@ func CreateAccessToken(ctx *context.APIContext) {
Name: form.Name, Name: form.Name,
} }
exist, err := auth_model.AccessTokenByNameExists(t) exist, err := auth_model.AccessTokenByNameExists(ctx, t)
if err != nil { if err != nil {
ctx.InternalServerError(err) ctx.InternalServerError(err)
return return
@ -120,7 +120,7 @@ func CreateAccessToken(ctx *context.APIContext) {
} }
t.Scope = scope t.Scope = scope
if err := auth_model.NewAccessToken(t); err != nil { if err := auth_model.NewAccessToken(ctx, t); err != nil {
ctx.Error(http.StatusInternalServerError, "NewAccessToken", err) ctx.Error(http.StatusInternalServerError, "NewAccessToken", err)
return return
} }
@ -162,7 +162,7 @@ func DeleteAccessToken(ctx *context.APIContext) {
tokenID, _ := strconv.ParseInt(token, 0, 64) tokenID, _ := strconv.ParseInt(token, 0, 64)
if tokenID == 0 { if tokenID == 0 {
tokens, err := auth_model.ListAccessTokens(auth_model.ListAccessTokensOptions{ tokens, err := auth_model.ListAccessTokens(ctx, auth_model.ListAccessTokensOptions{
Name: token, Name: token,
UserID: ctx.Doer.ID, UserID: ctx.Doer.ID,
}) })
@ -187,7 +187,7 @@ func DeleteAccessToken(ctx *context.APIContext) {
return return
} }
if err := auth_model.DeleteAccessTokenByID(tokenID, ctx.Doer.ID); err != nil { if err := auth_model.DeleteAccessTokenByID(ctx, tokenID, ctx.Doer.ID); err != nil {
if auth_model.IsErrAccessTokenNotExist(err) { if auth_model.IsErrAccessTokenNotExist(err) {
ctx.NotFound() ctx.NotFound()
} else { } else {

View File

@ -155,7 +155,7 @@ func Star(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
err := repo_model.StarRepo(ctx.Doer.ID, ctx.Repo.Repository.ID, true) err := repo_model.StarRepo(ctx, ctx.Doer.ID, ctx.Repo.Repository.ID, true)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "StarRepo", err) ctx.Error(http.StatusInternalServerError, "StarRepo", err)
return return
@ -185,7 +185,7 @@ func Unstar(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
err := repo_model.StarRepo(ctx.Doer.ID, ctx.Repo.Repository.ID, false) err := repo_model.StarRepo(ctx, ctx.Doer.ID, ctx.Repo.Repository.ID, false)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "StarRepo", err) ctx.Error(http.StatusInternalServerError, "StarRepo", err)
return return

View File

@ -124,7 +124,7 @@ func IsWatching(ctx *context.APIContext) {
// "404": // "404":
// description: User is not watching this repo or repo do not exist // description: User is not watching this repo or repo do not exist
if repo_model.IsWatching(ctx.Doer.ID, ctx.Repo.Repository.ID) { if repo_model.IsWatching(ctx, ctx.Doer.ID, ctx.Repo.Repository.ID) {
ctx.JSON(http.StatusOK, api.WatchInfo{ ctx.JSON(http.StatusOK, api.WatchInfo{
Subscribed: true, Subscribed: true,
Ignored: false, Ignored: false,

View File

@ -238,7 +238,7 @@ func prepareUserInfo(ctx *context.Context) *user_model.User {
} }
ctx.Data["Sources"] = sources ctx.Data["Sources"] = sources
hasTOTP, err := auth.HasTwoFactorByUID(u.ID) hasTOTP, err := auth.HasTwoFactorByUID(ctx, u.ID)
if err != nil { if err != nil {
ctx.ServerError("auth.HasTwoFactorByUID", err) ctx.ServerError("auth.HasTwoFactorByUID", err)
return nil return nil
@ -410,12 +410,12 @@ func EditUserPost(ctx *context.Context) {
} }
if form.Reset2FA { if form.Reset2FA {
tf, err := auth.GetTwoFactorByUID(u.ID) tf, err := auth.GetTwoFactorByUID(ctx, u.ID)
if err != nil && !auth.IsErrTwoFactorNotEnrolled(err) { if err != nil && !auth.IsErrTwoFactorNotEnrolled(err) {
ctx.ServerError("auth.GetTwoFactorByUID", err) ctx.ServerError("auth.GetTwoFactorByUID", err)
return return
} else if tf != nil { } else if tf != nil {
if err := auth.DeleteTwoFactorByID(tf.ID, u.ID); err != nil { if err := auth.DeleteTwoFactorByID(ctx, tf.ID, u.ID); err != nil {
ctx.ServerError("auth.DeleteTwoFactorByID", err) ctx.ServerError("auth.DeleteTwoFactorByID", err)
return return
} }

View File

@ -53,7 +53,7 @@ func TwoFactorPost(ctx *context.Context) {
} }
id := idSess.(int64) id := idSess.(int64)
twofa, err := auth.GetTwoFactorByUID(id) twofa, err := auth.GetTwoFactorByUID(ctx, id)
if err != nil { if err != nil {
ctx.ServerError("UserSignIn", err) ctx.ServerError("UserSignIn", err)
return return
@ -83,7 +83,7 @@ func TwoFactorPost(ctx *context.Context) {
} }
twofa.LastUsedPasscode = form.Passcode twofa.LastUsedPasscode = form.Passcode
if err = auth.UpdateTwoFactor(twofa); err != nil { if err = auth.UpdateTwoFactor(ctx, twofa); err != nil {
ctx.ServerError("UserSignIn", err) ctx.ServerError("UserSignIn", err)
return return
} }
@ -126,7 +126,7 @@ func TwoFactorScratchPost(ctx *context.Context) {
} }
id := idSess.(int64) id := idSess.(int64)
twofa, err := auth.GetTwoFactorByUID(id) twofa, err := auth.GetTwoFactorByUID(ctx, id)
if err != nil { if err != nil {
ctx.ServerError("UserSignIn", err) ctx.ServerError("UserSignIn", err)
return return
@ -140,7 +140,7 @@ func TwoFactorScratchPost(ctx *context.Context) {
ctx.ServerError("UserSignIn", err) ctx.ServerError("UserSignIn", err)
return return
} }
if err = auth.UpdateTwoFactor(twofa); err != nil { if err = auth.UpdateTwoFactor(ctx, twofa); err != nil {
ctx.ServerError("UserSignIn", err) ctx.ServerError("UserSignIn", err)
return return
} }

View File

@ -236,7 +236,7 @@ func SignInPost(ctx *context.Context) {
// If this user is enrolled in 2FA TOTP, we can't sign the user in just yet. // If this user is enrolled in 2FA TOTP, we can't sign the user in just yet.
// Instead, redirect them to the 2FA authentication page. // Instead, redirect them to the 2FA authentication page.
hasTOTPtwofa, err := auth.HasTwoFactorByUID(u.ID) hasTOTPtwofa, err := auth.HasTwoFactorByUID(ctx, u.ID)
if err != nil { if err != nil {
ctx.ServerError("UserSignIn", err) ctx.ServerError("UserSignIn", err)
return return

View File

@ -157,7 +157,7 @@ func linkAccount(ctx *context.Context, u *user_model.User, gothUser goth.User, r
// If this user is enrolled in 2FA, we can't sign the user in just yet. // If this user is enrolled in 2FA, we can't sign the user in just yet.
// Instead, redirect them to the 2FA authentication page. // Instead, redirect them to the 2FA authentication page.
// We deliberately ignore the skip local 2fa setting here because we are linking to a previous user here // We deliberately ignore the skip local 2fa setting here because we are linking to a previous user here
_, err := auth.GetTwoFactorByUID(u.ID) _, err := auth.GetTwoFactorByUID(ctx, u.ID)
if err != nil { if err != nil {
if !auth.IsErrTwoFactorNotEnrolled(err) { if !auth.IsErrTwoFactorNotEnrolled(err) {
ctx.ServerError("UserLinkAccount", err) ctx.ServerError("UserLinkAccount", err)

View File

@ -1097,7 +1097,7 @@ func handleOAuth2SignIn(ctx *context.Context, source *auth.Source, u *user_model
needs2FA := false needs2FA := false
if !source.Cfg.(*oauth2.Source).SkipLocalTwoFA { if !source.Cfg.(*oauth2.Source).SkipLocalTwoFA {
_, err := auth.GetTwoFactorByUID(u.ID) _, err := auth.GetTwoFactorByUID(ctx, u.ID)
if err != nil && !auth.IsErrTwoFactorNotEnrolled(err) { if err != nil && !auth.IsErrTwoFactorNotEnrolled(err) {
ctx.ServerError("UserSignIn", err) ctx.ServerError("UserSignIn", err)
return return

View File

@ -120,7 +120,7 @@ func commonResetPassword(ctx *context.Context) (*user_model.User, *auth.TwoFacto
return nil, nil return nil, nil
} }
twofa, err := auth.GetTwoFactorByUID(u.ID) twofa, err := auth.GetTwoFactorByUID(ctx, u.ID)
if err != nil { if err != nil {
if !auth.IsErrTwoFactorNotEnrolled(err) { if !auth.IsErrTwoFactorNotEnrolled(err) {
ctx.Error(http.StatusInternalServerError, "CommonResetPassword", err.Error()) ctx.Error(http.StatusInternalServerError, "CommonResetPassword", err.Error())
@ -217,7 +217,7 @@ func ResetPasswdPost(ctx *context.Context) {
} }
twofa.LastUsedPasscode = passcode twofa.LastUsedPasscode = passcode
if err = auth.UpdateTwoFactor(twofa); err != nil { if err = auth.UpdateTwoFactor(ctx, twofa); err != nil {
ctx.ServerError("ResetPasswdPost: UpdateTwoFactor", err) ctx.ServerError("ResetPasswdPost: UpdateTwoFactor", err)
return return
} }
@ -249,7 +249,7 @@ func ResetPasswdPost(ctx *context.Context) {
ctx.ServerError("UserSignIn", err) ctx.ServerError("UserSignIn", err)
return return
} }
if err = auth.UpdateTwoFactor(twofa); err != nil { if err = auth.UpdateTwoFactor(ctx, twofa); err != nil {
ctx.ServerError("UserSignIn", err) ctx.ServerError("UserSignIn", err)
return return
} }

View File

@ -247,7 +247,7 @@ func TeamsRepoAction(ctx *context.Context) {
ctx.ServerError("GetRepositoryByName", err) ctx.ServerError("GetRepositoryByName", err)
return return
} }
err = org_service.TeamAddRepository(ctx.Org.Team, repo) err = org_service.TeamAddRepository(ctx, ctx.Org.Team, repo)
case "remove": case "remove":
err = repo_service.RemoveRepositoryFromTeam(ctx, ctx.Org.Team, ctx.FormInt64("repoid")) err = repo_service.RemoveRepositoryFromTeam(ctx, ctx.Org.Team, ctx.FormInt64("repoid"))
case "addall": case "addall":

View File

@ -77,7 +77,7 @@ func DeleteAttachment(ctx *context.Context) {
ctx.Error(http.StatusForbidden) ctx.Error(http.StatusForbidden)
return return
} }
err = repo_model.DeleteAttachment(attach, true) err = repo_model.DeleteAttachment(ctx, attach, true)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, fmt.Sprintf("DeleteAttachment: %v", err)) ctx.Error(http.StatusInternalServerError, fmt.Sprintf("DeleteAttachment: %v", err))
return return
@ -122,7 +122,7 @@ func ServeAttachment(ctx *context.Context, uuid string) {
} }
} }
if err := attach.IncreaseDownloadCount(); err != nil { if err := attach.IncreaseDownloadCount(ctx); err != nil {
ctx.ServerError("IncreaseDownloadCount", err) ctx.ServerError("IncreaseDownloadCount", err)
return return
} }

View File

@ -812,7 +812,7 @@ func UploadFileToServer(ctx *context.Context) {
return return
} }
upload, err := repo_model.NewUpload(name, buf, file) upload, err := repo_model.NewUpload(ctx, name, buf, file)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, fmt.Sprintf("NewUpload: %v", err)) ctx.Error(http.StatusInternalServerError, fmt.Sprintf("NewUpload: %v", err))
return return
@ -832,7 +832,7 @@ func RemoveUploadFileFromServer(ctx *context.Context) {
return return
} }
if err := repo_model.DeleteUploadByUUID(form.File); err != nil { if err := repo_model.DeleteUploadByUUID(ctx, form.File); err != nil {
ctx.Error(http.StatusInternalServerError, fmt.Sprintf("DeleteUploadByUUID: %v", err)) ctx.Error(http.StatusInternalServerError, fmt.Sprintf("DeleteUploadByUUID: %v", err))
return return
} }

View File

@ -158,7 +158,7 @@ func httpBase(ctx *context.Context) *serviceHandler {
} }
if ctx.IsBasicAuth && ctx.Data["IsApiToken"] != true && ctx.Data["IsActionsToken"] != true { if ctx.IsBasicAuth && ctx.Data["IsApiToken"] != true && ctx.Data["IsActionsToken"] != true {
_, err = auth_model.GetTwoFactorByUID(ctx.Doer.ID) _, err = auth_model.GetTwoFactorByUID(ctx, ctx.Doer.ID)
if err == nil { if err == nil {
// TODO: This response should be changed to "invalid credentials" for security reasons once the expectation behind it (creating an app token to authenticate) is properly documented // TODO: This response should be changed to "invalid credentials" for security reasons once the expectation behind it (creating an app token to authenticate) is properly documented
ctx.PlainText(http.StatusUnauthorized, "Users with two-factor authentication enabled cannot perform HTTP/HTTPS operations via plain username and password. Please create and use a personal access token on the user settings page") ctx.PlainText(http.StatusUnauthorized, "Users with two-factor authentication enabled cannot perform HTTP/HTTPS operations via plain username and password. Please create and use a personal access token on the user settings page")

View File

@ -1975,7 +1975,7 @@ func ViewIssue(ctx *context.Context) {
var hiddenCommentTypes *big.Int var hiddenCommentTypes *big.Int
if ctx.IsSigned { if ctx.IsSigned {
val, err := user_model.GetUserSetting(ctx.Doer.ID, user_model.SettingsKeyHiddenCommentTypes) val, err := user_model.GetUserSetting(ctx, ctx.Doer.ID, user_model.SettingsKeyHiddenCommentTypes)
if err != nil { if err != nil {
ctx.ServerError("GetUserSetting", err) ctx.ServerError("GetUserSetting", err)
return return
@ -2205,7 +2205,7 @@ func UpdateIssueContent(ctx *context.Context) {
return return
} }
if err := issue_service.ChangeContent(issue, ctx.Doer, ctx.Req.FormValue("content")); err != nil { if err := issue_service.ChangeContent(ctx, issue, ctx.Doer, ctx.Req.FormValue("content")); err != nil {
ctx.ServerError("ChangeContent", err) ctx.ServerError("ChangeContent", err)
return return
} }
@ -3451,7 +3451,7 @@ func updateAttachments(ctx *context.Context, item any, files []string) error {
if util.SliceContainsString(files, attachments[i].UUID) { if util.SliceContainsString(files, attachments[i].UUID) {
continue continue
} }
if err := repo_model.DeleteAttachment(attachments[i], true); err != nil { if err := repo_model.DeleteAttachment(ctx, attachments[i], true); err != nil {
return err return err
} }
} }

View File

@ -72,12 +72,12 @@ func SetWhitespaceBehavior(ctx *context.Context) {
whitespaceBehavior = defaultWhitespaceBehavior whitespaceBehavior = defaultWhitespaceBehavior
} }
if ctx.IsSigned { if ctx.IsSigned {
userWhitespaceBehavior, err := user_model.GetUserSetting(ctx.Doer.ID, user_model.SettingsKeyDiffWhitespaceBehavior, defaultWhitespaceBehavior) userWhitespaceBehavior, err := user_model.GetUserSetting(ctx, ctx.Doer.ID, user_model.SettingsKeyDiffWhitespaceBehavior, defaultWhitespaceBehavior)
if err == nil { if err == nil {
if whitespaceBehavior == "" { if whitespaceBehavior == "" {
whitespaceBehavior = userWhitespaceBehavior whitespaceBehavior = userWhitespaceBehavior
} else if whitespaceBehavior != userWhitespaceBehavior { } else if whitespaceBehavior != userWhitespaceBehavior {
_ = user_model.SetUserSetting(ctx.Doer.ID, user_model.SettingsKeyDiffWhitespaceBehavior, whitespaceBehavior) _ = user_model.SetUserSetting(ctx, ctx.Doer.ID, user_model.SettingsKeyDiffWhitespaceBehavior, whitespaceBehavior)
} }
} // else: we can ignore the error safely } // else: we can ignore the error safely
} }
@ -98,7 +98,7 @@ func SetShowOutdatedComments(ctx *context.Context) {
if showOutdatedCommentsValue != "true" && showOutdatedCommentsValue != "false" { if showOutdatedCommentsValue != "true" && showOutdatedCommentsValue != "false" {
// invalid or no value for this form string -> use default or stored user setting // invalid or no value for this form string -> use default or stored user setting
if ctx.IsSigned { if ctx.IsSigned {
showOutdatedCommentsValue, _ = user_model.GetUserSetting(ctx.Doer.ID, user_model.SettingsKeyShowOutdatedComments, "false") showOutdatedCommentsValue, _ = user_model.GetUserSetting(ctx, ctx.Doer.ID, user_model.SettingsKeyShowOutdatedComments, "false")
} else { } else {
// not logged in user -> use the default value // not logged in user -> use the default value
showOutdatedCommentsValue = "false" showOutdatedCommentsValue = "false"
@ -106,7 +106,7 @@ func SetShowOutdatedComments(ctx *context.Context) {
} else { } else {
// valid value -> update user setting if user is logged in // valid value -> update user setting if user is logged in
if ctx.IsSigned { if ctx.IsSigned {
_ = user_model.SetUserSetting(ctx.Doer.ID, user_model.SettingsKeyShowOutdatedComments, showOutdatedCommentsValue) _ = user_model.SetUserSetting(ctx, ctx.Doer.ID, user_model.SettingsKeyShowOutdatedComments, showOutdatedCommentsValue)
} }
} }

View File

@ -308,9 +308,9 @@ func Action(ctx *context.Context) {
case "unwatch": case "unwatch":
err = repo_model.WatchRepo(ctx, ctx.Doer.ID, ctx.Repo.Repository.ID, false) err = repo_model.WatchRepo(ctx, ctx.Doer.ID, ctx.Repo.Repository.ID, false)
case "star": case "star":
err = repo_model.StarRepo(ctx.Doer.ID, ctx.Repo.Repository.ID, true) err = repo_model.StarRepo(ctx, ctx.Doer.ID, ctx.Repo.Repository.ID, true)
case "unstar": case "unstar":
err = repo_model.StarRepo(ctx.Doer.ID, ctx.Repo.Repository.ID, false) err = repo_model.StarRepo(ctx, ctx.Doer.ID, ctx.Repo.Repository.ID, false)
case "accept_transfer": case "accept_transfer":
err = acceptOrRejectRepoTransfer(ctx, true) err = acceptOrRejectRepoTransfer(ctx, true)
case "reject_transfer": case "reject_transfer":

View File

@ -173,7 +173,7 @@ func AddTeamPost(ctx *context.Context) {
return return
} }
if err = org_service.TeamAddRepository(team, ctx.Repo.Repository); err != nil { if err = org_service.TeamAddRepository(ctx, team, ctx.Repo.Repository); err != nil {
ctx.ServerError("TeamAddRepository", err) ctx.ServerError("TeamAddRepository", err)
return return
} }

View File

@ -8,6 +8,7 @@ import (
"testing" "testing"
asymkey_model "code.gitea.io/gitea/models/asymkey" asymkey_model "code.gitea.io/gitea/models/asymkey"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/organization" "code.gitea.io/gitea/models/organization"
"code.gitea.io/gitea/models/perm" "code.gitea.io/gitea/models/perm"
repo_model "code.gitea.io/gitea/models/repo" repo_model "code.gitea.io/gitea/models/repo"
@ -248,7 +249,7 @@ func TestAddTeamPost(t *testing.T) {
AddTeamPost(ctx) AddTeamPost(ctx)
assert.True(t, repo_service.HasRepository(team, re.ID)) assert.True(t, repo_service.HasRepository(db.DefaultContext, team, re.ID))
assert.EqualValues(t, http.StatusSeeOther, ctx.Resp.Status()) assert.EqualValues(t, http.StatusSeeOther, ctx.Resp.Status())
assert.Empty(t, ctx.Flash.ErrorMsg) assert.Empty(t, ctx.Flash.ErrorMsg)
} }
@ -288,7 +289,7 @@ func TestAddTeamPost_NotAllowed(t *testing.T) {
AddTeamPost(ctx) AddTeamPost(ctx)
assert.False(t, repo_service.HasRepository(team, re.ID)) assert.False(t, repo_service.HasRepository(db.DefaultContext, team, re.ID))
assert.EqualValues(t, http.StatusSeeOther, ctx.Resp.Status()) assert.EqualValues(t, http.StatusSeeOther, ctx.Resp.Status())
assert.NotEmpty(t, ctx.Flash.ErrorMsg) assert.NotEmpty(t, ctx.Flash.ErrorMsg)
} }
@ -329,7 +330,7 @@ func TestAddTeamPost_AddTeamTwice(t *testing.T) {
AddTeamPost(ctx) AddTeamPost(ctx)
AddTeamPost(ctx) AddTeamPost(ctx)
assert.True(t, repo_service.HasRepository(team, re.ID)) assert.True(t, repo_service.HasRepository(db.DefaultContext, team, re.ID))
assert.EqualValues(t, http.StatusSeeOther, ctx.Resp.Status()) assert.EqualValues(t, http.StatusSeeOther, ctx.Resp.Status())
assert.NotEmpty(t, ctx.Flash.ErrorMsg) assert.NotEmpty(t, ctx.Flash.ErrorMsg)
} }
@ -402,5 +403,5 @@ func TestDeleteTeam(t *testing.T) {
DeleteTeam(ctx) DeleteTeam(ctx)
assert.False(t, repo_service.HasRepository(team, re.ID)) assert.False(t, repo_service.HasRepository(db.DefaultContext, team, re.ID))
} }

View File

@ -1065,7 +1065,7 @@ func Watchers(ctx *context.Context) {
ctx.Data["PageIsWatchers"] = true ctx.Data["PageIsWatchers"] = true
RenderUserCards(ctx, ctx.Repo.Repository.NumWatches, func(opts db.ListOptions) ([]*user_model.User, error) { RenderUserCards(ctx, ctx.Repo.Repository.NumWatches, func(opts db.ListOptions) ([]*user_model.User, error) {
return repo_model.GetRepoWatchers(ctx.Repo.Repository.ID, opts) return repo_model.GetRepoWatchers(ctx, ctx.Repo.Repository.ID, opts)
}, tplWatchers) }, tplWatchers)
} }
@ -1075,7 +1075,7 @@ func Stars(ctx *context.Context) {
ctx.Data["CardsTitle"] = ctx.Tr("repo.stargazers") ctx.Data["CardsTitle"] = ctx.Tr("repo.stargazers")
ctx.Data["PageIsStargazers"] = true ctx.Data["PageIsStargazers"] = true
RenderUserCards(ctx, ctx.Repo.Repository.NumStars, func(opts db.ListOptions) ([]*user_model.User, error) { RenderUserCards(ctx, ctx.Repo.Repository.NumStars, func(opts db.ListOptions) ([]*user_model.User, error) {
return repo_model.GetStargazers(ctx.Repo.Repository, opts) return repo_model.GetStargazers(ctx, ctx.Repo.Repository, opts)
}, tplWatchers) }, tplWatchers)
} }

View File

@ -34,7 +34,7 @@ func PrepareContextForProfileBigAvatar(ctx *context.Context) {
ctx.Data["ShowUserEmail"] = setting.UI.ShowUserEmail && ctx.ContextUser.Email != "" && ctx.IsSigned && !ctx.ContextUser.KeepEmailPrivate ctx.Data["ShowUserEmail"] = setting.UI.ShowUserEmail && ctx.ContextUser.Email != "" && ctx.IsSigned && !ctx.ContextUser.KeepEmailPrivate
// Show OpenID URIs // Show OpenID URIs
openIDs, err := user_model.GetUserOpenIDs(ctx.ContextUser.ID) openIDs, err := user_model.GetUserOpenIDs(ctx, ctx.ContextUser.ID)
if err != nil { if err != nil {
ctx.ServerError("GetUserOpenIDs", err) ctx.ServerError("GetUserOpenIDs", err)
return return

View File

@ -53,7 +53,7 @@ func ApplicationsPost(ctx *context.Context) {
Scope: scope, Scope: scope,
} }
exist, err := auth_model.AccessTokenByNameExists(t) exist, err := auth_model.AccessTokenByNameExists(ctx, t)
if err != nil { if err != nil {
ctx.ServerError("AccessTokenByNameExists", err) ctx.ServerError("AccessTokenByNameExists", err)
return return
@ -64,7 +64,7 @@ func ApplicationsPost(ctx *context.Context) {
return return
} }
if err := auth_model.NewAccessToken(t); err != nil { if err := auth_model.NewAccessToken(ctx, t); err != nil {
ctx.ServerError("NewAccessToken", err) ctx.ServerError("NewAccessToken", err)
return return
} }
@ -77,7 +77,7 @@ func ApplicationsPost(ctx *context.Context) {
// DeleteApplication response for delete user access token // DeleteApplication response for delete user access token
func DeleteApplication(ctx *context.Context) { func DeleteApplication(ctx *context.Context) {
if err := auth_model.DeleteAccessTokenByID(ctx.FormInt64("id"), ctx.Doer.ID); err != nil { if err := auth_model.DeleteAccessTokenByID(ctx, ctx.FormInt64("id"), ctx.Doer.ID); err != nil {
ctx.Flash.Error("DeleteAccessTokenByID: " + err.Error()) ctx.Flash.Error("DeleteAccessTokenByID: " + err.Error())
} else { } else {
ctx.Flash.Success(ctx.Tr("settings.delete_token_success")) ctx.Flash.Success(ctx.Tr("settings.delete_token_success"))
@ -88,7 +88,7 @@ func DeleteApplication(ctx *context.Context) {
func loadApplicationsData(ctx *context.Context) { func loadApplicationsData(ctx *context.Context) {
ctx.Data["AccessTokenScopePublicOnly"] = auth_model.AccessTokenScopePublicOnly ctx.Data["AccessTokenScopePublicOnly"] = auth_model.AccessTokenScopePublicOnly
tokens, err := auth_model.ListAccessTokens(auth_model.ListAccessTokensOptions{UserID: ctx.Doer.ID}) tokens, err := auth_model.ListAccessTokens(ctx, auth_model.ListAccessTokensOptions{UserID: ctx.Doer.ID})
if err != nil { if err != nil {
ctx.ServerError("ListAccessTokens", err) ctx.ServerError("ListAccessTokens", err)
return return

View File

@ -107,7 +107,7 @@ func RegenerateChefKeyPair(ctx *context.Context) {
return return
} }
if err := user_model.SetUserSetting(ctx.Doer.ID, chef_module.SettingPublicPem, pub); err != nil { if err := user_model.SetUserSetting(ctx, ctx.Doer.ID, chef_module.SettingPublicPem, pub); err != nil {
ctx.ServerError("SetUserSetting", err) ctx.ServerError("SetUserSetting", err)
return return
} }

View File

@ -348,7 +348,7 @@ func Appearance(ctx *context.Context) {
ctx.Data["PageIsSettingsAppearance"] = true ctx.Data["PageIsSettingsAppearance"] = true
var hiddenCommentTypes *big.Int var hiddenCommentTypes *big.Int
val, err := user_model.GetUserSetting(ctx.Doer.ID, user_model.SettingsKeyHiddenCommentTypes) val, err := user_model.GetUserSetting(ctx, ctx.Doer.ID, user_model.SettingsKeyHiddenCommentTypes)
if err != nil { if err != nil {
ctx.ServerError("GetUserSetting", err) ctx.ServerError("GetUserSetting", err)
return return
@ -420,7 +420,7 @@ func UpdateUserLang(ctx *context.Context) {
// UpdateUserHiddenComments update a user's shown comment types // UpdateUserHiddenComments update a user's shown comment types
func UpdateUserHiddenComments(ctx *context.Context) { func UpdateUserHiddenComments(ctx *context.Context) {
err := user_model.SetUserSetting(ctx.Doer.ID, user_model.SettingsKeyHiddenCommentTypes, forms.UserHiddenCommentTypesFromRequest(ctx).String()) err := user_model.SetUserSetting(ctx, ctx.Doer.ID, user_model.SettingsKeyHiddenCommentTypes, forms.UserHiddenCommentTypesFromRequest(ctx).String())
if err != nil { if err != nil {
ctx.ServerError("SetUserSetting", err) ctx.ServerError("SetUserSetting", err)
return return

View File

@ -28,7 +28,7 @@ func RegenerateScratchTwoFactor(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("settings") ctx.Data["Title"] = ctx.Tr("settings")
ctx.Data["PageIsSettingsSecurity"] = true ctx.Data["PageIsSettingsSecurity"] = true
t, err := auth.GetTwoFactorByUID(ctx.Doer.ID) t, err := auth.GetTwoFactorByUID(ctx, ctx.Doer.ID)
if err != nil { if err != nil {
if auth.IsErrTwoFactorNotEnrolled(err) { if auth.IsErrTwoFactorNotEnrolled(err) {
ctx.Flash.Error(ctx.Tr("settings.twofa_not_enrolled")) ctx.Flash.Error(ctx.Tr("settings.twofa_not_enrolled"))
@ -44,7 +44,7 @@ func RegenerateScratchTwoFactor(ctx *context.Context) {
return return
} }
if err = auth.UpdateTwoFactor(t); err != nil { if err = auth.UpdateTwoFactor(ctx, t); err != nil {
ctx.ServerError("SettingsTwoFactor: Failed to UpdateTwoFactor", err) ctx.ServerError("SettingsTwoFactor: Failed to UpdateTwoFactor", err)
return return
} }
@ -58,7 +58,7 @@ func DisableTwoFactor(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("settings") ctx.Data["Title"] = ctx.Tr("settings")
ctx.Data["PageIsSettingsSecurity"] = true ctx.Data["PageIsSettingsSecurity"] = true
t, err := auth.GetTwoFactorByUID(ctx.Doer.ID) t, err := auth.GetTwoFactorByUID(ctx, ctx.Doer.ID)
if err != nil { if err != nil {
if auth.IsErrTwoFactorNotEnrolled(err) { if auth.IsErrTwoFactorNotEnrolled(err) {
ctx.Flash.Error(ctx.Tr("settings.twofa_not_enrolled")) ctx.Flash.Error(ctx.Tr("settings.twofa_not_enrolled"))
@ -68,7 +68,7 @@ func DisableTwoFactor(ctx *context.Context) {
return return
} }
if err = auth.DeleteTwoFactorByID(t.ID, ctx.Doer.ID); err != nil { if err = auth.DeleteTwoFactorByID(ctx, t.ID, ctx.Doer.ID); err != nil {
if auth.IsErrTwoFactorNotEnrolled(err) { if auth.IsErrTwoFactorNotEnrolled(err) {
// There is a potential DB race here - we must have been disabled by another request in the intervening period // There is a potential DB race here - we must have been disabled by another request in the intervening period
ctx.Flash.Success(ctx.Tr("settings.twofa_disabled")) ctx.Flash.Success(ctx.Tr("settings.twofa_disabled"))
@ -145,7 +145,7 @@ func EnrollTwoFactor(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("settings") ctx.Data["Title"] = ctx.Tr("settings")
ctx.Data["PageIsSettingsSecurity"] = true ctx.Data["PageIsSettingsSecurity"] = true
t, err := auth.GetTwoFactorByUID(ctx.Doer.ID) t, err := auth.GetTwoFactorByUID(ctx, ctx.Doer.ID)
if t != nil { if t != nil {
// already enrolled - we should redirect back! // already enrolled - we should redirect back!
log.Warn("Trying to re-enroll %-v in twofa when already enrolled", ctx.Doer) log.Warn("Trying to re-enroll %-v in twofa when already enrolled", ctx.Doer)
@ -171,7 +171,7 @@ func EnrollTwoFactorPost(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("settings") ctx.Data["Title"] = ctx.Tr("settings")
ctx.Data["PageIsSettingsSecurity"] = true ctx.Data["PageIsSettingsSecurity"] = true
t, err := auth.GetTwoFactorByUID(ctx.Doer.ID) t, err := auth.GetTwoFactorByUID(ctx, ctx.Doer.ID)
if t != nil { if t != nil {
// already enrolled // already enrolled
ctx.Flash.Error(ctx.Tr("settings.twofa_is_enrolled")) ctx.Flash.Error(ctx.Tr("settings.twofa_is_enrolled"))
@ -237,7 +237,7 @@ func EnrollTwoFactorPost(ctx *context.Context) {
log.Error("Unable to save changes to the session: %v", err) log.Error("Unable to save changes to the session: %v", err)
} }
if err = auth.NewTwoFactor(t); err != nil { if err = auth.NewTwoFactor(ctx, t); err != nil {
// FIXME: We need to handle a unique constraint fail here it's entirely possible that another request has beaten us. // FIXME: We need to handle a unique constraint fail here it's entirely possible that another request has beaten us.
// If there is a unique constraint fail we should just tolerate the error // If there is a unique constraint fail we should just tolerate the error
ctx.ServerError("SettingsTwoFactor: Failed to save two factor", err) ctx.ServerError("SettingsTwoFactor: Failed to save two factor", err)

View File

@ -44,7 +44,7 @@ func OpenIDPost(ctx *context.Context) {
form.Openid = id form.Openid = id
log.Trace("Normalized id: " + id) log.Trace("Normalized id: " + id)
oids, err := user_model.GetUserOpenIDs(ctx.Doer.ID) oids, err := user_model.GetUserOpenIDs(ctx, ctx.Doer.ID)
if err != nil { if err != nil {
ctx.ServerError("GetUserOpenIDs", err) ctx.ServerError("GetUserOpenIDs", err)
return return
@ -105,7 +105,7 @@ func settingsOpenIDVerify(ctx *context.Context) {
// DeleteOpenID response for delete user's openid // DeleteOpenID response for delete user's openid
func DeleteOpenID(ctx *context.Context) { func DeleteOpenID(ctx *context.Context) {
if err := user_model.DeleteUserOpenID(&user_model.UserOpenID{ID: ctx.FormInt64("id"), UID: ctx.Doer.ID}); err != nil { if err := user_model.DeleteUserOpenID(ctx, &user_model.UserOpenID{ID: ctx.FormInt64("id"), UID: ctx.Doer.ID}); err != nil {
ctx.ServerError("DeleteUserOpenID", err) ctx.ServerError("DeleteUserOpenID", err)
return return
} }
@ -117,7 +117,7 @@ func DeleteOpenID(ctx *context.Context) {
// ToggleOpenIDVisibility response for toggle visibility of user's openid // ToggleOpenIDVisibility response for toggle visibility of user's openid
func ToggleOpenIDVisibility(ctx *context.Context) { func ToggleOpenIDVisibility(ctx *context.Context) {
if err := user_model.ToggleUserOpenIDVisibility(ctx.FormInt64("id")); err != nil { if err := user_model.ToggleUserOpenIDVisibility(ctx, ctx.FormInt64("id")); err != nil {
ctx.ServerError("ToggleUserOpenIDVisibility", err) ctx.ServerError("ToggleUserOpenIDVisibility", err)
return return
} }

View File

@ -52,7 +52,7 @@ func DeleteAccountLink(ctx *context.Context) {
} }
func loadSecurityData(ctx *context.Context) { func loadSecurityData(ctx *context.Context) {
enrolled, err := auth_model.HasTwoFactorByUID(ctx.Doer.ID) enrolled, err := auth_model.HasTwoFactorByUID(ctx, ctx.Doer.ID)
if err != nil { if err != nil {
ctx.ServerError("SettingsTwoFactor", err) ctx.ServerError("SettingsTwoFactor", err)
return return
@ -66,7 +66,7 @@ func loadSecurityData(ctx *context.Context) {
} }
ctx.Data["WebAuthnCredentials"] = credentials ctx.Data["WebAuthnCredentials"] = credentials
tokens, err := auth_model.ListAccessTokens(auth_model.ListAccessTokensOptions{UserID: ctx.Doer.ID}) tokens, err := auth_model.ListAccessTokens(ctx, auth_model.ListAccessTokensOptions{UserID: ctx.Doer.ID})
if err != nil { if err != nil {
ctx.ServerError("ListAccessTokens", err) ctx.ServerError("ListAccessTokens", err)
return return
@ -113,7 +113,7 @@ func loadSecurityData(ctx *context.Context) {
ctx.Data["OrderedOAuth2Names"] = orderedOAuth2Names ctx.Data["OrderedOAuth2Names"] = orderedOAuth2Names
ctx.Data["OAuth2Providers"] = oauth2Providers ctx.Data["OAuth2Providers"] = oauth2Providers
openid, err := user_model.GetUserOpenIDs(ctx.Doer.ID) openid, err := user_model.GetUserOpenIDs(ctx, ctx.Doer.ID)
if err != nil { if err != nil {
ctx.ServerError("GetUserOpenIDs", err) ctx.ServerError("GetUserOpenIDs", err)
return return

View File

@ -151,7 +151,7 @@ Loop:
return false, "", nil, &ErrWontSign{pubkey} return false, "", nil, &ErrWontSign{pubkey}
} }
case twofa: case twofa:
twofaModel, err := auth.GetTwoFactorByUID(u.ID) twofaModel, err := auth.GetTwoFactorByUID(ctx, u.ID)
if err != nil && !auth.IsErrTwoFactorNotEnrolled(err) { if err != nil && !auth.IsErrTwoFactorNotEnrolled(err) {
return false, "", nil, err return false, "", nil, err
} }
@ -187,7 +187,7 @@ Loop:
return false, "", nil, &ErrWontSign{pubkey} return false, "", nil, &ErrWontSign{pubkey}
} }
case twofa: case twofa:
twofaModel, err := auth.GetTwoFactorByUID(u.ID) twofaModel, err := auth.GetTwoFactorByUID(ctx, u.ID)
if err != nil && !auth.IsErrTwoFactorNotEnrolled(err) { if err != nil && !auth.IsErrTwoFactorNotEnrolled(err) {
return false, "", nil, err return false, "", nil, err
} }
@ -240,7 +240,7 @@ Loop:
return false, "", nil, &ErrWontSign{pubkey} return false, "", nil, &ErrWontSign{pubkey}
} }
case twofa: case twofa:
twofaModel, err := auth.GetTwoFactorByUID(u.ID) twofaModel, err := auth.GetTwoFactorByUID(ctx, u.ID)
if err != nil && !auth.IsErrTwoFactorNotEnrolled(err) { if err != nil && !auth.IsErrTwoFactorNotEnrolled(err) {
return false, "", nil, err return false, "", nil, err
} }
@ -302,7 +302,7 @@ Loop:
return false, "", nil, &ErrWontSign{pubkey} return false, "", nil, &ErrWontSign{pubkey}
} }
case twofa: case twofa:
twofaModel, err := auth.GetTwoFactorByUID(u.ID) twofaModel, err := auth.GetTwoFactorByUID(ctx, u.ID)
if err != nil && !auth.IsErrTwoFactorNotEnrolled(err) { if err != nil && !auth.IsErrTwoFactorNotEnrolled(err) {
return false, "", nil, err return false, "", nil, err
} }

View File

@ -71,7 +71,7 @@ func (b *Basic) Verify(req *http.Request, w http.ResponseWriter, store DataStore
} }
// check oauth2 token // check oauth2 token
uid := CheckOAuthAccessToken(authToken) uid := CheckOAuthAccessToken(req.Context(), authToken)
if uid != 0 { if uid != 0 {
log.Trace("Basic Authorization: Valid OAuthAccessToken for user[%d]", uid) log.Trace("Basic Authorization: Valid OAuthAccessToken for user[%d]", uid)
@ -86,7 +86,7 @@ func (b *Basic) Verify(req *http.Request, w http.ResponseWriter, store DataStore
} }
// check personal access token // check personal access token
token, err := auth_model.GetAccessTokenBySHA(authToken) token, err := auth_model.GetAccessTokenBySHA(req.Context(), authToken)
if err == nil { if err == nil {
log.Trace("Basic Authorization: Valid AccessToken for user[%d]", uid) log.Trace("Basic Authorization: Valid AccessToken for user[%d]", uid)
u, err := user_model.GetUserByID(req.Context(), token.UID) u, err := user_model.GetUserByID(req.Context(), token.UID)
@ -96,7 +96,7 @@ func (b *Basic) Verify(req *http.Request, w http.ResponseWriter, store DataStore
} }
token.UpdatedUnix = timeutil.TimeStampNow() token.UpdatedUnix = timeutil.TimeStampNow()
if err = auth_model.UpdateAccessToken(token); err != nil { if err = auth_model.UpdateAccessToken(req.Context(), token); err != nil {
log.Error("UpdateAccessToken: %v", err) log.Error("UpdateAccessToken: %v", err)
} }

View File

@ -5,13 +5,13 @@
package auth package auth
import ( import (
"context"
"net/http" "net/http"
"strings" "strings"
"time" "time"
actions_model "code.gitea.io/gitea/models/actions" actions_model "code.gitea.io/gitea/models/actions"
auth_model "code.gitea.io/gitea/models/auth" auth_model "code.gitea.io/gitea/models/auth"
"code.gitea.io/gitea/models/db"
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/timeutil"
@ -25,7 +25,7 @@ var (
) )
// CheckOAuthAccessToken returns uid of user from oauth token // CheckOAuthAccessToken returns uid of user from oauth token
func CheckOAuthAccessToken(accessToken string) int64 { func CheckOAuthAccessToken(ctx context.Context, accessToken string) int64 {
// JWT tokens require a "." // JWT tokens require a "."
if !strings.Contains(accessToken, ".") { if !strings.Contains(accessToken, ".") {
return 0 return 0
@ -36,7 +36,7 @@ func CheckOAuthAccessToken(accessToken string) int64 {
return 0 return 0
} }
var grant *auth_model.OAuth2Grant var grant *auth_model.OAuth2Grant
if grant, err = auth_model.GetOAuth2GrantByID(db.DefaultContext, token.GrantID); err != nil || grant == nil { if grant, err = auth_model.GetOAuth2GrantByID(ctx, token.GrantID); err != nil || grant == nil {
return 0 return 0
} }
if token.Type != oauth2.TypeAccessToken { if token.Type != oauth2.TypeAccessToken {
@ -83,21 +83,21 @@ func parseToken(req *http.Request) (string, bool) {
// userIDFromToken returns the user id corresponding to the OAuth token. // userIDFromToken returns the user id corresponding to the OAuth token.
// It will set 'IsApiToken' to true if the token is an API token and // It will set 'IsApiToken' to true if the token is an API token and
// set 'ApiTokenScope' to the scope of the access token // set 'ApiTokenScope' to the scope of the access token
func (o *OAuth2) userIDFromToken(tokenSHA string, store DataStore) int64 { func (o *OAuth2) userIDFromToken(ctx context.Context, tokenSHA string, store DataStore) int64 {
// Let's see if token is valid. // Let's see if token is valid.
if strings.Contains(tokenSHA, ".") { if strings.Contains(tokenSHA, ".") {
uid := CheckOAuthAccessToken(tokenSHA) uid := CheckOAuthAccessToken(ctx, tokenSHA)
if uid != 0 { if uid != 0 {
store.GetData()["IsApiToken"] = true store.GetData()["IsApiToken"] = true
store.GetData()["ApiTokenScope"] = auth_model.AccessTokenScopeAll // fallback to all store.GetData()["ApiTokenScope"] = auth_model.AccessTokenScopeAll // fallback to all
} }
return uid return uid
} }
t, err := auth_model.GetAccessTokenBySHA(tokenSHA) t, err := auth_model.GetAccessTokenBySHA(ctx, tokenSHA)
if err != nil { if err != nil {
if auth_model.IsErrAccessTokenNotExist(err) { if auth_model.IsErrAccessTokenNotExist(err) {
// check task token // check task token
task, err := actions_model.GetRunningTaskByToken(db.DefaultContext, tokenSHA) task, err := actions_model.GetRunningTaskByToken(ctx, tokenSHA)
if err == nil && task != nil { if err == nil && task != nil {
log.Trace("Basic Authorization: Valid AccessToken for task[%d]", task.ID) log.Trace("Basic Authorization: Valid AccessToken for task[%d]", task.ID)
@ -112,7 +112,7 @@ func (o *OAuth2) userIDFromToken(tokenSHA string, store DataStore) int64 {
return 0 return 0
} }
t.UpdatedUnix = timeutil.TimeStampNow() t.UpdatedUnix = timeutil.TimeStampNow()
if err = auth_model.UpdateAccessToken(t); err != nil { if err = auth_model.UpdateAccessToken(ctx, t); err != nil {
log.Error("UpdateAccessToken: %v", err) log.Error("UpdateAccessToken: %v", err)
} }
store.GetData()["IsApiToken"] = true store.GetData()["IsApiToken"] = true
@ -134,7 +134,7 @@ func (o *OAuth2) Verify(req *http.Request, w http.ResponseWriter, store DataStor
return nil, nil return nil, nil
} }
id := o.userIDFromToken(token, store) id := o.userIDFromToken(req.Context(), token, store)
if id <= 0 && id != -2 { // -2 means actions, so we need to allow it. if id <= 0 && id != -2 { // -2 means actions, so we need to allow it.
return nil, user_model.ErrUserNotExist{} return nil, user_model.ErrUserNotExist{}

View File

@ -4,21 +4,22 @@
package issue package issue
import ( import (
"code.gitea.io/gitea/models/db" "context"
issues_model "code.gitea.io/gitea/models/issues" issues_model "code.gitea.io/gitea/models/issues"
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
notify_service "code.gitea.io/gitea/services/notify" notify_service "code.gitea.io/gitea/services/notify"
) )
// ChangeContent changes issue content, as the given user. // ChangeContent changes issue content, as the given user.
func ChangeContent(issue *issues_model.Issue, doer *user_model.User, content string) (err error) { func ChangeContent(ctx context.Context, issue *issues_model.Issue, doer *user_model.User, content string) (err error) {
oldContent := issue.Content oldContent := issue.Content
if err := issues_model.ChangeIssueContent(issue, doer, content); err != nil { if err := issues_model.ChangeIssueContent(issue, doer, content); err != nil {
return err return err
} }
notify_service.IssueChangeContent(db.DefaultContext, doer, issue, oldContent) notify_service.IssueChangeContent(ctx, doer, issue, oldContent)
return nil return nil
} }

View File

@ -113,7 +113,7 @@ func TestGiteaUploadRepo(t *testing.T) {
assert.NoError(t, issues[0].LoadDiscussComments(db.DefaultContext)) assert.NoError(t, issues[0].LoadDiscussComments(db.DefaultContext))
assert.Empty(t, issues[0].Comments) assert.Empty(t, issues[0].Comments)
pulls, _, err := issues_model.PullRequests(repo.ID, &issues_model.PullRequestsOptions{ pulls, _, err := issues_model.PullRequests(db.DefaultContext, repo.ID, &issues_model.PullRequestsOptions{
SortType: "oldest", SortType: "oldest",
}) })
assert.NoError(t, err) assert.NoError(t, err)

View File

@ -14,14 +14,14 @@ import (
) )
// TeamAddRepository adds new repository to team of organization. // TeamAddRepository adds new repository to team of organization.
func TeamAddRepository(t *organization.Team, repo *repo_model.Repository) (err error) { func TeamAddRepository(ctx context.Context, t *organization.Team, repo *repo_model.Repository) (err error) {
if repo.OwnerID != t.OrgID { if repo.OwnerID != t.OrgID {
return errors.New("repository does not belong to organization") return errors.New("repository does not belong to organization")
} else if organization.HasTeamRepo(db.DefaultContext, t.OrgID, t.ID, repo.ID) { } else if organization.HasTeamRepo(ctx, t.OrgID, t.ID, repo.ID) {
return nil return nil
} }
return db.WithTx(db.DefaultContext, func(ctx context.Context) error { return db.WithTx(ctx, func(ctx context.Context) error {
return models.AddRepository(ctx, t, repo) return models.AddRepository(ctx, t, repo)
}) })
} }

View File

@ -6,6 +6,7 @@ package org
import ( import (
"testing" "testing"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/organization" "code.gitea.io/gitea/models/organization"
repo_model "code.gitea.io/gitea/models/repo" repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
@ -19,7 +20,7 @@ func TestTeam_AddRepository(t *testing.T) {
testSuccess := func(teamID, repoID int64) { testSuccess := func(teamID, repoID int64) {
team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID})
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID})
assert.NoError(t, TeamAddRepository(team, repo)) assert.NoError(t, TeamAddRepository(db.DefaultContext, team, repo))
unittest.AssertExistsAndLoadBean(t, &organization.TeamRepo{TeamID: teamID, RepoID: repoID}) unittest.AssertExistsAndLoadBean(t, &organization.TeamRepo{TeamID: teamID, RepoID: repoID})
unittest.CheckConsistencyFor(t, &organization.Team{ID: teamID}, &repo_model.Repository{ID: repoID}) unittest.CheckConsistencyFor(t, &organization.Team{ID: teamID}, &repo_model.Repository{ID: repoID})
} }
@ -28,6 +29,6 @@ func TestTeam_AddRepository(t *testing.T) {
team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 1}) team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 1})
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
assert.Error(t, TeamAddRepository(team, repo)) assert.Error(t, TeamAddRepository(db.DefaultContext, team, repo))
unittest.CheckConsistencyFor(t, &organization.Team{ID: 1}, &repo_model.Repository{ID: 1}) unittest.CheckConsistencyFor(t, &organization.Team{ID: 1}, &repo_model.Repository{ID: 1})
} }

View File

@ -39,13 +39,13 @@ func GetOrCreateRepositoryVersion(ownerID int64) (*packages_model.PackageVersion
} }
// GetOrCreateKeyPair gets or creates the RSA keys used to sign repository files // GetOrCreateKeyPair gets or creates the RSA keys used to sign repository files
func GetOrCreateKeyPair(ownerID int64) (string, string, error) { func GetOrCreateKeyPair(ctx context.Context, ownerID int64) (string, string, error) {
priv, err := user_model.GetSetting(ownerID, alpine_module.SettingKeyPrivate) priv, err := user_model.GetSetting(ctx, ownerID, alpine_module.SettingKeyPrivate)
if err != nil && !errors.Is(err, util.ErrNotExist) { if err != nil && !errors.Is(err, util.ErrNotExist) {
return "", "", err return "", "", err
} }
pub, err := user_model.GetSetting(ownerID, alpine_module.SettingKeyPublic) pub, err := user_model.GetSetting(ctx, ownerID, alpine_module.SettingKeyPublic)
if err != nil && !errors.Is(err, util.ErrNotExist) { if err != nil && !errors.Is(err, util.ErrNotExist) {
return "", "", err return "", "", err
} }
@ -56,11 +56,11 @@ func GetOrCreateKeyPair(ownerID int64) (string, string, error) {
return "", "", err return "", "", err
} }
if err := user_model.SetUserSetting(ownerID, alpine_module.SettingKeyPrivate, priv); err != nil { if err := user_model.SetUserSetting(ctx, ownerID, alpine_module.SettingKeyPrivate, priv); err != nil {
return "", "", err return "", "", err
} }
if err := user_model.SetUserSetting(ownerID, alpine_module.SettingKeyPublic, pub); err != nil { if err := user_model.SetUserSetting(ctx, ownerID, alpine_module.SettingKeyPublic, pub); err != nil {
return "", "", err return "", "", err
} }
} }
@ -244,7 +244,7 @@ func buildPackagesIndex(ctx context.Context, ownerID int64, repoVersion *package
return err return err
} }
priv, _, err := GetOrCreateKeyPair(ownerID) priv, _, err := GetOrCreateKeyPair(ctx, ownerID)
if err != nil { if err != nil {
return err return err
} }

View File

@ -37,13 +37,13 @@ func GetOrCreateRepositoryVersion(ownerID int64) (*packages_model.PackageVersion
} }
// GetOrCreateKeyPair gets or creates the PGP keys used to sign repository files // GetOrCreateKeyPair gets or creates the PGP keys used to sign repository files
func GetOrCreateKeyPair(ownerID int64) (string, string, error) { func GetOrCreateKeyPair(ctx context.Context, ownerID int64) (string, string, error) {
priv, err := user_model.GetSetting(ownerID, debian_module.SettingKeyPrivate) priv, err := user_model.GetSetting(ctx, ownerID, debian_module.SettingKeyPrivate)
if err != nil && !errors.Is(err, util.ErrNotExist) { if err != nil && !errors.Is(err, util.ErrNotExist) {
return "", "", err return "", "", err
} }
pub, err := user_model.GetSetting(ownerID, debian_module.SettingKeyPublic) pub, err := user_model.GetSetting(ctx, ownerID, debian_module.SettingKeyPublic)
if err != nil && !errors.Is(err, util.ErrNotExist) { if err != nil && !errors.Is(err, util.ErrNotExist) {
return "", "", err return "", "", err
} }
@ -54,11 +54,11 @@ func GetOrCreateKeyPair(ownerID int64) (string, string, error) {
return "", "", err return "", "", err
} }
if err := user_model.SetUserSetting(ownerID, debian_module.SettingKeyPrivate, priv); err != nil { if err := user_model.SetUserSetting(ctx, ownerID, debian_module.SettingKeyPrivate, priv); err != nil {
return "", "", err return "", "", err
} }
if err := user_model.SetUserSetting(ownerID, debian_module.SettingKeyPublic, pub); err != nil { if err := user_model.SetUserSetting(ctx, ownerID, debian_module.SettingKeyPublic, pub); err != nil {
return "", "", err return "", "", err
} }
} }
@ -306,7 +306,7 @@ func buildReleaseFiles(ctx context.Context, ownerID int64, repoVersion *packages
sort.Strings(architectures) sort.Strings(architectures)
priv, _, err := GetOrCreateKeyPair(ownerID) priv, _, err := GetOrCreateKeyPair(ctx, ownerID)
if err != nil { if err != nil {
return err return err
} }

View File

@ -38,13 +38,13 @@ func GetOrCreateRepositoryVersion(ownerID int64) (*packages_model.PackageVersion
} }
// GetOrCreateKeyPair gets or creates the PGP keys used to sign repository metadata files // GetOrCreateKeyPair gets or creates the PGP keys used to sign repository metadata files
func GetOrCreateKeyPair(ownerID int64) (string, string, error) { func GetOrCreateKeyPair(ctx context.Context, ownerID int64) (string, string, error) {
priv, err := user_model.GetSetting(ownerID, rpm_module.SettingKeyPrivate) priv, err := user_model.GetSetting(ctx, ownerID, rpm_module.SettingKeyPrivate)
if err != nil && !errors.Is(err, util.ErrNotExist) { if err != nil && !errors.Is(err, util.ErrNotExist) {
return "", "", err return "", "", err
} }
pub, err := user_model.GetSetting(ownerID, rpm_module.SettingKeyPublic) pub, err := user_model.GetSetting(ctx, ownerID, rpm_module.SettingKeyPublic)
if err != nil && !errors.Is(err, util.ErrNotExist) { if err != nil && !errors.Is(err, util.ErrNotExist) {
return "", "", err return "", "", err
} }
@ -55,11 +55,11 @@ func GetOrCreateKeyPair(ownerID int64) (string, string, error) {
return "", "", err return "", "", err
} }
if err := user_model.SetUserSetting(ownerID, rpm_module.SettingKeyPrivate, priv); err != nil { if err := user_model.SetUserSetting(ctx, ownerID, rpm_module.SettingKeyPrivate, priv); err != nil {
return "", "", err return "", "", err
} }
if err := user_model.SetUserSetting(ownerID, rpm_module.SettingKeyPublic, pub); err != nil { if err := user_model.SetUserSetting(ctx, ownerID, rpm_module.SettingKeyPublic, pub); err != nil {
return "", "", err return "", "", err
} }
} }
@ -212,6 +212,7 @@ func BuildRepositoryFiles(ctx context.Context, ownerID int64) error {
} }
return buildRepomd( return buildRepomd(
ctx,
pv, pv,
ownerID, ownerID,
[]*repoData{ []*repoData{
@ -223,7 +224,7 @@ func BuildRepositoryFiles(ctx context.Context, ownerID int64) error {
} }
// https://docs.pulpproject.org/en/2.19/plugins/pulp_rpm/tech-reference/rpm.html#repomd-xml // https://docs.pulpproject.org/en/2.19/plugins/pulp_rpm/tech-reference/rpm.html#repomd-xml
func buildRepomd(pv *packages_model.PackageVersion, ownerID int64, data []*repoData) error { func buildRepomd(ctx context.Context, pv *packages_model.PackageVersion, ownerID int64, data []*repoData) error {
type Repomd struct { type Repomd struct {
XMLName xml.Name `xml:"repomd"` XMLName xml.Name `xml:"repomd"`
Xmlns string `xml:"xmlns,attr"` Xmlns string `xml:"xmlns,attr"`
@ -241,7 +242,7 @@ func buildRepomd(pv *packages_model.PackageVersion, ownerID int64, data []*repoD
return err return err
} }
priv, _, err := GetOrCreateKeyPair(ownerID) priv, _, err := GetOrCreateKeyPair(ctx, ownerID)
if err != nil { if err != nil {
return err return err
} }

View File

@ -303,7 +303,7 @@ func manuallyMerged(ctx context.Context, pr *issues_model.PullRequest) bool {
// InitializePullRequests checks and tests untested patches of pull requests. // InitializePullRequests checks and tests untested patches of pull requests.
func InitializePullRequests(ctx context.Context) { func InitializePullRequests(ctx context.Context) {
prs, err := issues_model.GetPullRequestIDsByCheckStatus(issues_model.PullRequestStatusChecking) prs, err := issues_model.GetPullRequestIDsByCheckStatus(ctx, issues_model.PullRequestStatusChecking)
if err != nil { if err != nil {
log.Error("Find Checking PRs: %v", err) log.Error("Find Checking PRs: %v", err)
return return

View File

@ -28,7 +28,7 @@ func TestIncludesAllRepositoriesTeams(t *testing.T) {
assert.Len(t, team.Repos, len(repoIds), "%s: repo count", team.Name) assert.Len(t, team.Repos, len(repoIds), "%s: repo count", team.Name)
for i, rid := range repoIds { for i, rid := range repoIds {
if rid > 0 { if rid > 0 {
assert.True(t, HasRepository(team, rid), "%s: HasRepository(%d) %d", rid, i) assert.True(t, HasRepository(db.DefaultContext, team, rid), "%s: HasRepository(%d) %d", rid, i)
} }
} }
} }

View File

@ -286,36 +286,36 @@ func DeleteRepositoryDirectly(ctx context.Context, doer *user_model.User, uid, r
// Remove repository files. // Remove repository files.
repoPath := repo.RepoPath() repoPath := repo.RepoPath()
system_model.RemoveAllWithNotice(db.DefaultContext, "Delete repository files", repoPath) system_model.RemoveAllWithNotice(ctx, "Delete repository files", repoPath)
// Remove wiki files // Remove wiki files
if repo.HasWiki() { if repo.HasWiki() {
system_model.RemoveAllWithNotice(db.DefaultContext, "Delete repository wiki", repo.WikiPath()) system_model.RemoveAllWithNotice(ctx, "Delete repository wiki", repo.WikiPath())
} }
// Remove archives // Remove archives
for _, archive := range archivePaths { for _, archive := range archivePaths {
system_model.RemoveStorageWithNotice(db.DefaultContext, storage.RepoArchives, "Delete repo archive file", archive) system_model.RemoveStorageWithNotice(ctx, storage.RepoArchives, "Delete repo archive file", archive)
} }
// Remove lfs objects // Remove lfs objects
for _, lfsObj := range lfsPaths { for _, lfsObj := range lfsPaths {
system_model.RemoveStorageWithNotice(db.DefaultContext, storage.LFS, "Delete orphaned LFS file", lfsObj) system_model.RemoveStorageWithNotice(ctx, storage.LFS, "Delete orphaned LFS file", lfsObj)
} }
// Remove issue attachment files. // Remove issue attachment files.
for _, attachment := range attachmentPaths { for _, attachment := range attachmentPaths {
system_model.RemoveStorageWithNotice(db.DefaultContext, storage.Attachments, "Delete issue attachment", attachment) system_model.RemoveStorageWithNotice(ctx, storage.Attachments, "Delete issue attachment", attachment)
} }
// Remove release attachment files. // Remove release attachment files.
for _, releaseAttachment := range releaseAttachments { for _, releaseAttachment := range releaseAttachments {
system_model.RemoveStorageWithNotice(db.DefaultContext, storage.Attachments, "Delete release attachment", releaseAttachment) system_model.RemoveStorageWithNotice(ctx, storage.Attachments, "Delete release attachment", releaseAttachment)
} }
// Remove attachment with no issue_id and release_id. // Remove attachment with no issue_id and release_id.
for _, newAttachment := range newAttachmentPaths { for _, newAttachment := range newAttachmentPaths {
system_model.RemoveStorageWithNotice(db.DefaultContext, storage.Attachments, "Delete issue attachment", newAttachment) system_model.RemoveStorageWithNotice(ctx, storage.Attachments, "Delete issue attachment", newAttachment)
} }
if len(repo.Avatar) > 0 { if len(repo.Avatar) > 0 {
@ -390,14 +390,14 @@ func removeRepositoryFromTeam(ctx context.Context, t *organization.Team, repo *r
} }
// HasRepository returns true if given repository belong to team. // HasRepository returns true if given repository belong to team.
func HasRepository(t *organization.Team, repoID int64) bool { func HasRepository(ctx context.Context, t *organization.Team, repoID int64) bool {
return organization.HasTeamRepo(db.DefaultContext, t.OrgID, t.ID, repoID) return organization.HasTeamRepo(ctx, t.OrgID, t.ID, repoID)
} }
// RemoveRepositoryFromTeam removes repository from team of organization. // RemoveRepositoryFromTeam removes repository from team of organization.
// If the team shall include all repositories the request is ignored. // If the team shall include all repositories the request is ignored.
func RemoveRepositoryFromTeam(ctx context.Context, t *organization.Team, repoID int64) error { func RemoveRepositoryFromTeam(ctx context.Context, t *organization.Team, repoID int64) error {
if !HasRepository(t, repoID) { if !HasRepository(ctx, t, repoID) {
return nil return nil
} }

View File

@ -19,7 +19,7 @@ func TestTeam_HasRepository(t *testing.T) {
test := func(teamID, repoID int64, expected bool) { test := func(teamID, repoID int64, expected bool) {
team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID})
assert.Equal(t, expected, HasRepository(team, repoID)) assert.Equal(t, expected, HasRepository(db.DefaultContext, team, repoID))
} }
test(1, 1, false) test(1, 1, false)
test(1, 3, true) test(1, 3, true)

View File

@ -10,7 +10,6 @@ import (
"path" "path"
"strings" "strings"
"code.gitea.io/gitea/models/db"
git_model "code.gitea.io/gitea/models/git" git_model "code.gitea.io/gitea/models/git"
repo_model "code.gitea.io/gitea/models/repo" repo_model "code.gitea.io/gitea/models/repo"
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
@ -35,13 +34,13 @@ type uploadInfo struct {
lfsMetaObject *git_model.LFSMetaObject lfsMetaObject *git_model.LFSMetaObject
} }
func cleanUpAfterFailure(infos *[]uploadInfo, t *TemporaryUploadRepository, original error) error { func cleanUpAfterFailure(ctx context.Context, infos *[]uploadInfo, t *TemporaryUploadRepository, original error) error {
for _, info := range *infos { for _, info := range *infos {
if info.lfsMetaObject == nil { if info.lfsMetaObject == nil {
continue continue
} }
if !info.lfsMetaObject.Existing { if !info.lfsMetaObject.Existing {
if _, err := git_model.RemoveLFSMetaObjectByOid(db.DefaultContext, t.repo.ID, info.lfsMetaObject.Oid); err != nil { if _, err := git_model.RemoveLFSMetaObjectByOid(ctx, t.repo.ID, info.lfsMetaObject.Oid); err != nil {
original = fmt.Errorf("%w, %v", original, err) // We wrap the original error - as this is the underlying error that required the fallback original = fmt.Errorf("%w, %v", original, err) // We wrap the original error - as this is the underlying error that required the fallback
} }
} }
@ -55,7 +54,7 @@ func UploadRepoFiles(ctx context.Context, repo *repo_model.Repository, doer *use
return nil return nil
} }
uploads, err := repo_model.GetUploadsByUUIDs(opts.Files) uploads, err := repo_model.GetUploadsByUUIDs(ctx, opts.Files)
if err != nil { if err != nil {
return fmt.Errorf("GetUploadsByUUIDs [uuids: %v]: %w", opts.Files, err) return fmt.Errorf("GetUploadsByUUIDs [uuids: %v]: %w", opts.Files, err)
} }
@ -147,7 +146,7 @@ func UploadRepoFiles(ctx context.Context, repo *repo_model.Repository, doer *use
infos[i].lfsMetaObject, err = git_model.NewLFSMetaObject(ctx, infos[i].lfsMetaObject) infos[i].lfsMetaObject, err = git_model.NewLFSMetaObject(ctx, infos[i].lfsMetaObject)
if err != nil { if err != nil {
// OK Now we need to cleanup // OK Now we need to cleanup
return cleanUpAfterFailure(&infos, t, err) return cleanUpAfterFailure(ctx, &infos, t, err)
} }
// Don't move the files yet - we need to ensure that // Don't move the files yet - we need to ensure that
// everything can be inserted first // everything can be inserted first
@ -158,7 +157,7 @@ func UploadRepoFiles(ctx context.Context, repo *repo_model.Repository, doer *use
contentStore := lfs.NewContentStore() contentStore := lfs.NewContentStore()
for _, info := range infos { for _, info := range infos {
if err := uploadToLFSContentStore(info, contentStore); err != nil { if err := uploadToLFSContentStore(info, contentStore); err != nil {
return cleanUpAfterFailure(&infos, t, err) return cleanUpAfterFailure(ctx, &infos, t, err)
} }
} }
@ -167,7 +166,7 @@ func UploadRepoFiles(ctx context.Context, repo *repo_model.Repository, doer *use
return err return err
} }
return repo_model.DeleteUploads(uploads...) return repo_model.DeleteUploads(ctx, uploads...)
} }
func copyUploadedLFSFileIntoRepository(info *uploadInfo, filename2attribute2info map[string]map[string]string, t *TemporaryUploadRepository, treePath string) error { func copyUploadedLFSFileIntoRepository(info *uploadInfo, filename2attribute2info map[string]map[string]string, t *TemporaryUploadRepository, treePath string) error {

View File

@ -11,6 +11,7 @@ import (
"net/url" "net/url"
"testing" "testing"
"code.gitea.io/gitea/models/db"
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/activitypub" "code.gitea.io/gitea/modules/activitypub"
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
@ -96,7 +97,7 @@ func TestActivityPubPersonInbox(t *testing.T) {
user1, err := user_model.GetUserByName(ctx, username1) user1, err := user_model.GetUserByName(ctx, username1)
assert.NoError(t, err) assert.NoError(t, err)
user1url := fmt.Sprintf("%s/api/v1/activitypub/user-id/1#main-key", srv.URL) user1url := fmt.Sprintf("%s/api/v1/activitypub/user-id/1#main-key", srv.URL)
c, err := activitypub.NewClient(user1, user1url) c, err := activitypub.NewClient(db.DefaultContext, user1, user1url)
assert.NoError(t, err) assert.NoError(t, err)
user2inboxurl := fmt.Sprintf("%s/api/v1/activitypub/user-id/2/inbox", srv.URL) user2inboxurl := fmt.Sprintf("%s/api/v1/activitypub/user-id/2/inbox", srv.URL)

View File

@ -83,7 +83,7 @@ kPuCu6vH9brvOuYo0q8hLVNkBeXcimRpsDjLhQYzEJjoMTbaiVGnjBky+PWNiofJ
nwIDAQAB nwIDAQAB
-----END PUBLIC KEY-----` -----END PUBLIC KEY-----`
err := user_model.SetUserSetting(user.ID, chef_module.SettingPublicPem, pubPem) err := user_model.SetUserSetting(db.DefaultContext, user.ID, chef_module.SettingPublicPem, pubPem)
assert.NoError(t, err) assert.NoError(t, err)
t.Run("Authenticate", func(t *testing.T) { t.Run("Authenticate", func(t *testing.T) {