Merge remote-tracking branch 'github/main' into feature-activitypub

This commit is contained in:
Anthony Wang 2022-06-09 17:18:33 -05:00
commit 1e57f01001
No known key found for this signature in database
GPG key ID: BC96B00AEC5F2D76
579 changed files with 13380 additions and 15234 deletions

View file

@ -113,7 +113,6 @@ func apiErrorDefined(ctx *context.Context, err *namedError) {
func ReqContainerAccess(ctx *context.Context) {
if ctx.Doer == nil {
ctx.Resp.Header().Add("WWW-Authenticate", `Bearer realm="`+setting.AppURL+`v2/token"`)
ctx.Resp.Header().Add("WWW-Authenticate", `Basic`)
apiErrorDefined(ctx, errUnauthorized)
}
}

View file

@ -85,7 +85,7 @@ func AdoptRepository(ctx *context.APIContext) {
ownerName := ctx.Params(":username")
repoName := ctx.Params(":reponame")
ctxUser, err := user_model.GetUserByName(ownerName)
ctxUser, err := user_model.GetUserByName(ctx, ownerName)
if err != nil {
if user_model.IsErrUserNotExist(err) {
ctx.NotFound()
@ -96,7 +96,7 @@ func AdoptRepository(ctx *context.APIContext) {
}
// check not a repo
has, err := repo_model.IsRepositoryExist(ctxUser, repoName)
has, err := repo_model.IsRepositoryExist(ctx, ctxUser, repoName)
if err != nil {
ctx.InternalServerError(err)
return
@ -147,7 +147,7 @@ func DeleteUnadoptedRepository(ctx *context.APIContext) {
ownerName := ctx.Params(":username")
repoName := ctx.Params(":reponame")
ctxUser, err := user_model.GetUserByName(ownerName)
ctxUser, err := user_model.GetUserByName(ctx, ownerName)
if err != nil {
if user_model.IsErrUserNotExist(err) {
ctx.NotFound()
@ -158,7 +158,7 @@ func DeleteUnadoptedRepository(ctx *context.APIContext) {
}
// check not a repo
has, err := repo_model.IsRepositoryExist(ctxUser, repoName)
has, err := repo_model.IsRepositoryExist(ctx, ctxUser, repoName)
if err != nil {
ctx.InternalServerError(err)
return

View file

@ -269,7 +269,7 @@ func EditUser(ctx *context.APIContext) {
ctx.ContextUser.IsRestricted = *form.Restricted
}
if err := user_model.UpdateUser(ctx.ContextUser, emailChanged); err != nil {
if err := user_model.UpdateUser(ctx, ctx.ContextUser, emailChanged); err != nil {
if user_model.IsErrEmailAlreadyUsed(err) ||
user_model.IsErrEmailCharIsNotSupported(err) ||
user_model.IsErrEmailInvalid(err) {

View file

@ -70,9 +70,9 @@ import (
"reflect"
"strings"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/organization"
"code.gitea.io/gitea/models/perm"
access_model "code.gitea.io/gitea/models/perm/access"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unit"
user_model "code.gitea.io/gitea/models/user"
@ -109,7 +109,7 @@ func sudo() func(ctx *context.APIContext) {
if len(sudo) > 0 {
if ctx.IsSigned && ctx.Doer.IsAdmin {
user, err := user_model.GetUserByName(sudo)
user, err := user_model.GetUserByName(ctx, sudo)
if err != nil {
if user_model.IsErrUserNotExist(err) {
ctx.NotFound()
@ -144,7 +144,7 @@ func repoAssignment() func(ctx *context.APIContext) {
if ctx.IsSigned && ctx.Doer.LowerName == strings.ToLower(userName) {
owner = ctx.Doer
} else {
owner, err = user_model.GetUserByName(userName)
owner, err = user_model.GetUserByName(ctx, userName)
if err != nil {
if user_model.IsErrUserNotExist(err) {
if redirectUserID, err := user_model.LookupUserRedirect(userName); err == nil {
@ -184,7 +184,7 @@ func repoAssignment() func(ctx *context.APIContext) {
repo.Owner = owner
ctx.Repo.Repository = repo
ctx.Repo.Permission, err = models.GetUserRepoPermission(ctx, repo, ctx.Doer)
ctx.Repo.Permission, err = access_model.GetUserRepoPermission(ctx, repo, ctx.Doer)
if err != nil {
ctx.Error(http.StatusInternalServerError, "GetUserRepoPermission", err)
return
@ -468,7 +468,7 @@ func orgAssignment(args ...bool) func(ctx *context.APIContext) {
}
if assignTeam {
ctx.Org.Team, err = organization.GetTeamByID(ctx.ParamsInt64(":teamid"))
ctx.Org.Team, err = organization.GetTeamByID(ctx, ctx.ParamsInt64(":teamid"))
if err != nil {
if organization.IsErrTeamNotExist(err) {
ctx.NotFound()
@ -593,6 +593,7 @@ func bind(obj interface{}) http.HandlerFunc {
func buildAuthGroup() *auth.Group {
group := auth.NewGroup(
&auth.OAuth2{},
&auth.HTTPSign{},
&auth.Basic{}, // FIXME: this should be removed once we don't allow basic auth in API
)
if setting.Service.EnableReverseProxyAuth {
@ -831,6 +832,7 @@ func Routes() *web.Route {
Delete(reqAdmin(), repo.DeleteTeam)
}, reqToken())
m.Get("/raw/*", context.ReferencesGitRepo(), context.RepoRefForAPI, reqRepoReader(unit.TypeCode), repo.GetRawFile)
m.Get("/media/*", context.ReferencesGitRepo(), context.RepoRefForAPI, reqRepoReader(unit.TypeCode), repo.GetRawFileOrLFS)
m.Get("/archive/*", reqRepoReader(unit.TypeCode), repo.GetArchive)
m.Combo("/forks").Get(repo.ListForks).
Post(reqToken(), reqRepoReader(unit.TypeCode), bind(api.CreateForkOption{}), repo.CreateFork)

View file

@ -30,8 +30,11 @@ func NodeInfo(ctx *context.APIContext) {
nodeInfoUsage := structs.NodeInfoUsage{}
if setting.Federation.ShareUserStatistics {
info, ok := ctx.Cache.Get(cacheKeyNodeInfoUsage).(structs.NodeInfoUsage)
if !ok {
cached := false
if setting.CacheService.Enabled {
nodeInfoUsage, cached = ctx.Cache.Get(cacheKeyNodeInfoUsage).(structs.NodeInfoUsage)
}
if !cached {
usersTotal := int(user_model.CountUsers(nil))
now := time.Now()
timeOneMonthAgo := now.AddDate(0, -1, 0).Unix()
@ -42,7 +45,7 @@ func NodeInfo(ctx *context.APIContext) {
allIssues, _ := models.CountIssues(&models.IssuesOptions{})
allComments, _ := models.CountComments(&models.FindCommentsOptions{})
info = structs.NodeInfoUsage{
nodeInfoUsage = structs.NodeInfoUsage{
Users: structs.NodeInfoUsageUsers{
Total: usersTotal,
ActiveMonth: usersActiveMonth,
@ -51,12 +54,13 @@ func NodeInfo(ctx *context.APIContext) {
LocalPosts: int(allIssues),
LocalComments: int(allComments),
}
if err := ctx.Cache.Put(cacheKeyNodeInfoUsage, nodeInfoUsage, 180); err != nil {
ctx.InternalServerError(err)
return
if setting.CacheService.Enabled {
if err := ctx.Cache.Put(cacheKeyNodeInfoUsage, nodeInfoUsage, 180); err != nil {
ctx.InternalServerError(err)
return
}
}
}
nodeInfoUsage = info
}
nodeInfo := &structs.NodeInfo{

View file

@ -22,7 +22,7 @@ func NewAvailable(ctx *context.APIContext) {
// responses:
// "200":
// "$ref": "#/responses/NotificationCount"
ctx.JSON(http.StatusOK, api.NotificationCount{New: models.CountUnread(ctx.Doer)})
ctx.JSON(http.StatusOK, api.NotificationCount{New: models.CountUnread(ctx, ctx.Doer.ID)})
}
func getFindNotificationOptions(ctx *context.APIContext) *models.FindNotificationOptions {

View file

@ -115,7 +115,7 @@ func ListRepoNotifications(ctx *context.APIContext) {
return
}
nl, err := models.GetNotifications(opts)
nl, err := models.GetNotifications(ctx, opts)
if err != nil {
ctx.InternalServerError(err)
return
@ -203,7 +203,7 @@ func ReadRepoNotifications(ctx *context.APIContext) {
opts.Status = statusStringsToNotificationStatuses(statuses, []string{"unread"})
log.Error("%v", opts.Status)
}
nl, err := models.GetNotifications(opts)
nl, err := models.GetNotifications(ctx, opts)
if err != nil {
ctx.InternalServerError(err)
return

View file

@ -75,7 +75,7 @@ func ListNotifications(ctx *context.APIContext) {
return
}
nl, err := models.GetNotifications(opts)
nl, err := models.GetNotifications(ctx, opts)
if err != nil {
ctx.InternalServerError(err)
return
@ -148,7 +148,7 @@ func ReadNotifications(ctx *context.APIContext) {
statuses := ctx.FormStrings("status-types")
opts.Status = statusStringsToNotificationStatuses(statuses, []string{"unread"})
}
nl, err := models.GetNotifications(opts)
nl, err := models.GetNotifications(ctx, opts)
if err != nil {
ctx.InternalServerError(err)
return

View file

@ -51,7 +51,7 @@ func ListHooks(ctx *context.APIContext) {
return
}
orgHooks, err := webhook.ListWebhooksByOpts(opts)
orgHooks, err := webhook.ListWebhooksByOpts(ctx, opts)
if err != nil {
ctx.InternalServerError(err)
return

View file

@ -43,7 +43,7 @@ func ListLabels(ctx *context.APIContext) {
// "200":
// "$ref": "#/responses/LabelList"
labels, err := models.GetLabelsByOrgID(ctx.Org.Organization.ID, ctx.FormString("sort"), utils.GetListOptions(ctx))
labels, err := models.GetLabelsByOrgID(ctx, ctx.Org.Organization.ID, ctx.FormString("sort"), utils.GetListOptions(ctx))
if err != nil {
ctx.Error(http.StatusInternalServerError, "GetLabelsByOrgID", err)
return
@ -136,9 +136,9 @@ func GetLabel(ctx *context.APIContext) {
)
strID := ctx.Params(":id")
if intID, err2 := strconv.ParseInt(strID, 10, 64); err2 != nil {
label, err = models.GetLabelInOrgByName(ctx.Org.Organization.ID, strID)
label, err = models.GetLabelInOrgByName(ctx, ctx.Org.Organization.ID, strID)
} else {
label, err = models.GetLabelInOrgByID(ctx.Org.Organization.ID, intID)
label, err = models.GetLabelInOrgByID(ctx, ctx.Org.Organization.ID, intID)
}
if err != nil {
if models.IsErrOrgLabelNotExist(err) {
@ -183,7 +183,7 @@ func EditLabel(ctx *context.APIContext) {
// "422":
// "$ref": "#/responses/validationError"
form := web.GetForm(ctx).(*api.EditLabelOption)
label, err := models.GetLabelInOrgByID(ctx.Org.Organization.ID, ctx.ParamsInt64(":id"))
label, err := models.GetLabelInOrgByID(ctx, ctx.Org.Organization.ID, ctx.ParamsInt64(":id"))
if err != nil {
if models.IsErrOrgLabelNotExist(err) {
ctx.NotFound()

View file

@ -12,6 +12,7 @@ import (
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/organization"
"code.gitea.io/gitea/models/perm"
access_model "code.gitea.io/gitea/models/perm/access"
repo_model "code.gitea.io/gitea/models/repo"
unit_model "code.gitea.io/gitea/models/unit"
"code.gitea.io/gitea/modules/context"
@ -57,14 +58,10 @@ func ListTeams(ctx *context.APIContext) {
return
}
apiTeams := make([]*api.Team, len(teams))
for i := range teams {
if err := teams[i].GetUnits(); err != nil {
ctx.Error(http.StatusInternalServerError, "GetUnits", err)
return
}
apiTeams[i] = convert.ToTeam(teams[i])
apiTeams, err := convert.ToTeams(teams, false)
if err != nil {
ctx.Error(http.StatusInternalServerError, "ConvertToTeams", err)
return
}
ctx.SetTotalCountHeader(count)
@ -100,25 +97,10 @@ func ListUserTeams(ctx *context.APIContext) {
return
}
cache := make(map[int64]*api.Organization)
apiTeams := make([]*api.Team, len(teams))
for i := range teams {
apiOrg, ok := cache[teams[i].OrgID]
if !ok {
org, err := organization.GetOrgByID(teams[i].OrgID)
if err != nil {
ctx.Error(http.StatusInternalServerError, "GetUserByID", err)
return
}
apiOrg = convert.ToOrganization(org)
cache[teams[i].OrgID] = apiOrg
}
if err := teams[i].GetUnits(); err != nil {
ctx.Error(http.StatusInternalServerError, "teams[i].GetUnits()", err)
return
}
apiTeams[i] = convert.ToTeam(teams[i])
apiTeams[i].Organization = apiOrg
apiTeams, err := convert.ToTeams(teams, true)
if err != nil {
ctx.Error(http.StatusInternalServerError, "ConvertToTeams", err)
return
}
ctx.SetTotalCountHeader(count)
@ -143,12 +125,13 @@ func GetTeam(ctx *context.APIContext) {
// "200":
// "$ref": "#/responses/Team"
if err := ctx.Org.Team.GetUnits(); err != nil {
ctx.Error(http.StatusInternalServerError, "team.GetUnits", err)
apiTeam, err := convert.ToTeam(ctx.Org.Team)
if err != nil {
ctx.InternalServerError(err)
return
}
ctx.JSON(http.StatusOK, convert.ToTeam(ctx.Org.Team))
ctx.JSON(http.StatusOK, apiTeam)
}
func attachTeamUnits(team *organization.Team, units []string) {
@ -240,7 +223,12 @@ func CreateTeam(ctx *context.APIContext) {
return
}
ctx.JSON(http.StatusCreated, convert.ToTeam(team))
apiTeam, err := convert.ToTeam(team)
if err != nil {
ctx.InternalServerError(err)
return
}
ctx.JSON(http.StatusCreated, apiTeam)
}
// EditTeam api for edit a team
@ -317,7 +305,13 @@ func EditTeam(ctx *context.APIContext) {
ctx.Error(http.StatusInternalServerError, "EditTeam", err)
return
}
ctx.JSON(http.StatusOK, convert.ToTeam(team))
apiTeam, err := convert.ToTeam(team)
if err != nil {
ctx.InternalServerError(err)
return
}
ctx.JSON(http.StatusOK, apiTeam)
}
// DeleteTeam api for delete a team
@ -547,7 +541,7 @@ func GetTeamRepos(ctx *context.APIContext) {
}
repos := make([]*api.Repository, len(teamRepos))
for i, repo := range teamRepos {
access, err := models.AccessLevel(ctx.Doer, repo)
access, err := access_model.AccessLevel(ctx.Doer, repo)
if err != nil {
ctx.Error(http.StatusInternalServerError, "GetTeamRepos", err)
return
@ -598,7 +592,7 @@ func GetTeamRepo(ctx *context.APIContext) {
return
}
access, err := models.AccessLevel(ctx.Doer, repo)
access, err := access_model.AccessLevel(ctx.Doer, repo)
if err != nil {
ctx.Error(http.StatusInternalServerError, "GetTeamRepos", err)
return
@ -655,7 +649,7 @@ func AddTeamRepository(ctx *context.APIContext) {
if ctx.Written() {
return
}
if access, err := models.AccessLevel(ctx.Doer, repo); err != nil {
if access, err := access_model.AccessLevel(ctx.Doer, repo); err != nil {
ctx.Error(http.StatusInternalServerError, "AccessLevel", err)
return
} else if access < perm.AccessModeAdmin {
@ -705,7 +699,7 @@ func RemoveTeamRepository(ctx *context.APIContext) {
if ctx.Written() {
return
}
if access, err := models.AccessLevel(ctx.Doer, repo); err != nil {
if access, err := access_model.AccessLevel(ctx.Doer, repo); err != nil {
ctx.Error(http.StatusInternalServerError, "AccessLevel", err)
return
} else if access < perm.AccessModeAdmin {
@ -781,17 +775,10 @@ func SearchTeam(ctx *context.APIContext) {
return
}
apiTeams := make([]*api.Team, len(teams))
for i := range teams {
if err := teams[i].GetUnits(); err != nil {
log.Error("Team GetUnits failed: %v", err)
ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
"ok": false,
"error": "SearchTeam failed to get units",
})
return
}
apiTeams[i] = convert.ToTeam(teams[i])
apiTeams, err := convert.ToTeams(teams, false)
if err != nil {
ctx.InternalServerError(err)
return
}
ctx.SetLinkHeader(int(maxResults), listOptions.PageSize)

View file

@ -70,7 +70,7 @@ func GetBranch(ctx *context.APIContext) {
return
}
branchProtection, err := models.GetProtectedBranchBy(ctx.Repo.Repository.ID, branchName)
branchProtection, err := models.GetProtectedBranchBy(ctx, ctx.Repo.Repository.ID, branchName)
if err != nil {
ctx.Error(http.StatusInternalServerError, "GetBranchProtection", err)
return
@ -206,7 +206,7 @@ func CreateBranch(ctx *context.APIContext) {
return
}
branchProtection, err := models.GetProtectedBranchBy(ctx.Repo.Repository.ID, branch.Name)
branchProtection, err := models.GetProtectedBranchBy(ctx, ctx.Repo.Repository.ID, branch.Name)
if err != nil {
ctx.Error(http.StatusInternalServerError, "GetBranchProtection", err)
return
@ -271,7 +271,7 @@ func ListBranches(ctx *context.APIContext) {
ctx.Error(http.StatusInternalServerError, "GetCommit", err)
return
}
branchProtection, err := models.GetProtectedBranchBy(ctx.Repo.Repository.ID, branches[i].Name)
branchProtection, err := models.GetProtectedBranchBy(ctx, ctx.Repo.Repository.ID, branches[i].Name)
if err != nil {
ctx.Error(http.StatusInternalServerError, "GetBranchProtection", err)
return
@ -320,7 +320,7 @@ func GetBranchProtection(ctx *context.APIContext) {
repo := ctx.Repo.Repository
bpName := ctx.Params(":name")
bp, err := models.GetProtectedBranchBy(repo.ID, bpName)
bp, err := models.GetProtectedBranchBy(ctx, repo.ID, bpName)
if err != nil {
ctx.Error(http.StatusInternalServerError, "GetProtectedBranchByID", err)
return
@ -412,7 +412,7 @@ func CreateBranchProtection(ctx *context.APIContext) {
return
}
protectBranch, err := models.GetProtectedBranchBy(repo.ID, form.BranchName)
protectBranch, err := models.GetProtectedBranchBy(ctx, repo.ID, form.BranchName)
if err != nil {
ctx.Error(http.StatusInternalServerError, "GetProtectBranchOfRepoByName", err)
return
@ -523,7 +523,7 @@ func CreateBranchProtection(ctx *context.APIContext) {
}
// Reload from db to get all whitelists
bp, err := models.GetProtectedBranchBy(ctx.Repo.Repository.ID, form.BranchName)
bp, err := models.GetProtectedBranchBy(ctx, ctx.Repo.Repository.ID, form.BranchName)
if err != nil {
ctx.Error(http.StatusInternalServerError, "GetProtectedBranchByID", err)
return
@ -575,7 +575,7 @@ func EditBranchProtection(ctx *context.APIContext) {
form := web.GetForm(ctx).(*api.EditBranchProtectionOption)
repo := ctx.Repo.Repository
bpName := ctx.Params(":name")
protectBranch, err := models.GetProtectedBranchBy(repo.ID, bpName)
protectBranch, err := models.GetProtectedBranchBy(ctx, repo.ID, bpName)
if err != nil {
ctx.Error(http.StatusInternalServerError, "GetProtectedBranchByID", err)
return
@ -758,7 +758,7 @@ func EditBranchProtection(ctx *context.APIContext) {
}
// Reload from db to ensure get all whitelists
bp, err := models.GetProtectedBranchBy(repo.ID, bpName)
bp, err := models.GetProtectedBranchBy(ctx, repo.ID, bpName)
if err != nil {
ctx.Error(http.StatusInternalServerError, "GetProtectedBranchBy", err)
return
@ -802,7 +802,7 @@ func DeleteBranchProtection(ctx *context.APIContext) {
repo := ctx.Repo.Repository
bpName := ctx.Params(":name")
bp, err := models.GetProtectedBranchBy(repo.ID, bpName)
bp, err := models.GetProtectedBranchBy(ctx, repo.ID, bpName)
if err != nil {
ctx.Error(http.StatusInternalServerError, "GetProtectedBranchByID", err)
return

View file

@ -11,6 +11,8 @@ import (
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/perm"
access_model "code.gitea.io/gitea/models/perm/access"
repo_model "code.gitea.io/gitea/models/repo"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/convert"
@ -49,13 +51,13 @@ func ListCollaborators(ctx *context.APIContext) {
// "200":
// "$ref": "#/responses/UserList"
count, err := models.CountCollaborators(ctx.Repo.Repository.ID)
count, err := repo_model.CountCollaborators(ctx.Repo.Repository.ID)
if err != nil {
ctx.InternalServerError(err)
return
}
collaborators, err := models.GetCollaborators(ctx.Repo.Repository.ID, utils.GetListOptions(ctx))
collaborators, err := repo_model.GetCollaborators(ctx, ctx.Repo.Repository.ID, utils.GetListOptions(ctx))
if err != nil {
ctx.Error(http.StatusInternalServerError, "ListCollaborators", err)
return
@ -101,7 +103,7 @@ func IsCollaborator(ctx *context.APIContext) {
// "422":
// "$ref": "#/responses/validationError"
user, err := user_model.GetUserByName(ctx.Params(":collaborator"))
user, err := user_model.GetUserByName(ctx, ctx.Params(":collaborator"))
if err != nil {
if user_model.IsErrUserNotExist(err) {
ctx.Error(http.StatusUnprocessableEntity, "", err)
@ -110,7 +112,7 @@ func IsCollaborator(ctx *context.APIContext) {
}
return
}
isColab, err := models.IsCollaborator(ctx.Repo.Repository.ID, user.ID)
isColab, err := repo_model.IsCollaborator(ctx, ctx.Repo.Repository.ID, user.ID)
if err != nil {
ctx.Error(http.StatusInternalServerError, "IsCollaborator", err)
return
@ -157,7 +159,7 @@ func AddCollaborator(ctx *context.APIContext) {
form := web.GetForm(ctx).(*api.AddCollaboratorOption)
collaborator, err := user_model.GetUserByName(ctx.Params(":collaborator"))
collaborator, err := user_model.GetUserByName(ctx, ctx.Params(":collaborator"))
if err != nil {
if user_model.IsErrUserNotExist(err) {
ctx.Error(http.StatusUnprocessableEntity, "", err)
@ -178,7 +180,7 @@ func AddCollaborator(ctx *context.APIContext) {
}
if form.Permission != nil {
if err := models.ChangeCollaborationAccessMode(ctx.Repo.Repository, collaborator.ID, perm.ParseAccessMode(*form.Permission)); err != nil {
if err := repo_model.ChangeCollaborationAccessMode(ctx.Repo.Repository, collaborator.ID, perm.ParseAccessMode(*form.Permission)); err != nil {
ctx.Error(http.StatusInternalServerError, "ChangeCollaborationAccessMode", err)
return
}
@ -216,7 +218,7 @@ func DeleteCollaborator(ctx *context.APIContext) {
// "422":
// "$ref": "#/responses/validationError"
collaborator, err := user_model.GetUserByName(ctx.Params(":collaborator"))
collaborator, err := user_model.GetUserByName(ctx, ctx.Params(":collaborator"))
if err != nil {
if user_model.IsErrUserNotExist(err) {
ctx.Error(http.StatusUnprocessableEntity, "", err)
@ -269,7 +271,7 @@ func GetRepoPermissions(ctx *context.APIContext) {
return
}
collaborator, err := user_model.GetUserByName(ctx.Params(":collaborator"))
collaborator, err := user_model.GetUserByName(ctx, ctx.Params(":collaborator"))
if err != nil {
if user_model.IsErrUserNotExist(err) {
ctx.Error(http.StatusNotFound, "GetUserByName", err)
@ -279,7 +281,7 @@ func GetRepoPermissions(ctx *context.APIContext) {
return
}
permission, err := models.GetUserRepoPermission(ctx, ctx.Repo.Repository, collaborator)
permission, err := access_model.GetUserRepoPermission(ctx, ctx.Repo.Repository, collaborator)
if err != nil {
ctx.Error(http.StatusInternalServerError, "GetUserRepoPermission", err)
return
@ -310,7 +312,7 @@ func GetReviewers(ctx *context.APIContext) {
// "200":
// "$ref": "#/responses/UserList"
reviewers, err := models.GetReviewers(ctx.Repo.Repository, ctx.Doer.ID, 0)
reviewers, err := repo_model.GetReviewers(ctx, ctx.Repo.Repository, ctx.Doer.ID, 0)
if err != nil {
ctx.Error(http.StatusInternalServerError, "ListCollaborators", err)
return
@ -340,7 +342,7 @@ func GetAssignees(ctx *context.APIContext) {
// "200":
// "$ref": "#/responses/UserList"
assignees, err := models.GetRepoAssignees(ctx.Repo.Repository)
assignees, err := repo_model.GetRepoAssignees(ctx, ctx.Repo.Repository)
if err != nil {
ctx.Error(http.StatusInternalServerError, "ListCollaborators", err)
return

View file

@ -6,8 +6,10 @@
package repo
import (
"bytes"
"encoding/base64"
"fmt"
"io"
"net/http"
"path"
"time"
@ -18,7 +20,11 @@ import (
"code.gitea.io/gitea/modules/cache"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/httpcache"
"code.gitea.io/gitea/modules/lfs"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/storage"
api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/web"
"code.gitea.io/gitea/routers/common"
@ -75,6 +81,142 @@ func GetRawFile(ctx *context.APIContext) {
}
}
// GetRawFileOrLFS get a file by repo's path, redirecting to LFS if necessary.
func GetRawFileOrLFS(ctx *context.APIContext) {
// swagger:operation GET /repos/{owner}/{repo}/media/{filepath} repository repoGetRawFileOrLFS
// ---
// summary: Get a file or it's LFS object from a repository
// parameters:
// - name: owner
// in: path
// description: owner of the repo
// type: string
// required: true
// - name: repo
// in: path
// description: name of the repo
// type: string
// required: true
// - name: filepath
// in: path
// description: filepath of the file to get
// type: string
// required: true
// - name: ref
// in: query
// description: "The name of the commit/branch/tag. Default the repositorys default branch (usually master)"
// type: string
// required: false
// responses:
// 200:
// description: Returns raw file content.
// "404":
// "$ref": "#/responses/notFound"
if ctx.Repo.Repository.IsEmpty {
ctx.NotFound()
return
}
blob, lastModified := getBlobForEntry(ctx)
if ctx.Written() {
return
}
// LFS Pointer files are at most 1024 bytes - so any blob greater than 1024 bytes cannot be an LFS file
if blob.Size() > 1024 {
// First handle caching for the blob
if httpcache.HandleGenericETagTimeCache(ctx.Req, ctx.Resp, `"`+blob.ID.String()+`"`, lastModified) {
return
}
// OK not cached - serve!
if err := common.ServeBlob(ctx.Context, blob, lastModified); err != nil {
ctx.ServerError("ServeBlob", err)
}
return
}
// OK, now the blob is known to have at most 1024 bytes we can simply read this in in one go (This saves reading it twice)
dataRc, err := blob.DataAsync()
if err != nil {
ctx.ServerError("DataAsync", err)
return
}
buf, err := io.ReadAll(dataRc)
if err != nil {
_ = dataRc.Close()
ctx.ServerError("DataAsync", err)
return
}
if err := dataRc.Close(); err != nil {
log.Error("Error whilst closing blob %s reader in %-v. Error: %v", blob.ID, ctx.Context.Repo.Repository, err)
}
// Check if the blob represents a pointer
pointer, _ := lfs.ReadPointer(bytes.NewReader(buf))
// if its not a pointer just serve the data directly
if !pointer.IsValid() {
// First handle caching for the blob
if httpcache.HandleGenericETagTimeCache(ctx.Req, ctx.Resp, `"`+blob.ID.String()+`"`, lastModified) {
return
}
// OK not cached - serve!
if err := common.ServeData(ctx.Context, ctx.Repo.TreePath, blob.Size(), bytes.NewReader(buf)); err != nil {
ctx.ServerError("ServeBlob", err)
}
return
}
// Now check if there is a meta object for this pointer
meta, err := models.GetLFSMetaObjectByOid(ctx.Repo.Repository.ID, pointer.Oid)
// If there isn't one just serve the data directly
if err == models.ErrLFSObjectNotExist {
// Handle caching for the blob SHA (not the LFS object OID)
if httpcache.HandleGenericETagTimeCache(ctx.Req, ctx.Resp, `"`+blob.ID.String()+`"`, lastModified) {
return
}
if err := common.ServeData(ctx.Context, ctx.Repo.TreePath, blob.Size(), bytes.NewReader(buf)); err != nil {
ctx.ServerError("ServeBlob", err)
}
return
} else if err != nil {
ctx.ServerError("GetLFSMetaObjectByOid", err)
return
}
// Handle caching for the LFS object OID
if httpcache.HandleGenericETagCache(ctx.Req, ctx.Resp, `"`+pointer.Oid+`"`) {
return
}
if setting.LFS.ServeDirect {
// If we have a signed url (S3, object storage), redirect to this directly.
u, err := storage.LFS.URL(pointer.RelativePath(), blob.Name())
if u != nil && err == nil {
ctx.Redirect(u.String())
return
}
}
lfsDataRc, err := lfs.ReadMetaObject(meta.Pointer)
if err != nil {
ctx.ServerError("ReadMetaObject", err)
return
}
defer lfsDataRc.Close()
if err := common.ServeData(ctx.Context, ctx.Repo.TreePath, meta.Size, lfsDataRc); err != nil {
ctx.ServerError("ServeData", err)
}
}
func getBlobForEntry(ctx *context.APIContext) (blob *git.Blob, lastModified time.Time) {
entry, err := ctx.Repo.Commit.GetTreeEntryByPath(ctx.Repo.TreePath)
if err != nil {
@ -209,7 +351,7 @@ func GetEditorconfig(ctx *context.APIContext) {
// canWriteFiles returns true if repository is editable and user has proper access level.
func canWriteFiles(ctx *context.APIContext, branch string) bool {
return ctx.Repo.Permission.CanWriteToBranch(ctx.Doer, branch) &&
return ctx.Repo.CanWriteToBranch(ctx.Doer, branch) &&
!ctx.Repo.Repository.IsMirror &&
!ctx.Repo.Repository.IsArchived
}

View file

@ -9,9 +9,9 @@ import (
"fmt"
"net/http"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/organization"
"code.gitea.io/gitea/models/perm"
access_model "code.gitea.io/gitea/models/perm/access"
repo_model "code.gitea.io/gitea/models/repo"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/context"
@ -59,7 +59,7 @@ func ListForks(ctx *context.APIContext) {
}
apiForks := make([]*api.Repository, len(forks))
for i, fork := range forks {
access, err := models.AccessLevel(ctx.Doer, fork)
access, err := access_model.AccessLevel(ctx.Doer, fork)
if err != nil {
ctx.Error(http.StatusInternalServerError, "AccessLevel", err)
return

View file

@ -60,7 +60,7 @@ func ListHooks(ctx *context.APIContext) {
return
}
hooks, err := webhook.ListWebhooksByOpts(opts)
hooks, err := webhook.ListWebhooksByOpts(ctx, opts)
if err != nil {
ctx.InternalServerError(err)
return

View file

@ -16,6 +16,8 @@ import (
"code.gitea.io/gitea/models/db"
issues_model "code.gitea.io/gitea/models/issues"
"code.gitea.io/gitea/models/organization"
access_model "code.gitea.io/gitea/models/perm/access"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unit"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/context"
@ -129,7 +131,7 @@ func SearchIssues(ctx *context.APIContext) {
}
// find repos user can access (for issue search)
opts := &models.SearchRepoOptions{
opts := &repo_model.SearchRepoOptions{
Private: false,
AllPublic: true,
TopicOnly: false,
@ -144,7 +146,7 @@ func SearchIssues(ctx *context.APIContext) {
opts.AllLimited = true
}
if ctx.FormString("owner") != "" {
owner, err := user_model.GetUserByName(ctx.FormString("owner"))
owner, err := user_model.GetUserByName(ctx, ctx.FormString("owner"))
if err != nil {
if user_model.IsErrUserNotExist(err) {
ctx.Error(http.StatusBadRequest, "Owner not found", err)
@ -163,7 +165,7 @@ func SearchIssues(ctx *context.APIContext) {
ctx.Error(http.StatusBadRequest, "", "Owner organisation is required for filtering on team")
return
}
team, err := organization.GetTeam(opts.OwnerID, ctx.FormString("team"))
team, err := organization.GetTeam(ctx, opts.OwnerID, ctx.FormString("team"))
if err != nil {
if organization.IsErrTeamNotExist(err) {
ctx.Error(http.StatusBadRequest, "Team not found", err)
@ -175,8 +177,8 @@ func SearchIssues(ctx *context.APIContext) {
opts.TeamID = team.ID
}
repoCond := models.SearchRepositoryCondition(opts)
repoIDs, _, err := models.SearchRepositoryIDs(opts)
repoCond := repo_model.SearchRepositoryCondition(opts)
repoIDs, _, err := repo_model.SearchRepositoryIDs(opts)
if err != nil {
ctx.Error(http.StatusInternalServerError, "SearchRepositoryByName", err)
return
@ -501,7 +503,7 @@ func getUserIDForFilter(ctx *context.APIContext, queryName string) int64 {
return 0
}
user, err := user_model.GetUserByName(userName)
user, err := user_model.GetUserByName(ctx, userName)
if user_model.IsErrUserNotExist(err) {
ctx.NotFound(err)
return 0
@ -629,7 +631,7 @@ func CreateIssue(ctx *context.APIContext) {
return
}
valid, err := models.CanBeAssigned(assignee, ctx.Repo.Repository, false)
valid, err := access_model.CanBeAssigned(ctx, assignee, ctx.Repo.Repository, false)
if err != nil {
ctx.Error(http.StatusInternalServerError, "canBeAssigned", err)
return

View file

@ -11,6 +11,7 @@ import (
"net/http"
"code.gitea.io/gitea/models"
access_model "code.gitea.io/gitea/models/perm/access"
repo_model "code.gitea.io/gitea/models/repo"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/context"
@ -78,7 +79,7 @@ func ListIssueComments(ctx *context.APIContext) {
Type: models.CommentTypeComment,
}
comments, err := models.FindComments(opts)
comments, err := models.FindComments(ctx, opts)
if err != nil {
ctx.Error(http.StatusInternalServerError, "FindComments", err)
return
@ -171,7 +172,7 @@ func ListIssueCommentsAndTimeline(ctx *context.APIContext) {
Type: models.CommentTypeUnknown,
}
comments, err := models.FindComments(opts)
comments, err := models.FindComments(ctx, opts)
if err != nil {
ctx.Error(http.StatusInternalServerError, "FindComments", err)
return
@ -203,7 +204,7 @@ func isXRefCommentAccessible(ctx stdCtx.Context, user *user_model.User, c *model
if err != nil {
return false
}
perm, err := models.GetUserRepoPermission(ctx, c.RefRepo, user)
perm, err := access_model.GetUserRepoPermission(ctx, c.RefRepo, user)
if err != nil {
return false
}
@ -268,7 +269,7 @@ func ListRepoIssueComments(ctx *context.APIContext) {
Before: before,
}
comments, err := models.FindComments(opts)
comments, err := models.FindComments(ctx, opts)
if err != nil {
ctx.Error(http.StatusInternalServerError, "FindComments", err)
return
@ -398,7 +399,7 @@ func GetIssueComment(ctx *context.APIContext) {
// "404":
// "$ref": "#/responses/notFound"
comment, err := models.GetCommentByID(ctx.ParamsInt64(":id"))
comment, err := models.GetCommentByID(ctx, ctx.ParamsInt64(":id"))
if err != nil {
if models.IsErrCommentNotExist(err) {
ctx.NotFound(err)
@ -525,7 +526,7 @@ func EditIssueCommentDeprecated(ctx *context.APIContext) {
}
func editIssueComment(ctx *context.APIContext, form api.EditIssueCommentOption) {
comment, err := models.GetCommentByID(ctx.ParamsInt64(":id"))
comment, err := models.GetCommentByID(ctx, ctx.ParamsInt64(":id"))
if err != nil {
if models.IsErrCommentNotExist(err) {
ctx.NotFound(err)
@ -628,7 +629,7 @@ func DeleteIssueCommentDeprecated(ctx *context.APIContext) {
}
func deleteIssueComment(ctx *context.APIContext) {
comment, err := models.GetCommentByID(ctx.ParamsInt64(":id"))
comment, err := models.GetCommentByID(ctx, ctx.ParamsInt64(":id"))
if err != nil {
if models.IsErrCommentNotExist(err) {
ctx.NotFound(err)

View file

@ -111,7 +111,7 @@ func AddIssueLabels(ctx *context.APIContext) {
return
}
labels, err = models.GetLabelsByIssueID(issue.ID)
labels, err = models.GetLabelsByIssueID(ctx, issue.ID)
if err != nil {
ctx.Error(http.StatusInternalServerError, "GetLabelsByIssueID", err)
return
@ -173,7 +173,7 @@ func DeleteIssueLabel(ctx *context.APIContext) {
return
}
label, err := models.GetLabelByID(ctx.ParamsInt64(":id"))
label, err := models.GetLabelByID(ctx, ctx.ParamsInt64(":id"))
if err != nil {
if models.IsErrLabelNotExist(err) {
ctx.Error(http.StatusUnprocessableEntity, "", err)
@ -237,7 +237,7 @@ func ReplaceIssueLabels(ctx *context.APIContext) {
return
}
labels, err = models.GetLabelsByIssueID(issue.ID)
labels, err = models.GetLabelsByIssueID(ctx, issue.ID)
if err != nil {
ctx.Error(http.StatusInternalServerError, "GetLabelsByIssueID", err)
return

View file

@ -49,7 +49,7 @@ func GetIssueCommentReactions(ctx *context.APIContext) {
// "403":
// "$ref": "#/responses/forbidden"
comment, err := models.GetCommentByID(ctx.ParamsInt64(":id"))
comment, err := models.GetCommentByID(ctx, ctx.ParamsInt64(":id"))
if err != nil {
if models.IsErrCommentNotExist(err) {
ctx.NotFound(err)
@ -176,7 +176,7 @@ func DeleteIssueCommentReaction(ctx *context.APIContext) {
}
func changeIssueCommentReaction(ctx *context.APIContext, form api.EditReactionOption, isCreateType bool) {
comment, err := models.GetCommentByID(ctx.ParamsInt64(":id"))
comment, err := models.GetCommentByID(ctx, ctx.ParamsInt64(":id"))
if err != nil {
if models.IsErrCommentNotExist(err) {
ctx.NotFound(err)

View file

@ -116,7 +116,7 @@ func setIssueSubscription(ctx *context.APIContext, watch bool) {
return
}
user, err := user_model.GetUserByName(ctx.Params(":user"))
user, err := user_model.GetUserByName(ctx, ctx.Params(":user"))
if err != nil {
if user_model.IsErrUserNotExist(err) {
ctx.NotFound()
@ -263,7 +263,7 @@ func GetIssueSubscribers(ctx *context.APIContext) {
return
}
iwl, err := models.GetIssueWatchers(issue.ID, utils.GetListOptions(ctx))
iwl, err := models.GetIssueWatchers(ctx, issue.ID, utils.GetListOptions(ctx))
if err != nil {
ctx.Error(http.StatusInternalServerError, "GetIssueWatchers", err)
return
@ -284,7 +284,7 @@ func GetIssueSubscribers(ctx *context.APIContext) {
apiUsers = append(apiUsers, convert.ToUser(v, ctx.Doer))
}
count, err := models.CountIssueWatchers(issue.ID)
count, err := models.CountIssueWatchers(ctx, issue.ID)
if err != nil {
ctx.Error(http.StatusInternalServerError, "CountIssueWatchers", err)
return

View file

@ -94,7 +94,7 @@ func ListTrackedTimes(ctx *context.APIContext) {
qUser := ctx.FormTrim("user")
if qUser != "" {
user, err := user_model.GetUserByName(qUser)
user, err := user_model.GetUserByName(ctx, qUser)
if user_model.IsErrUserNotExist(err) {
ctx.Error(http.StatusNotFound, "User does not exist", err)
} else if err != nil {
@ -128,7 +128,7 @@ func ListTrackedTimes(ctx *context.APIContext) {
return
}
trackedTimes, err := models.GetTrackedTimes(opts)
trackedTimes, err := models.GetTrackedTimes(ctx, opts)
if err != nil {
ctx.Error(http.StatusInternalServerError, "GetTrackedTimes", err)
return
@ -203,7 +203,7 @@ func AddTime(ctx *context.APIContext) {
if form.User != "" {
if (ctx.IsUserRepoAdmin() && ctx.Doer.Name != form.User) || ctx.Doer.IsAdmin {
// allow only RepoAdmin, Admin and User to add time
user, err = user_model.GetUserByName(form.User)
user, err = user_model.GetUserByName(ctx, form.User)
if err != nil {
ctx.Error(http.StatusInternalServerError, "GetUserByName", err)
}
@ -415,7 +415,7 @@ func ListTrackedTimesByUser(ctx *context.APIContext) {
ctx.Error(http.StatusBadRequest, "", "time tracking disabled")
return
}
user, err := user_model.GetUserByName(ctx.Params(":timetrackingusername"))
user, err := user_model.GetUserByName(ctx, ctx.Params(":timetrackingusername"))
if err != nil {
if user_model.IsErrUserNotExist(err) {
ctx.NotFound(err)
@ -439,7 +439,7 @@ func ListTrackedTimesByUser(ctx *context.APIContext) {
RepositoryID: ctx.Repo.Repository.ID,
}
trackedTimes, err := models.GetTrackedTimes(opts)
trackedTimes, err := models.GetTrackedTimes(ctx, opts)
if err != nil {
ctx.Error(http.StatusInternalServerError, "GetTrackedTimes", err)
return
@ -512,7 +512,7 @@ func ListTrackedTimesByRepository(ctx *context.APIContext) {
// Filters
qUser := ctx.FormTrim("user")
if qUser != "" {
user, err := user_model.GetUserByName(qUser)
user, err := user_model.GetUserByName(ctx, qUser)
if user_model.IsErrUserNotExist(err) {
ctx.Error(http.StatusNotFound, "User does not exist", err)
} else if err != nil {
@ -547,7 +547,7 @@ func ListTrackedTimesByRepository(ctx *context.APIContext) {
return
}
trackedTimes, err := models.GetTrackedTimes(opts)
trackedTimes, err := models.GetTrackedTimes(ctx, opts)
if err != nil {
ctx.Error(http.StatusInternalServerError, "GetTrackedTimes", err)
return
@ -609,7 +609,7 @@ func ListMyTrackedTimes(ctx *context.APIContext) {
return
}
trackedTimes, err := models.GetTrackedTimes(opts)
trackedTimes, err := models.GetTrackedTimes(ctx, opts)
if err != nil {
ctx.Error(http.StatusInternalServerError, "GetTrackedTimesByUser", err)
return

View file

@ -49,7 +49,7 @@ func ListLabels(ctx *context.APIContext) {
// "200":
// "$ref": "#/responses/LabelList"
labels, err := models.GetLabelsByRepoID(ctx.Repo.Repository.ID, ctx.FormString("sort"), utils.GetListOptions(ctx))
labels, err := models.GetLabelsByRepoID(ctx, ctx.Repo.Repository.ID, ctx.FormString("sort"), utils.GetListOptions(ctx))
if err != nil {
ctx.Error(http.StatusInternalServerError, "GetLabelsByRepoID", err)
return
@ -99,9 +99,9 @@ func GetLabel(ctx *context.APIContext) {
)
strID := ctx.Params(":id")
if intID, err2 := strconv.ParseInt(strID, 10, 64); err2 != nil {
label, err = models.GetLabelInRepoByName(ctx.Repo.Repository.ID, strID)
label, err = models.GetLabelInRepoByName(ctx, ctx.Repo.Repository.ID, strID)
} else {
label, err = models.GetLabelInRepoByID(ctx.Repo.Repository.ID, intID)
label, err = models.GetLabelInRepoByID(ctx, ctx.Repo.Repository.ID, intID)
}
if err != nil {
if models.IsErrRepoLabelNotExist(err) {
@ -206,7 +206,7 @@ func EditLabel(ctx *context.APIContext) {
// "$ref": "#/responses/validationError"
form := web.GetForm(ctx).(*api.EditLabelOption)
label, err := models.GetLabelInRepoByID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id"))
label, err := models.GetLabelInRepoByID(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":id"))
if err != nil {
if models.IsErrRepoLabelNotExist(err) {
ctx.NotFound()

View file

@ -68,7 +68,7 @@ func GetLanguages(ctx *context.APIContext) {
// "200":
// "$ref": "#/responses/LanguageStatistics"
langs, err := repo_model.GetLanguageStats(ctx.Repo.Repository)
langs, err := repo_model.GetLanguageStats(ctx, ctx.Repo.Repository)
if err != nil {
log.Error("GetLanguageStats failed: %v", err)
ctx.InternalServerError(err)

View file

@ -65,7 +65,7 @@ func Migrate(ctx *context.APIContext) {
err error
)
if len(form.RepoOwner) != 0 {
repoOwner, err = user_model.GetUserByName(form.RepoOwner)
repoOwner, err = user_model.GetUserByName(ctx, form.RepoOwner)
} else if form.RepoOwnerID != 0 {
repoOwner, err = user_model.GetUserByID(form.RepoOwnerID)
} else {

View file

@ -50,7 +50,7 @@ func MirrorSync(ctx *context.APIContext) {
return
}
if _, err := repo_model.GetMirrorByRepoID(repo.ID); err != nil {
if _, err := repo_model.GetMirrorByRepoID(ctx, repo.ID); err != nil {
if errors.Is(err, repo_model.ErrMirrorNotExist) {
ctx.Error(http.StatusBadRequest, "MirrorSync", "Repository is not a mirror")
return

View file

@ -15,6 +15,7 @@ import (
"code.gitea.io/gitea/models"
issues_model "code.gitea.io/gitea/models/issues"
access_model "code.gitea.io/gitea/models/perm/access"
pull_model "code.gitea.io/gitea/models/pull"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unit"
@ -159,7 +160,7 @@ func GetPullRequest(ctx *context.APIContext) {
// "404":
// "$ref": "#/responses/notFound"
pr, err := models.GetPullRequestByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
pr, err := models.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
if err != nil {
if models.IsErrPullRequestNotExist(err) {
ctx.NotFound()
@ -219,7 +220,7 @@ func DownloadPullDiffOrPatch(ctx *context.APIContext) {
// "$ref": "#/responses/string"
// "404":
// "$ref": "#/responses/notFound"
pr, err := models.GetPullRequestByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
pr, err := models.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
if err != nil {
if models.IsErrPullRequestNotExist(err) {
ctx.NotFound()
@ -402,7 +403,7 @@ func CreatePullRequest(ctx *context.APIContext) {
return
}
valid, err := models.CanBeAssigned(assignee, repo, true)
valid, err := access_model.CanBeAssigned(ctx, assignee, repo, true)
if err != nil {
ctx.Error(http.StatusInternalServerError, "canBeAssigned", err)
return
@ -469,7 +470,7 @@ func EditPullRequest(ctx *context.APIContext) {
// "$ref": "#/responses/validationError"
form := web.GetForm(ctx).(*api.EditPullRequestOption)
pr, err := models.GetPullRequestByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
pr, err := models.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
if err != nil {
if models.IsErrPullRequestNotExist(err) {
ctx.NotFound()
@ -631,7 +632,7 @@ func EditPullRequest(ctx *context.APIContext) {
}
// Refetch from database
pr, err = models.GetPullRequestByIndex(ctx.Repo.Repository.ID, pr.Index)
pr, err = models.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, pr.Index)
if err != nil {
if models.IsErrPullRequestNotExist(err) {
ctx.NotFound()
@ -675,7 +676,7 @@ func IsPullRequestMerged(ctx *context.APIContext) {
// "404":
// description: pull request has not been merged
pr, err := models.GetPullRequestByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
pr, err := models.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
if err != nil {
if models.IsErrPullRequestNotExist(err) {
ctx.NotFound()
@ -729,7 +730,7 @@ func MergePullRequest(ctx *context.APIContext) {
form := web.GetForm(ctx).(*forms.MergePullRequestForm)
pr, err := models.GetPullRequestByIndexCtx(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
pr, err := models.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
if err != nil {
if models.IsErrPullRequestNotExist(err) {
ctx.NotFound("GetPullRequestByIndex", err)
@ -937,7 +938,7 @@ func parseCompareInfo(ctx *context.APIContext, form api.CreatePullRequestOption)
headBranch = headInfos[0]
} else if len(headInfos) == 2 {
headUser, err = user_model.GetUserByName(headInfos[0])
headUser, err = user_model.GetUserByName(ctx, headInfos[0])
if err != nil {
if user_model.IsErrUserNotExist(err) {
ctx.NotFound("GetUserByName")
@ -983,7 +984,7 @@ func parseCompareInfo(ctx *context.APIContext, form api.CreatePullRequestOption)
}
// user should have permission to read baseRepo's codes and pulls, NOT headRepo's
permBase, err := models.GetUserRepoPermission(ctx, baseRepo, ctx.Doer)
permBase, err := access_model.GetUserRepoPermission(ctx, baseRepo, ctx.Doer)
if err != nil {
headGitRepo.Close()
ctx.Error(http.StatusInternalServerError, "GetUserRepoPermission", err)
@ -1002,7 +1003,7 @@ func parseCompareInfo(ctx *context.APIContext, form api.CreatePullRequestOption)
}
// user should have permission to read headrepo's codes
permHead, err := models.GetUserRepoPermission(ctx, headRepo, ctx.Doer)
permHead, err := access_model.GetUserRepoPermission(ctx, headRepo, ctx.Doer)
if err != nil {
headGitRepo.Close()
ctx.Error(http.StatusInternalServerError, "GetUserRepoPermission", err)
@ -1078,7 +1079,7 @@ func UpdatePullRequest(ctx *context.APIContext) {
// "422":
// "$ref": "#/responses/validationError"
pr, err := models.GetPullRequestByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
pr, err := models.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
if err != nil {
if models.IsErrPullRequestNotExist(err) {
ctx.NotFound()
@ -1176,7 +1177,7 @@ func CancelScheduledAutoMerge(ctx *context.APIContext) {
// "$ref": "#/responses/notFound"
pullIndex := ctx.ParamsInt64(":index")
pull, err := models.GetPullRequestByIndex(ctx.Repo.Repository.ID, pullIndex)
pull, err := models.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, pullIndex)
if err != nil {
if models.IsErrPullRequestNotExist(err) {
ctx.NotFound()
@ -1197,7 +1198,7 @@ func CancelScheduledAutoMerge(ctx *context.APIContext) {
}
if ctx.Doer.ID != autoMerge.DoerID {
allowed, err := models.IsUserRepoAdminCtx(ctx, ctx.Repo.Repository, ctx.Doer)
allowed, err := access_model.IsUserRepoAdmin(ctx, ctx.Repo.Repository, ctx.Doer)
if err != nil {
ctx.InternalServerError(err)
return
@ -1253,7 +1254,7 @@ func GetPullRequestCommits(ctx *context.APIContext) {
// "404":
// "$ref": "#/responses/notFound"
pr, err := models.GetPullRequestByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
pr, err := models.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
if err != nil {
if models.IsErrPullRequestNotExist(err) {
ctx.NotFound()

View file

@ -11,6 +11,7 @@ import (
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/organization"
access_model "code.gitea.io/gitea/models/perm/access"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/convert"
@ -60,7 +61,7 @@ func ListPullReviews(ctx *context.APIContext) {
// "404":
// "$ref": "#/responses/notFound"
pr, err := models.GetPullRequestByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
pr, err := models.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
if err != nil {
if models.IsErrPullRequestNotExist(err) {
ctx.NotFound("GetPullRequestByIndex", err)
@ -86,7 +87,7 @@ func ListPullReviews(ctx *context.APIContext) {
IssueID: pr.IssueID,
}
allReviews, err := models.FindReviews(opts)
allReviews, err := models.FindReviews(ctx, opts)
if err != nil {
ctx.InternalServerError(err)
return
@ -306,7 +307,7 @@ func CreatePullReview(ctx *context.APIContext) {
// "$ref": "#/responses/validationError"
opts := web.GetForm(ctx).(*api.CreatePullReviewOptions)
pr, err := models.GetPullRequestByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
pr, err := models.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
if err != nil {
if models.IsErrPullRequestNotExist(err) {
ctx.NotFound("GetPullRequestByIndex", err)
@ -525,7 +526,7 @@ func preparePullReviewType(ctx *context.APIContext, pr *models.PullRequest, even
// prepareSingleReview return review, related pull and false or nil, nil and true if an error happen
func prepareSingleReview(ctx *context.APIContext) (*models.Review, *models.PullRequest, bool) {
pr, err := models.GetPullRequestByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
pr, err := models.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
if err != nil {
if models.IsErrPullRequestNotExist(err) {
ctx.NotFound("GetPullRequestByIndex", err)
@ -535,7 +536,7 @@ func prepareSingleReview(ctx *context.APIContext) (*models.Review, *models.PullR
return nil, nil, true
}
review, err := models.GetReviewByID(ctx.ParamsInt64(":id"))
review, err := models.GetReviewByID(ctx, ctx.ParamsInt64(":id"))
if err != nil {
if models.IsErrReviewNotExist(err) {
ctx.NotFound("GetReviewByID", err)
@ -647,7 +648,7 @@ func DeleteReviewRequests(ctx *context.APIContext) {
}
func apiReviewRequest(ctx *context.APIContext, opts api.PullReviewRequestOptions, isAdd bool) {
pr, err := models.GetPullRequestByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
pr, err := models.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
if err != nil {
if models.IsErrPullRequestNotExist(err) {
ctx.NotFound("GetPullRequestByIndex", err)
@ -664,7 +665,7 @@ func apiReviewRequest(ctx *context.APIContext, opts api.PullReviewRequestOptions
reviewers := make([]*user_model.User, 0, len(opts.Reviewers))
permDoer, err := models.GetUserRepoPermission(ctx, pr.Issue.Repo, ctx.Doer)
permDoer, err := access_model.GetUserRepoPermission(ctx, pr.Issue.Repo, ctx.Doer)
if err != nil {
ctx.Error(http.StatusInternalServerError, "GetUserRepoPermission", err)
return
@ -675,7 +676,7 @@ func apiReviewRequest(ctx *context.APIContext, opts api.PullReviewRequestOptions
if strings.Contains(r, "@") {
reviewer, err = user_model.GetUserByEmail(r)
} else {
reviewer, err = user_model.GetUserByName(r)
reviewer, err = user_model.GetUserByName(ctx, r)
}
if err != nil {
@ -726,7 +727,7 @@ func apiReviewRequest(ctx *context.APIContext, opts api.PullReviewRequestOptions
teamReviewers := make([]*organization.Team, 0, len(opts.TeamReviewers))
for _, t := range opts.TeamReviewers {
var teamReviewer *organization.Team
teamReviewer, err = organization.GetTeam(ctx.Repo.Owner.ID, t)
teamReviewer, err = organization.GetTeam(ctx, ctx.Repo.Owner.ID, t)
if err != nil {
if organization.IsErrTeamNotExist(err) {
ctx.NotFound("TeamNotExist", fmt.Sprintf("Team '%s' not exist", t))
@ -891,7 +892,7 @@ func dismissReview(ctx *context.APIContext, msg string, isDismiss bool) {
return
}
if review, err = models.GetReviewByID(review.ID); err != nil {
if review, err = models.GetReviewByID(ctx, review.ID); err != nil {
ctx.Error(http.StatusInternalServerError, "GetReviewByID", err)
return
}

View file

@ -15,7 +15,7 @@ import (
api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/web"
"code.gitea.io/gitea/routers/api/v1/utils"
releaseservice "code.gitea.io/gitea/services/release"
release_service "code.gitea.io/gitea/services/release"
)
// GetRelease get a single release of a repository
@ -49,7 +49,7 @@ func GetRelease(ctx *context.APIContext) {
// "$ref": "#/responses/notFound"
id := ctx.ParamsInt64(":id")
release, err := models.GetReleaseByID(id)
release, err := models.GetReleaseByID(ctx, id)
if err != nil && !models.IsErrReleaseNotExist(err) {
ctx.Error(http.StatusInternalServerError, "GetReleaseByID", err)
return
@ -202,7 +202,7 @@ func CreateRelease(ctx *context.APIContext) {
IsTag: false,
Repo: ctx.Repo.Repository,
}
if err := releaseservice.CreateRelease(ctx.Repo.GitRepo, rel, nil, ""); err != nil {
if err := release_service.CreateRelease(ctx.Repo.GitRepo, rel, nil, ""); err != nil {
if models.IsErrReleaseAlreadyExist(err) {
ctx.Error(http.StatusConflict, "ReleaseAlreadyExist", err)
} else {
@ -225,7 +225,7 @@ func CreateRelease(ctx *context.APIContext) {
rel.Repo = ctx.Repo.Repository
rel.Publisher = ctx.Doer
if err = releaseservice.UpdateRelease(ctx.Doer, ctx.Repo.GitRepo, rel, nil, nil, nil); err != nil {
if err = release_service.UpdateRelease(ctx.Doer, ctx.Repo.GitRepo, rel, nil, nil, nil); err != nil {
ctx.Error(http.StatusInternalServerError, "UpdateRelease", err)
return
}
@ -271,7 +271,7 @@ func EditRelease(ctx *context.APIContext) {
form := web.GetForm(ctx).(*api.EditReleaseOption)
id := ctx.ParamsInt64(":id")
rel, err := models.GetReleaseByID(id)
rel, err := models.GetReleaseByID(ctx, id)
if err != nil && !models.IsErrReleaseNotExist(err) {
ctx.Error(http.StatusInternalServerError, "GetReleaseByID", err)
return
@ -300,12 +300,13 @@ func EditRelease(ctx *context.APIContext) {
if form.IsPrerelease != nil {
rel.IsPrerelease = *form.IsPrerelease
}
if err := releaseservice.UpdateRelease(ctx.Doer, ctx.Repo.GitRepo, rel, nil, nil, nil); err != nil {
if err := release_service.UpdateRelease(ctx.Doer, ctx.Repo.GitRepo, rel, nil, nil, nil); err != nil {
ctx.Error(http.StatusInternalServerError, "UpdateRelease", err)
return
}
rel, err = models.GetReleaseByID(id)
// reload data from database
rel, err = models.GetReleaseByID(ctx, id)
if err != nil {
ctx.Error(http.StatusInternalServerError, "GetReleaseByID", err)
return
@ -346,7 +347,7 @@ func DeleteRelease(ctx *context.APIContext) {
// "$ref": "#/responses/notFound"
id := ctx.ParamsInt64(":id")
rel, err := models.GetReleaseByID(id)
rel, err := models.GetReleaseByID(ctx, id)
if err != nil && !models.IsErrReleaseNotExist(err) {
ctx.Error(http.StatusInternalServerError, "GetReleaseByID", err)
return
@ -356,7 +357,7 @@ func DeleteRelease(ctx *context.APIContext) {
ctx.NotFound()
return
}
if err := releaseservice.DeleteReleaseByID(ctx, id, ctx.Doer, false); err != nil {
if err := release_service.DeleteReleaseByID(ctx, id, ctx.Doer, false); err != nil {
ctx.Error(http.StatusInternalServerError, "DeleteReleaseByID", err)
return
}

View file

@ -55,7 +55,7 @@ func GetReleaseAttachment(ctx *context.APIContext) {
releaseID := ctx.ParamsInt64(":id")
attachID := ctx.ParamsInt64(":asset")
attach, err := repo_model.GetAttachmentByID(attachID)
attach, err := repo_model.GetAttachmentByID(ctx, attachID)
if err != nil {
ctx.Error(http.StatusInternalServerError, "GetAttachmentByID", err)
return
@ -98,7 +98,7 @@ func ListReleaseAttachments(ctx *context.APIContext) {
// "$ref": "#/responses/AttachmentList"
releaseID := ctx.ParamsInt64(":id")
release, err := models.GetReleaseByID(releaseID)
release, err := models.GetReleaseByID(ctx, releaseID)
if err != nil {
ctx.Error(http.StatusInternalServerError, "GetReleaseByID", err)
return
@ -164,7 +164,7 @@ func CreateReleaseAttachment(ctx *context.APIContext) {
// Check if release exists an load release
releaseID := ctx.ParamsInt64(":id")
release, err := models.GetReleaseByID(releaseID)
release, err := models.GetReleaseByID(ctx, releaseID)
if err != nil {
ctx.Error(http.StatusInternalServerError, "GetReleaseByID", err)
return
@ -242,7 +242,7 @@ func EditReleaseAttachment(ctx *context.APIContext) {
// Check if release exists an load release
releaseID := ctx.ParamsInt64(":id")
attachID := ctx.ParamsInt64(":asset")
attach, err := repo_model.GetAttachmentByID(attachID)
attach, err := repo_model.GetAttachmentByID(ctx, attachID)
if err != nil {
ctx.Error(http.StatusInternalServerError, "GetAttachmentByID", err)
return
@ -257,7 +257,7 @@ func EditReleaseAttachment(ctx *context.APIContext) {
attach.Name = form.Name
}
if err := repo_model.UpdateAttachment(attach); err != nil {
if err := repo_model.UpdateAttachment(ctx, attach); err != nil {
ctx.Error(http.StatusInternalServerError, "UpdateAttachment", attach)
}
ctx.JSON(http.StatusCreated, convert.ToReleaseAttachment(attach))
@ -300,7 +300,7 @@ func DeleteReleaseAttachment(ctx *context.APIContext) {
// Check if release exists an load release
releaseID := ctx.ParamsInt64(":id")
attachID := ctx.ParamsInt64(":asset")
attach, err := repo_model.GetAttachmentByID(attachID)
attach, err := repo_model.GetAttachmentByID(ctx, attachID)
if err != nil {
ctx.Error(http.StatusInternalServerError, "GetAttachmentByID", err)
return

View file

@ -15,6 +15,7 @@ import (
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/organization"
"code.gitea.io/gitea/models/perm"
access_model "code.gitea.io/gitea/models/perm/access"
repo_model "code.gitea.io/gitea/models/repo"
unit_model "code.gitea.io/gitea/models/unit"
user_model "code.gitea.io/gitea/models/user"
@ -122,7 +123,7 @@ func Search(ctx *context.APIContext) {
// "422":
// "$ref": "#/responses/validationError"
opts := &models.SearchRepoOptions{
opts := &repo_model.SearchRepoOptions{
ListOptions: utils.GetListOptions(ctx),
Actor: ctx.Doer,
Keyword: ctx.FormTrim("q"),
@ -191,7 +192,7 @@ func Search(ctx *context.APIContext) {
}
var err error
repos, count, err := models.SearchRepository(opts)
repos, count, err := repo_model.SearchRepository(opts)
if err != nil {
ctx.JSON(http.StatusInternalServerError, api.SearchError{
OK: false,
@ -209,7 +210,7 @@ func Search(ctx *context.APIContext) {
})
return
}
accessMode, err := models.AccessLevel(ctx.Doer, repo)
accessMode, err := access_model.AccessLevel(ctx.Doer, repo)
if err != nil {
ctx.JSON(http.StatusInternalServerError, api.SearchError{
OK: false,
@ -343,7 +344,7 @@ func Generate(ctx *context.APIContext) {
return
}
opts := models.GenerateRepoOptions{
opts := repo_module.GenerateRepoOptions{
Name: form.Name,
DefaultBranch: form.DefaultBranch,
Description: form.Description,
@ -364,7 +365,7 @@ func Generate(ctx *context.APIContext) {
ctxUser := ctx.Doer
var err error
if form.Owner != ctxUser.Name {
ctxUser, err = user_model.GetUserByName(form.Owner)
ctxUser, err = user_model.GetUserByName(ctx, form.Owner)
if err != nil {
if user_model.IsErrUserNotExist(err) {
ctx.JSON(http.StatusNotFound, map[string]interface{}{
@ -555,7 +556,7 @@ func GetByID(ctx *context.APIContext) {
return
}
perm, err := models.GetUserRepoPermission(ctx, repo, ctx.Doer)
perm, err := access_model.GetUserRepoPermission(ctx, repo, ctx.Doer)
if err != nil {
ctx.Error(http.StatusInternalServerError, "AccessLevel", err)
return
@ -716,7 +717,7 @@ func updateBasicProperties(ctx *context.APIContext, opts api.EditRepoOption) err
repo.DefaultBranch = *opts.DefaultBranch
}
if err := models.UpdateRepository(repo, visibilityChanged); err != nil {
if err := repo_service.UpdateRepository(repo, visibilityChanged); err != nil {
ctx.Error(http.StatusInternalServerError, "UpdateRepository", err)
return err
}
@ -961,7 +962,7 @@ func updateMirror(ctx *context.APIContext, opts api.EditRepoOption) error {
}
// get the mirror from the repo
mirror, err := repo_model.GetMirrorByRepoID(repo.ID)
mirror, err := repo_model.GetMirrorByRepoID(ctx, repo.ID)
if err != nil {
log.Error("Failed to get mirror: %s", err)
ctx.Error(http.StatusInternalServerError, "MirrorInterval", err)
@ -999,7 +1000,7 @@ func updateMirror(ctx *context.APIContext, opts api.EditRepoOption) error {
}
// finally update the mirror in the DB
if err := repo_model.UpdateMirror(mirror); err != nil {
if err := repo_model.UpdateMirror(ctx, mirror); err != nil {
log.Error("Failed to Set Mirror Interval: %s", err)
ctx.Error(http.StatusUnprocessableEntity, "MirrorInterval", err)
return err
@ -1035,7 +1036,7 @@ func Delete(ctx *context.APIContext) {
owner := ctx.Repo.Owner
repo := ctx.Repo.Repository
canDelete, err := models.CanUserDelete(repo, ctx.Doer)
canDelete, err := repo_module.CanUserDelete(repo, ctx.Doer)
if err != nil {
ctx.Error(http.StatusInternalServerError, "CanUserDelete", err)
return

View file

@ -253,7 +253,7 @@ func GetCombinedCommitStatusByRef(ctx *context.APIContext) {
repo := ctx.Repo.Repository
statuses, count, err := models.GetLatestCommitStatus(repo.ID, sha, utils.GetListOptions(ctx))
statuses, count, err := models.GetLatestCommitStatus(ctx, repo.ID, sha, utils.GetListOptions(ctx))
if err != nil {
ctx.Error(http.StatusInternalServerError, "GetLatestCommitStatus", fmt.Errorf("GetLatestCommitStatus[%s, %s]: %v", repo.FullName(), sha, err))
return

View file

@ -12,7 +12,6 @@ import (
"code.gitea.io/gitea/models/organization"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/convert"
api "code.gitea.io/gitea/modules/structs"
)
// ListTeams list a repository's teams
@ -42,20 +41,16 @@ func ListTeams(ctx *context.APIContext) {
return
}
teams, err := organization.GetRepoTeams(ctx.Repo.Repository)
teams, err := organization.GetRepoTeams(ctx, ctx.Repo.Repository)
if err != nil {
ctx.InternalServerError(err)
return
}
apiTeams := make([]*api.Team, len(teams))
for i := range teams {
if err := teams[i].GetUnits(); err != nil {
ctx.Error(http.StatusInternalServerError, "GetUnits", err)
return
}
apiTeams[i] = convert.ToTeam(teams[i])
apiTeams, err := convert.ToTeams(teams, false)
if err != nil {
ctx.InternalServerError(err)
return
}
ctx.JSON(http.StatusOK, apiTeams)
@ -103,11 +98,11 @@ func IsTeam(ctx *context.APIContext) {
}
if models.HasRepository(team, ctx.Repo.Repository.ID) {
if err := team.GetUnits(); err != nil {
ctx.Error(http.StatusInternalServerError, "GetUnits", err)
apiTeam, err := convert.ToTeam(team)
if err != nil {
ctx.InternalServerError(err)
return
}
apiTeam := convert.ToTeam(team)
ctx.JSON(http.StatusOK, apiTeam)
return
}
@ -221,7 +216,7 @@ func changeRepoTeam(ctx *context.APIContext, add bool) {
}
func getTeamByParam(ctx *context.APIContext) *organization.Team {
team, err := organization.GetTeam(ctx.Repo.Owner.ID, ctx.Params(":team"))
team, err := organization.GetTeam(ctx, ctx.Repo.Owner.ID, ctx.Params(":team"))
if err != nil {
if organization.IsErrTeamNotExist(err) {
ctx.Error(http.StatusNotFound, "TeamNotExit", err)

View file

@ -57,7 +57,7 @@ func Transfer(ctx *context.APIContext) {
opts := web.GetForm(ctx).(*api.TransferRepoOption)
newOwner, err := user_model.GetUserByName(opts.NewOwner)
newOwner, err := user_model.GetUserByName(ctx, opts.NewOwner)
if err != nil {
if user_model.IsErrUserNotExist(err) {
ctx.Error(http.StatusNotFound, "", "The new owner does not exist or cannot be found")
@ -84,7 +84,7 @@ func Transfer(ctx *context.APIContext) {
org := convert.ToOrganization(organization.OrgFromUser(newOwner))
for _, tID := range *opts.TeamIDs {
team, err := organization.GetTeamByID(tID)
team, err := organization.GetTeamByID(ctx, tID)
if err != nil {
ctx.Error(http.StatusUnprocessableEntity, "team", fmt.Errorf("team %d not found", tID))
return

View file

@ -213,7 +213,7 @@ func CreateOauth2Application(ctx *context.APIContext) {
data := web.GetForm(ctx).(*api.CreateOAuth2ApplicationOptions)
app, err := auth.CreateOAuth2Application(auth.CreateOAuth2ApplicationOptions{
app, err := auth.CreateOAuth2Application(ctx, auth.CreateOAuth2ApplicationOptions{
Name: data.Name,
UserID: ctx.Doer.ID,
RedirectURIs: data.RedirectURIs,
@ -320,7 +320,7 @@ func GetOauth2Application(ctx *context.APIContext) {
// "404":
// "$ref": "#/responses/notFound"
appID := ctx.ParamsInt64(":id")
app, err := auth.GetOAuth2ApplicationByID(appID)
app, err := auth.GetOAuth2ApplicationByID(ctx, appID)
if err != nil {
if auth.IsErrOauthClientIDInvalid(err) || auth.IsErrOAuthApplicationNotFound(err) {
ctx.NotFound()

View file

@ -14,7 +14,7 @@ import (
// GetUserByParamsName get user by name
func GetUserByParamsName(ctx *context.APIContext, name string) *user_model.User {
username := ctx.Params(name)
user, err := user_model.GetUserByName(username)
user, err := user_model.GetUserByName(ctx, username)
if err != nil {
if user_model.IsErrUserNotExist(err) {
if redirectUserID, err2 := user_model.LookupUserRedirect(username); err2 == nil {

View file

@ -7,8 +7,9 @@ package user
import (
"net/http"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/perm"
access_model "code.gitea.io/gitea/models/perm/access"
repo_model "code.gitea.io/gitea/models/repo"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/convert"
@ -20,7 +21,7 @@ import (
func listUserRepos(ctx *context.APIContext, u *user_model.User, private bool) {
opts := utils.GetListOptions(ctx)
repos, count, err := models.GetUserRepositories(&models.SearchRepoOptions{
repos, count, err := repo_model.GetUserRepositories(&repo_model.SearchRepoOptions{
Actor: u,
Private: private,
ListOptions: opts,
@ -38,7 +39,7 @@ func listUserRepos(ctx *context.APIContext, u *user_model.User, private bool) {
apiRepos := make([]*api.Repository, 0, len(repos))
for i := range repos {
access, err := models.AccessLevel(ctx.Doer, repos[i])
access, err := access_model.AccessLevel(ctx.Doer, repos[i])
if err != nil {
ctx.Error(http.StatusInternalServerError, "AccessLevel", err)
return
@ -102,7 +103,7 @@ func ListMyRepos(ctx *context.APIContext) {
// "200":
// "$ref": "#/responses/RepositoryList"
opts := &models.SearchRepoOptions{
opts := &repo_model.SearchRepoOptions{
ListOptions: utils.GetListOptions(ctx),
Actor: ctx.Doer,
OwnerID: ctx.Doer.ID,
@ -111,7 +112,7 @@ func ListMyRepos(ctx *context.APIContext) {
}
var err error
repos, count, err := models.SearchRepository(opts)
repos, count, err := repo_model.SearchRepository(opts)
if err != nil {
ctx.Error(http.StatusInternalServerError, "SearchRepository", err)
return
@ -123,7 +124,7 @@ func ListMyRepos(ctx *context.APIContext) {
ctx.Error(http.StatusInternalServerError, "GetOwner", err)
return
}
accessMode, err := models.AccessLevel(ctx.Doer, repo)
accessMode, err := access_model.AccessLevel(ctx.Doer, repo)
if err != nil {
ctx.Error(http.StatusInternalServerError, "AccessLevel", err)
}

View file

@ -74,7 +74,7 @@ func UpdateUserSettings(ctx *context.APIContext) {
ctx.Doer.KeepActivityPrivate = *form.HideActivity
}
if err := user_model.UpdateUser(ctx.Doer, false); err != nil {
if err := user_model.UpdateUser(ctx, ctx.Doer, false); err != nil {
ctx.InternalServerError(err)
return
}

View file

@ -8,8 +8,8 @@ package user
import (
"net/http"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
access_model "code.gitea.io/gitea/models/perm/access"
repo_model "code.gitea.io/gitea/models/repo"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/context"
@ -28,7 +28,7 @@ func getStarredRepos(user *user_model.User, private bool, listOptions db.ListOpt
repos := make([]*api.Repository, len(starredRepos))
for i, starred := range starredRepos {
access, err := models.AccessLevel(user, starred)
access, err := access_model.AccessLevel(user, starred)
if err != nil {
return nil, err
}
@ -124,7 +124,7 @@ func IsStarring(ctx *context.APIContext) {
// "404":
// "$ref": "#/responses/notFound"
if repo_model.IsStaring(ctx.Doer.ID, ctx.Repo.Repository.ID) {
if repo_model.IsStaring(ctx, ctx.Doer.ID, ctx.Repo.Repository.ID) {
ctx.Status(http.StatusNoContent)
} else {
ctx.NotFound()

View file

@ -98,7 +98,7 @@ func GetInfo(ctx *context.APIContext) {
// "404":
// "$ref": "#/responses/notFound"
if !user_model.IsUserVisibleToViewer(ctx.ContextUser, ctx.Doer) {
if !user_model.IsUserVisibleToViewer(ctx, ctx.ContextUser, ctx.Doer) {
// fake ErrUserNotExist error message to not leak information about existence
ctx.NotFound("GetUserByName", user_model.ErrUserNotExist{Name: ctx.Params(":username")})
return

View file

@ -7,8 +7,8 @@ package user
import (
"net/http"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
access_model "code.gitea.io/gitea/models/perm/access"
repo_model "code.gitea.io/gitea/models/repo"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/context"
@ -26,7 +26,7 @@ func getWatchedRepos(user *user_model.User, private bool, listOptions db.ListOpt
repos := make([]*api.Repository, len(watchedRepos))
for i, watched := range watchedRepos {
access, err := models.AccessLevel(user, watched)
access, err := access_model.AccessLevel(user, watched)
if err != nil {
return nil, 0, err
}
@ -156,7 +156,7 @@ func Watch(ctx *context.APIContext) {
// "200":
// "$ref": "#/responses/WatchInfo"
err := repo_model.WatchRepo(ctx.Doer.ID, ctx.Repo.Repository.ID, true)
err := repo_model.WatchRepo(ctx, ctx.Doer.ID, ctx.Repo.Repository.ID, true)
if err != nil {
ctx.Error(http.StatusInternalServerError, "WatchRepo", err)
return
@ -191,7 +191,7 @@ func Unwatch(ctx *context.APIContext) {
// "204":
// "$ref": "#/responses/empty"
err := repo_model.WatchRepo(ctx.Doer.ID, ctx.Repo.Repository.ID, false)
err := repo_model.WatchRepo(ctx, ctx.Doer.ID, ctx.Repo.Repository.ID, false)
if err != nil {
ctx.Error(http.StatusInternalServerError, "UnwatchRepo", err)
return

View file

@ -88,10 +88,14 @@ func ServeData(ctx *context.Context, name string, size int64, reader io.Reader)
}
if (st.IsImage() || st.IsPDF()) && (setting.UI.SVG.Enabled || !st.IsSvgImage()) {
ctx.Resp.Header().Set("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, name))
if st.IsSvgImage() {
if st.IsSvgImage() || st.IsPDF() {
ctx.Resp.Header().Set("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; sandbox")
ctx.Resp.Header().Set("X-Content-Type-Options", "nosniff")
ctx.Resp.Header().Set("Content-Type", typesniffer.SvgMimeType)
if st.IsSvgImage() {
ctx.Resp.Header().Set("Content-Type", typesniffer.SvgMimeType)
} else {
ctx.Resp.Header().Set("Content-Type", typesniffer.ApplicationOctetStream)
}
}
} else {
ctx.Resp.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, name))

View file

@ -10,7 +10,6 @@ import (
"reflect"
"runtime"
"strconv"
"strings"
"code.gitea.io/gitea/models"
asymkey_model "code.gitea.io/gitea/models/asymkey"
@ -31,6 +30,7 @@ import (
"code.gitea.io/gitea/modules/storage"
"code.gitea.io/gitea/modules/svg"
"code.gitea.io/gitea/modules/translation"
"code.gitea.io/gitea/modules/util"
"code.gitea.io/gitea/modules/web"
packages_router "code.gitea.io/gitea/routers/api/packages"
apiv1 "code.gitea.io/gitea/routers/api/v1"
@ -111,7 +111,7 @@ func GlobalInitInstalled(ctx context.Context) {
log.Info("Custom path: %s", setting.CustomPath)
log.Info("Log path: %s", setting.LogRootPath)
log.Info("Configuration file: %s", setting.CustomConf)
log.Info("Run Mode: %s", strings.Title(setting.RunMode))
log.Info("Run Mode: %s", util.ToTitleCase(setting.RunMode))
// Setup i18n
translation.InitLocales()

View file

@ -456,6 +456,8 @@ func SubmitInstall(ctx *context.Context) {
cfg.Section("log").Key("ROOT_PATH").SetValue(form.LogRootPath)
cfg.Section("log").Key("ROUTER").SetValue("console")
cfg.Section("repository.pull-request").Key("DEFAULT_MERGE_STYLE").SetValue("merge")
cfg.Section("repository.signing").Key("DEFAULT_TRUST_MODEL").SetValue("committer")
cfg.Section("security").Key("INSTALL_LOCK").SetValue("true")
@ -521,7 +523,7 @@ func SubmitInstall(ctx *context.Context) {
return
}
log.Info("Admin account already exist")
u, _ = user_model.GetUserByName(u.Name)
u, _ = user_model.GetUserByName(ctx, u.Name)
}
days := 86400 * setting.LogInRememberDays

View file

@ -106,7 +106,7 @@ func HookPostReceive(ctx *gitea_context.PrivateContext) {
repo.IsPrivate = opts.GitPushOptions.Bool(private.GitPushOptionRepoPrivate, repo.IsPrivate)
repo.IsTemplate = opts.GitPushOptions.Bool(private.GitPushOptionRepoTemplate, repo.IsTemplate)
if err := repo_model.UpdateRepositoryCols(repo, "is_private", "is_template"); err != nil {
if err := repo_model.UpdateRepositoryCols(ctx, repo, "is_private", "is_template"); err != nil {
log.Error("Failed to Update: %s/%s Error: %v", ownerName, repoName, err)
ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{
Err: fmt.Sprintf("Failed to Update: %s/%s Error: %v", ownerName, repoName, err),
@ -141,7 +141,7 @@ func HookPostReceive(ctx *gitea_context.PrivateContext) {
continue
}
pr, err := models.GetPullRequestByIndex(repo.ID, pullIndex)
pr, err := models.GetPullRequestByIndex(ctx, repo.ID, pullIndex)
if err != nil && !models.IsErrPullRequestNotExist(err) {
log.Error("Failed to get PR by index %v Error: %v", pullIndex, err)
ctx.JSON(http.StatusInternalServerError, private.Response{

View file

@ -14,6 +14,7 @@ import (
"code.gitea.io/gitea/models"
asymkey_model "code.gitea.io/gitea/models/asymkey"
perm_model "code.gitea.io/gitea/models/perm"
access_model "code.gitea.io/gitea/models/perm/access"
"code.gitea.io/gitea/models/unit"
user_model "code.gitea.io/gitea/models/user"
gitea_context "code.gitea.io/gitea/modules/context"
@ -30,7 +31,7 @@ type preReceiveContext struct {
// loadedPusher indicates that where the following information are loaded
loadedPusher bool
user *user_model.User // it's the org user if a DeployKey is used
userPerm models.Permission
userPerm access_model.Permission
deployKeyAccessMode perm_model.AccessMode
canCreatePullRequest bool
@ -55,7 +56,7 @@ func (ctx *preReceiveContext) CanWriteCode() bool {
if !ctx.loadPusherAndPermission() {
return false
}
ctx.canWriteCode = ctx.userPerm.CanWriteToBranch(ctx.user, ctx.branchName) || ctx.deployKeyAccessMode >= perm_model.AccessModeWrite
ctx.canWriteCode = models.CanMaintainerWriteToBranch(ctx.userPerm, ctx.branchName, ctx.user) || ctx.deployKeyAccessMode >= perm_model.AccessModeWrite
ctx.checkedCanWriteCode = true
}
return ctx.canWriteCode
@ -154,7 +155,7 @@ func preReceiveBranch(ctx *preReceiveContext, oldCommitID, newCommitID, refFullN
return
}
protectBranch, err := models.GetProtectedBranchBy(repo.ID, branchName)
protectBranch, err := models.GetProtectedBranchBy(ctx, repo.ID, branchName)
if err != nil {
log.Error("Unable to get protected branch: %s in %-v Error: %v", branchName, repo, err)
ctx.JSON(http.StatusInternalServerError, private.Response{
@ -472,7 +473,7 @@ func (ctx *preReceiveContext) loadPusherAndPermission() bool {
}
ctx.user = user
userPerm, err := models.GetUserRepoPermission(ctx, ctx.Repo.Repository, user)
userPerm, err := access_model.GetUserRepoPermission(ctx, ctx.Repo.Repository, user)
if err != nil {
log.Error("Unable to get Repo permission of repo %s/%s of User %s", ctx.Repo.Repository.OwnerName, ctx.Repo.Repository.Name, user.Name, err)
ctx.JSON(http.StatusInternalServerError, private.Response{

View file

@ -23,7 +23,7 @@ func HookProcReceive(ctx *gitea_context.PrivateContext) {
return
}
results := agit.ProcRecive(ctx, opts)
results := agit.ProcReceive(ctx, opts)
if ctx.Written() {
return
}

View file

@ -25,7 +25,7 @@ func UpdatePublicKeyInRepo(ctx *context.PrivateContext) {
return
}
deployKey, err := asymkey_model.GetDeployKeyByRepo(keyID, repoID)
deployKey, err := asymkey_model.GetDeployKeyByRepo(ctx, keyID, repoID)
if err != nil {
if asymkey_model.IsErrDeployKeyNotExist(err) {
ctx.PlainText(http.StatusOK, "success")
@ -52,7 +52,7 @@ func UpdatePublicKeyInRepo(ctx *context.PrivateContext) {
func AuthorizedPublicKeyByContent(ctx *context.PrivateContext) {
content := ctx.FormString("content")
publicKey, err := asymkey_model.SearchPublicKeyByContent(content)
publicKey, err := asymkey_model.SearchPublicKeyByContent(ctx, content)
if err != nil {
ctx.JSON(http.StatusInternalServerError, private.Response{
Err: err.Error(),

View file

@ -44,7 +44,7 @@ func SendEmail(ctx *context.PrivateContext) {
var emails []string
if len(mail.To) > 0 {
for _, uname := range mail.To {
user, err := user_model.GetUserByName(uname)
user, err := user_model.GetUserByName(ctx, uname)
if err != nil {
err := fmt.Sprintf("Failed to get user information: %v", err)
log.Error(err)

View file

@ -10,9 +10,9 @@ import (
"net/http"
"strings"
"code.gitea.io/gitea/models"
asymkey_model "code.gitea.io/gitea/models/asymkey"
"code.gitea.io/gitea/models/perm"
access_model "code.gitea.io/gitea/models/perm/access"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unit"
user_model "code.gitea.io/gitea/models/user"
@ -109,7 +109,7 @@ func ServCommand(ctx *context.PrivateContext) {
results.RepoName = repoName[:len(repoName)-5]
}
owner, err := user_model.GetUserByName(results.OwnerName)
owner, err := user_model.GetUserByName(ctx, results.OwnerName)
if err != nil {
if user_model.IsErrUserNotExist(err) {
// User is fetching/cloning a non-existent repository
@ -230,7 +230,7 @@ func ServCommand(ctx *context.PrivateContext) {
var user *user_model.User
if key.Type == asymkey_model.KeyTypeDeploy {
var err error
deployKey, err = asymkey_model.GetDeployKeyByRepo(key.ID, repo.ID)
deployKey, err = asymkey_model.GetDeployKeyByRepo(ctx, key.ID, repo.ID)
if err != nil {
if asymkey_model.IsErrDeployKeyNotExist(err) {
ctx.JSON(http.StatusNotFound, private.ErrServCommand{
@ -320,7 +320,7 @@ func ServCommand(ctx *context.PrivateContext) {
mode = perm.AccessModeRead
}
perm, err := models.GetUserRepoPermission(ctx, repo, user)
perm, err := access_model.GetUserRepoPermission(ctx, repo, user)
if err != nil {
log.Error("Unable to get permissions for %-v with key %d in %-v Error: %v", user, key.ID, repo, err)
ctx.JSON(http.StatusInternalServerError, private.ErrServCommand{
@ -345,7 +345,7 @@ func ServCommand(ctx *context.PrivateContext) {
// We already know we aren't using a deploy key
if !repoExist {
owner, err := user_model.GetUserByName(ownerName)
owner, err := user_model.GetUserByName(ctx, ownerName)
if err != nil {
ctx.JSON(http.StatusInternalServerError, private.ErrServCommand{
Results: results,

View file

@ -26,6 +26,7 @@ import (
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/timeutil"
"code.gitea.io/gitea/modules/updatechecker"
"code.gitea.io/gitea/modules/util"
"code.gitea.io/gitea/modules/web"
"code.gitea.io/gitea/services/cron"
"code.gitea.io/gitea/services/forms"
@ -245,7 +246,7 @@ func Config(ctx *context.Context) {
ctx.Data["OfflineMode"] = setting.OfflineMode
ctx.Data["DisableRouterLog"] = setting.DisableRouterLog
ctx.Data["RunUser"] = setting.RunUser
ctx.Data["RunMode"] = strings.Title(setting.RunMode)
ctx.Data["RunMode"] = util.ToTitleCase(setting.RunMode)
if version, err := git.LocalVersion(); err == nil {
ctx.Data["GitVersion"] = version.Original()
}

View file

@ -112,7 +112,7 @@ func NewAuthSource(ctx *context.Context) {
ctx.Data["SSPIDefaultLanguage"] = ""
// only the first as default
ctx.Data["oauth2_provider"] = oauth2providers[0].Name
ctx.Data["oauth2_provider"] = oauth2providers[0].Name()
ctx.HTML(http.StatusOK, tplAuthNew)
}

View file

@ -35,7 +35,7 @@ func DefaultOrSystemWebhooks(ctx *context.Context) {
sys["Title"] = ctx.Tr("admin.systemhooks")
sys["Description"] = ctx.Tr("admin.systemhooks.desc")
sys["Webhooks"], err = webhook.GetSystemWebhooks(util.OptionalBoolNone)
sys["Webhooks"], err = webhook.GetSystemWebhooks(ctx, util.OptionalBoolNone)
sys["BaseLink"] = setting.AppSubURL + "/admin/hooks"
sys["BaseLinkNew"] = setting.AppSubURL + "/admin/system-hooks"
if err != nil {
@ -45,7 +45,7 @@ func DefaultOrSystemWebhooks(ctx *context.Context) {
def["Title"] = ctx.Tr("admin.defaulthooks")
def["Description"] = ctx.Tr("admin.defaulthooks.desc")
def["Webhooks"], err = webhook.GetDefaultWebhooks()
def["Webhooks"], err = webhook.GetDefaultWebhooks(ctx)
def["BaseLink"] = setting.AppSubURL + "/admin/hooks"
def["BaseLinkNew"] = setting.AppSubURL + "/admin/default-hooks"
if err != nil {

View file

@ -121,7 +121,7 @@ func AdoptOrDeleteRepository(ctx *context.Context) {
return
}
ctxUser, err := user_model.GetUserByName(dirSplit[0])
ctxUser, err := user_model.GetUserByName(ctx, dirSplit[0])
if err != nil {
if user_model.IsErrUserNotExist(err) {
log.Debug("User does not exist: %s", dirSplit[0])
@ -135,7 +135,7 @@ func AdoptOrDeleteRepository(ctx *context.Context) {
repoName := dirSplit[1]
// check not a repo
has, err := repo_model.IsRepositoryExist(ctxUser, repoName)
has, err := repo_model.IsRepositoryExist(ctx, ctxUser, repoName)
if err != nil {
ctx.ServerError("IsRepositoryExist", err)
return

View file

@ -389,7 +389,7 @@ func EditUserPost(ctx *context.Context) {
u.ProhibitLogin = form.ProhibitLogin
}
if err := user_model.UpdateUser(u, emailChanged); err != nil {
if err := user_model.UpdateUser(ctx, u, emailChanged); err != nil {
if user_model.IsErrEmailAlreadyUsed(err) {
ctx.Data["Err_Email"] = true
ctx.RenderWithErr(ctx.Tr("form.email_been_used"), tplUserEdit, &form)

View file

@ -47,7 +47,7 @@ func TestNewUserPost_MustChangePassword(t *testing.T) {
assert.NotEmpty(t, ctx.Flash.SuccessMsg)
u, err := user_model.GetUserByName(username)
u, err := user_model.GetUserByName(ctx, username)
assert.NoError(t, err)
assert.Equal(t, username, u.Name)
@ -84,7 +84,7 @@ func TestNewUserPost_MustChangePasswordFalse(t *testing.T) {
assert.NotEmpty(t, ctx.Flash.SuccessMsg)
u, err := user_model.GetUserByName(username)
u, err := user_model.GetUserByName(ctx, username)
assert.NoError(t, err)
assert.Equal(t, username, u.Name)
@ -151,7 +151,7 @@ func TestNewUserPost_VisibilityDefaultPublic(t *testing.T) {
assert.NotEmpty(t, ctx.Flash.SuccessMsg)
u, err := user_model.GetUserByName(username)
u, err := user_model.GetUserByName(ctx, username)
assert.NoError(t, err)
assert.Equal(t, username, u.Name)
@ -190,7 +190,7 @@ func TestNewUserPost_VisibilityPrivate(t *testing.T) {
assert.NotEmpty(t, ctx.Flash.SuccessMsg)
u, err := user_model.GetUserByName(username)
u, err := user_model.GetUserByName(ctx, username)
assert.NoError(t, err)
assert.Equal(t, username, u.Name)

View file

@ -64,7 +64,7 @@ func AutoSignIn(ctx *context.Context) (bool, error) {
}
}()
u, err := user_model.GetUserByName(uname)
u, err := user_model.GetUserByName(ctx, uname)
if err != nil {
if !user_model.IsErrUserNotExist(err) {
return false, fmt.Errorf("GetUserByName: %v", err)
@ -632,8 +632,10 @@ func handleUserCreated(ctx *context.Context, u *user_model.User, gothUser *goth.
ctx.Data["ActiveCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale.Language())
ctx.HTML(http.StatusOK, TplActivate)
if err := ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
log.Error("Set cache(MailResendLimit) fail: %v", err)
if setting.CacheService.Enabled {
if err := ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
log.Error("Set cache(MailResendLimit) fail: %v", err)
}
}
return
}
@ -653,14 +655,16 @@ func Activate(ctx *context.Context) {
}
// Resend confirmation email.
if setting.Service.RegisterEmailConfirm {
if ctx.Cache.IsExist("MailResendLimit_" + ctx.Doer.LowerName) {
if setting.CacheService.Enabled && ctx.Cache.IsExist("MailResendLimit_"+ctx.Doer.LowerName) {
ctx.Data["ResendLimited"] = true
} else {
ctx.Data["ActiveCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale.Language())
mailer.SendActivateAccountMail(ctx.Locale, ctx.Doer)
if err := ctx.Cache.Put("MailResendLimit_"+ctx.Doer.LowerName, ctx.Doer.LowerName, 180); err != nil {
log.Error("Set cache(MailResendLimit) fail: %v", err)
if setting.CacheService.Enabled {
if err := ctx.Cache.Put("MailResendLimit_"+ctx.Doer.LowerName, ctx.Doer.LowerName, 180); err != nil {
log.Error("Set cache(MailResendLimit) fail: %v", err)
}
}
}
} else {
@ -789,7 +793,7 @@ func ActivateEmail(ctx *context.Context) {
if u, err := user_model.GetUserByID(email.UID); err != nil {
log.Warn("GetUserByID: %d", email.UID)
} else {
} else if setting.CacheService.Enabled {
// Allow user to validate more emails
_ = ctx.Cache.Delete("MailResendLimit_" + u.LowerName)
}

View file

@ -70,7 +70,7 @@ func LinkAccount(ctx *context.Context) {
ctx.Data["user_exists"] = true
}
} else if len(uname) != 0 {
u, err := user_model.GetUserByName(uname)
u, err := user_model.GetUserByName(ctx, uname)
if err != nil && !user_model.IsErrUserNotExist(err) {
ctx.ServerError("UserSignIn", err)
return

View file

@ -5,6 +5,7 @@
package auth
import (
stdContext "context"
"encoding/base64"
"errors"
"fmt"
@ -135,9 +136,9 @@ type AccessTokenResponse struct {
IDToken string `json:"id_token,omitempty"`
}
func newAccessTokenResponse(grant *auth.OAuth2Grant, serverKey, clientKey oauth2.JWTSigningKey) (*AccessTokenResponse, *AccessTokenError) {
func newAccessTokenResponse(ctx stdContext.Context, grant *auth.OAuth2Grant, serverKey, clientKey oauth2.JWTSigningKey) (*AccessTokenResponse, *AccessTokenError) {
if setting.OAuth2.InvalidateRefreshTokens {
if err := grant.IncreaseCounter(); err != nil {
if err := grant.IncreaseCounter(ctx); err != nil {
return nil, &AccessTokenError{
ErrorCode: AccessTokenErrorCodeInvalidGrant,
ErrorDescription: "cannot increase the grant counter",
@ -182,7 +183,7 @@ func newAccessTokenResponse(grant *auth.OAuth2Grant, serverKey, clientKey oauth2
// generate OpenID Connect id_token
signedIDToken := ""
if grant.ScopeContains("openid") {
app, err := auth.GetOAuth2ApplicationByID(grant.ApplicationID)
app, err := auth.GetOAuth2ApplicationByID(ctx, grant.ApplicationID)
if err != nil {
return nil, &AccessTokenError{
ErrorCode: AccessTokenErrorCodeInvalidRequest,
@ -333,9 +334,9 @@ func IntrospectOAuth(ctx *context.Context) {
token, err := oauth2.ParseToken(form.Token, oauth2.DefaultSigningKey)
if err == nil {
if token.Valid() == nil {
grant, err := auth.GetOAuth2GrantByID(token.GrantID)
grant, err := auth.GetOAuth2GrantByID(ctx, token.GrantID)
if err == nil && grant != nil {
app, err := auth.GetOAuth2ApplicationByID(grant.ApplicationID)
app, err := auth.GetOAuth2ApplicationByID(ctx, grant.ApplicationID)
if err == nil && app != nil {
response.Active = true
response.Scope = grant.Scope
@ -364,7 +365,7 @@ func AuthorizeOAuth(ctx *context.Context) {
return
}
app, err := auth.GetOAuth2ApplicationByClientID(form.ClientID)
app, err := auth.GetOAuth2ApplicationByClientID(ctx, form.ClientID)
if err != nil {
if auth.IsErrOauthClientIDInvalid(err) {
handleAuthorizeError(ctx, AuthorizeError{
@ -438,7 +439,7 @@ func AuthorizeOAuth(ctx *context.Context) {
return
}
grant, err := app.GetGrantByUserID(ctx.Doer.ID)
grant, err := app.GetGrantByUserID(ctx, ctx.Doer.ID)
if err != nil {
handleServerError(ctx, form.State, form.RedirectURI)
return
@ -446,7 +447,7 @@ func AuthorizeOAuth(ctx *context.Context) {
// Redirect if user already granted access
if grant != nil {
code, err := grant.GenerateNewAuthorizationCode(form.RedirectURI, form.CodeChallenge, form.CodeChallengeMethod)
code, err := grant.GenerateNewAuthorizationCode(ctx, form.RedirectURI, form.CodeChallenge, form.CodeChallengeMethod)
if err != nil {
handleServerError(ctx, form.State, form.RedirectURI)
return
@ -458,7 +459,7 @@ func AuthorizeOAuth(ctx *context.Context) {
}
// Update nonce to reflect the new session
if len(form.Nonce) > 0 {
err := grant.SetNonce(form.Nonce)
err := grant.SetNonce(ctx, form.Nonce)
if err != nil {
log.Error("Unable to update nonce: %v", err)
}
@ -510,12 +511,12 @@ func GrantApplicationOAuth(ctx *context.Context) {
ctx.Error(http.StatusBadRequest)
return
}
app, err := auth.GetOAuth2ApplicationByClientID(form.ClientID)
app, err := auth.GetOAuth2ApplicationByClientID(ctx, form.ClientID)
if err != nil {
ctx.ServerError("GetOAuth2ApplicationByClientID", err)
return
}
grant, err := app.CreateGrant(ctx.Doer.ID, form.Scope)
grant, err := app.CreateGrant(ctx, ctx.Doer.ID, form.Scope)
if err != nil {
handleAuthorizeError(ctx, AuthorizeError{
State: form.State,
@ -525,7 +526,7 @@ func GrantApplicationOAuth(ctx *context.Context) {
return
}
if len(form.Nonce) > 0 {
err := grant.SetNonce(form.Nonce)
err := grant.SetNonce(ctx, form.Nonce)
if err != nil {
log.Error("Unable to update nonce: %v", err)
}
@ -535,7 +536,7 @@ func GrantApplicationOAuth(ctx *context.Context) {
codeChallenge, _ = ctx.Session.Get("CodeChallenge").(string)
codeChallengeMethod, _ = ctx.Session.Get("CodeChallengeMethod").(string)
code, err := grant.GenerateNewAuthorizationCode(form.RedirectURI, codeChallenge, codeChallengeMethod)
code, err := grant.GenerateNewAuthorizationCode(ctx, form.RedirectURI, codeChallenge, codeChallengeMethod)
if err != nil {
handleServerError(ctx, form.State, form.RedirectURI)
return
@ -648,7 +649,7 @@ func handleRefreshToken(ctx *context.Context, form forms.AccessTokenForm, server
return
}
// get grant before increasing counter
grant, err := auth.GetOAuth2GrantByID(token.GrantID)
grant, err := auth.GetOAuth2GrantByID(ctx, token.GrantID)
if err != nil || grant == nil {
handleAccessTokenError(ctx, AccessTokenError{
ErrorCode: AccessTokenErrorCodeInvalidGrant,
@ -666,7 +667,7 @@ func handleRefreshToken(ctx *context.Context, form forms.AccessTokenForm, server
log.Warn("A client tried to use a refresh token for grant_id = %d was used twice!", grant.ID)
return
}
accessToken, tokenErr := newAccessTokenResponse(grant, serverKey, clientKey)
accessToken, tokenErr := newAccessTokenResponse(ctx, grant, serverKey, clientKey)
if tokenErr != nil {
handleAccessTokenError(ctx, *tokenErr)
return
@ -675,7 +676,7 @@ func handleRefreshToken(ctx *context.Context, form forms.AccessTokenForm, server
}
func handleAuthorizationCode(ctx *context.Context, form forms.AccessTokenForm, serverKey, clientKey oauth2.JWTSigningKey) {
app, err := auth.GetOAuth2ApplicationByClientID(form.ClientID)
app, err := auth.GetOAuth2ApplicationByClientID(ctx, form.ClientID)
if err != nil {
handleAccessTokenError(ctx, AccessTokenError{
ErrorCode: AccessTokenErrorCodeInvalidClient,
@ -697,7 +698,7 @@ func handleAuthorizationCode(ctx *context.Context, form forms.AccessTokenForm, s
})
return
}
authorizationCode, err := auth.GetOAuth2AuthorizationByCode(form.Code)
authorizationCode, err := auth.GetOAuth2AuthorizationByCode(ctx, form.Code)
if err != nil || authorizationCode == nil {
handleAccessTokenError(ctx, AccessTokenError{
ErrorCode: AccessTokenErrorCodeUnauthorizedClient,
@ -722,13 +723,13 @@ func handleAuthorizationCode(ctx *context.Context, form forms.AccessTokenForm, s
return
}
// remove token from database to deny duplicate usage
if err := authorizationCode.Invalidate(); err != nil {
if err := authorizationCode.Invalidate(ctx); err != nil {
handleAccessTokenError(ctx, AccessTokenError{
ErrorCode: AccessTokenErrorCodeInvalidRequest,
ErrorDescription: "cannot proceed your request",
})
}
resp, tokenErr := newAccessTokenResponse(authorizationCode.Grant, serverKey, clientKey)
resp, tokenErr := newAccessTokenResponse(ctx, authorizationCode.Grant, serverKey, clientKey)
if tokenErr != nil {
handleAccessTokenError(ctx, *tokenErr)
return
@ -846,7 +847,17 @@ func SignInOAuthCallback(ctx *context.Context) {
}
if u == nil {
if !setting.Service.AllowOnlyInternalRegistration && setting.OAuth2Client.EnableAutoRegistration {
if ctx.Doer != nil {
// attach user to already logged in user
err = externalaccount.LinkAccountToUser(ctx.Doer, gothUser)
if err != nil {
ctx.ServerError("UserLinkAccount", err)
return
}
ctx.Redirect(setting.AppSubURL + "/user/settings/security")
return
} else if !setting.Service.AllowOnlyInternalRegistration && setting.OAuth2Client.EnableAutoRegistration {
// create new user with details from oauth2 provider
var missingFields []string
if gothUser.UserID == "" {

View file

@ -8,6 +8,7 @@ import (
"testing"
"code.gitea.io/gitea/models/auth"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/services/auth/source/oauth2"
@ -21,7 +22,7 @@ func createAndParseToken(t *testing.T, grant *auth.OAuth2Grant) *oauth2.OIDCToke
assert.NoError(t, err)
assert.NotNil(t, signingKey)
response, terr := newAccessTokenResponse(grant, signingKey, signingKey)
response, terr := newAccessTokenResponse(db.DefaultContext, grant, signingKey, signingKey)
assert.Nil(t, terr)
assert.NotNil(t, response)
@ -43,7 +44,7 @@ func createAndParseToken(t *testing.T, grant *auth.OAuth2Grant) *oauth2.OIDCToke
func TestNewAccessTokenResponse_OIDCToken(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
grants, err := auth.GetOAuth2GrantsByUserID(3)
grants, err := auth.GetOAuth2GrantsByUserID(db.DefaultContext, 3)
assert.NoError(t, err)
assert.Len(t, grants, 1)
@ -59,7 +60,7 @@ func TestNewAccessTokenResponse_OIDCToken(t *testing.T) {
assert.False(t, oidcToken.EmailVerified)
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}).(*user_model.User)
grants, err = auth.GetOAuth2GrantsByUserID(user.ID)
grants, err = auth.GetOAuth2GrantsByUserID(db.DefaultContext, user.ID)
assert.NoError(t, err)
assert.Len(t, grants, 1)

View file

@ -217,7 +217,7 @@ func signInOpenIDVerify(ctx *context.Context) {
}
if u == nil && nickname != "" {
u, _ = user_model.GetUserByName(nickname)
u, _ = user_model.GetUserByName(ctx, nickname)
if err != nil {
if !user_model.IsErrUserNotExist(err) {
ctx.RenderWithErr(err.Error(), tplSignInOpenID, &forms.SignInOpenIDForm{
@ -307,7 +307,7 @@ func ConnectOpenIDPost(ctx *context.Context) {
// add OpenID for the user
userOID := &user_model.UserOpenID{UID: u.ID, URI: oid}
if err = user_model.AddUserOpenID(userOID); err != nil {
if err = user_model.AddUserOpenID(ctx, userOID); err != nil {
if user_model.IsErrOpenIDAlreadyUsed(err) {
ctx.RenderWithErr(ctx.Tr("form.openid_been_used", oid), tplConnectOID, &form)
return
@ -434,7 +434,7 @@ func RegisterOpenIDPost(ctx *context.Context) {
// add OpenID for the user
userOID := &user_model.UserOpenID{UID: u.ID, URI: oid}
if err = user_model.AddUserOpenID(userOID); err != nil {
if err = user_model.AddUserOpenID(ctx, userOID); err != nil {
if user_model.IsErrOpenIDAlreadyUsed(err) {
ctx.RenderWithErr(ctx.Tr("form.openid_been_used", oid), tplSignUpOID, &form)
return

View file

@ -79,7 +79,7 @@ func ForgotPasswdPost(ctx *context.Context) {
return
}
if ctx.Cache.IsExist("MailResendLimit_" + u.LowerName) {
if setting.CacheService.Enabled && ctx.Cache.IsExist("MailResendLimit_"+u.LowerName) {
ctx.Data["ResendLimited"] = true
ctx.HTML(http.StatusOK, tplForgotPassword)
return
@ -87,8 +87,10 @@ func ForgotPasswdPost(ctx *context.Context) {
mailer.SendResetPasswordMail(u)
if err = ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
log.Error("Set cache(MailResendLimit) fail: %v", err)
if setting.CacheService.Enabled {
if err = ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
log.Error("Set cache(MailResendLimit) fail: %v", err)
}
}
ctx.Data["ResetPwdCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ResetPwdCodeLives, ctx.Locale.Language())

View file

@ -62,7 +62,7 @@ func storageHandler(storageSetting setting.Storage, prefix string, objStore stor
w,
req,
u.String(),
http.StatusPermanentRedirect,
http.StatusTemporaryRedirect,
)
})
}

View file

@ -55,7 +55,7 @@ func Code(ctx *context.Context) {
// guest user or non-admin user
if ctx.Doer == nil || !isAdmin {
repoIDs, err = models.FindUserAccessibleRepoIDs(ctx.Doer)
repoIDs, err = repo_model.FindUserAccessibleRepoIDs(ctx.Doer)
if err != nil {
ctx.ServerError("SearchResults", err)
return
@ -79,7 +79,7 @@ func Code(ctx *context.Context) {
rightRepoMap := make(map[int64]*repo_model.Repository, len(repoMaps))
repoIDs = make([]int64, 0, len(repoMaps))
for id, repo := range repoMaps {
if models.CheckRepoUnitUser(repo, ctx.Doer, unit.TypeCode) {
if models.CheckRepoUnitUser(ctx, repo, ctx.Doer, unit.TypeCode) {
rightRepoMap[id] = repo
repoIDs = append(repoIDs, id)
}

View file

@ -7,7 +7,6 @@ package explore
import (
"net/http"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/modules/base"
@ -81,7 +80,7 @@ func RenderRepoSearch(ctx *context.Context, opts *RepoSearchOptions) {
language := ctx.FormTrim("language")
ctx.Data["Language"] = language
repos, count, err = models.SearchRepository(&models.SearchRepoOptions{
repos, count, err = repo_model.SearchRepository(&repo_model.SearchRepoOptions{
ListOptions: db.ListOptions{
Page: page,
PageSize: opts.PageSize,

View file

@ -126,7 +126,7 @@ func checkCache(checks checks) status {
}
st := componentStatus{}
if err := cache.Ping(); err != nil {
if err := cache.GetCache().Ping(); err != nil {
st.Status = fail
st.Time = getCheckTime()
log.Error("cache ping failed with error: %v", err)

View file

@ -8,7 +8,6 @@ import (
"net/http"
"strings"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/organization"
repo_model "code.gitea.io/gitea/models/repo"
@ -105,7 +104,7 @@ func Home(ctx *context.Context) {
count int64
err error
)
repos, count, err = models.SearchRepository(&models.SearchRepoOptions{
repos, count, err = repo_model.SearchRepository(&repo_model.SearchRepoOptions{
ListOptions: db.ListOptions{
PageSize: setting.UI.User.RepoPagingNum,
Page: page,

View file

@ -63,7 +63,7 @@ func Members(ctx *context.Context) {
ctx.Data["Page"] = pager
ctx.Data["Members"] = members
ctx.Data["MembersIsPublicMember"] = membersIsPublic
ctx.Data["MembersIsUserOrgOwner"] = models.IsUserOrgOwner(members, org.ID)
ctx.Data["MembersIsUserOrgOwner"] = organization.IsUserOrgOwner(members, org.ID)
ctx.Data["MembersTwoFaStatus"] = members.GetTwoFaStatus()
ctx.HTML(http.StatusOK, tplMembers)

View file

@ -17,7 +17,7 @@ import (
// RetrieveLabels find all the labels of an organization
func RetrieveLabels(ctx *context.Context) {
labels, err := models.GetLabelsByOrgID(ctx.Org.Organization.ID, ctx.FormString("sort"), db.ListOptions{})
labels, err := models.GetLabelsByOrgID(ctx, ctx.Org.Organization.ID, ctx.FormString("sort"), db.ListOptions{})
if err != nil {
ctx.ServerError("RetrieveLabels.GetLabels", err)
return
@ -59,7 +59,7 @@ func NewLabel(ctx *context.Context) {
// UpdateLabel update a label's name and color
func UpdateLabel(ctx *context.Context) {
form := web.GetForm(ctx).(*forms.CreateLabelForm)
l, err := models.GetLabelInOrgByID(ctx.Org.Organization.ID, form.ID)
l, err := models.GetLabelInOrgByID(ctx, ctx.Org.Organization.ID, form.ID)
if err != nil {
switch {
case models.IsErrOrgLabelNotExist(err):

View file

@ -24,6 +24,7 @@ import (
user_setting "code.gitea.io/gitea/routers/web/user/setting"
"code.gitea.io/gitea/services/forms"
"code.gitea.io/gitea/services/org"
repo_service "code.gitea.io/gitea/services/repository"
user_service "code.gitea.io/gitea/services/user"
)
@ -66,7 +67,7 @@ func SettingsPost(ctx *context.Context) {
// Check if organization name has been changed.
if org.LowerName != strings.ToLower(form.Name) {
isExist, err := user_model.IsUserExist(org.ID, form.Name)
isExist, err := user_model.IsUserExist(ctx, org.ID, form.Name)
if err != nil {
ctx.ServerError("IsUserExist", err)
return
@ -110,14 +111,14 @@ func SettingsPost(ctx *context.Context) {
visibilityChanged := form.Visibility != org.Visibility
org.Visibility = form.Visibility
if err := user_model.UpdateUser(org.AsUser(), false); err != nil {
if err := user_model.UpdateUser(ctx, org.AsUser(), false); err != nil {
ctx.ServerError("UpdateUser", err)
return
}
// update forks visibility
if visibilityChanged {
repos, _, err := models.GetUserRepositories(&models.SearchRepoOptions{
repos, _, err := repo_model.GetUserRepositories(&repo_model.SearchRepoOptions{
Actor: org.AsUser(), Private: true, ListOptions: db.ListOptions{Page: 1, PageSize: org.NumRepos},
})
if err != nil {
@ -126,7 +127,7 @@ func SettingsPost(ctx *context.Context) {
}
for _, repo := range repos {
repo.OwnerName = org.Name
if err := models.UpdateRepository(repo, true); err != nil {
if err := repo_service.UpdateRepository(repo, true); err != nil {
ctx.ServerError("UpdateRepository", err)
return
}
@ -207,7 +208,7 @@ func Webhooks(ctx *context.Context) {
ctx.Data["BaseLinkNew"] = ctx.Org.OrgLink + "/settings/hooks"
ctx.Data["Description"] = ctx.Tr("org.settings.hooks_desc")
ws, err := webhook.ListWebhooksByOpts(&webhook.ListWebhookOptions{OrgID: ctx.Org.Organization.ID})
ws, err := webhook.ListWebhooksByOpts(ctx, &webhook.ListWebhookOptions{OrgID: ctx.Org.Organization.ID})
if err != nil {
ctx.ServerError("GetWebhooksByOrgId", err)
return

View file

@ -23,7 +23,6 @@ import (
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/convert"
"code.gitea.io/gitea/modules/log"
api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/web"
"code.gitea.io/gitea/routers/utils"
"code.gitea.io/gitea/services/forms"
@ -123,7 +122,7 @@ func TeamsAction(ctx *context.Context) {
}
uname := utils.RemoveUsernameParameterSuffix(strings.ToLower(ctx.FormString("uname")))
var u *user_model.User
u, err = user_model.GetUserByName(uname)
u, err = user_model.GetUserByName(ctx, uname)
if err != nil {
if user_model.IsErrUserNotExist(err) {
ctx.Flash.Error(ctx.Tr("form.user_not_exist"))
@ -357,17 +356,14 @@ func SearchTeam(ctx *context.Context) {
return
}
apiTeams := make([]*api.Team, len(teams))
for i := range teams {
if err := teams[i].GetUnits(); err != nil {
log.Error("Team GetUnits failed: %v", err)
ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
"ok": false,
"error": "SearchTeam failed to get units",
})
return
}
apiTeams[i] = convert.ToTeam(teams[i])
apiTeams, err := convert.ToTeams(teams, false)
if err != nil {
log.Error("convert ToTeams failed: %v", err)
ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
"ok": false,
"error": "SearchTeam failed to get units",
})
return
}
ctx.SetTotalCountHeader(maxResults)

View file

@ -8,7 +8,7 @@ import (
"fmt"
"net/http"
"code.gitea.io/gitea/models"
access_model "code.gitea.io/gitea/models/perm/access"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/httpcache"
@ -18,6 +18,7 @@ import (
"code.gitea.io/gitea/modules/upload"
"code.gitea.io/gitea/routers/common"
"code.gitea.io/gitea/services/attachment"
repo_service "code.gitea.io/gitea/services/repository"
)
// UploadIssueAttachment response for Issue/PR attachments
@ -63,7 +64,7 @@ func uploadAttachment(ctx *context.Context, repoID int64, allowedTypes string) {
// DeleteAttachment response for deleting issue's attachment
func DeleteAttachment(ctx *context.Context) {
file := ctx.FormString("file")
attach, err := repo_model.GetAttachmentByUUID(file)
attach, err := repo_model.GetAttachmentByUUID(ctx, file)
if err != nil {
ctx.Error(http.StatusBadRequest, err.Error())
return
@ -84,7 +85,7 @@ func DeleteAttachment(ctx *context.Context) {
// GetAttachment serve attachements
func GetAttachment(ctx *context.Context) {
attach, err := repo_model.GetAttachmentByUUID(ctx.Params(":uuid"))
attach, err := repo_model.GetAttachmentByUUID(ctx, ctx.Params(":uuid"))
if err != nil {
if repo_model.IsErrAttachmentNotExist(err) {
ctx.Error(http.StatusNotFound)
@ -94,7 +95,7 @@ func GetAttachment(ctx *context.Context) {
return
}
repository, unitType, err := models.LinkedRepository(attach)
repository, unitType, err := repo_service.LinkedRepository(attach)
if err != nil {
ctx.ServerError("LinkedRepository", err)
return
@ -106,7 +107,7 @@ func GetAttachment(ctx *context.Context) {
return
}
} else { // If we have the repository we check access
perm, err := models.GetUserRepoPermission(ctx, repository, ctx.Doer)
perm, err := access_model.GetUserRepoPermission(ctx, repository, ctx.Doer)
if err != nil {
ctx.Error(http.StatusInternalServerError, "GetUserRepoPermission", err.Error())
return

View file

@ -335,7 +335,7 @@ func Diff(ctx *context.Context) {
ctx.Data["Commit"] = commit
ctx.Data["Diff"] = diff
statuses, _, err := models.GetLatestCommitStatus(ctx.Repo.Repository.ID, commitID, db.ListOptions{})
statuses, _, err := models.GetLatestCommitStatus(ctx, ctx.Repo.Repository.ID, commitID, db.ListOptions{})
if err != nil {
log.Error("GetLatestCommitStatus: %v", err)
}

View file

@ -18,6 +18,7 @@ import (
"strings"
"code.gitea.io/gitea/models"
access_model "code.gitea.io/gitea/models/perm/access"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unit"
user_model "code.gitea.io/gitea/models/user"
@ -253,7 +254,7 @@ func ParseCompareInfo(ctx *context.Context) *CompareInfo {
} else if len(headInfos) == 2 {
headInfosSplit := strings.Split(headInfos[0], "/")
if len(headInfosSplit) == 1 {
ci.HeadUser, err = user_model.GetUserByName(headInfos[0])
ci.HeadUser, err = user_model.GetUserByName(ctx, headInfos[0])
if err != nil {
if user_model.IsErrUserNotExist(err) {
ctx.NotFound("GetUserByName", nil)
@ -412,7 +413,7 @@ func ParseCompareInfo(ctx *context.Context) *CompareInfo {
// Now we need to assert that the ctx.Doer has permission to read
// the baseRepo's code and pulls
// (NOT headRepo's)
permBase, err := models.GetUserRepoPermission(ctx, baseRepo, ctx.Doer)
permBase, err := access_model.GetUserRepoPermission(ctx, baseRepo, ctx.Doer)
if err != nil {
ctx.ServerError("GetUserRepoPermission", err)
return nil
@ -431,7 +432,7 @@ func ParseCompareInfo(ctx *context.Context) *CompareInfo {
// If we're not merging from the same repo:
if !isSameRepo {
// Assert ctx.Doer has permission to read headRepo's codes
permHead, err := models.GetUserRepoPermission(ctx, ci.HeadRepo, ctx.Doer)
permHead, err := access_model.GetUserRepoPermission(ctx, ci.HeadRepo, ctx.Doer)
if err != nil {
ctx.ServerError("GetUserRepoPermission", err)
return nil
@ -456,7 +457,7 @@ func ParseCompareInfo(ctx *context.Context) *CompareInfo {
if rootRepo != nil &&
rootRepo.ID != ci.HeadRepo.ID &&
rootRepo.ID != baseRepo.ID {
canRead := models.CheckRepoUnitUser(rootRepo, ctx.Doer, unit.TypeCode)
canRead := models.CheckRepoUnitUser(ctx, rootRepo, ctx.Doer, unit.TypeCode)
if canRead {
ctx.Data["RootRepo"] = rootRepo
if !fileOnly {
@ -481,7 +482,7 @@ func ParseCompareInfo(ctx *context.Context) *CompareInfo {
ownForkRepo.ID != ci.HeadRepo.ID &&
ownForkRepo.ID != baseRepo.ID &&
(rootRepo == nil || ownForkRepo.ID != rootRepo.ID) {
canRead := models.CheckRepoUnitUser(ownForkRepo, ctx.Doer, unit.TypeCode)
canRead := models.CheckRepoUnitUser(ctx, ownForkRepo, ctx.Doer, unit.TypeCode)
if canRead {
ctx.Data["OwnForkRepo"] = ownForkRepo
if !fileOnly {

24
routers/web/repo/find.go Normal file
View file

@ -0,0 +1,24 @@
// Copyright 2022 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package repo
import (
"net/http"
"code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/context"
)
const (
tplFindFiles base.TplName = "repo/find/files"
)
// FindFiles render the page to find repository files
func FindFiles(ctx *context.Context) {
path := ctx.Params("*")
ctx.Data["TreeLink"] = ctx.Repo.RepoLink + "/src/" + path
ctx.Data["DataLink"] = ctx.Repo.RepoLink + "/tree-list/" + path
ctx.HTML(http.StatusOK, tplFindFiles)
}

View file

@ -19,9 +19,9 @@ import (
"sync"
"time"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/auth"
"code.gitea.io/gitea/models/perm"
access_model "code.gitea.io/gitea/models/perm/access"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unit"
"code.gitea.io/gitea/modules/context"
@ -182,7 +182,7 @@ func httpBase(ctx *context.Context) (h *serviceHandler) {
}
if repoExist {
p, err := models.GetUserRepoPermission(ctx, repo, ctx.Doer)
p, err := access_model.GetUserRepoPermission(ctx, repo, ctx.Doer)
if err != nil {
ctx.ServerError("GetUserRepoPermission", err)
return

View file

@ -23,6 +23,7 @@ import (
"code.gitea.io/gitea/models/db"
issues_model "code.gitea.io/gitea/models/issues"
"code.gitea.io/gitea/models/organization"
access_model "code.gitea.io/gitea/models/perm/access"
project_model "code.gitea.io/gitea/models/project"
pull_model "code.gitea.io/gitea/models/pull"
repo_model "code.gitea.io/gitea/models/repo"
@ -48,6 +49,7 @@ import (
"code.gitea.io/gitea/services/forms"
issue_service "code.gitea.io/gitea/services/issue"
pull_service "code.gitea.io/gitea/services/pull"
repo_service "code.gitea.io/gitea/services/repository"
)
const (
@ -254,7 +256,7 @@ func issues(ctx *context.Context, milestoneID, projectID int64, isPullOption uti
}
issueList := models.IssueList(issues)
approvalCounts, err := issueList.GetApprovalCounts()
approvalCounts, err := issueList.GetApprovalCounts(ctx)
if err != nil {
ctx.ServerError("ApprovalCounts", err)
return
@ -282,7 +284,7 @@ func issues(ctx *context.Context, milestoneID, projectID int64, isPullOption uti
ctx.Data["CommitStatuses"] = commitStatuses
// Get assignees.
ctx.Data["Assignees"], err = models.GetRepoAssignees(repo)
ctx.Data["Assignees"], err = repo_model.GetRepoAssignees(ctx, repo)
if err != nil {
ctx.ServerError("GetAssignees", err)
return
@ -293,14 +295,14 @@ func issues(ctx *context.Context, milestoneID, projectID int64, isPullOption uti
return
}
labels, err := models.GetLabelsByRepoID(repo.ID, "", db.ListOptions{})
labels, err := models.GetLabelsByRepoID(ctx, repo.ID, "", db.ListOptions{})
if err != nil {
ctx.ServerError("GetLabelsByRepoID", err)
return
}
if repo.Owner.IsOrganization() {
orgLabels, err := models.GetLabelsByOrgID(repo.Owner.ID, ctx.FormString("sort"), db.ListOptions{})
orgLabels, err := models.GetLabelsByOrgID(ctx, repo.Owner.ID, ctx.FormString("sort"), db.ListOptions{})
if err != nil {
ctx.ServerError("GetLabelsByOrgID", err)
return
@ -342,7 +344,7 @@ func issues(ctx *context.Context, milestoneID, projectID int64, isPullOption uti
}
if ctx.Repo.CanWriteIssuesOrPulls(ctx.Params(":type") == "pulls") {
projects, _, err := project_model.GetProjects(project_model.SearchOptions{
projects, _, err := project_model.GetProjects(ctx, project_model.SearchOptions{
RepoID: repo.ID,
Type: project_model.TypeRepository,
IsClosed: util.OptionalBoolOf(isShowClosed),
@ -440,7 +442,7 @@ func RetrieveRepoMilestonesAndAssignees(ctx *context.Context, repo *repo_model.R
return
}
ctx.Data["Assignees"], err = models.GetRepoAssignees(repo)
ctx.Data["Assignees"], err = repo_model.GetRepoAssignees(ctx, repo)
if err != nil {
ctx.ServerError("GetAssignees", err)
return
@ -452,7 +454,7 @@ func RetrieveRepoMilestonesAndAssignees(ctx *context.Context, repo *repo_model.R
func retrieveProjects(ctx *context.Context, repo *repo_model.Repository) {
var err error
ctx.Data["OpenProjects"], _, err = project_model.GetProjects(project_model.SearchOptions{
ctx.Data["OpenProjects"], _, err = project_model.GetProjects(ctx, project_model.SearchOptions{
RepoID: repo.ID,
Page: -1,
IsClosed: util.OptionalBoolFalse,
@ -463,7 +465,7 @@ func retrieveProjects(ctx *context.Context, repo *repo_model.Repository) {
return
}
ctx.Data["ClosedProjects"], _, err = project_model.GetProjects(project_model.SearchOptions{
ctx.Data["ClosedProjects"], _, err = project_model.GetProjects(ctx, project_model.SearchOptions{
RepoID: repo.ID,
Page: -1,
IsClosed: util.OptionalBoolTrue,
@ -521,13 +523,13 @@ func RetrieveRepoReviewers(ctx *context.Context, repo *repo_model.Repository, is
posterID = 0
}
reviewers, err = models.GetReviewers(repo, ctx.Doer.ID, posterID)
reviewers, err = repo_model.GetReviewers(ctx, repo, ctx.Doer.ID, posterID)
if err != nil {
ctx.ServerError("GetReviewers", err)
return
}
teamReviewers, err = models.GetReviewerTeams(repo)
teamReviewers, err = repo_service.GetReviewerTeams(repo)
if err != nil {
ctx.ServerError("GetReviewerTeams", err)
return
@ -672,14 +674,14 @@ func RetrieveRepoMetas(ctx *context.Context, repo *repo_model.Repository, isPull
return nil
}
labels, err := models.GetLabelsByRepoID(repo.ID, "", db.ListOptions{})
labels, err := models.GetLabelsByRepoID(ctx, repo.ID, "", db.ListOptions{})
if err != nil {
ctx.ServerError("GetLabelsByRepoID", err)
return nil
}
ctx.Data["Labels"] = labels
if repo.Owner.IsOrganization() {
orgLabels, err := models.GetLabelsByOrgID(repo.Owner.ID, ctx.FormString("sort"), db.ListOptions{})
orgLabels, err := models.GetLabelsByOrgID(ctx, repo.Owner.ID, ctx.FormString("sort"), db.ListOptions{})
if err != nil {
return nil
}
@ -760,10 +762,10 @@ func setTemplateIfExists(ctx *context.Context, ctxDataKey string, possibleDirs,
ctx.Data[issueTemplateTitleKey] = meta.Title
ctx.Data[ctxDataKey] = templateBody
labelIDs := make([]string, 0, len(meta.Labels))
if repoLabels, err := models.GetLabelsByRepoID(ctx.Repo.Repository.ID, "", db.ListOptions{}); err == nil {
if repoLabels, err := models.GetLabelsByRepoID(ctx, ctx.Repo.Repository.ID, "", db.ListOptions{}); err == nil {
ctx.Data["Labels"] = repoLabels
if ctx.Repo.Owner.IsOrganization() {
if orgLabels, err := models.GetLabelsByOrgID(ctx.Repo.Owner.ID, ctx.FormString("sort"), db.ListOptions{}); err == nil {
if orgLabels, err := models.GetLabelsByOrgID(ctx, ctx.Repo.Owner.ID, ctx.FormString("sort"), db.ListOptions{}); err == nil {
ctx.Data["OrgLabels"] = orgLabels
repoLabels = append(repoLabels, orgLabels...)
}
@ -817,7 +819,7 @@ func NewIssue(ctx *context.Context) {
projectID := ctx.FormInt64("project")
if projectID > 0 {
project, err := project_model.GetProjectByID(projectID)
project, err := project_model.GetProjectByID(ctx, projectID)
if err != nil {
log.Error("GetProjectByID: %d: %v", projectID, err)
} else if project.RepoID != ctx.Repo.Repository.ID {
@ -929,7 +931,7 @@ func ValidateRepoMetas(ctx *context.Context, form forms.CreateIssueForm, isPull
}
if form.ProjectID > 0 {
p, err := project_model.GetProjectByID(form.ProjectID)
p, err := project_model.GetProjectByID(ctx, form.ProjectID)
if err != nil {
ctx.ServerError("GetProjectByID", err)
return nil, nil, 0, 0
@ -959,7 +961,7 @@ func ValidateRepoMetas(ctx *context.Context, form forms.CreateIssueForm, isPull
return nil, nil, 0, 0
}
valid, err := models.CanBeAssigned(assignee, repo, isPull)
valid, err := access_model.CanBeAssigned(ctx, assignee, repo, isPull)
if err != nil {
ctx.ServerError("CanBeAssigned", err)
return nil, nil, 0, 0
@ -1051,7 +1053,7 @@ func NewIssuePost(ctx *context.Context) {
// roleDescriptor returns the Role Descriptor for a comment in/with the given repo, poster and issue
func roleDescriptor(ctx stdCtx.Context, repo *repo_model.Repository, poster *user_model.User, issue *models.Issue) (models.RoleDescriptor, error) {
perm, err := models.GetUserRepoPermission(ctx, repo, poster)
perm, err := access_model.GetUserRepoPermission(ctx, repo, poster)
if err != nil {
return models.RoleDescriptorNone, err
}
@ -1067,7 +1069,7 @@ func roleDescriptor(ctx stdCtx.Context, repo *repo_model.Repository, poster *use
} else {
// Otherwise check if poster is the real repo admin.
ok, err := models.IsUserRealRepoAdmin(repo, poster)
ok, err := access_model.IsUserRealRepoAdmin(repo, poster)
if err != nil {
return models.RoleDescriptorNone, err
}
@ -1236,7 +1238,7 @@ func ViewIssue(ctx *context.Context) {
for i := range issue.Labels {
labelIDMark[issue.Labels[i].ID] = true
}
labels, err := models.GetLabelsByRepoID(repo.ID, "", db.ListOptions{})
labels, err := models.GetLabelsByRepoID(ctx, repo.ID, "", db.ListOptions{})
if err != nil {
ctx.ServerError("GetLabelsByRepoID", err)
return
@ -1244,7 +1246,7 @@ func ViewIssue(ctx *context.Context) {
ctx.Data["Labels"] = labels
if repo.Owner.IsOrganization() {
orgLabels, err := models.GetLabelsByOrgID(repo.Owner.ID, ctx.FormString("sort"), db.ListOptions{})
orgLabels, err := models.GetLabelsByOrgID(ctx, repo.Owner.ID, ctx.FormString("sort"), db.ListOptions{})
if err != nil {
ctx.ServerError("GetLabelsByOrgID", err)
return
@ -1276,7 +1278,7 @@ func ViewIssue(ctx *context.Context) {
if issue.IsPull {
canChooseReviewer := ctx.Repo.CanWrite(unit.TypePullRequests)
if !canChooseReviewer && ctx.Doer != nil && ctx.IsSigned {
canChooseReviewer, err = models.IsOfficialReviewer(issue, ctx.Doer)
canChooseReviewer, err = models.IsOfficialReviewer(ctx, issue, ctx.Doer)
if err != nil {
ctx.ServerError("IsOfficialReviewer", err)
return
@ -1311,7 +1313,7 @@ func ViewIssue(ctx *context.Context) {
if !ctx.Data["IsStopwatchRunning"].(bool) {
var exists bool
var sw *models.Stopwatch
if exists, sw, err = models.HasUserStopwatch(ctx.Doer.ID); err != nil {
if exists, sw, err = models.HasUserStopwatch(ctx, ctx.Doer.ID); err != nil {
ctx.ServerError("HasUserStopwatch", err)
return
}
@ -1526,7 +1528,7 @@ func ViewIssue(ctx *context.Context) {
if err := pull.LoadHeadRepoCtx(ctx); err != nil {
log.Error("LoadHeadRepo: %v", err)
} else if pull.HeadRepo != nil {
perm, err := models.GetUserRepoPermission(ctx, pull.HeadRepo, ctx.Doer)
perm, err := access_model.GetUserRepoPermission(ctx, pull.HeadRepo, ctx.Doer)
if err != nil {
ctx.ServerError("GetUserRepoPermission", err)
return
@ -1548,7 +1550,7 @@ func ViewIssue(ctx *context.Context) {
if err := pull.LoadBaseRepoCtx(ctx); err != nil {
log.Error("LoadBaseRepo: %v", err)
}
perm, err := models.GetUserRepoPermission(ctx, pull.BaseRepo, ctx.Doer)
perm, err := access_model.GetUserRepoPermission(ctx, pull.BaseRepo, ctx.Doer)
if err != nil {
ctx.ServerError("GetUserRepoPermission", err)
return
@ -1687,12 +1689,12 @@ func ViewIssue(ctx *context.Context) {
}
// Get Dependencies
ctx.Data["BlockedByDependencies"], err = issue.BlockedByDependencies()
ctx.Data["BlockedByDependencies"], err = issue.BlockedByDependencies(ctx)
if err != nil {
ctx.ServerError("BlockedByDependencies", err)
return
}
ctx.Data["BlockingDependencies"], err = issue.BlockingDependencies()
ctx.Data["BlockingDependencies"], err = issue.BlockingDependencies(ctx)
if err != nil {
ctx.ServerError("BlockingDependencies", err)
return
@ -1766,7 +1768,7 @@ func getActionIssues(ctx *context.Context) []*models.Issue {
}
issueIDs = append(issueIDs, issueID)
}
issues, err := models.GetIssuesByIDs(issueIDs)
issues, err := models.GetIssuesByIDs(ctx, issueIDs)
if err != nil {
ctx.ServerError("GetIssuesByIDs", err)
return nil
@ -1798,6 +1800,21 @@ func GetIssueInfo(ctx *context.Context) {
}
return
}
if issue.IsPull {
// Need to check if Pulls are enabled and we can read Pulls
if !ctx.Repo.Repository.CanEnablePulls() || !ctx.Repo.CanRead(unit.TypePullRequests) {
ctx.Error(http.StatusNotFound)
return
}
} else {
// Need to check if Issues are enabled and we can read Issues
if !ctx.Repo.CanRead(unit.TypeIssues) {
ctx.Error(http.StatusNotFound)
return
}
}
ctx.JSON(http.StatusOK, convert.ToAPIIssue(issue))
}
@ -1872,7 +1889,7 @@ func UpdateIssueContent(ctx *context.Context) {
// when update the request doesn't intend to update attachments (eg: change checkbox state), ignore attachment updates
if !ctx.FormBool("ignore_attachments") {
if err := updateAttachments(issue, ctx.FormStrings("files[]")); err != nil {
if err := updateAttachments(ctx, issue, ctx.FormStrings("files[]")); err != nil {
ctx.ServerError("UpdateAttachments", err)
return
}
@ -1978,7 +1995,7 @@ func UpdateIssueAssignee(ctx *context.Context) {
return
}
valid, err := models.CanBeAssigned(assignee, issue.Repo, issue.IsPull)
valid, err := access_model.CanBeAssigned(ctx, assignee, issue.Repo, issue.IsPull)
if err != nil {
ctx.ServerError("canBeAssigned", err)
return
@ -2046,7 +2063,7 @@ func UpdatePullReviewRequest(ctx *context.Context) {
return
}
team, err := organization.GetTeamByID(-reviewID)
team, err := organization.GetTeamByID(ctx, -reviewID)
if err != nil {
ctx.ServerError("GetTeamByID", err)
return
@ -2144,7 +2161,7 @@ func SearchIssues(ctx *context.Context) {
}
// find repos user can access (for issue search)
opts := &models.SearchRepoOptions{
opts := &repo_model.SearchRepoOptions{
Private: false,
AllPublic: true,
TopicOnly: false,
@ -2159,7 +2176,7 @@ func SearchIssues(ctx *context.Context) {
opts.AllLimited = true
}
if ctx.FormString("owner") != "" {
owner, err := user_model.GetUserByName(ctx.FormString("owner"))
owner, err := user_model.GetUserByName(ctx, ctx.FormString("owner"))
if err != nil {
if user_model.IsErrUserNotExist(err) {
ctx.Error(http.StatusBadRequest, "Owner not found", err.Error())
@ -2178,7 +2195,7 @@ func SearchIssues(ctx *context.Context) {
ctx.Error(http.StatusBadRequest, "", "Owner organisation is required for filtering on team")
return
}
team, err := organization.GetTeam(opts.OwnerID, ctx.FormString("team"))
team, err := organization.GetTeam(ctx, opts.OwnerID, ctx.FormString("team"))
if err != nil {
if organization.IsErrTeamNotExist(err) {
ctx.Error(http.StatusBadRequest, "Team not found", err.Error())
@ -2190,8 +2207,8 @@ func SearchIssues(ctx *context.Context) {
opts.TeamID = team.ID
}
repoCond := models.SearchRepositoryCondition(opts)
repoIDs, _, err := models.SearchRepositoryIDs(opts)
repoCond := repo_model.SearchRepositoryCondition(opts)
repoIDs, _, err := repo_model.SearchRepositoryIDs(opts)
if err != nil {
ctx.Error(http.StatusInternalServerError, "SearchRepositoryByName", err.Error())
return
@ -2306,7 +2323,7 @@ func getUserIDForFilter(ctx *context.Context, queryName string) int64 {
return 0
}
user, err := user_model.GetUserByName(userName)
user, err := user_model.GetUserByName(ctx, userName)
if user_model.IsErrUserNotExist(err) {
ctx.NotFound("", err)
return 0
@ -2630,7 +2647,7 @@ func NewComment(ctx *context.Context) {
// UpdateCommentContent change comment of issue's content
func UpdateCommentContent(ctx *context.Context) {
comment, err := models.GetCommentByID(ctx.ParamsInt64(":id"))
comment, err := models.GetCommentByID(ctx, ctx.ParamsInt64(":id"))
if err != nil {
ctx.NotFoundOrServerError("GetCommentByID", models.IsErrCommentNotExist, err)
return
@ -2671,7 +2688,7 @@ func UpdateCommentContent(ctx *context.Context) {
// when the update request doesn't intend to update attachments (eg: change checkbox state), ignore attachment updates
if !ctx.FormBool("ignore_attachments") {
if err := updateAttachments(comment, ctx.FormStrings("files[]")); err != nil {
if err := updateAttachments(ctx, comment, ctx.FormStrings("files[]")); err != nil {
ctx.ServerError("UpdateAttachments", err)
return
}
@ -2696,7 +2713,7 @@ func UpdateCommentContent(ctx *context.Context) {
// DeleteComment delete comment of issue
func DeleteComment(ctx *context.Context) {
comment, err := models.GetCommentByID(ctx.ParamsInt64(":id"))
comment, err := models.GetCommentByID(ctx, ctx.ParamsInt64(":id"))
if err != nil {
ctx.NotFoundOrServerError("GetCommentByID", models.IsErrCommentNotExist, err)
return
@ -2822,7 +2839,7 @@ func ChangeIssueReaction(ctx *context.Context) {
// ChangeCommentReaction create a reaction for comment
func ChangeCommentReaction(ctx *context.Context) {
form := web.GetForm(ctx).(*forms.ReactionForm)
comment, err := models.GetCommentByID(ctx.ParamsInt64(":id"))
comment, err := models.GetCommentByID(ctx, ctx.ParamsInt64(":id"))
if err != nil {
ctx.NotFoundOrServerError("GetCommentByID", models.IsErrCommentNotExist, err)
return
@ -2941,7 +2958,7 @@ func filterXRefComments(ctx *context.Context, issue *models.Issue) error {
if err != nil {
return err
}
perm, err := models.GetUserRepoPermission(ctx, c.RefRepo, ctx.Doer)
perm, err := access_model.GetUserRepoPermission(ctx, c.RefRepo, ctx.Doer)
if err != nil {
return err
}
@ -2967,7 +2984,7 @@ func GetIssueAttachments(ctx *context.Context) {
// GetCommentAttachments returns attachments for the comment
func GetCommentAttachments(ctx *context.Context) {
comment, err := models.GetCommentByID(ctx.ParamsInt64(":id"))
comment, err := models.GetCommentByID(ctx, ctx.ParamsInt64(":id"))
if err != nil {
ctx.NotFoundOrServerError("GetCommentByID", models.IsErrCommentNotExist, err)
return
@ -2985,7 +3002,7 @@ func GetCommentAttachments(ctx *context.Context) {
ctx.JSON(http.StatusOK, attachments)
}
func updateAttachments(item interface{}, files []string) error {
func updateAttachments(ctx *context.Context, item interface{}, files []string) error {
var attachments []*repo_model.Attachment
switch content := item.(type) {
case *models.Issue:
@ -3019,9 +3036,9 @@ func updateAttachments(item interface{}, files []string) error {
}
switch content := item.(type) {
case *models.Issue:
content.Attachments, err = repo_model.GetAttachmentsByIssueID(content.ID)
content.Attachments, err = repo_model.GetAttachmentsByIssueID(ctx, content.ID)
case *models.Comment:
content.Attachments, err = repo_model.GetAttachmentsByCommentID(content.ID)
content.Attachments, err = repo_model.GetAttachmentsByCommentID(ctx, content.ID)
default:
return fmt.Errorf("unknown Type: %T", content)
}

View file

@ -130,7 +130,7 @@ func GetContentHistoryDetail(ctx *context.Context) {
var comment *models.Comment
if history.CommentID != 0 {
var err error
if comment, err = models.GetCommentByID(history.CommentID); err != nil {
if comment, err = models.GetCommentByID(ctx, history.CommentID); err != nil {
log.Error("can not get comment for issue content history %v. err=%v", historyID, err)
return
}
@ -190,7 +190,7 @@ func SoftDeleteContentHistory(ctx *context.Context) {
var history *issuesModel.ContentHistory
var err error
if commentID != 0 {
if comment, err = models.GetCommentByID(commentID); err != nil {
if comment, err = models.GetCommentByID(ctx, commentID); err != nil {
log.Error("can not get comment for issue content history %v. err=%v", historyID, err)
return
}

View file

@ -56,7 +56,7 @@ func InitializeLabels(ctx *context.Context) {
// RetrieveLabels find all the labels of a repository and organization
func RetrieveLabels(ctx *context.Context) {
labels, err := models.GetLabelsByRepoID(ctx.Repo.Repository.ID, ctx.FormString("sort"), db.ListOptions{})
labels, err := models.GetLabelsByRepoID(ctx, ctx.Repo.Repository.ID, ctx.FormString("sort"), db.ListOptions{})
if err != nil {
ctx.ServerError("RetrieveLabels.GetLabels", err)
return
@ -69,7 +69,7 @@ func RetrieveLabels(ctx *context.Context) {
ctx.Data["Labels"] = labels
if ctx.Repo.Owner.IsOrganization() {
orgLabels, err := models.GetLabelsByOrgID(ctx.Repo.Owner.ID, ctx.FormString("sort"), db.ListOptions{})
orgLabels, err := models.GetLabelsByOrgID(ctx, ctx.Repo.Owner.ID, ctx.FormString("sort"), db.ListOptions{})
if err != nil {
ctx.ServerError("GetLabelsByOrgID", err)
return
@ -127,7 +127,7 @@ func NewLabel(ctx *context.Context) {
// UpdateLabel update a label's name and color
func UpdateLabel(ctx *context.Context) {
form := web.GetForm(ctx).(*forms.CreateLabelForm)
l, err := models.GetLabelInRepoByID(ctx.Repo.Repository.ID, form.ID)
l, err := models.GetLabelInRepoByID(ctx, ctx.Repo.Repository.ID, form.ID)
if err != nil {
switch {
case models.IsErrRepoLabelNotExist(err):
@ -177,7 +177,7 @@ func UpdateIssueLabel(ctx *context.Context) {
}
}
case "attach", "detach", "toggle":
label, err := models.GetLabelByID(ctx.FormInt64("id"))
label, err := models.GetLabelByID(ctx, ctx.FormInt64("id"))
if err != nil {
if models.IsErrRepoLabelNotExist(err) {
ctx.Error(http.StatusNotFound, "GetLabelByID")
@ -191,7 +191,7 @@ func UpdateIssueLabel(ctx *context.Context) {
// detach if any issues already have label, otherwise attach
action = "attach"
for _, issue := range issues {
if models.HasIssueLabel(issue.ID, label.ID) {
if models.HasIssueLabel(ctx, issue.ID, label.ID) {
action = "detach"
break
}

View file

@ -87,7 +87,7 @@ func GetActiveStopwatch(ctx *context.Context) {
return
}
_, sw, err := models.HasUserStopwatch(ctx.Doer.ID)
_, sw, err := models.HasUserStopwatch(ctx, ctx.Doer.ID)
if err != nil {
ctx.ServerError("HasUserStopwatch", err)
return

View file

@ -70,7 +70,7 @@ func Projects(ctx *context.Context) {
total = repo.NumClosedProjects
}
projects, count, err := project_model.GetProjects(project_model.SearchOptions{
projects, count, err := project_model.GetProjects(ctx, project_model.SearchOptions{
RepoID: repo.ID,
Page: page,
IsClosed: util.OptionalBoolOf(isShowClosed),
@ -182,7 +182,7 @@ func ChangeProjectStatus(ctx *context.Context) {
// DeleteProject delete a project
func DeleteProject(ctx *context.Context) {
p, err := project_model.GetProjectByID(ctx.ParamsInt64(":id"))
p, err := project_model.GetProjectByID(ctx, ctx.ParamsInt64(":id"))
if err != nil {
if project_model.IsErrProjectNotExist(err) {
ctx.NotFound("", nil)
@ -213,7 +213,7 @@ func EditProject(ctx *context.Context) {
ctx.Data["PageIsEditProjects"] = true
ctx.Data["CanWriteProjects"] = ctx.Repo.Permission.CanWrite(unit.TypeProjects)
p, err := project_model.GetProjectByID(ctx.ParamsInt64(":id"))
p, err := project_model.GetProjectByID(ctx, ctx.ParamsInt64(":id"))
if err != nil {
if project_model.IsErrProjectNotExist(err) {
ctx.NotFound("", nil)
@ -245,7 +245,7 @@ func EditProjectPost(ctx *context.Context) {
return
}
p, err := project_model.GetProjectByID(ctx.ParamsInt64(":id"))
p, err := project_model.GetProjectByID(ctx, ctx.ParamsInt64(":id"))
if err != nil {
if project_model.IsErrProjectNotExist(err) {
ctx.NotFound("", nil)
@ -261,7 +261,7 @@ func EditProjectPost(ctx *context.Context) {
p.Title = form.Title
p.Description = form.Content
if err = project_model.UpdateProject(p); err != nil {
if err = project_model.UpdateProject(ctx, p); err != nil {
ctx.ServerError("UpdateProjects", err)
return
}
@ -272,7 +272,7 @@ func EditProjectPost(ctx *context.Context) {
// ViewProject renders the project board for a project
func ViewProject(ctx *context.Context) {
project, err := project_model.GetProjectByID(ctx.ParamsInt64(":id"))
project, err := project_model.GetProjectByID(ctx, ctx.ParamsInt64(":id"))
if err != nil {
if project_model.IsErrProjectNotExist(err) {
ctx.NotFound("", nil)
@ -286,7 +286,7 @@ func ViewProject(ctx *context.Context) {
return
}
boards, err := project_model.GetBoards(project.ID)
boards, err := project_model.GetBoards(ctx, project.ID)
if err != nil {
ctx.ServerError("GetProjectBoards", err)
return
@ -385,7 +385,7 @@ func DeleteProjectBoard(ctx *context.Context) {
return
}
project, err := project_model.GetProjectByID(ctx.ParamsInt64(":id"))
project, err := project_model.GetProjectByID(ctx, ctx.ParamsInt64(":id"))
if err != nil {
if project_model.IsErrProjectNotExist(err) {
ctx.NotFound("", nil)
@ -395,7 +395,7 @@ func DeleteProjectBoard(ctx *context.Context) {
return
}
pb, err := project_model.GetBoard(ctx.ParamsInt64(":boardID"))
pb, err := project_model.GetBoard(ctx, ctx.ParamsInt64(":boardID"))
if err != nil {
ctx.ServerError("GetProjectBoard", err)
return
@ -434,7 +434,7 @@ func AddBoardToProjectPost(ctx *context.Context) {
return
}
project, err := project_model.GetProjectByID(ctx.ParamsInt64(":id"))
project, err := project_model.GetProjectByID(ctx, ctx.ParamsInt64(":id"))
if err != nil {
if project_model.IsErrProjectNotExist(err) {
ctx.NotFound("", nil)
@ -474,7 +474,7 @@ func checkProjectBoardChangePermissions(ctx *context.Context) (*project_model.Pr
return nil, nil
}
project, err := project_model.GetProjectByID(ctx.ParamsInt64(":id"))
project, err := project_model.GetProjectByID(ctx, ctx.ParamsInt64(":id"))
if err != nil {
if project_model.IsErrProjectNotExist(err) {
ctx.NotFound("", nil)
@ -484,7 +484,7 @@ func checkProjectBoardChangePermissions(ctx *context.Context) (*project_model.Pr
return nil, nil
}
board, err := project_model.GetBoard(ctx.ParamsInt64(":boardID"))
board, err := project_model.GetBoard(ctx, ctx.ParamsInt64(":boardID"))
if err != nil {
ctx.ServerError("GetProjectBoard", err)
return nil, nil
@ -523,7 +523,7 @@ func EditProjectBoard(ctx *context.Context) {
board.Sorting = form.Sorting
}
if err := project_model.UpdateBoard(board); err != nil {
if err := project_model.UpdateBoard(ctx, board); err != nil {
ctx.ServerError("UpdateProjectBoard", err)
return
}
@ -566,7 +566,7 @@ func MoveIssues(ctx *context.Context) {
return
}
project, err := project_model.GetProjectByID(ctx.ParamsInt64(":id"))
project, err := project_model.GetProjectByID(ctx, ctx.ParamsInt64(":id"))
if err != nil {
if project_model.IsErrProjectNotExist(err) {
ctx.NotFound("ProjectNotExist", nil)
@ -589,7 +589,7 @@ func MoveIssues(ctx *context.Context) {
Title: ctx.Tr("repo.projects.type.uncategorized"),
}
} else {
board, err = project_model.GetBoard(ctx.ParamsInt64(":boardID"))
board, err = project_model.GetBoard(ctx, ctx.ParamsInt64(":boardID"))
if err != nil {
if project_model.IsErrProjectBoardNotExist(err) {
ctx.NotFound("ProjectBoardNotExist", nil)
@ -622,7 +622,7 @@ func MoveIssues(ctx *context.Context) {
issueIDs = append(issueIDs, issue.IssueID)
sortedIssueIDs[issue.Sorting] = issue.IssueID
}
movedIssues, err := models.GetIssuesByIDs(issueIDs)
movedIssues, err := models.GetIssuesByIDs(ctx, issueIDs)
if err != nil {
if models.IsErrIssueNotExist(err) {
ctx.NotFound("IssueNotExisting", nil)

View file

@ -19,6 +19,7 @@ import (
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/organization"
access_model "code.gitea.io/gitea/models/perm/access"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unit"
user_model "code.gitea.io/gitea/models/user"
@ -70,7 +71,7 @@ func getRepository(ctx *context.Context, repoID int64) *repo_model.Repository {
return nil
}
perm, err := models.GetUserRepoPermission(ctx, repo, ctx.Doer)
perm, err := access_model.GetUserRepoPermission(ctx, repo, ctx.Doer)
if err != nil {
ctx.ServerError("GetUserRepoPermission", err)
return nil
@ -376,7 +377,7 @@ func PrepareMergedViewPullInfo(ctx *context.Context, issue *models.Issue) *git.C
if len(compareInfo.Commits) != 0 {
sha := compareInfo.Commits[0].ID.String()
commitStatuses, _, err := models.GetLatestCommitStatus(ctx.Repo.Repository.ID, sha, db.ListOptions{})
commitStatuses, _, err := models.GetLatestCommitStatus(ctx, ctx.Repo.Repository.ID, sha, db.ListOptions{})
if err != nil {
ctx.ServerError("GetLatestCommitStatus", err)
return nil
@ -437,7 +438,7 @@ func PrepareViewPullInfo(ctx *context.Context, issue *models.Issue) *git.Compare
ctx.ServerError(fmt.Sprintf("GetRefCommitID(%s)", pull.GetGitRefName()), err)
return nil
}
commitStatuses, _, err := models.GetLatestCommitStatus(repo.ID, sha, db.ListOptions{})
commitStatuses, _, err := models.GetLatestCommitStatus(ctx, repo.ID, sha, db.ListOptions{})
if err != nil {
ctx.ServerError("GetLatestCommitStatus", err)
return nil
@ -527,7 +528,7 @@ func PrepareViewPullInfo(ctx *context.Context, issue *models.Issue) *git.Compare
return nil
}
commitStatuses, _, err := models.GetLatestCommitStatus(repo.ID, sha, db.ListOptions{})
commitStatuses, _, err := models.GetLatestCommitStatus(ctx, repo.ID, sha, db.ListOptions{})
if err != nil {
ctx.ServerError("GetLatestCommitStatus", err)
return nil
@ -757,7 +758,7 @@ func ViewPullFiles(ctx *context.Context) {
setCompareContext(ctx, baseCommit, commit, ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
ctx.Data["RequireTribute"] = true
if ctx.Data["Assignees"], err = models.GetRepoAssignees(ctx.Repo.Repository); err != nil {
if ctx.Data["Assignees"], err = repo_model.GetRepoAssignees(ctx, ctx.Repo.Repository); err != nil {
ctx.ServerError("GetAssignees", err)
return
}
@ -766,7 +767,7 @@ func ViewPullFiles(ctx *context.Context) {
return
}
currentReview, err := models.GetCurrentReview(ctx.Doer, issue)
currentReview, err := models.GetCurrentReview(ctx, ctx.Doer, issue)
if err != nil && !models.IsErrReviewNotExist(err) {
ctx.ServerError("GetCurrentReview", err)
return
@ -1247,7 +1248,7 @@ func CleanUpPullRequest(ctx *context.Context) {
return
}
perm, err := models.GetUserRepoPermission(ctx, pr.HeadRepo, ctx.Doer)
perm, err := access_model.GetUserRepoPermission(ctx, pr.HeadRepo, ctx.Doer)
if err != nil {
ctx.ServerError("GetUserRepoPermission", err)
return
@ -1353,7 +1354,7 @@ func DownloadPullPatch(ctx *context.Context) {
// DownloadPullDiffOrPatch render a pull's raw diff or patch
func DownloadPullDiffOrPatch(ctx *context.Context, patch bool) {
pr, err := models.GetPullRequestByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
pr, err := models.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
if err != nil {
if models.IsErrPullRequestNotExist(err) {
ctx.NotFound("GetPullRequestByIndex", err)
@ -1446,7 +1447,7 @@ func UpdatePullRequestTarget(ctx *context.Context) {
func SetAllowEdits(ctx *context.Context) {
form := web.GetForm(ctx).(*forms.UpdateAllowEditsForm)
pr, err := models.GetPullRequestByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
pr, err := models.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
if err != nil {
if models.IsErrPullRequestNotExist(err) {
ctx.NotFound("GetPullRequestByIndex", err)

View file

@ -31,7 +31,7 @@ func RenderNewCodeCommentForm(ctx *context.Context) {
if !issue.IsPull {
return
}
currentReview, err := models.GetCurrentReview(ctx.Doer, issue)
currentReview, err := models.GetCurrentReview(ctx, ctx.Doer, issue)
if err != nil && !models.IsErrReviewNotExist(err) {
ctx.ServerError("GetCurrentReview", err)
return
@ -107,7 +107,7 @@ func UpdateResolveConversation(ctx *context.Context) {
action := ctx.FormString("action")
commentID := ctx.FormInt64("comment_id")
comment, err := models.GetCommentByID(commentID)
comment, err := models.GetCommentByID(ctx, commentID)
if err != nil {
ctx.ServerError("GetIssueByID", err)
return

View file

@ -126,7 +126,7 @@ func releasesOrTags(ctx *context.Context, isTagList bool) {
return
}
if err = models.GetReleaseAttachments(releases...); err != nil {
if err = models.GetReleaseAttachments(ctx, releases...); err != nil {
ctx.ServerError("GetReleaseAttachments", err)
return
}
@ -202,7 +202,7 @@ func SingleRelease(ctx *context.Context) {
return
}
err = models.GetReleaseAttachments(release)
err = models.GetReleaseAttachments(ctx, release)
if err != nil {
ctx.ServerError("GetReleaseAttachments", err)
return
@ -279,7 +279,9 @@ func NewRelease(ctx *context.Context) {
}
ctx.Data["tag_name"] = rel.TagName
ctx.Data["tag_target"] = rel.Target
if rel.Target != "" {
ctx.Data["tag_target"] = rel.Target
}
ctx.Data["title"] = rel.Title
ctx.Data["content"] = rel.Note
ctx.Data["attachments"] = rel.Attachments

View file

@ -152,7 +152,7 @@ func Create(ctx *context.Context) {
templateID := ctx.FormInt64("template_id")
if templateID > 0 {
templateRepo, err := repo_model.GetRepositoryByID(templateID)
if err == nil && models.CheckRepoUnitUser(templateRepo, ctxUser, unit.TypeCode) {
if err == nil && models.CheckRepoUnitUser(ctx, templateRepo, ctxUser, unit.TypeCode) {
ctx.Data["repo_template"] = templateID
ctx.Data["repo_template_name"] = templateRepo.Name
}
@ -223,7 +223,7 @@ func CreatePost(ctx *context.Context) {
var repo *repo_model.Repository
var err error
if form.RepoTemplate > 0 {
opts := models.GenerateRepoOptions{
opts := repo_module.GenerateRepoOptions{
Name: form.RepoName,
Description: form.Description,
Private: form.Private,
@ -285,9 +285,9 @@ func Action(ctx *context.Context) {
var err error
switch ctx.Params(":action") {
case "watch":
err = repo_model.WatchRepo(ctx.Doer.ID, ctx.Repo.Repository.ID, true)
err = repo_model.WatchRepo(ctx, ctx.Doer.ID, ctx.Repo.Repository.ID, true)
case "unwatch":
err = repo_model.WatchRepo(ctx.Doer.ID, ctx.Repo.Repository.ID, false)
err = repo_model.WatchRepo(ctx, ctx.Doer.ID, ctx.Repo.Repository.ID, false)
case "star":
err = repo_model.StarRepo(ctx.Doer.ID, ctx.Repo.Repository.ID, true)
case "unstar":
@ -304,7 +304,7 @@ func Action(ctx *context.Context) {
ctx.Repo.Repository.Description = ctx.FormString("desc")
ctx.Repo.Repository.Website = ctx.FormString("site")
err = models.UpdateRepository(ctx.Repo.Repository, false)
err = repo_service.UpdateRepository(ctx.Repo.Repository, false)
}
if err != nil {
@ -369,7 +369,7 @@ func RedirectDownload(ctx *context.Context) {
}
if len(releases) == 1 {
release := releases[0]
att, err := repo_model.GetAttachmentByReleaseIDFileName(release.ID, fileName)
att, err := repo_model.GetAttachmentByReleaseIDFileName(ctx, release.ID, fileName)
if err != nil {
ctx.Error(http.StatusNotFound)
return
@ -509,7 +509,7 @@ func InitiateDownload(ctx *context.Context) {
// SearchRepo repositories via options
func SearchRepo(ctx *context.Context) {
opts := &models.SearchRepoOptions{
opts := &repo_model.SearchRepoOptions{
ListOptions: db.ListOptions{
Page: ctx.FormInt("page"),
PageSize: convert.ToCorrectPageSize(ctx.FormInt("limit")),
@ -581,7 +581,7 @@ func SearchRepo(ctx *context.Context) {
}
var err error
repos, count, err := models.SearchRepository(opts)
repos, count, err := repo_model.SearchRepository(opts)
if err != nil {
ctx.JSON(http.StatusInternalServerError, api.SearchError{
OK: false,

View file

@ -65,21 +65,23 @@ func Settings(ctx *context.Context) {
ctx.Data["MirrorsEnabled"] = setting.Mirror.Enabled
ctx.Data["DisableNewPushMirrors"] = setting.Mirror.DisableNewPush
ctx.Data["DefaultMirrorInterval"] = setting.Mirror.DefaultInterval
ctx.Data["MinimumMirrorInterval"] = setting.Mirror.MinInterval
signing, _ := asymkey_service.SigningKey(ctx, ctx.Repo.Repository.RepoPath())
ctx.Data["SigningKeyAvailable"] = len(signing) > 0
ctx.Data["SigningSettings"] = setting.Repository.Signing
ctx.Data["CodeIndexerEnabled"] = setting.Indexer.RepoIndexerEnabled
if ctx.Doer.IsAdmin {
if setting.Indexer.RepoIndexerEnabled {
status, err := repo_model.GetIndexerStatus(ctx.Repo.Repository, repo_model.RepoIndexerTypeCode)
status, err := repo_model.GetIndexerStatus(ctx, ctx.Repo.Repository, repo_model.RepoIndexerTypeCode)
if err != nil {
ctx.ServerError("repo.indexer_status", err)
return
}
ctx.Data["CodeIndexerStatus"] = status
}
status, err := repo_model.GetIndexerStatus(ctx.Repo.Repository, repo_model.RepoIndexerTypeStats)
status, err := repo_model.GetIndexerStatus(ctx, ctx.Repo.Repository, repo_model.RepoIndexerTypeStats)
if err != nil {
ctx.ServerError("repo.indexer_status", err)
return
@ -102,6 +104,17 @@ func SettingsPost(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("repo.settings")
ctx.Data["PageIsSettingsOptions"] = true
ctx.Data["ForcePrivate"] = setting.Repository.ForcePrivate
ctx.Data["MirrorsEnabled"] = setting.Mirror.Enabled
ctx.Data["DisableNewPushMirrors"] = setting.Mirror.DisableNewPush
ctx.Data["DefaultMirrorInterval"] = setting.Mirror.DefaultInterval
ctx.Data["MinimumMirrorInterval"] = setting.Mirror.MinInterval
signing, _ := asymkey_service.SigningKey(ctx, ctx.Repo.Repository.RepoPath())
ctx.Data["SigningKeyAvailable"] = len(signing) > 0
ctx.Data["SigningSettings"] = setting.Repository.Signing
ctx.Data["CodeIndexerEnabled"] = setting.Indexer.RepoIndexerEnabled
repo := ctx.Repo.Repository
switch ctx.FormString("action") {
@ -168,7 +181,7 @@ func SettingsPost(ctx *context.Context) {
}
repo.IsPrivate = form.Private
if err := models.UpdateRepository(repo, visibilityChanged); err != nil {
if err := repo_service.UpdateRepository(repo, visibilityChanged); err != nil {
ctx.ServerError("UpdateRepository", err)
return
}
@ -191,15 +204,15 @@ func SettingsPost(ctx *context.Context) {
if err != nil || (interval != 0 && interval < setting.Mirror.MinInterval) {
ctx.Data["Err_Interval"] = true
ctx.RenderWithErr(ctx.Tr("repo.mirror_interval_invalid"), tplSettingsOptions, &form)
} else {
ctx.Repo.Mirror.EnablePrune = form.EnablePrune
ctx.Repo.Mirror.Interval = interval
ctx.Repo.Mirror.ScheduleNextUpdate()
if err := repo_model.UpdateMirror(ctx.Repo.Mirror); err != nil {
ctx.Data["Err_Interval"] = true
ctx.RenderWithErr(ctx.Tr("repo.mirror_interval_invalid"), tplSettingsOptions, &form)
return
}
return
}
ctx.Repo.Mirror.EnablePrune = form.EnablePrune
ctx.Repo.Mirror.Interval = interval
ctx.Repo.Mirror.ScheduleNextUpdate()
if err := repo_model.UpdateMirror(ctx, ctx.Repo.Mirror); err != nil {
ctx.ServerError("UpdateMirror", err)
return
}
u, _ := git.GetRemoteAddress(ctx, ctx.Repo.Repository.RepoPath(), ctx.Repo.Mirror.GetRemoteName())
@ -241,7 +254,7 @@ func SettingsPost(ctx *context.Context) {
ctx.Repo.Mirror.LFS = form.LFS
ctx.Repo.Mirror.LFSEndpoint = form.LFSEndpoint
if err := repo_model.UpdateMirror(ctx.Repo.Mirror); err != nil {
if err := repo_model.UpdateMirror(ctx, ctx.Repo.Mirror); err != nil {
ctx.ServerError("UpdateMirror", err)
return
}
@ -491,7 +504,7 @@ func SettingsPost(ctx *context.Context) {
return
}
if repoChanged {
if err := models.UpdateRepository(repo, false); err != nil {
if err := repo_service.UpdateRepository(repo, false); err != nil {
ctx.ServerError("UpdateRepository", err)
return
}
@ -510,7 +523,7 @@ func SettingsPost(ctx *context.Context) {
}
if changed {
if err := models.UpdateRepository(repo, false); err != nil {
if err := repo_service.UpdateRepository(repo, false); err != nil {
ctx.ServerError("UpdateRepository", err)
return
}
@ -530,7 +543,7 @@ func SettingsPost(ctx *context.Context) {
repo.IsFsckEnabled = form.EnableHealthCheck
}
if err := models.UpdateRepository(repo, false); err != nil {
if err := repo_service.UpdateRepository(repo, false); err != nil {
ctx.ServerError("UpdateRepository", err)
return
}
@ -642,7 +655,7 @@ func SettingsPost(ctx *context.Context) {
return
}
newOwner, err := user_model.GetUserByName(ctx.FormString("new_owner_name"))
newOwner, err := user_model.GetUserByName(ctx, ctx.FormString("new_owner_name"))
if err != nil {
if user_model.IsErrUserNotExist(err) {
ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_owner_name"), tplSettingsOptions, nil)
@ -833,14 +846,14 @@ func Collaboration(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("repo.settings")
ctx.Data["PageIsSettingsCollaboration"] = true
users, err := models.GetCollaborators(ctx.Repo.Repository.ID, db.ListOptions{})
users, err := repo_model.GetCollaborators(ctx, ctx.Repo.Repository.ID, db.ListOptions{})
if err != nil {
ctx.ServerError("GetCollaborators", err)
return
}
ctx.Data["Collaborators"] = users
teams, err := organization.GetRepoTeams(ctx.Repo.Repository)
teams, err := organization.GetRepoTeams(ctx, ctx.Repo.Repository)
if err != nil {
ctx.ServerError("GetRepoTeams", err)
return
@ -863,7 +876,7 @@ func CollaborationPost(ctx *context.Context) {
return
}
u, err := user_model.GetUserByName(name)
u, err := user_model.GetUserByName(ctx, name)
if err != nil {
if user_model.IsErrUserNotExist(err) {
ctx.Flash.Error(ctx.Tr("form.user_not_exist"))
@ -887,7 +900,7 @@ func CollaborationPost(ctx *context.Context) {
return
}
if got, err := models.IsCollaborator(ctx.Repo.Repository.ID, u.ID); err == nil && got {
if got, err := repo_model.IsCollaborator(ctx, ctx.Repo.Repository.ID, u.ID); err == nil && got {
ctx.Flash.Error(ctx.Tr("repo.settings.add_collaborator_duplicate"))
ctx.Redirect(ctx.Repo.RepoLink + "/settings/collaboration")
return
@ -908,7 +921,7 @@ func CollaborationPost(ctx *context.Context) {
// ChangeCollaborationAccessMode response for changing access of a collaboration
func ChangeCollaborationAccessMode(ctx *context.Context) {
if err := models.ChangeCollaborationAccessMode(
if err := repo_model.ChangeCollaborationAccessMode(
ctx.Repo.Repository,
ctx.FormInt64("uid"),
perm.AccessMode(ctx.FormInt("mode"))); err != nil {
@ -983,7 +996,7 @@ func DeleteTeam(ctx *context.Context) {
return
}
team, err := organization.GetTeamByID(ctx.FormInt64("id"))
team, err := organization.GetTeamByID(ctx, ctx.FormInt64("id"))
if err != nil {
ctx.ServerError("GetTeamByID", err)
return
@ -1215,6 +1228,7 @@ func selectPushMirrorByForm(form *forms.RepoSettingForm, repo *repo_model.Reposi
for _, m := range pushMirrors {
if m.ID == id {
m.Repo = repo
return m, nil
}
}

View file

@ -13,6 +13,7 @@ import (
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/organization"
"code.gitea.io/gitea/models/perm"
access_model "code.gitea.io/gitea/models/perm/access"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/context"
@ -110,7 +111,7 @@ func SettingsProtectedBranch(c *context.Context) {
c.Data["Title"] = c.Tr("repo.settings.protected_branch") + " - " + branch
c.Data["PageIsSettingsBranches"] = true
protectBranch, err := models.GetProtectedBranchBy(c.Repo.Repository.ID, branch)
protectBranch, err := models.GetProtectedBranchBy(c, c.Repo.Repository.ID, branch)
if err != nil {
if !git.IsErrBranchNotExist(err) {
c.ServerError("GetProtectBranchOfRepoByName", err)
@ -125,7 +126,7 @@ func SettingsProtectedBranch(c *context.Context) {
}
}
users, err := models.GetRepoReaders(c.Repo.Repository)
users, err := access_model.GetRepoReaders(c.Repo.Repository)
if err != nil {
c.ServerError("Repo.Repository.GetReaders", err)
return
@ -183,7 +184,7 @@ func SettingsProtectedBranchPost(ctx *context.Context) {
return
}
protectBranch, err := models.GetProtectedBranchBy(ctx.Repo.Repository.ID, branch)
protectBranch, err := models.GetProtectedBranchBy(ctx, ctx.Repo.Repository.ID, branch)
if err != nil {
if !git.IsErrBranchNotExist(err) {
ctx.ServerError("GetProtectBranchOfRepoByName", err)

View file

@ -130,7 +130,7 @@ func TestCollaborationPost(t *testing.T) {
assert.EqualValues(t, http.StatusSeeOther, ctx.Resp.Status())
exists, err := models.IsCollaborator(re.ID, 4)
exists, err := repo_model.IsCollaborator(ctx, re.ID, 4)
assert.NoError(t, err)
assert.True(t, exists)
}
@ -188,7 +188,7 @@ func TestCollaborationPost_AddCollaboratorTwice(t *testing.T) {
assert.EqualValues(t, http.StatusSeeOther, ctx.Resp.Status())
exists, err := models.IsCollaborator(re.ID, 4)
exists, err := repo_model.IsCollaborator(ctx, re.ID, 4)
assert.NoError(t, err)
assert.True(t, exists)

View file

@ -12,6 +12,7 @@ import (
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/organization"
"code.gitea.io/gitea/models/perm"
access_model "code.gitea.io/gitea/models/perm/access"
"code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/setting"
@ -143,7 +144,7 @@ func setTagsContext(ctx *context.Context) error {
}
ctx.Data["ProtectedTags"] = protectedTags
users, err := models.GetRepoReaders(ctx.Repo.Repository)
users, err := access_model.GetRepoReaders(ctx.Repo.Repository)
if err != nil {
ctx.ServerError("Repo.Repository.GetReaders", err)
return err

View file

@ -0,0 +1,55 @@
// Copyright 2022 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package repo
import (
"net/http"
"code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/git"
"github.com/go-enry/go-enry/v2"
)
// TreeList get all files' entries of a repository
func TreeList(ctx *context.Context) {
tree, err := ctx.Repo.Commit.SubTree("/")
if err != nil {
ctx.ServerError("Repo.Commit.SubTree", err)
return
}
entries, err := tree.ListEntriesRecursive()
if err != nil {
ctx.ServerError("ListEntriesRecursive", err)
return
}
entries.CustomSort(base.NaturalSortLess)
files := make([]string, 0, len(entries))
for _, entry := range entries {
if !isExcludedEntry(entry) {
files = append(files, entry.Name())
}
}
ctx.JSON(http.StatusOK, files)
}
func isExcludedEntry(entry *git.TreeEntry) bool {
if entry.IsDir() {
return true
}
if entry.IsSubModule() {
return true
}
if enry.IsVendor(entry.Name()) {
return true
}
return false
}

View file

@ -34,6 +34,7 @@ import (
"code.gitea.io/gitea/modules/lfs"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/markup"
repo_module "code.gitea.io/gitea/modules/repository"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/typesniffer"
@ -508,6 +509,13 @@ func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink st
ctx.Data["ReadmeExist"] = readmeExist
markupType := markup.Type(blob.Name())
// If the markup is detected by custom markup renderer it should not be reset later on
// to not pass it down to the render context.
detected := false
if markupType == "" {
detected = true
markupType = markup.DetectRendererType(blob.Name(), bytes.NewReader(buf))
}
if markupType != "" {
ctx.Data["HasSourceRenderedToggle"] = true
}
@ -516,8 +524,12 @@ func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink st
ctx.Data["IsMarkup"] = true
ctx.Data["MarkupType"] = markupType
var result strings.Builder
if !detected {
markupType = ""
}
err := markup.Render(&markup.RenderContext{
Ctx: ctx,
Type: markupType,
Filename: blob.Name(),
URLPrefix: path.Dir(treeLink),
Metas: ctx.Repo.Repository.ComposeDocumentMetas(),
@ -684,7 +696,7 @@ func checkHomeCodeViewable(ctx *context.Context) {
if ctx.IsSigned {
// Set repo notification-status read if unread
if err := models.SetRepoReadBy(ctx.Repo.Repository.ID, ctx.Doer.ID); err != nil {
if err := models.SetRepoReadBy(ctx, ctx.Repo.Repository.ID, ctx.Doer.ID); err != nil {
ctx.ServerError("ReadBy", err)
return
}
@ -839,7 +851,7 @@ func renderDirectoryFiles(ctx *context.Context, timeout time.Duration) git.Entri
ctx.Data["LatestCommitUser"] = user_model.ValidateCommitWithEmail(latestCommit)
}
statuses, _, err := models.GetLatestCommitStatus(ctx.Repo.Repository.ID, ctx.Repo.Commit.ID.String(), db.ListOptions{})
statuses, _, err := models.GetLatestCommitStatus(ctx, ctx.Repo.Repository.ID, ctx.Repo.Commit.ID.String(), db.ListOptions{})
if err != nil {
log.Error("GetLatestCommitStatus: %v", err)
}
@ -901,11 +913,11 @@ func renderCode(ctx *context.Context) {
// it's possible for a repository to be non-empty by that flag but still 500
// because there are no branches - only tags -or the default branch is non-extant as it has been 0-pushed.
ctx.Repo.Repository.IsEmpty = false
if err = repo_model.UpdateRepositoryCols(ctx.Repo.Repository, "is_empty"); err != nil {
if err = repo_model.UpdateRepositoryCols(ctx, ctx.Repo.Repository, "is_empty"); err != nil {
ctx.ServerError("UpdateRepositoryCols", err)
return
}
if err = models.UpdateRepoSize(ctx, ctx.Repo.Repository); err != nil {
if err = repo_module.UpdateRepoSize(ctx, ctx.Repo.Repository); err != nil {
ctx.ServerError("UpdateRepoSize", err)
return
}

View file

@ -44,7 +44,7 @@ func Webhooks(ctx *context.Context) {
ctx.Data["BaseLinkNew"] = ctx.Repo.RepoLink + "/settings/hooks"
ctx.Data["Description"] = ctx.Tr("repo.settings.hooks_desc", "https://docs.gitea.io/en-us/webhooks/")
ws, err := webhook.ListWebhooksByOpts(&webhook.ListWebhookOptions{RepoID: ctx.Repo.Repository.ID})
ws, err := webhook.ListWebhooksByOpts(ctx, &webhook.ListWebhookOptions{RepoID: ctx.Repo.Repository.ID})
if err != nil {
ctx.ServerError("GetWebhooksByRepoID", err)
return

View file

@ -280,6 +280,8 @@ func renderViewPage(ctx *context.Context) (*git.Repository, *git.TreeEntry) {
ctx.Data["footerPresent"] = false
}
ctx.Data["toc"] = rctx.TableOfContents
// get commit count - wiki revisions
commitsCount, _ := wikiRepo.FileCommitsCount("master", pageFilename)
ctx.Data["CommitCount"] = commitsCount

View file

@ -30,7 +30,7 @@ func AvatarByUserName(ctx *context.Context) {
var user *user_model.User
if strings.ToLower(userName) != "ghost" {
var err error
if user, err = user_model.GetUserByName(userName); err != nil {
if user, err = user_model.GetUserByName(ctx, userName); err != nil {
ctx.ServerError("Invalid user: "+userName, err)
return
}

View file

@ -78,6 +78,7 @@ func Dashboard(ctx *context.Context) {
ctx.Data["PageIsNews"] = true
cnt, _ := organization.GetOrganizationCount(ctx, ctxUser)
ctx.Data["UserOrgsCount"] = cnt
ctx.Data["MirrorsEnabled"] = setting.Mirror.Enabled
var uid int64
if ctxUser != nil {
@ -165,12 +166,13 @@ func Milestones(ctx *context.Context) {
return
}
repoOpts := models.SearchRepoOptions{
repoOpts := repo_model.SearchRepoOptions{
Actor: ctxUser,
OwnerID: ctxUser.ID,
Private: true,
AllPublic: false, // Include also all public repositories of users and public organisations
AllLimited: false, // Include also all public repositories of limited organisations
AllPublic: false, // Include also all public repositories of users and public organisations
AllLimited: false, // Include also all public repositories of limited organisations
Archived: util.OptionalBoolFalse,
HasMilestones: util.OptionalBoolTrue, // Just needs display repos has milestones
}
@ -179,7 +181,7 @@ func Milestones(ctx *context.Context) {
}
var (
userRepoCond = models.SearchRepositoryCondition(&repoOpts) // all repo condition user could visit
userRepoCond = repo_model.SearchRepositoryCondition(&repoOpts) // all repo condition user could visit
repoCond = userRepoCond
repoIDs []int64
@ -232,7 +234,7 @@ func Milestones(ctx *context.Context) {
return
}
showRepos, _, err := models.SearchRepositoryByCondition(&repoOpts, userRepoCond, false)
showRepos, _, err := repo_model.SearchRepositoryByCondition(&repoOpts, userRepoCond, false)
if err != nil {
ctx.ServerError("SearchRepositoryByCondition", err)
return
@ -435,7 +437,7 @@ func buildIssueOverview(ctx *context.Context, unitType unit.Type) {
// As team:
// - Team org's owns the repository.
// - Team has read permission to repository.
repoOpts := &models.SearchRepoOptions{
repoOpts := &repo_model.SearchRepoOptions{
Actor: ctx.Doer,
OwnerID: ctx.Doer.ID,
Private: true,
@ -443,12 +445,13 @@ func buildIssueOverview(ctx *context.Context, unitType unit.Type) {
AllLimited: false,
}
if ctxUser.IsOrganization() && ctx.Org.Team != nil {
repoOpts.TeamID = ctx.Org.Team.ID
if team != nil {
repoOpts.TeamID = team.ID
}
switch filterMode {
case models.FilterModeAll:
case models.FilterModeYourRepositories:
case models.FilterModeAssign:
opts.AssigneeID = ctx.Doer.ID
case models.FilterModeCreate:
@ -457,13 +460,6 @@ func buildIssueOverview(ctx *context.Context, unitType unit.Type) {
opts.MentionedID = ctx.Doer.ID
case models.FilterModeReviewRequested:
opts.ReviewRequestedID = ctx.Doer.ID
case models.FilterModeYourRepositories:
if ctxUser.IsOrganization() && ctx.Org.Team != nil {
// Fixes a issue whereby the user's ID would be used
// to check if it's in the team(which possible isn't the case).
opts.User = nil
}
opts.RepoCond = models.SearchRepositoryCondition(repoOpts)
}
// keyword holds the search term entered into the search field.
@ -563,7 +559,7 @@ func buildIssueOverview(ctx *context.Context, unitType unit.Type) {
}
// a RepositoryList
showRepos := models.RepositoryListOfMap(showReposMap)
showRepos := repo_model.RepositoryListOfMap(showReposMap)
sort.Sort(showRepos)
// maps pull request IDs to their CommitStatus. Will be posted to ctx.Data.
@ -595,13 +591,7 @@ func buildIssueOverview(ctx *context.Context, unitType unit.Type) {
Org: org,
Team: team,
}
if filterMode == models.FilterModeYourRepositories {
statsOpts.RepoCond = models.SearchRepositoryCondition(repoOpts)
}
// Detect when we only should search by team.
if opts.User == nil {
statsOpts.UserID = 0
}
issueStats, err = models.GetUserIssueStats(statsOpts)
if err != nil {
ctx.ServerError("GetUserIssueStats Shown", err)
@ -620,6 +610,12 @@ func buildIssueOverview(ctx *context.Context, unitType unit.Type) {
shownIssues = int(issueStats.ClosedCount)
ctx.Data["TotalIssueCount"] = shownIssues
}
if len(repoIDs) != 0 {
shownIssues = 0
for _, repoID := range repoIDs {
shownIssues += int(issueCountByRepo[repoID])
}
}
ctx.Data["IsShowClosed"] = isShowClosed
@ -627,7 +623,7 @@ func buildIssueOverview(ctx *context.Context, unitType unit.Type) {
ctx.Data["Issues"] = issues
approvalCounts, err := models.IssueList(issues).GetApprovalCounts()
approvalCounts, err := models.IssueList(issues).GetApprovalCounts(ctx)
if err != nil {
ctx.ServerError("ApprovalCounts", err)
return

View file

@ -8,7 +8,7 @@ import (
"net/http"
"testing"
"code.gitea.io/gitea/models"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/test"
@ -26,7 +26,7 @@ func TestArchivedIssues(t *testing.T) {
ctx.Req.Form.Set("state", "open")
// Assume: User 30 has access to two Repos with Issues, one of the Repos being archived.
repos, _, _ := models.GetUserRepositories(&models.SearchRepoOptions{Actor: ctx.Doer})
repos, _, _ := repo_model.GetUserRepositories(&repo_model.SearchRepoOptions{Actor: ctx.Doer})
assert.Len(t, repos, 2)
IsArchived := make(map[int64]bool)
NumIssues := make(map[int64]int)

View file

@ -5,6 +5,7 @@
package user
import (
goctx "context"
"errors"
"fmt"
"net/http"
@ -14,6 +15,7 @@ import (
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/structs"
)
@ -34,9 +36,11 @@ func GetNotificationCount(c *context.Context) {
}
c.Data["NotificationUnreadCount"] = func() int64 {
count, err := models.GetNotificationCount(c.Doer, models.NotificationStatusUnread)
count, err := models.GetNotificationCount(c, c.Doer, models.NotificationStatusUnread)
if err != nil {
c.ServerError("GetNotificationCount", err)
if err != goctx.Canceled {
log.Error("Unable to GetNotificationCount for user:%-v: %v", c.Doer, err)
}
return -1
}
@ -79,7 +83,7 @@ func getNotifications(c *context.Context) {
status = models.NotificationStatusUnread
}
total, err := models.GetNotificationCount(c.Doer, status)
total, err := models.GetNotificationCount(c, c.Doer, status)
if err != nil {
c.ServerError("ErrGetNotificationCount", err)
return
@ -93,7 +97,7 @@ func getNotifications(c *context.Context) {
}
statuses := []models.NotificationStatus{status, models.NotificationStatusPinned}
notifications, err := models.NotificationsForUser(c.Doer, statuses, page, perPage)
notifications, err := models.NotificationsForUser(c, c.Doer, statuses, page, perPage)
if err != nil {
c.ServerError("ErrNotificationsForUser", err)
return
@ -195,5 +199,5 @@ func NotificationPurgePost(c *context.Context) {
// NewAvailable returns the notification counts
func NewAvailable(ctx *context.Context) {
ctx.JSON(http.StatusOK, structs.NotificationCount{New: models.CountUnread(ctx.Doer)})
ctx.JSON(http.StatusOK, structs.NotificationCount{New: models.CountUnread(ctx, ctx.Doer.ID)})
}

View file

@ -7,11 +7,11 @@ package user
import (
"net/http"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
packages_model "code.gitea.io/gitea/models/packages"
container_model "code.gitea.io/gitea/models/packages/container"
"code.gitea.io/gitea/models/perm"
access_model "code.gitea.io/gitea/models/perm/access"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/context"
@ -67,7 +67,7 @@ func ListPackages(ctx *context.Context) {
continue
}
permission, err := models.GetUserRepoPermission(ctx, pd.Repository, ctx.Doer)
permission, err := access_model.GetUserRepoPermission(ctx, pd.Repository, ctx.Doer)
if err != nil {
ctx.ServerError("GetUserRepoPermission", err)
return
@ -177,7 +177,7 @@ func ViewPackageVersion(ctx *context.Context) {
hasRepositoryAccess := false
if pd.Repository != nil {
permission, err := models.GetUserRepoPermission(ctx, pd.Repository, ctx.Doer)
permission, err := access_model.GetUserRepoPermission(ctx, pd.Repository, ctx.Doer)
if err != nil {
ctx.ServerError("GetUserRepoPermission", err)
return
@ -287,7 +287,7 @@ func PackageSettings(ctx *context.Context) {
ctx.Data["ContextUser"] = ctx.ContextUser
ctx.Data["PackageDescriptor"] = pd
repos, _, _ := models.GetUserRepositories(&models.SearchRepoOptions{
repos, _, _ := repo_model.GetUserRepositories(&repo_model.SearchRepoOptions{
Actor: pd.Owner,
Private: true,
})

View file

@ -42,7 +42,7 @@ func Profile(ctx *context.Context) {
}
// check view permissions
if !user_model.IsUserVisibleToViewer(ctx.ContextUser, ctx.Doer) {
if !user_model.IsUserVisibleToViewer(ctx, ctx.ContextUser, ctx.Doer) {
ctx.NotFound("user", fmt.Errorf(ctx.ContextUser.Name))
return
}
@ -195,7 +195,7 @@ func Profile(ctx *context.Context) {
}
case "stars":
ctx.Data["PageIsProfileStarList"] = true
repos, count, err = models.SearchRepository(&models.SearchRepoOptions{
repos, count, err = repo_model.SearchRepository(&repo_model.SearchRepoOptions{
ListOptions: db.ListOptions{
PageSize: setting.UI.User.RepoPagingNum,
Page: page,
@ -217,7 +217,7 @@ func Profile(ctx *context.Context) {
total = int(count)
case "projects":
ctx.Data["OpenProjects"], _, err = project_model.GetProjects(project_model.SearchOptions{
ctx.Data["OpenProjects"], _, err = project_model.GetProjects(ctx, project_model.SearchOptions{
Page: -1,
IsClosed: util.OptionalBoolFalse,
Type: project_model.TypeIndividual,
@ -227,7 +227,7 @@ func Profile(ctx *context.Context) {
return
}
case "watching":
repos, count, err = models.SearchRepository(&models.SearchRepoOptions{
repos, count, err = repo_model.SearchRepository(&repo_model.SearchRepoOptions{
ListOptions: db.ListOptions{
PageSize: setting.UI.User.RepoPagingNum,
Page: page,
@ -249,7 +249,7 @@ func Profile(ctx *context.Context) {
total = int(count)
default:
repos, count, err = models.SearchRepository(&models.SearchRepoOptions{
repos, count, err = repo_model.SearchRepository(&repo_model.SearchRepoOptions{
ListOptions: db.ListOptions{
PageSize: setting.UI.User.RepoPagingNum,
Page: page,

View file

@ -105,7 +105,7 @@ func EmailPost(ctx *context.Context) {
// Send activation Email
if ctx.FormString("_method") == "SENDACTIVATION" {
var address string
if ctx.Cache.IsExist("MailResendLimit_" + ctx.Doer.LowerName) {
if setting.CacheService.Enabled && ctx.Cache.IsExist("MailResendLimit_"+ctx.Doer.LowerName) {
log.Error("Send activation: activation still pending")
ctx.Redirect(setting.AppSubURL + "/user/settings/account")
return
@ -141,8 +141,10 @@ func EmailPost(ctx *context.Context) {
}
address = email.Email
if err := ctx.Cache.Put("MailResendLimit_"+ctx.Doer.LowerName, ctx.Doer.LowerName, 180); err != nil {
log.Error("Set cache(MailResendLimit) fail: %v", err)
if setting.CacheService.Enabled {
if err := ctx.Cache.Put("MailResendLimit_"+ctx.Doer.LowerName, ctx.Doer.LowerName, 180); err != nil {
log.Error("Set cache(MailResendLimit) fail: %v", err)
}
}
ctx.Flash.Info(ctx.Tr("settings.add_email_confirmation_sent", address, timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale.Language())))
ctx.Redirect(setting.AppSubURL + "/user/settings/account")
@ -181,7 +183,7 @@ func EmailPost(ctx *context.Context) {
Email: form.Email,
IsActivated: !setting.Service.RegisterEmailConfirm,
}
if err := user_model.AddEmailAddress(email); err != nil {
if err := user_model.AddEmailAddress(ctx, email); err != nil {
if user_model.IsErrEmailAlreadyUsed(err) {
loadAccountData(ctx)
@ -201,8 +203,10 @@ func EmailPost(ctx *context.Context) {
// Send confirmation email
if setting.Service.RegisterEmailConfirm {
mailer.SendActivateEmailMail(ctx.Doer, email)
if err := ctx.Cache.Put("MailResendLimit_"+ctx.Doer.LowerName, ctx.Doer.LowerName, 180); err != nil {
log.Error("Set cache(MailResendLimit) fail: %v", err)
if setting.CacheService.Enabled {
if err := ctx.Cache.Put("MailResendLimit_"+ctx.Doer.LowerName, ctx.Doer.LowerName, 180); err != nil {
log.Error("Set cache(MailResendLimit) fail: %v", err)
}
}
ctx.Flash.Info(ctx.Tr("settings.add_email_confirmation_sent", email.Email, timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale.Language())))
} else {
@ -273,7 +277,7 @@ func loadAccountData(ctx *context.Context) {
user_model.EmailAddress
CanBePrimary bool
}
pendingActivation := ctx.Cache.IsExist("MailResendLimit_" + ctx.Doer.LowerName)
pendingActivation := setting.CacheService.Enabled && ctx.Cache.IsExist("MailResendLimit_"+ctx.Doer.LowerName)
emails := make([]*UserEmail, len(emlist))
for i, em := range emlist {
var email UserEmail

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