mirror of
https://github.com/go-gitea/gitea
synced 2025-12-07 13:28:25 +00:00
Merge branch 'master' into feature-activitypub
This commit is contained in:
@@ -110,7 +110,7 @@ func AdoptRepository(ctx *context.APIContext) {
|
||||
ctx.NotFound()
|
||||
return
|
||||
}
|
||||
if _, err := repo_service.AdoptRepository(ctx.User, ctxUser, models.CreateRepoOptions{
|
||||
if _, err := repo_service.AdoptRepository(ctx.Doer, ctxUser, models.CreateRepoOptions{
|
||||
Name: repoName,
|
||||
IsPrivate: true,
|
||||
}); err != nil {
|
||||
@@ -173,7 +173,7 @@ func DeleteUnadoptedRepository(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := repo_service.DeleteUnadoptedRepository(ctx.User, ctxUser, repoName); err != nil {
|
||||
if err := repo_service.DeleteUnadoptedRepository(ctx.Doer, ctxUser, repoName); err != nil {
|
||||
ctx.InternalServerError(err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -81,7 +81,7 @@ func PostCronTask(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
task.Run()
|
||||
log.Trace("Cron Task %s started by admin(%s)", task.Name, ctx.User.Name)
|
||||
log.Trace("Cron Task %s started by admin(%s)", task.Name, ctx.Doer.Name)
|
||||
|
||||
ctx.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
@@ -8,14 +8,13 @@ package admin
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"code.gitea.io/gitea/models"
|
||||
"code.gitea.io/gitea/models/db"
|
||||
"code.gitea.io/gitea/models/organization"
|
||||
user_model "code.gitea.io/gitea/models/user"
|
||||
"code.gitea.io/gitea/modules/context"
|
||||
"code.gitea.io/gitea/modules/convert"
|
||||
api "code.gitea.io/gitea/modules/structs"
|
||||
"code.gitea.io/gitea/modules/web"
|
||||
"code.gitea.io/gitea/routers/api/v1/user"
|
||||
"code.gitea.io/gitea/routers/api/v1/utils"
|
||||
)
|
||||
|
||||
@@ -45,18 +44,15 @@ func CreateOrg(ctx *context.APIContext) {
|
||||
// "$ref": "#/responses/forbidden"
|
||||
// "422":
|
||||
// "$ref": "#/responses/validationError"
|
||||
|
||||
form := web.GetForm(ctx).(*api.CreateOrgOption)
|
||||
u := user.GetUserByParams(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
|
||||
visibility := api.VisibleTypePublic
|
||||
if form.Visibility != "" {
|
||||
visibility = api.VisibilityModes[form.Visibility]
|
||||
}
|
||||
|
||||
org := &models.Organization{
|
||||
org := &organization.Organization{
|
||||
Name: form.UserName,
|
||||
FullName: form.FullName,
|
||||
Description: form.Description,
|
||||
@@ -67,7 +63,7 @@ func CreateOrg(ctx *context.APIContext) {
|
||||
Visibility: visibility,
|
||||
}
|
||||
|
||||
if err := models.CreateOrganization(org, u); err != nil {
|
||||
if err := organization.CreateOrganization(org, ctx.ContextUser); err != nil {
|
||||
if user_model.IsErrUserAlreadyExist(err) ||
|
||||
db.IsErrNameReserved(err) ||
|
||||
db.IsErrNameCharsNotAllowed(err) ||
|
||||
@@ -107,7 +103,7 @@ func GetAllOrgs(ctx *context.APIContext) {
|
||||
listOptions := utils.GetListOptions(ctx)
|
||||
|
||||
users, maxResults, err := user_model.SearchUsers(&user_model.SearchUserOptions{
|
||||
Actor: ctx.User,
|
||||
Actor: ctx.Doer,
|
||||
Type: user_model.UserTypeOrganization,
|
||||
OrderBy: db.SearchOrderByAlphabetically,
|
||||
ListOptions: listOptions,
|
||||
@@ -119,7 +115,7 @@ func GetAllOrgs(ctx *context.APIContext) {
|
||||
}
|
||||
orgs := make([]*api.Organization, len(users))
|
||||
for i := range users {
|
||||
orgs[i] = convert.ToOrganization(models.OrgFromUser(users[i]))
|
||||
orgs[i] = convert.ToOrganization(organization.OrgFromUser(users[i]))
|
||||
}
|
||||
|
||||
ctx.SetLinkHeader(int(maxResults), listOptions.PageSize)
|
||||
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
api "code.gitea.io/gitea/modules/structs"
|
||||
"code.gitea.io/gitea/modules/web"
|
||||
"code.gitea.io/gitea/routers/api/v1/repo"
|
||||
"code.gitea.io/gitea/routers/api/v1/user"
|
||||
)
|
||||
|
||||
// CreateRepo api for creating a repository
|
||||
@@ -42,11 +41,8 @@ func CreateRepo(ctx *context.APIContext) {
|
||||
// "$ref": "#/responses/error"
|
||||
// "422":
|
||||
// "$ref": "#/responses/validationError"
|
||||
form := web.GetForm(ctx).(*api.CreateRepoOption)
|
||||
owner := user.GetUserByParams(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
|
||||
repo.CreateUserRepo(ctx, owner, *form)
|
||||
form := web.GetForm(ctx).(*api.CreateRepoOption)
|
||||
|
||||
repo.CreateUserRepo(ctx, ctx.ContextUser, *form)
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ import (
|
||||
"code.gitea.io/gitea/modules/password"
|
||||
"code.gitea.io/gitea/modules/setting"
|
||||
api "code.gitea.io/gitea/modules/structs"
|
||||
"code.gitea.io/gitea/modules/util"
|
||||
"code.gitea.io/gitea/modules/web"
|
||||
"code.gitea.io/gitea/routers/api/v1/user"
|
||||
"code.gitea.io/gitea/routers/api/v1/utils"
|
||||
@@ -73,6 +74,7 @@ func CreateUser(ctx *context.APIContext) {
|
||||
// "$ref": "#/responses/forbidden"
|
||||
// "422":
|
||||
// "$ref": "#/responses/validationError"
|
||||
|
||||
form := web.GetForm(ctx).(*api.CreateUserOption)
|
||||
|
||||
u := &user_model.User{
|
||||
@@ -81,7 +83,6 @@ func CreateUser(ctx *context.APIContext) {
|
||||
Email: form.Email,
|
||||
Passwd: form.Password,
|
||||
MustChangePassword: true,
|
||||
IsActive: true,
|
||||
LoginType: auth.Plain,
|
||||
}
|
||||
if form.MustChangePassword != nil {
|
||||
@@ -107,11 +108,17 @@ func CreateUser(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
var overwriteDefault *user_model.CreateUserOverwriteOptions
|
||||
overwriteDefault := &user_model.CreateUserOverwriteOptions{
|
||||
IsActive: util.OptionalBoolTrue,
|
||||
}
|
||||
|
||||
if form.Restricted != nil {
|
||||
overwriteDefault.IsRestricted = util.OptionalBoolOf(*form.Restricted)
|
||||
}
|
||||
|
||||
if form.Visibility != "" {
|
||||
overwriteDefault = &user_model.CreateUserOverwriteOptions{
|
||||
Visibility: api.VisibilityModes[form.Visibility],
|
||||
}
|
||||
visibility := api.VisibilityModes[form.Visibility]
|
||||
overwriteDefault.Visibility = &visibility
|
||||
}
|
||||
|
||||
if err := user_model.CreateUser(u, overwriteDefault); err != nil {
|
||||
@@ -119,6 +126,7 @@ func CreateUser(ctx *context.APIContext) {
|
||||
user_model.IsErrEmailAlreadyUsed(err) ||
|
||||
db.IsErrNameReserved(err) ||
|
||||
db.IsErrNameCharsNotAllowed(err) ||
|
||||
user_model.IsErrEmailCharIsNotSupported(err) ||
|
||||
user_model.IsErrEmailInvalid(err) ||
|
||||
db.IsErrNamePatternNotAllowed(err) {
|
||||
ctx.Error(http.StatusUnprocessableEntity, "", err)
|
||||
@@ -127,13 +135,13 @@ func CreateUser(ctx *context.APIContext) {
|
||||
}
|
||||
return
|
||||
}
|
||||
log.Trace("Account created by admin (%s): %s", ctx.User.Name, u.Name)
|
||||
log.Trace("Account created by admin (%s): %s", ctx.Doer.Name, u.Name)
|
||||
|
||||
// Send email notification.
|
||||
if form.SendNotify {
|
||||
mailer.SendRegisterNotifyMail(u)
|
||||
}
|
||||
ctx.JSON(http.StatusCreated, convert.ToUser(u, ctx.User))
|
||||
ctx.JSON(http.StatusCreated, convert.ToUser(u, ctx.Doer))
|
||||
}
|
||||
|
||||
// EditUser api for modifying a user's information
|
||||
@@ -162,13 +170,10 @@ func EditUser(ctx *context.APIContext) {
|
||||
// "$ref": "#/responses/forbidden"
|
||||
// "422":
|
||||
// "$ref": "#/responses/validationError"
|
||||
form := web.GetForm(ctx).(*api.EditUserOption)
|
||||
u := user.GetUserByParams(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
|
||||
parseAuthSource(ctx, u, form.SourceID, form.LoginName)
|
||||
form := web.GetForm(ctx).(*api.EditUserOption)
|
||||
|
||||
parseAuthSource(ctx, ctx.ContextUser, form.SourceID, form.LoginName)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
@@ -192,24 +197,24 @@ func EditUser(ctx *context.APIContext) {
|
||||
ctx.Error(http.StatusBadRequest, "PasswordPwned", errors.New("PasswordPwned"))
|
||||
return
|
||||
}
|
||||
if u.Salt, err = user_model.GetUserSalt(); err != nil {
|
||||
if ctx.ContextUser.Salt, err = user_model.GetUserSalt(); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "UpdateUser", err)
|
||||
return
|
||||
}
|
||||
if err = u.SetPassword(form.Password); err != nil {
|
||||
if err = ctx.ContextUser.SetPassword(form.Password); err != nil {
|
||||
ctx.InternalServerError(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if form.MustChangePassword != nil {
|
||||
u.MustChangePassword = *form.MustChangePassword
|
||||
ctx.ContextUser.MustChangePassword = *form.MustChangePassword
|
||||
}
|
||||
|
||||
u.LoginName = form.LoginName
|
||||
ctx.ContextUser.LoginName = form.LoginName
|
||||
|
||||
if form.FullName != nil {
|
||||
u.FullName = *form.FullName
|
||||
ctx.ContextUser.FullName = *form.FullName
|
||||
}
|
||||
var emailChanged bool
|
||||
if form.Email != nil {
|
||||
@@ -224,57 +229,59 @@ func EditUser(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
emailChanged = !strings.EqualFold(u.Email, email)
|
||||
u.Email = email
|
||||
emailChanged = !strings.EqualFold(ctx.ContextUser.Email, email)
|
||||
ctx.ContextUser.Email = email
|
||||
}
|
||||
if form.Website != nil {
|
||||
u.Website = *form.Website
|
||||
ctx.ContextUser.Website = *form.Website
|
||||
}
|
||||
if form.Location != nil {
|
||||
u.Location = *form.Location
|
||||
ctx.ContextUser.Location = *form.Location
|
||||
}
|
||||
if form.Description != nil {
|
||||
u.Description = *form.Description
|
||||
ctx.ContextUser.Description = *form.Description
|
||||
}
|
||||
if form.Active != nil {
|
||||
u.IsActive = *form.Active
|
||||
ctx.ContextUser.IsActive = *form.Active
|
||||
}
|
||||
if len(form.Visibility) != 0 {
|
||||
u.Visibility = api.VisibilityModes[form.Visibility]
|
||||
ctx.ContextUser.Visibility = api.VisibilityModes[form.Visibility]
|
||||
}
|
||||
if form.Admin != nil {
|
||||
u.IsAdmin = *form.Admin
|
||||
ctx.ContextUser.IsAdmin = *form.Admin
|
||||
}
|
||||
if form.AllowGitHook != nil {
|
||||
u.AllowGitHook = *form.AllowGitHook
|
||||
ctx.ContextUser.AllowGitHook = *form.AllowGitHook
|
||||
}
|
||||
if form.AllowImportLocal != nil {
|
||||
u.AllowImportLocal = *form.AllowImportLocal
|
||||
ctx.ContextUser.AllowImportLocal = *form.AllowImportLocal
|
||||
}
|
||||
if form.MaxRepoCreation != nil {
|
||||
u.MaxRepoCreation = *form.MaxRepoCreation
|
||||
ctx.ContextUser.MaxRepoCreation = *form.MaxRepoCreation
|
||||
}
|
||||
if form.AllowCreateOrganization != nil {
|
||||
u.AllowCreateOrganization = *form.AllowCreateOrganization
|
||||
ctx.ContextUser.AllowCreateOrganization = *form.AllowCreateOrganization
|
||||
}
|
||||
if form.ProhibitLogin != nil {
|
||||
u.ProhibitLogin = *form.ProhibitLogin
|
||||
ctx.ContextUser.ProhibitLogin = *form.ProhibitLogin
|
||||
}
|
||||
if form.Restricted != nil {
|
||||
u.IsRestricted = *form.Restricted
|
||||
ctx.ContextUser.IsRestricted = *form.Restricted
|
||||
}
|
||||
|
||||
if err := user_model.UpdateUser(u, emailChanged); err != nil {
|
||||
if user_model.IsErrEmailAlreadyUsed(err) || user_model.IsErrEmailInvalid(err) {
|
||||
if err := user_model.UpdateUser(ctx.ContextUser, emailChanged); err != nil {
|
||||
if user_model.IsErrEmailAlreadyUsed(err) ||
|
||||
user_model.IsErrEmailCharIsNotSupported(err) ||
|
||||
user_model.IsErrEmailInvalid(err) {
|
||||
ctx.Error(http.StatusUnprocessableEntity, "", err)
|
||||
} else {
|
||||
ctx.Error(http.StatusInternalServerError, "UpdateUser", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
log.Trace("Account profile updated by admin (%s): %s", ctx.User.Name, u.Name)
|
||||
log.Trace("Account profile updated by admin (%s): %s", ctx.Doer.Name, ctx.ContextUser.Name)
|
||||
|
||||
ctx.JSON(http.StatusOK, convert.ToUser(u, ctx.User))
|
||||
ctx.JSON(http.StatusOK, convert.ToUser(ctx.ContextUser, ctx.Doer))
|
||||
}
|
||||
|
||||
// DeleteUser api for deleting a user
|
||||
@@ -298,26 +305,28 @@ func DeleteUser(ctx *context.APIContext) {
|
||||
// "422":
|
||||
// "$ref": "#/responses/validationError"
|
||||
|
||||
u := user.GetUserByParams(ctx)
|
||||
if ctx.Written() {
|
||||
if ctx.ContextUser.IsOrganization() {
|
||||
ctx.Error(http.StatusUnprocessableEntity, "", fmt.Errorf("%s is an organization not a user", ctx.ContextUser.Name))
|
||||
return
|
||||
}
|
||||
|
||||
if u.IsOrganization() {
|
||||
ctx.Error(http.StatusUnprocessableEntity, "", fmt.Errorf("%s is an organization not a user", u.Name))
|
||||
// admin should not delete themself
|
||||
if ctx.ContextUser.ID == ctx.Doer.ID {
|
||||
ctx.Error(http.StatusUnprocessableEntity, "", fmt.Errorf("you cannot delete yourself"))
|
||||
return
|
||||
}
|
||||
|
||||
if err := user_service.DeleteUser(u); err != nil {
|
||||
if err := user_service.DeleteUser(ctx.ContextUser); err != nil {
|
||||
if models.IsErrUserOwnRepos(err) ||
|
||||
models.IsErrUserHasOrgs(err) {
|
||||
models.IsErrUserHasOrgs(err) ||
|
||||
models.IsErrUserOwnPackages(err) {
|
||||
ctx.Error(http.StatusUnprocessableEntity, "", err)
|
||||
} else {
|
||||
ctx.Error(http.StatusInternalServerError, "DeleteUser", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
log.Trace("Account deleted by admin(%s): %s", ctx.User.Name, u.Name)
|
||||
log.Trace("Account deleted by admin(%s): %s", ctx.Doer.Name, ctx.ContextUser.Name)
|
||||
|
||||
ctx.Status(http.StatusNoContent)
|
||||
}
|
||||
@@ -348,12 +357,10 @@ func CreatePublicKey(ctx *context.APIContext) {
|
||||
// "$ref": "#/responses/forbidden"
|
||||
// "422":
|
||||
// "$ref": "#/responses/validationError"
|
||||
|
||||
form := web.GetForm(ctx).(*api.CreateKeyOption)
|
||||
u := user.GetUserByParams(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
user.CreateUserPublicKey(ctx, *form, u.ID)
|
||||
|
||||
user.CreateUserPublicKey(ctx, *form, ctx.ContextUser.ID)
|
||||
}
|
||||
|
||||
// DeleteUserPublicKey api for deleting a user's public key
|
||||
@@ -383,12 +390,7 @@ func DeleteUserPublicKey(ctx *context.APIContext) {
|
||||
// "404":
|
||||
// "$ref": "#/responses/notFound"
|
||||
|
||||
u := user.GetUserByParams(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
|
||||
if err := asymkey_service.DeletePublicKey(u, ctx.ParamsInt64(":id")); err != nil {
|
||||
if err := asymkey_service.DeletePublicKey(ctx.ContextUser, ctx.ParamsInt64(":id")); err != nil {
|
||||
if asymkey_model.IsErrKeyNotExist(err) {
|
||||
ctx.NotFound()
|
||||
} else if asymkey_model.IsErrKeyAccessDenied(err) {
|
||||
@@ -398,7 +400,7 @@ func DeleteUserPublicKey(ctx *context.APIContext) {
|
||||
}
|
||||
return
|
||||
}
|
||||
log.Trace("Key deleted by admin(%s): %s", ctx.User.Name, u.Name)
|
||||
log.Trace("Key deleted by admin(%s): %s", ctx.Doer.Name, ctx.ContextUser.Name)
|
||||
|
||||
ctx.Status(http.StatusNoContent)
|
||||
}
|
||||
@@ -428,7 +430,7 @@ func GetAllUsers(ctx *context.APIContext) {
|
||||
listOptions := utils.GetListOptions(ctx)
|
||||
|
||||
users, maxResults, err := user_model.SearchUsers(&user_model.SearchUserOptions{
|
||||
Actor: ctx.User,
|
||||
Actor: ctx.Doer,
|
||||
Type: user_model.UserTypeIndividual,
|
||||
OrderBy: db.SearchOrderByAlphabetically,
|
||||
ListOptions: listOptions,
|
||||
@@ -440,7 +442,7 @@ func GetAllUsers(ctx *context.APIContext) {
|
||||
|
||||
results := make([]*api.User, len(users))
|
||||
for i := range users {
|
||||
results[i] = convert.ToUser(users[i], ctx.User)
|
||||
results[i] = convert.ToUser(users[i], ctx.Doer)
|
||||
}
|
||||
|
||||
ctx.SetLinkHeader(int(maxResults), listOptions.PageSize)
|
||||
|
||||
+122
-59
@@ -71,6 +71,8 @@ import (
|
||||
"strings"
|
||||
|
||||
"code.gitea.io/gitea/models"
|
||||
"code.gitea.io/gitea/models/organization"
|
||||
"code.gitea.io/gitea/models/perm"
|
||||
repo_model "code.gitea.io/gitea/models/repo"
|
||||
"code.gitea.io/gitea/models/unit"
|
||||
user_model "code.gitea.io/gitea/models/user"
|
||||
@@ -84,10 +86,12 @@ import (
|
||||
"code.gitea.io/gitea/routers/api/v1/misc"
|
||||
"code.gitea.io/gitea/routers/api/v1/notify"
|
||||
"code.gitea.io/gitea/routers/api/v1/org"
|
||||
"code.gitea.io/gitea/routers/api/v1/packages"
|
||||
"code.gitea.io/gitea/routers/api/v1/repo"
|
||||
"code.gitea.io/gitea/routers/api/v1/settings"
|
||||
"code.gitea.io/gitea/routers/api/v1/user"
|
||||
"code.gitea.io/gitea/services/auth"
|
||||
context_service "code.gitea.io/gitea/services/context"
|
||||
"code.gitea.io/gitea/services/forms"
|
||||
|
||||
_ "code.gitea.io/gitea/routers/api/v1/swagger" // for swagger generation
|
||||
@@ -104,7 +108,7 @@ func sudo() func(ctx *context.APIContext) {
|
||||
}
|
||||
|
||||
if len(sudo) > 0 {
|
||||
if ctx.IsSigned && ctx.User.IsAdmin {
|
||||
if ctx.IsSigned && ctx.Doer.IsAdmin {
|
||||
user, err := user_model.GetUserByName(sudo)
|
||||
if err != nil {
|
||||
if user_model.IsErrUserNotExist(err) {
|
||||
@@ -114,8 +118,8 @@ func sudo() func(ctx *context.APIContext) {
|
||||
}
|
||||
return
|
||||
}
|
||||
log.Trace("Sudo from (%s) to: %s", ctx.User.Name, user.Name)
|
||||
ctx.User = user
|
||||
log.Trace("Sudo from (%s) to: %s", ctx.Doer.Name, user.Name)
|
||||
ctx.Doer = user
|
||||
} else {
|
||||
ctx.JSON(http.StatusForbidden, map[string]string{
|
||||
"message": "Only administrators allowed to sudo.",
|
||||
@@ -137,8 +141,8 @@ func repoAssignment() func(ctx *context.APIContext) {
|
||||
)
|
||||
|
||||
// Check if the user is the same as the repository owner.
|
||||
if ctx.IsSigned && ctx.User.LowerName == strings.ToLower(userName) {
|
||||
owner = ctx.User
|
||||
if ctx.IsSigned && ctx.Doer.LowerName == strings.ToLower(userName) {
|
||||
owner = ctx.Doer
|
||||
} else {
|
||||
owner, err = user_model.GetUserByName(userName)
|
||||
if err != nil {
|
||||
@@ -157,6 +161,7 @@ func repoAssignment() func(ctx *context.APIContext) {
|
||||
}
|
||||
}
|
||||
ctx.Repo.Owner = owner
|
||||
ctx.ContextUser = owner
|
||||
|
||||
// Get repository.
|
||||
repo, err := repo_model.GetRepositoryByName(owner.ID, repoName)
|
||||
@@ -179,7 +184,7 @@ func repoAssignment() func(ctx *context.APIContext) {
|
||||
repo.Owner = owner
|
||||
ctx.Repo.Repository = repo
|
||||
|
||||
ctx.Repo.Permission, err = models.GetUserRepoPermission(repo, ctx.User)
|
||||
ctx.Repo.Permission, err = models.GetUserRepoPermission(ctx, repo, ctx.Doer)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "GetUserRepoPermission", err)
|
||||
return
|
||||
@@ -192,6 +197,15 @@ func repoAssignment() func(ctx *context.APIContext) {
|
||||
}
|
||||
}
|
||||
|
||||
func reqPackageAccess(accessMode perm.AccessMode) func(ctx *context.APIContext) {
|
||||
return func(ctx *context.APIContext) {
|
||||
if ctx.Package.AccessMode < accessMode && !ctx.IsUserSiteAdmin() {
|
||||
ctx.Error(http.StatusForbidden, "reqPackageAccess", "user should have specific permission or be a site admin")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Contexter middleware already checks token for user sign in process.
|
||||
func reqToken() func(ctx *context.APIContext) {
|
||||
return func(ctx *context.APIContext) {
|
||||
@@ -203,7 +217,6 @@ func reqToken() func(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
if ctx.IsSigned {
|
||||
ctx.RequireCSRF()
|
||||
return
|
||||
}
|
||||
ctx.Error(http.StatusUnauthorized, "reqToken", "token is required")
|
||||
@@ -271,6 +284,15 @@ func reqRepoWriter(unitTypes ...unit.Type) func(ctx *context.APIContext) {
|
||||
}
|
||||
}
|
||||
|
||||
// reqRepoBranchWriter user should have a permission to write to a branch, or be a site admin
|
||||
func reqRepoBranchWriter(ctx *context.APIContext) {
|
||||
options, ok := web.GetForm(ctx).(api.FileOptionInterface)
|
||||
if !ok || (!ctx.Repo.CanWriteToBranch(ctx.Doer, options.Branch()) && !ctx.IsUserSiteAdmin()) {
|
||||
ctx.Error(http.StatusForbidden, "reqRepoBranchWriter", "user should have a permission to write to this branch")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// reqRepoReader user should have specific read permission or be a repo admin or a site admin
|
||||
func reqRepoReader(unitType unit.Type) func(ctx *context.APIContext) {
|
||||
return func(ctx *context.APIContext) {
|
||||
@@ -308,7 +330,7 @@ func reqOrgOwnership() func(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
isOwner, err := models.IsOrganizationOwner(orgID, ctx.User.ID)
|
||||
isOwner, err := organization.IsOrganizationOwner(ctx, orgID, ctx.Doer.ID)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "IsOrganizationOwner", err)
|
||||
return
|
||||
@@ -335,7 +357,7 @@ func reqTeamMembership() func(ctx *context.APIContext) {
|
||||
}
|
||||
|
||||
orgID := ctx.Org.Team.OrgID
|
||||
isOwner, err := models.IsOrganizationOwner(orgID, ctx.User.ID)
|
||||
isOwner, err := organization.IsOrganizationOwner(ctx, orgID, ctx.Doer.ID)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "IsOrganizationOwner", err)
|
||||
return
|
||||
@@ -343,11 +365,11 @@ func reqTeamMembership() func(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
if isTeamMember, err := models.IsTeamMember(orgID, ctx.Org.Team.ID, ctx.User.ID); err != nil {
|
||||
if isTeamMember, err := organization.IsTeamMember(ctx, orgID, ctx.Org.Team.ID, ctx.Doer.ID); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "IsTeamMember", err)
|
||||
return
|
||||
} else if !isTeamMember {
|
||||
isOrgMember, err := models.IsOrganizationMember(orgID, ctx.User.ID)
|
||||
isOrgMember, err := organization.IsOrganizationMember(ctx, orgID, ctx.Doer.ID)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "IsOrganizationMember", err)
|
||||
} else if isOrgMember {
|
||||
@@ -377,7 +399,7 @@ func reqOrgMembership() func(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
if isMember, err := models.IsOrganizationMember(orgID, ctx.User.ID); err != nil {
|
||||
if isMember, err := organization.IsOrganizationMember(ctx, orgID, ctx.Doer.ID); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "IsOrganizationMember", err)
|
||||
return
|
||||
} else if !isMember {
|
||||
@@ -393,7 +415,7 @@ func reqOrgMembership() func(ctx *context.APIContext) {
|
||||
|
||||
func reqGitHook() func(ctx *context.APIContext) {
|
||||
return func(ctx *context.APIContext) {
|
||||
if !ctx.User.CanEditGitHook() {
|
||||
if !ctx.Doer.CanEditGitHook() {
|
||||
ctx.Error(http.StatusForbidden, "", "must be allowed to edit Git hooks")
|
||||
return
|
||||
}
|
||||
@@ -426,9 +448,9 @@ func orgAssignment(args ...bool) func(ctx *context.APIContext) {
|
||||
|
||||
var err error
|
||||
if assignOrg {
|
||||
ctx.Org.Organization, err = models.GetOrgByName(ctx.Params(":org"))
|
||||
ctx.Org.Organization, err = organization.GetOrgByName(ctx.Params(":org"))
|
||||
if err != nil {
|
||||
if models.IsErrOrgNotExist(err) {
|
||||
if organization.IsErrOrgNotExist(err) {
|
||||
redirectUserID, err := user_model.LookupUserRedirect(ctx.Params(":org"))
|
||||
if err == nil {
|
||||
context.RedirectToUser(ctx.Context, ctx.Params(":org"), redirectUserID)
|
||||
@@ -442,12 +464,13 @@ func orgAssignment(args ...bool) func(ctx *context.APIContext) {
|
||||
}
|
||||
return
|
||||
}
|
||||
ctx.ContextUser = ctx.Org.Organization.AsUser()
|
||||
}
|
||||
|
||||
if assignTeam {
|
||||
ctx.Org.Team, err = models.GetTeamByID(ctx.ParamsInt64(":teamid"))
|
||||
ctx.Org.Team, err = organization.GetTeamByID(ctx.ParamsInt64(":teamid"))
|
||||
if err != nil {
|
||||
if models.IsErrTeamNotExist(err) {
|
||||
if organization.IsErrTeamNotExist(err) {
|
||||
ctx.NotFound()
|
||||
} else {
|
||||
ctx.Error(http.StatusInternalServerError, "GetTeamById", err)
|
||||
@@ -464,7 +487,7 @@ func mustEnableIssues(ctx *context.APIContext) {
|
||||
if ctx.IsSigned {
|
||||
log.Trace("Permission Denied: User %-v cannot read %-v in Repo %-v\n"+
|
||||
"User in Repo has Permissions: %-+v",
|
||||
ctx.User,
|
||||
ctx.Doer,
|
||||
unit.TypeIssues,
|
||||
ctx.Repo.Repository,
|
||||
ctx.Repo.Permission)
|
||||
@@ -487,7 +510,7 @@ func mustAllowPulls(ctx *context.APIContext) {
|
||||
if ctx.IsSigned {
|
||||
log.Trace("Permission Denied: User %-v cannot read %-v in Repo %-v\n"+
|
||||
"User in Repo has Permissions: %-+v",
|
||||
ctx.User,
|
||||
ctx.Doer,
|
||||
unit.TypePullRequests,
|
||||
ctx.Repo.Repository,
|
||||
ctx.Repo.Permission)
|
||||
@@ -511,7 +534,7 @@ func mustEnableIssuesOrPulls(ctx *context.APIContext) {
|
||||
if ctx.IsSigned {
|
||||
log.Trace("Permission Denied: User %-v cannot read %-v and %-v in Repo %-v\n"+
|
||||
"User in Repo has Permissions: %-+v",
|
||||
ctx.User,
|
||||
ctx.Doer,
|
||||
unit.TypeIssues,
|
||||
unit.TypePullRequests,
|
||||
ctx.Repo.Repository,
|
||||
@@ -561,11 +584,28 @@ func bind(obj interface{}) http.HandlerFunc {
|
||||
})
|
||||
}
|
||||
|
||||
// Routes registers all v1 APIs routes to web application.
|
||||
func Routes(sessioner func(http.Handler) http.Handler) *web.Route {
|
||||
m := web.NewRoute()
|
||||
// The OAuth2 plugin is expected to be executed first, as it must ignore the user id stored
|
||||
// in the session (if there is a user id stored in session other plugins might return the user
|
||||
// object for that id).
|
||||
//
|
||||
// The Session plugin is expected to be executed second, in order to skip authentication
|
||||
// for users that have already signed in.
|
||||
func buildAuthGroup() *auth.Group {
|
||||
group := auth.NewGroup(
|
||||
&auth.OAuth2{},
|
||||
&auth.Basic{}, // FIXME: this should be removed once we don't allow basic auth in API
|
||||
)
|
||||
if setting.Service.EnableReverseProxyAuth {
|
||||
group.Add(&auth.ReverseProxy{})
|
||||
}
|
||||
specialAdd(group)
|
||||
|
||||
m.Use(sessioner)
|
||||
return group
|
||||
}
|
||||
|
||||
// Routes registers all v1 APIs routes to web application.
|
||||
func Routes() *web.Route {
|
||||
m := web.NewRoute()
|
||||
|
||||
m.Use(securityHeaders())
|
||||
if setting.CORSConfig.Enabled {
|
||||
@@ -575,14 +615,19 @@ func Routes(sessioner func(http.Handler) http.Handler) *web.Route {
|
||||
// setting.CORSConfig.AllowSubdomain // FIXME: the cors middleware needs allowSubdomain option
|
||||
AllowedMethods: setting.CORSConfig.Methods,
|
||||
AllowCredentials: setting.CORSConfig.AllowCredentials,
|
||||
AllowedHeaders: []string{"Authorization", "X-CSRFToken", "X-Gitea-OTP"},
|
||||
AllowedHeaders: []string{"Authorization", "X-Gitea-OTP"},
|
||||
MaxAge: int(setting.CORSConfig.MaxAge.Seconds()),
|
||||
}))
|
||||
}
|
||||
m.Use(context.APIContexter())
|
||||
|
||||
group := buildAuthGroup()
|
||||
if err := group.Init(); err != nil {
|
||||
log.Error("Could not initialize '%s' auth method, error: %s", group.Name(), err)
|
||||
}
|
||||
|
||||
// Get user from session if logged in.
|
||||
m.Use(context.APIAuth(auth.NewGroup(auth.Methods()...)))
|
||||
m.Use(context.APIAuth(group))
|
||||
|
||||
m.Use(context.ToggleAPI(&context.ToggleOptions{
|
||||
SignInRequired: setting.Service.RequireSignInView,
|
||||
@@ -641,7 +686,7 @@ func Routes(sessioner func(http.Handler) http.Handler) *web.Route {
|
||||
Post(bind(api.CreateAccessTokenOption{}), user.CreateAccessToken)
|
||||
m.Combo("/{id}").Delete(user.DeleteAccessToken)
|
||||
}, reqBasicOrRevProxyAuth())
|
||||
})
|
||||
}, context_service.UserAssignmentAPI())
|
||||
})
|
||||
|
||||
m.Group("/users", func() {
|
||||
@@ -658,7 +703,7 @@ func Routes(sessioner func(http.Handler) http.Handler) *web.Route {
|
||||
m.Get("/starred", user.GetStarredRepos)
|
||||
|
||||
m.Get("/subscriptions", user.GetWatchedRepos)
|
||||
})
|
||||
}, context_service.UserAssignmentAPI())
|
||||
}, reqToken())
|
||||
|
||||
m.Group("/user", func() {
|
||||
@@ -674,7 +719,11 @@ func Routes(sessioner func(http.Handler) http.Handler) *web.Route {
|
||||
m.Get("/followers", user.ListMyFollowers)
|
||||
m.Group("/following", func() {
|
||||
m.Get("", user.ListMyFollowing)
|
||||
m.Combo("/{username}").Get(user.CheckMyFollowing).Put(user.Follow).Delete(user.Unfollow)
|
||||
m.Group("/{username}", func() {
|
||||
m.Get("", user.CheckMyFollowing)
|
||||
m.Put("", user.Follow)
|
||||
m.Delete("", user.Unfollow)
|
||||
}, context_service.UserAssignmentAPI())
|
||||
})
|
||||
|
||||
m.Group("/keys", func() {
|
||||
@@ -761,14 +810,17 @@ func Routes(sessioner func(http.Handler) http.Handler) *web.Route {
|
||||
m.Combo("").Get(repo.GetHook).
|
||||
Patch(bind(api.EditHookOption{}), repo.EditHook).
|
||||
Delete(repo.DeleteHook)
|
||||
m.Post("/tests", context.RepoRefForAPI, repo.TestHook)
|
||||
m.Post("/tests", context.ReferencesGitRepo(), context.RepoRefForAPI, repo.TestHook)
|
||||
})
|
||||
}, reqToken(), reqAdmin(), reqWebhooksEnabled())
|
||||
m.Group("/collaborators", func() {
|
||||
m.Get("", reqAnyRepoReader(), repo.ListCollaborators)
|
||||
m.Combo("/{collaborator}").Get(reqAnyRepoReader(), repo.IsCollaborator).
|
||||
Put(reqAdmin(), bind(api.AddCollaboratorOption{}), repo.AddCollaborator).
|
||||
Delete(reqAdmin(), repo.DeleteCollaborator)
|
||||
m.Group("/{collaborator}", func() {
|
||||
m.Combo("").Get(reqAnyRepoReader(), repo.IsCollaborator).
|
||||
Put(reqAdmin(), bind(api.AddCollaboratorOption{}), repo.AddCollaborator).
|
||||
Delete(reqAdmin(), repo.DeleteCollaborator)
|
||||
m.Get("/permission", repo.GetRepoPermissions)
|
||||
}, reqToken())
|
||||
}, reqToken())
|
||||
m.Get("/assignees", reqToken(), reqAnyRepoReader(), repo.GetAssignees)
|
||||
m.Get("/reviewers", reqToken(), reqAnyRepoReader(), repo.GetReviewers)
|
||||
@@ -778,16 +830,16 @@ func Routes(sessioner func(http.Handler) http.Handler) *web.Route {
|
||||
Put(reqAdmin(), repo.AddTeam).
|
||||
Delete(reqAdmin(), repo.DeleteTeam)
|
||||
}, reqToken())
|
||||
m.Get("/raw/*", context.RepoRefForAPI, reqRepoReader(unit.TypeCode), repo.GetRawFile)
|
||||
m.Get("/raw/*", context.ReferencesGitRepo(), context.RepoRefForAPI, reqRepoReader(unit.TypeCode), repo.GetRawFile)
|
||||
m.Get("/archive/*", reqRepoReader(unit.TypeCode), repo.GetArchive)
|
||||
m.Combo("/forks").Get(repo.ListForks).
|
||||
Post(reqToken(), reqRepoReader(unit.TypeCode), bind(api.CreateForkOption{}), repo.CreateFork)
|
||||
m.Group("/branches", func() {
|
||||
m.Get("", context.ReferencesGitRepo(false), repo.ListBranches)
|
||||
m.Get("/*", context.ReferencesGitRepo(false), repo.GetBranch)
|
||||
m.Delete("/*", reqRepoWriter(unit.TypeCode), context.ReferencesGitRepo(false), repo.DeleteBranch)
|
||||
m.Post("", reqRepoWriter(unit.TypeCode), context.ReferencesGitRepo(false), bind(api.CreateBranchRepoOption{}), repo.CreateBranch)
|
||||
}, reqRepoReader(unit.TypeCode))
|
||||
m.Get("", repo.ListBranches)
|
||||
m.Get("/*", repo.GetBranch)
|
||||
m.Delete("/*", reqRepoWriter(unit.TypeCode), repo.DeleteBranch)
|
||||
m.Post("", reqRepoWriter(unit.TypeCode), bind(api.CreateBranchRepoOption{}), repo.CreateBranch)
|
||||
}, context.ReferencesGitRepo(), reqRepoReader(unit.TypeCode))
|
||||
m.Group("/branch_protections", func() {
|
||||
m.Get("", repo.ListBranchProtections)
|
||||
m.Post("", bind(api.CreateBranchProtectionOption{}), repo.CreateBranchProtection)
|
||||
@@ -906,10 +958,10 @@ func Routes(sessioner func(http.Handler) http.Handler) *web.Route {
|
||||
})
|
||||
m.Group("/releases", func() {
|
||||
m.Combo("").Get(repo.ListReleases).
|
||||
Post(reqToken(), reqRepoWriter(unit.TypeReleases), context.ReferencesGitRepo(false), bind(api.CreateReleaseOption{}), repo.CreateRelease)
|
||||
Post(reqToken(), reqRepoWriter(unit.TypeReleases), context.ReferencesGitRepo(), bind(api.CreateReleaseOption{}), repo.CreateRelease)
|
||||
m.Group("/{id}", func() {
|
||||
m.Combo("").Get(repo.GetRelease).
|
||||
Patch(reqToken(), reqRepoWriter(unit.TypeReleases), context.ReferencesGitRepo(false), bind(api.EditReleaseOption{}), repo.EditRelease).
|
||||
Patch(reqToken(), reqRepoWriter(unit.TypeReleases), context.ReferencesGitRepo(), bind(api.EditReleaseOption{}), repo.EditRelease).
|
||||
Delete(reqToken(), reqRepoWriter(unit.TypeReleases), repo.DeleteRelease)
|
||||
m.Group("/assets", func() {
|
||||
m.Combo("").Get(repo.ListReleaseAttachments).
|
||||
@@ -926,7 +978,7 @@ func Routes(sessioner func(http.Handler) http.Handler) *web.Route {
|
||||
})
|
||||
}, reqRepoReader(unit.TypeReleases))
|
||||
m.Post("/mirror-sync", reqToken(), reqRepoWriter(unit.TypeCode), repo.MirrorSync)
|
||||
m.Get("/editorconfig/{filename}", context.RepoRefForAPI, reqRepoReader(unit.TypeCode), repo.GetEditorconfig)
|
||||
m.Get("/editorconfig/{filename}", context.ReferencesGitRepo(), context.RepoRefForAPI, reqRepoReader(unit.TypeCode), repo.GetEditorconfig)
|
||||
m.Group("/pulls", func() {
|
||||
m.Combo("").Get(repo.ListPullRequests).
|
||||
Post(reqToken(), mustNotBeArchived, bind(api.CreatePullRequestOption{}), repo.CreatePullRequest)
|
||||
@@ -937,7 +989,8 @@ func Routes(sessioner func(http.Handler) http.Handler) *web.Route {
|
||||
m.Post("/update", reqToken(), repo.UpdatePullRequest)
|
||||
m.Get("/commits", repo.GetPullRequestCommits)
|
||||
m.Combo("/merge").Get(repo.IsPullRequestMerged).
|
||||
Post(reqToken(), mustNotBeArchived, bind(forms.MergePullRequestForm{}), repo.MergePullRequest)
|
||||
Post(reqToken(), mustNotBeArchived, bind(forms.MergePullRequestForm{}), repo.MergePullRequest).
|
||||
Delete(reqToken(), mustNotBeArchived, repo.CancelScheduledAutoMerge)
|
||||
m.Group("/reviews", func() {
|
||||
m.Combo("").
|
||||
Get(repo.ListPullReviews).
|
||||
@@ -957,39 +1010,39 @@ func Routes(sessioner func(http.Handler) http.Handler) *web.Route {
|
||||
Delete(reqToken(), bind(api.PullReviewRequestOptions{}), repo.DeleteReviewRequests).
|
||||
Post(reqToken(), bind(api.PullReviewRequestOptions{}), repo.CreateReviewRequests)
|
||||
})
|
||||
}, mustAllowPulls, reqRepoReader(unit.TypeCode), context.ReferencesGitRepo(false))
|
||||
}, mustAllowPulls, reqRepoReader(unit.TypeCode), context.ReferencesGitRepo())
|
||||
m.Group("/statuses", func() {
|
||||
m.Combo("/{sha}").Get(repo.GetCommitStatuses).
|
||||
Post(reqToken(), bind(api.CreateStatusOption{}), repo.NewCommitStatus)
|
||||
}, reqRepoReader(unit.TypeCode))
|
||||
m.Group("/commits", func() {
|
||||
m.Get("", context.ReferencesGitRepo(false), repo.GetAllCommits)
|
||||
m.Get("", context.ReferencesGitRepo(), repo.GetAllCommits)
|
||||
m.Group("/{ref}", func() {
|
||||
m.Get("/status", repo.GetCombinedCommitStatusByRef)
|
||||
m.Get("/statuses", repo.GetCommitStatusesByRef)
|
||||
})
|
||||
}, context.ReferencesGitRepo())
|
||||
}, reqRepoReader(unit.TypeCode))
|
||||
m.Group("/git", func() {
|
||||
m.Group("/commits", func() {
|
||||
m.Get("/{sha}", context.ReferencesGitRepo(false), repo.GetSingleCommit)
|
||||
m.Get("/{sha}", repo.GetSingleCommit)
|
||||
m.Get("/{sha}.{diffType:diff|patch}", repo.DownloadCommitDiffOrPatch)
|
||||
})
|
||||
m.Get("/refs", repo.GetGitAllRefs)
|
||||
m.Get("/refs/*", repo.GetGitRefs)
|
||||
m.Get("/trees/{sha}", context.RepoRefForAPI, repo.GetTree)
|
||||
m.Get("/blobs/{sha}", context.RepoRefForAPI, repo.GetBlob)
|
||||
m.Get("/tags/{sha}", context.RepoRefForAPI, repo.GetAnnotatedTag)
|
||||
m.Get("/trees/{sha}", repo.GetTree)
|
||||
m.Get("/blobs/{sha}", repo.GetBlob)
|
||||
m.Get("/tags/{sha}", repo.GetAnnotatedTag)
|
||||
m.Get("/notes/{sha}", repo.GetNote)
|
||||
}, reqRepoReader(unit.TypeCode))
|
||||
}, context.ReferencesGitRepo(), reqRepoReader(unit.TypeCode))
|
||||
m.Post("/diffpatch", reqRepoWriter(unit.TypeCode), reqToken(), bind(api.ApplyDiffPatchFileOptions{}), repo.ApplyDiffPatch)
|
||||
m.Group("/contents", func() {
|
||||
m.Get("", repo.GetContentsList)
|
||||
m.Get("/*", repo.GetContents)
|
||||
m.Group("/*", func() {
|
||||
m.Post("", bind(api.CreateFileOptions{}), repo.CreateFile)
|
||||
m.Put("", bind(api.UpdateFileOptions{}), repo.UpdateFile)
|
||||
m.Delete("", bind(api.DeleteFileOptions{}), repo.DeleteFile)
|
||||
}, reqRepoWriter(unit.TypeCode), reqToken())
|
||||
m.Post("", bind(api.CreateFileOptions{}), reqRepoBranchWriter, repo.CreateFile)
|
||||
m.Put("", bind(api.UpdateFileOptions{}), reqRepoBranchWriter, repo.UpdateFile)
|
||||
m.Delete("", bind(api.DeleteFileOptions{}), reqRepoBranchWriter, repo.DeleteFile)
|
||||
}, reqToken())
|
||||
}, reqRepoReader(unit.TypeCode))
|
||||
m.Get("/signing-key.gpg", misc.SigningKey)
|
||||
m.Group("/topics", func() {
|
||||
@@ -1000,17 +1053,26 @@ func Routes(sessioner func(http.Handler) http.Handler) *web.Route {
|
||||
Delete(reqToken(), repo.DeleteTopic)
|
||||
}, reqAdmin())
|
||||
}, reqAnyRepoReader())
|
||||
m.Get("/issue_templates", context.ReferencesGitRepo(false), repo.GetIssueTemplates)
|
||||
m.Get("/issue_templates", context.ReferencesGitRepo(), repo.GetIssueTemplates)
|
||||
m.Get("/languages", reqRepoReader(unit.TypeCode), repo.GetLanguages)
|
||||
}, repoAssignment())
|
||||
})
|
||||
|
||||
m.Group("/packages/{username}", func() {
|
||||
m.Group("/{type}/{name}/{version}", func() {
|
||||
m.Get("", packages.GetPackage)
|
||||
m.Delete("", reqPackageAccess(perm.AccessModeWrite), packages.DeletePackage)
|
||||
m.Get("/files", packages.ListPackageFiles)
|
||||
})
|
||||
m.Get("/", packages.ListPackages)
|
||||
}, context_service.UserAssignmentAPI(), context.PackageAssignmentAPI(), reqPackageAccess(perm.AccessModeRead))
|
||||
|
||||
// Organizations
|
||||
m.Get("/user/orgs", reqToken(), org.ListMyOrgs)
|
||||
m.Group("/users/{username}/orgs", func() {
|
||||
m.Get("", org.ListUserOrgs)
|
||||
m.Get("/{org}/permissions", reqToken(), org.GetUserOrgsPermissions)
|
||||
})
|
||||
}, context_service.UserAssignmentAPI())
|
||||
m.Post("/orgs", reqToken(), bind(api.CreateOrgOption{}), org.Create)
|
||||
m.Get("/orgs", org.GetAll)
|
||||
m.Group("/orgs/{org}", func() {
|
||||
@@ -1065,7 +1127,8 @@ func Routes(sessioner func(http.Handler) http.Handler) *web.Route {
|
||||
m.Get("", org.GetTeamRepos)
|
||||
m.Combo("/{org}/{reponame}").
|
||||
Put(org.AddTeamRepository).
|
||||
Delete(org.RemoveTeamRepository)
|
||||
Delete(org.RemoveTeamRepository).
|
||||
Get(org.GetTeamRepo)
|
||||
})
|
||||
}, orgAssignment(false, true), reqToken(), reqTeamMembership())
|
||||
|
||||
@@ -1088,7 +1151,7 @@ func Routes(sessioner func(http.Handler) http.Handler) *web.Route {
|
||||
m.Get("/orgs", org.ListUserOrgs)
|
||||
m.Post("/orgs", bind(api.CreateOrgOption{}), admin.CreateOrg)
|
||||
m.Post("/repos", bind(api.CreateRepoOption{}), admin.CreateRepo)
|
||||
})
|
||||
}, context_service.UserAssignmentAPI())
|
||||
})
|
||||
m.Group("/unadopted", func() {
|
||||
m.Get("", admin.ListUnadoptedRepositories)
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
// 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.
|
||||
|
||||
//go:build !windows
|
||||
|
||||
package v1
|
||||
|
||||
import auth_service "code.gitea.io/gitea/services/auth"
|
||||
|
||||
func specialAdd(group *auth_service.Group) {}
|
||||
@@ -0,0 +1,20 @@
|
||||
// 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 v1
|
||||
|
||||
import (
|
||||
"code.gitea.io/gitea/models/auth"
|
||||
auth_service "code.gitea.io/gitea/services/auth"
|
||||
)
|
||||
|
||||
// specialAdd registers the SSPI auth method as the last method in the list.
|
||||
// The SSPI plugin is expected to be executed last, as it returns 401 status code if negotiation
|
||||
// fails (or if negotiation should continue), which would prevent other authentication methods
|
||||
// to execute at all.
|
||||
func specialAdd(group *auth_service.Group) {
|
||||
if auth.IsSSPIEnabled() {
|
||||
group.Add(&auth_service.SSPI{})
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,8 @@ func createContext(req *http.Request) (*context.Context, *httptest.ResponseRecor
|
||||
Render: rnd,
|
||||
Data: make(map[string]interface{}),
|
||||
}
|
||||
defer c.Close()
|
||||
|
||||
return c, resp
|
||||
}
|
||||
|
||||
|
||||
@@ -6,12 +6,17 @@ package misc
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"code.gitea.io/gitea/models"
|
||||
user_model "code.gitea.io/gitea/models/user"
|
||||
"code.gitea.io/gitea/modules/context"
|
||||
"code.gitea.io/gitea/modules/setting"
|
||||
"code.gitea.io/gitea/modules/structs"
|
||||
)
|
||||
|
||||
const cacheKeyNodeInfoUsage = "API_NodeInfoUsage"
|
||||
|
||||
// NodeInfo returns the NodeInfo for the Gitea instance to allow for federation
|
||||
func NodeInfo(ctx *context.APIContext) {
|
||||
// swagger:operation GET /nodeinfo miscellaneous getNodeInfo
|
||||
@@ -23,6 +28,37 @@ func NodeInfo(ctx *context.APIContext) {
|
||||
// "200":
|
||||
// "$ref": "#/responses/NodeInfo"
|
||||
|
||||
nodeInfoUsage := structs.NodeInfoUsage{}
|
||||
if setting.Federation.ShareUserStatistics {
|
||||
info, ok := ctx.Cache.Get(cacheKeyNodeInfoUsage).(structs.NodeInfoUsage)
|
||||
if !ok {
|
||||
usersTotal := int(user_model.CountUsers(nil))
|
||||
now := time.Now()
|
||||
timeOneMonthAgo := now.AddDate(0, -1, 0).Unix()
|
||||
timeHaveYearAgo := now.AddDate(0, -6, 0).Unix()
|
||||
usersActiveMonth := int(user_model.CountUsers(&user_model.CountUserFilter{LastLoginSince: &timeOneMonthAgo}))
|
||||
usersActiveHalfyear := int(user_model.CountUsers(&user_model.CountUserFilter{LastLoginSince: &timeHaveYearAgo}))
|
||||
|
||||
allIssues, _ := models.CountIssues(&models.IssuesOptions{})
|
||||
allComments, _ := models.CountComments(&models.FindCommentsOptions{})
|
||||
|
||||
info = structs.NodeInfoUsage{
|
||||
Users: structs.NodeInfoUsageUsers{
|
||||
Total: usersTotal,
|
||||
ActiveMonth: usersActiveMonth,
|
||||
ActiveHalfyear: usersActiveHalfyear,
|
||||
},
|
||||
LocalPosts: int(allIssues),
|
||||
LocalComments: int(allComments),
|
||||
}
|
||||
if err := ctx.Cache.Put(cacheKeyNodeInfoUsage, nodeInfoUsage, 180); err != nil {
|
||||
ctx.InternalServerError(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
nodeInfoUsage = info
|
||||
}
|
||||
|
||||
nodeInfo := &structs.NodeInfo{
|
||||
Version: "2.1",
|
||||
Software: structs.NodeInfoSoftware{
|
||||
@@ -34,12 +70,10 @@ func NodeInfo(ctx *context.APIContext) {
|
||||
Protocols: []string{"activitypub"},
|
||||
Services: structs.NodeInfoServices{
|
||||
Inbound: []string{},
|
||||
Outbound: []string{},
|
||||
Outbound: []string{"rss2.0"},
|
||||
},
|
||||
OpenRegistrations: setting.Service.ShowRegistrationButton,
|
||||
Usage: structs.NodeInfoUsage{
|
||||
Users: structs.NodeInfoUsageUsers{},
|
||||
},
|
||||
Usage: nodeInfoUsage,
|
||||
}
|
||||
ctx.JSON(http.StatusOK, nodeInfo)
|
||||
}
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
// Copyright 2017 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 misc
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"code.gitea.io/gitea/modules/base"
|
||||
"code.gitea.io/gitea/modules/context"
|
||||
)
|
||||
|
||||
// tplSwagger swagger page template
|
||||
const tplSwagger base.TplName = "swagger/ui"
|
||||
|
||||
// Swagger render swagger-ui page with v1 json
|
||||
func Swagger(ctx *context.Context) {
|
||||
ctx.Data["APIJSONVersion"] = "v1"
|
||||
ctx.HTML(http.StatusOK, tplSwagger)
|
||||
}
|
||||
@@ -22,18 +22,18 @@ func NewAvailable(ctx *context.APIContext) {
|
||||
// responses:
|
||||
// "200":
|
||||
// "$ref": "#/responses/NotificationCount"
|
||||
ctx.JSON(http.StatusOK, api.NotificationCount{New: models.CountUnread(ctx.User)})
|
||||
ctx.JSON(http.StatusOK, api.NotificationCount{New: models.CountUnread(ctx.Doer)})
|
||||
}
|
||||
|
||||
func getFindNotificationOptions(ctx *context.APIContext) *models.FindNotificationOptions {
|
||||
before, since, err := utils.GetQueryBeforeSince(ctx)
|
||||
before, since, err := context.GetQueryBeforeSince(ctx.Context)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusUnprocessableEntity, "GetQueryBeforeSince", err)
|
||||
return nil
|
||||
}
|
||||
opts := &models.FindNotificationOptions{
|
||||
ListOptions: utils.GetListOptions(ctx),
|
||||
UserID: ctx.User.ID,
|
||||
UserID: ctx.Doer.ID,
|
||||
UpdatedBeforeUnix: before,
|
||||
UpdatedAfterUnix: since,
|
||||
}
|
||||
|
||||
@@ -193,7 +193,7 @@ func ReadRepoNotifications(ctx *context.APIContext) {
|
||||
}
|
||||
|
||||
opts := &models.FindNotificationOptions{
|
||||
UserID: ctx.User.ID,
|
||||
UserID: ctx.Doer.ID,
|
||||
RepoID: ctx.Repo.Repository.ID,
|
||||
UpdatedBeforeUnix: lastRead,
|
||||
}
|
||||
@@ -214,10 +214,10 @@ func ReadRepoNotifications(ctx *context.APIContext) {
|
||||
targetStatus = models.NotificationStatusRead
|
||||
}
|
||||
|
||||
changed := make([]*structs.NotificationThread, len(nl))
|
||||
changed := make([]*structs.NotificationThread, 0, len(nl))
|
||||
|
||||
for _, n := range nl {
|
||||
notif, err := models.SetNotificationStatus(n.ID, ctx.User, targetStatus)
|
||||
notif, err := models.SetNotificationStatus(n.ID, ctx.Doer, targetStatus)
|
||||
if err != nil {
|
||||
ctx.InternalServerError(err)
|
||||
return
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"net/http"
|
||||
|
||||
"code.gitea.io/gitea/models"
|
||||
"code.gitea.io/gitea/models/db"
|
||||
"code.gitea.io/gitea/modules/context"
|
||||
"code.gitea.io/gitea/modules/convert"
|
||||
)
|
||||
@@ -87,7 +88,7 @@ func ReadThread(ctx *context.APIContext) {
|
||||
targetStatus = models.NotificationStatusRead
|
||||
}
|
||||
|
||||
notif, err := models.SetNotificationStatus(n.ID, ctx.User, targetStatus)
|
||||
notif, err := models.SetNotificationStatus(n.ID, ctx.Doer, targetStatus)
|
||||
if err != nil {
|
||||
ctx.InternalServerError(err)
|
||||
return
|
||||
@@ -102,14 +103,14 @@ func ReadThread(ctx *context.APIContext) {
|
||||
func getThread(ctx *context.APIContext) *models.Notification {
|
||||
n, err := models.GetNotificationByID(ctx.ParamsInt64(":id"))
|
||||
if err != nil {
|
||||
if models.IsErrNotExist(err) {
|
||||
if db.IsErrNotExist(err) {
|
||||
ctx.Error(http.StatusNotFound, "GetNotificationByID", err)
|
||||
} else {
|
||||
ctx.InternalServerError(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if n.UserID != ctx.User.ID && !ctx.User.IsAdmin {
|
||||
if n.UserID != ctx.Doer.ID && !ctx.Doer.IsAdmin {
|
||||
ctx.Error(http.StatusForbidden, "GetNotificationByID", fmt.Errorf("only user itself and admin are allowed to read/change this thread %d", n.ID))
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -141,7 +141,7 @@ func ReadNotifications(ctx *context.APIContext) {
|
||||
}
|
||||
}
|
||||
opts := &models.FindNotificationOptions{
|
||||
UserID: ctx.User.ID,
|
||||
UserID: ctx.Doer.ID,
|
||||
UpdatedBeforeUnix: lastRead,
|
||||
}
|
||||
if !ctx.FormBool("all") {
|
||||
@@ -162,7 +162,7 @@ func ReadNotifications(ctx *context.APIContext) {
|
||||
changed := make([]*structs.NotificationThread, 0, len(nl))
|
||||
|
||||
for _, n := range nl {
|
||||
notif, err := models.SetNotificationStatus(n.ID, ctx.User, targetStatus)
|
||||
notif, err := models.SetNotificationStatus(n.ID, ctx.Doer, targetStatus)
|
||||
if err != nil {
|
||||
ctx.InternalServerError(err)
|
||||
return
|
||||
|
||||
@@ -99,7 +99,7 @@ func CreateLabel(ctx *context.APIContext) {
|
||||
OrgID: ctx.Org.Organization.ID,
|
||||
Description: form.Description,
|
||||
}
|
||||
if err := models.NewLabel(label); err != nil {
|
||||
if err := models.NewLabel(ctx, label); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "NewLabel", err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"net/url"
|
||||
|
||||
"code.gitea.io/gitea/models"
|
||||
"code.gitea.io/gitea/models/organization"
|
||||
"code.gitea.io/gitea/modules/context"
|
||||
"code.gitea.io/gitea/modules/convert"
|
||||
"code.gitea.io/gitea/modules/setting"
|
||||
@@ -19,19 +20,19 @@ import (
|
||||
|
||||
// listMembers list an organization's members
|
||||
func listMembers(ctx *context.APIContext, publicOnly bool) {
|
||||
opts := &models.FindOrgMembersOpts{
|
||||
opts := &organization.FindOrgMembersOpts{
|
||||
OrgID: ctx.Org.Organization.ID,
|
||||
PublicOnly: publicOnly,
|
||||
ListOptions: utils.GetListOptions(ctx),
|
||||
}
|
||||
|
||||
count, err := models.CountOrgMembers(opts)
|
||||
count, err := organization.CountOrgMembers(opts)
|
||||
if err != nil {
|
||||
ctx.InternalServerError(err)
|
||||
return
|
||||
}
|
||||
|
||||
members, _, err := models.FindOrgMembers(opts)
|
||||
members, _, err := organization.FindOrgMembers(opts)
|
||||
if err != nil {
|
||||
ctx.InternalServerError(err)
|
||||
return
|
||||
@@ -39,7 +40,7 @@ func listMembers(ctx *context.APIContext, publicOnly bool) {
|
||||
|
||||
apiMembers := make([]*api.User, len(members))
|
||||
for i, member := range members {
|
||||
apiMembers[i] = convert.ToUser(member, ctx.User)
|
||||
apiMembers[i] = convert.ToUser(member, ctx.Doer)
|
||||
}
|
||||
|
||||
ctx.SetTotalCountHeader(count)
|
||||
@@ -72,13 +73,13 @@ func ListMembers(ctx *context.APIContext) {
|
||||
// "$ref": "#/responses/UserList"
|
||||
|
||||
publicOnly := true
|
||||
if ctx.User != nil {
|
||||
isMember, err := ctx.Org.Organization.IsOrgMember(ctx.User.ID)
|
||||
if ctx.Doer != nil {
|
||||
isMember, err := ctx.Org.Organization.IsOrgMember(ctx.Doer.ID)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "IsOrgMember", err)
|
||||
return
|
||||
}
|
||||
publicOnly = !isMember && !ctx.User.IsAdmin
|
||||
publicOnly = !isMember && !ctx.Doer.IsAdmin
|
||||
}
|
||||
listMembers(ctx, publicOnly)
|
||||
}
|
||||
@@ -130,7 +131,7 @@ func IsMember(ctx *context.APIContext) {
|
||||
// responses:
|
||||
// "204":
|
||||
// description: user is a member
|
||||
// "302":
|
||||
// "303":
|
||||
// description: redirection to /orgs/{org}/public_members/{username}
|
||||
// "404":
|
||||
// description: user is not a member
|
||||
@@ -139,12 +140,12 @@ func IsMember(ctx *context.APIContext) {
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
if ctx.User != nil {
|
||||
userIsMember, err := ctx.Org.Organization.IsOrgMember(ctx.User.ID)
|
||||
if ctx.Doer != nil {
|
||||
userIsMember, err := ctx.Org.Organization.IsOrgMember(ctx.Doer.ID)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "IsOrgMember", err)
|
||||
return
|
||||
} else if userIsMember || ctx.User.IsAdmin {
|
||||
} else if userIsMember || ctx.Doer.IsAdmin {
|
||||
userToCheckIsMember, err := ctx.Org.Organization.IsOrgMember(userToCheck.ID)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "IsOrgMember", err)
|
||||
@@ -154,14 +155,14 @@ func IsMember(ctx *context.APIContext) {
|
||||
ctx.NotFound()
|
||||
}
|
||||
return
|
||||
} else if ctx.User.ID == userToCheck.ID {
|
||||
} else if ctx.Doer.ID == userToCheck.ID {
|
||||
ctx.NotFound()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
redirectURL := setting.AppSubURL + "/api/v1/orgs/" + url.PathEscape(ctx.Org.Organization.Name) + "/public_members/" + url.PathEscape(userToCheck.Name)
|
||||
ctx.Redirect(redirectURL, 302)
|
||||
ctx.Redirect(redirectURL)
|
||||
}
|
||||
|
||||
// IsPublicMember check if a user is a public member of an organization
|
||||
@@ -190,7 +191,7 @@ func IsPublicMember(ctx *context.APIContext) {
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
is, err := models.IsPublicMembership(ctx.Org.Organization.ID, userToCheck.ID)
|
||||
is, err := organization.IsPublicMembership(ctx.Org.Organization.ID, userToCheck.ID)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "IsPublicMembership", err)
|
||||
return
|
||||
@@ -230,11 +231,11 @@ func PublicizeMember(ctx *context.APIContext) {
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
if userToPublicize.ID != ctx.User.ID {
|
||||
if userToPublicize.ID != ctx.Doer.ID {
|
||||
ctx.Error(http.StatusForbidden, "", "Cannot publicize another member")
|
||||
return
|
||||
}
|
||||
err := models.ChangeOrgUserStatus(ctx.Org.Organization.ID, userToPublicize.ID, true)
|
||||
err := organization.ChangeOrgUserStatus(ctx.Org.Organization.ID, userToPublicize.ID, true)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "ChangeOrgUserStatus", err)
|
||||
return
|
||||
@@ -270,11 +271,11 @@ func ConcealMember(ctx *context.APIContext) {
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
if userToConceal.ID != ctx.User.ID {
|
||||
if userToConceal.ID != ctx.Doer.ID {
|
||||
ctx.Error(http.StatusForbidden, "", "Cannot conceal another member")
|
||||
return
|
||||
}
|
||||
err := models.ChangeOrgUserStatus(ctx.Org.Organization.ID, userToConceal.ID, false)
|
||||
err := organization.ChangeOrgUserStatus(ctx.Org.Organization.ID, userToConceal.ID, false)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "ChangeOrgUserStatus", err)
|
||||
return
|
||||
@@ -308,8 +309,8 @@ func DeleteMember(ctx *context.APIContext) {
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
if err := ctx.Org.Organization.RemoveMember(member.ID); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "RemoveMember", err)
|
||||
if err := models.RemoveOrgUser(ctx.Org.Organization.ID, member.ID); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "RemoveOrgUser", err)
|
||||
}
|
||||
ctx.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
+19
-28
@@ -8,8 +8,8 @@ package org
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"code.gitea.io/gitea/models"
|
||||
"code.gitea.io/gitea/models/db"
|
||||
"code.gitea.io/gitea/models/organization"
|
||||
"code.gitea.io/gitea/models/perm"
|
||||
user_model "code.gitea.io/gitea/models/user"
|
||||
"code.gitea.io/gitea/modules/context"
|
||||
@@ -23,19 +23,19 @@ import (
|
||||
|
||||
func listUserOrgs(ctx *context.APIContext, u *user_model.User) {
|
||||
listOptions := utils.GetListOptions(ctx)
|
||||
showPrivate := ctx.IsSigned && (ctx.User.IsAdmin || ctx.User.ID == u.ID)
|
||||
showPrivate := ctx.IsSigned && (ctx.Doer.IsAdmin || ctx.Doer.ID == u.ID)
|
||||
|
||||
opts := models.FindOrgOptions{
|
||||
opts := organization.FindOrgOptions{
|
||||
ListOptions: listOptions,
|
||||
UserID: u.ID,
|
||||
IncludePrivate: showPrivate,
|
||||
}
|
||||
orgs, err := models.FindOrgs(opts)
|
||||
orgs, err := organization.FindOrgs(opts)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "FindOrgs", err)
|
||||
return
|
||||
}
|
||||
maxResults, err := models.CountOrgs(opts)
|
||||
maxResults, err := organization.CountOrgs(opts)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "CountOrgs", err)
|
||||
return
|
||||
@@ -71,7 +71,7 @@ func ListMyOrgs(ctx *context.APIContext) {
|
||||
// "200":
|
||||
// "$ref": "#/responses/OrganizationList"
|
||||
|
||||
listUserOrgs(ctx, ctx.User)
|
||||
listUserOrgs(ctx, ctx.Doer)
|
||||
}
|
||||
|
||||
// ListUserOrgs list user's orgs
|
||||
@@ -99,11 +99,7 @@ func ListUserOrgs(ctx *context.APIContext) {
|
||||
// "200":
|
||||
// "$ref": "#/responses/OrganizationList"
|
||||
|
||||
u := user.GetUserByParams(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
listUserOrgs(ctx, u)
|
||||
listUserOrgs(ctx, ctx.ContextUser)
|
||||
}
|
||||
|
||||
// GetUserOrgsPermissions get user permissions in organization
|
||||
@@ -132,11 +128,6 @@ func GetUserOrgsPermissions(ctx *context.APIContext) {
|
||||
// "404":
|
||||
// "$ref": "#/responses/notFound"
|
||||
|
||||
var u *user_model.User
|
||||
if u = user.GetUserByParams(ctx); u == nil {
|
||||
return
|
||||
}
|
||||
|
||||
var o *user_model.User
|
||||
if o = user.GetUserByParamsName(ctx, ":org"); o == nil {
|
||||
return
|
||||
@@ -144,13 +135,13 @@ func GetUserOrgsPermissions(ctx *context.APIContext) {
|
||||
|
||||
op := api.OrganizationPermissions{}
|
||||
|
||||
if !models.HasOrgOrUserVisible(o, u) {
|
||||
if !organization.HasOrgOrUserVisible(ctx, o, ctx.ContextUser) {
|
||||
ctx.NotFound("HasOrgOrUserVisible", nil)
|
||||
return
|
||||
}
|
||||
|
||||
org := models.OrgFromUser(o)
|
||||
authorizeLevel, err := org.GetOrgUserMaxAuthorizeLevel(u.ID)
|
||||
org := organization.OrgFromUser(o)
|
||||
authorizeLevel, err := org.GetOrgUserMaxAuthorizeLevel(ctx.ContextUser.ID)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "GetOrgUserAuthorizeLevel", err)
|
||||
return
|
||||
@@ -169,7 +160,7 @@ func GetUserOrgsPermissions(ctx *context.APIContext) {
|
||||
op.IsOwner = true
|
||||
}
|
||||
|
||||
op.CanCreateRepository, err = org.CanCreateOrgRepo(u.ID)
|
||||
op.CanCreateRepository, err = org.CanCreateOrgRepo(ctx.ContextUser.ID)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "CanCreateOrgRepo", err)
|
||||
return
|
||||
@@ -201,7 +192,7 @@ func GetAll(ctx *context.APIContext) {
|
||||
vMode := []api.VisibleType{api.VisibleTypePublic}
|
||||
if ctx.IsSigned {
|
||||
vMode = append(vMode, api.VisibleTypeLimited)
|
||||
if ctx.User.IsAdmin {
|
||||
if ctx.Doer.IsAdmin {
|
||||
vMode = append(vMode, api.VisibleTypePrivate)
|
||||
}
|
||||
}
|
||||
@@ -209,7 +200,7 @@ func GetAll(ctx *context.APIContext) {
|
||||
listOptions := utils.GetListOptions(ctx)
|
||||
|
||||
publicOrgs, maxResults, err := user_model.SearchUsers(&user_model.SearchUserOptions{
|
||||
Actor: ctx.User,
|
||||
Actor: ctx.Doer,
|
||||
ListOptions: listOptions,
|
||||
Type: user_model.UserTypeOrganization,
|
||||
OrderBy: db.SearchOrderByAlphabetically,
|
||||
@@ -221,7 +212,7 @@ func GetAll(ctx *context.APIContext) {
|
||||
}
|
||||
orgs := make([]*api.Organization, len(publicOrgs))
|
||||
for i := range publicOrgs {
|
||||
orgs[i] = convert.ToOrganization(models.OrgFromUser(publicOrgs[i]))
|
||||
orgs[i] = convert.ToOrganization(organization.OrgFromUser(publicOrgs[i]))
|
||||
}
|
||||
|
||||
ctx.SetLinkHeader(int(maxResults), listOptions.PageSize)
|
||||
@@ -251,7 +242,7 @@ func Create(ctx *context.APIContext) {
|
||||
// "422":
|
||||
// "$ref": "#/responses/validationError"
|
||||
form := web.GetForm(ctx).(*api.CreateOrgOption)
|
||||
if !ctx.User.CanCreateOrganization() {
|
||||
if !ctx.Doer.CanCreateOrganization() {
|
||||
ctx.Error(http.StatusForbidden, "Create organization not allowed", nil)
|
||||
return
|
||||
}
|
||||
@@ -261,7 +252,7 @@ func Create(ctx *context.APIContext) {
|
||||
visibility = api.VisibilityModes[form.Visibility]
|
||||
}
|
||||
|
||||
org := &models.Organization{
|
||||
org := &organization.Organization{
|
||||
Name: form.UserName,
|
||||
FullName: form.FullName,
|
||||
Description: form.Description,
|
||||
@@ -272,7 +263,7 @@ func Create(ctx *context.APIContext) {
|
||||
Visibility: visibility,
|
||||
RepoAdminChangeTeamAccess: form.RepoAdminChangeTeamAccess,
|
||||
}
|
||||
if err := models.CreateOrganization(org, ctx.User); err != nil {
|
||||
if err := organization.CreateOrganization(org, ctx.Doer); err != nil {
|
||||
if user_model.IsErrUserAlreadyExist(err) ||
|
||||
db.IsErrNameReserved(err) ||
|
||||
db.IsErrNameCharsNotAllowed(err) ||
|
||||
@@ -304,7 +295,7 @@ func Get(ctx *context.APIContext) {
|
||||
// "200":
|
||||
// "$ref": "#/responses/Organization"
|
||||
|
||||
if !models.HasOrgOrUserVisible(ctx.Org.Organization.AsUser(), ctx.User) {
|
||||
if !organization.HasOrgOrUserVisible(ctx, ctx.Org.Organization.AsUser(), ctx.Doer) {
|
||||
ctx.NotFound("HasOrgOrUserVisible", nil)
|
||||
return
|
||||
}
|
||||
@@ -346,7 +337,7 @@ func Edit(ctx *context.APIContext) {
|
||||
if form.RepoAdminChangeTeamAccess != nil {
|
||||
org.RepoAdminChangeTeamAccess = *form.RepoAdminChangeTeamAccess
|
||||
}
|
||||
if err := user_model.UpdateUserCols(db.DefaultContext, org.AsUser(),
|
||||
if err := user_model.UpdateUserCols(ctx, org.AsUser(),
|
||||
"full_name", "description", "website", "location",
|
||||
"visibility", "repo_admin_change_team_access",
|
||||
); err != nil {
|
||||
|
||||
+92
-35
@@ -10,6 +10,7 @@ import (
|
||||
"net/http"
|
||||
|
||||
"code.gitea.io/gitea/models"
|
||||
"code.gitea.io/gitea/models/organization"
|
||||
"code.gitea.io/gitea/models/perm"
|
||||
repo_model "code.gitea.io/gitea/models/repo"
|
||||
unit_model "code.gitea.io/gitea/models/unit"
|
||||
@@ -47,7 +48,7 @@ func ListTeams(ctx *context.APIContext) {
|
||||
// "200":
|
||||
// "$ref": "#/responses/TeamList"
|
||||
|
||||
teams, count, err := models.SearchOrgTeams(&models.SearchOrgTeamOptions{
|
||||
teams, count, err := organization.SearchTeam(&organization.SearchTeamOptions{
|
||||
ListOptions: utils.GetListOptions(ctx),
|
||||
OrgID: ctx.Org.Organization.ID,
|
||||
})
|
||||
@@ -90,9 +91,9 @@ func ListUserTeams(ctx *context.APIContext) {
|
||||
// "200":
|
||||
// "$ref": "#/responses/TeamList"
|
||||
|
||||
teams, count, err := models.GetUserTeams(&models.GetUserTeamOptions{
|
||||
teams, count, err := organization.SearchTeam(&organization.SearchTeamOptions{
|
||||
ListOptions: utils.GetListOptions(ctx),
|
||||
UserID: ctx.User.ID,
|
||||
UserID: ctx.Doer.ID,
|
||||
})
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "GetUserTeams", err)
|
||||
@@ -104,7 +105,7 @@ func ListUserTeams(ctx *context.APIContext) {
|
||||
for i := range teams {
|
||||
apiOrg, ok := cache[teams[i].OrgID]
|
||||
if !ok {
|
||||
org, err := models.GetOrgByID(teams[i].OrgID)
|
||||
org, err := organization.GetOrgByID(teams[i].OrgID)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "GetUserByID", err)
|
||||
return
|
||||
@@ -150,11 +151,11 @@ func GetTeam(ctx *context.APIContext) {
|
||||
ctx.JSON(http.StatusOK, convert.ToTeam(ctx.Org.Team))
|
||||
}
|
||||
|
||||
func attachTeamUnits(team *models.Team, units []string) {
|
||||
func attachTeamUnits(team *organization.Team, units []string) {
|
||||
unitTypes := unit_model.FindUnitTypes(units...)
|
||||
team.Units = make([]*models.TeamUnit, 0, len(units))
|
||||
team.Units = make([]*organization.TeamUnit, 0, len(units))
|
||||
for _, tp := range unitTypes {
|
||||
team.Units = append(team.Units, &models.TeamUnit{
|
||||
team.Units = append(team.Units, &organization.TeamUnit{
|
||||
OrgID: team.OrgID,
|
||||
Type: tp,
|
||||
AccessMode: team.AccessMode,
|
||||
@@ -170,10 +171,10 @@ func convertUnitsMap(unitsMap map[string]string) map[unit_model.Type]perm.Access
|
||||
return res
|
||||
}
|
||||
|
||||
func attachTeamUnitsMap(team *models.Team, unitsMap map[string]string) {
|
||||
team.Units = make([]*models.TeamUnit, 0, len(unitsMap))
|
||||
func attachTeamUnitsMap(team *organization.Team, unitsMap map[string]string) {
|
||||
team.Units = make([]*organization.TeamUnit, 0, len(unitsMap))
|
||||
for unitKey, p := range unitsMap {
|
||||
team.Units = append(team.Units, &models.TeamUnit{
|
||||
team.Units = append(team.Units, &organization.TeamUnit{
|
||||
OrgID: team.OrgID,
|
||||
Type: unit_model.TypeFromKey(unitKey),
|
||||
AccessMode: perm.ParseAccessMode(p),
|
||||
@@ -210,7 +211,7 @@ func CreateTeam(ctx *context.APIContext) {
|
||||
if p < perm.AccessModeAdmin && len(form.UnitsMap) > 0 {
|
||||
p = unit_model.MinUnitAccessMode(convertUnitsMap(form.UnitsMap))
|
||||
}
|
||||
team := &models.Team{
|
||||
team := &organization.Team{
|
||||
OrgID: ctx.Org.Organization.ID,
|
||||
Name: form.Name,
|
||||
Description: form.Description,
|
||||
@@ -231,7 +232,7 @@ func CreateTeam(ctx *context.APIContext) {
|
||||
}
|
||||
|
||||
if err := models.NewTeam(team); err != nil {
|
||||
if models.IsErrTeamAlreadyExist(err) {
|
||||
if organization.IsErrTeamAlreadyExist(err) {
|
||||
ctx.Error(http.StatusUnprocessableEntity, "", err)
|
||||
} else {
|
||||
ctx.Error(http.StatusInternalServerError, "NewTeam", err)
|
||||
@@ -368,24 +369,27 @@ func GetTeamMembers(ctx *context.APIContext) {
|
||||
// "200":
|
||||
// "$ref": "#/responses/UserList"
|
||||
|
||||
isMember, err := models.IsOrganizationMember(ctx.Org.Team.OrgID, ctx.User.ID)
|
||||
isMember, err := organization.IsOrganizationMember(ctx, ctx.Org.Team.OrgID, ctx.Doer.ID)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "IsOrganizationMember", err)
|
||||
return
|
||||
} else if !isMember && !ctx.User.IsAdmin {
|
||||
} else if !isMember && !ctx.Doer.IsAdmin {
|
||||
ctx.NotFound()
|
||||
return
|
||||
}
|
||||
|
||||
if err := ctx.Org.Team.GetMembers(&models.SearchMembersOptions{
|
||||
teamMembers, err := organization.GetTeamMembers(ctx, &organization.SearchMembersOptions{
|
||||
ListOptions: utils.GetListOptions(ctx),
|
||||
}); err != nil {
|
||||
TeamID: ctx.Org.Team.ID,
|
||||
})
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "GetTeamMembers", err)
|
||||
return
|
||||
}
|
||||
members := make([]*api.User, len(ctx.Org.Team.Members))
|
||||
for i, member := range ctx.Org.Team.Members {
|
||||
members[i] = convert.ToUser(member, ctx.User)
|
||||
|
||||
members := make([]*api.User, len(teamMembers))
|
||||
for i, member := range teamMembers {
|
||||
members[i] = convert.ToUser(member, ctx.Doer)
|
||||
}
|
||||
|
||||
ctx.SetTotalCountHeader(int64(ctx.Org.Team.NumMembers))
|
||||
@@ -422,7 +426,7 @@ func GetTeamMember(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
teamID := ctx.ParamsInt64("teamid")
|
||||
isTeamMember, err := models.IsUserInTeams(u.ID, []int64{teamID})
|
||||
isTeamMember, err := organization.IsUserInTeams(ctx, u.ID, []int64{teamID})
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "IsUserInTeams", err)
|
||||
return
|
||||
@@ -430,7 +434,7 @@ func GetTeamMember(ctx *context.APIContext) {
|
||||
ctx.NotFound()
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusOK, convert.ToUser(u, ctx.User))
|
||||
ctx.JSON(http.StatusOK, convert.ToUser(u, ctx.Doer))
|
||||
}
|
||||
|
||||
// AddTeamMember api for add a member to a team
|
||||
@@ -462,7 +466,7 @@ func AddTeamMember(ctx *context.APIContext) {
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
if err := ctx.Org.Team.AddMember(u.ID); err != nil {
|
||||
if err := models.AddTeamMember(ctx.Org.Team, u.ID); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "AddMember", err)
|
||||
return
|
||||
}
|
||||
@@ -499,8 +503,8 @@ func RemoveTeamMember(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := ctx.Org.Team.RemoveMember(u.ID); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "RemoveMember", err)
|
||||
if err := models.RemoveTeamMember(ctx.Org.Team, u.ID); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "RemoveTeamMember", err)
|
||||
return
|
||||
}
|
||||
ctx.Status(http.StatusNoContent)
|
||||
@@ -533,14 +537,17 @@ func GetTeamRepos(ctx *context.APIContext) {
|
||||
// "$ref": "#/responses/RepositoryList"
|
||||
|
||||
team := ctx.Org.Team
|
||||
if err := team.GetRepositories(&models.SearchOrgTeamOptions{
|
||||
teamRepos, err := organization.GetTeamRepositories(ctx, &organization.SearchTeamRepoOptions{
|
||||
ListOptions: utils.GetListOptions(ctx),
|
||||
}); err != nil {
|
||||
TeamID: team.ID,
|
||||
})
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "GetTeamRepos", err)
|
||||
return
|
||||
}
|
||||
repos := make([]*api.Repository, len(team.Repos))
|
||||
for i, repo := range team.Repos {
|
||||
access, err := models.AccessLevel(ctx.User, repo)
|
||||
repos := make([]*api.Repository, len(teamRepos))
|
||||
for i, repo := range teamRepos {
|
||||
access, err := models.AccessLevel(ctx.Doer, repo)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "GetTeamRepos", err)
|
||||
return
|
||||
@@ -551,6 +558,55 @@ func GetTeamRepos(ctx *context.APIContext) {
|
||||
ctx.JSON(http.StatusOK, repos)
|
||||
}
|
||||
|
||||
// GetTeamRepo api for get a particular repo of team
|
||||
func GetTeamRepo(ctx *context.APIContext) {
|
||||
// swagger:operation GET /teams/{id}/repos/{org}/{repo} organization orgListTeamRepo
|
||||
// ---
|
||||
// summary: List a particular repo of team
|
||||
// produces:
|
||||
// - application/json
|
||||
// parameters:
|
||||
// - name: id
|
||||
// in: path
|
||||
// description: id of the team
|
||||
// type: integer
|
||||
// format: int64
|
||||
// required: true
|
||||
// - name: org
|
||||
// in: path
|
||||
// description: organization that owns the repo to list
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: repo
|
||||
// in: path
|
||||
// description: name of the repo to list
|
||||
// type: string
|
||||
// required: true
|
||||
// responses:
|
||||
// "200":
|
||||
// "$ref": "#/responses/Repository"
|
||||
// "404":
|
||||
// "$ref": "#/responses/notFound"
|
||||
|
||||
repo := getRepositoryByParams(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
|
||||
if !organization.HasTeamRepo(ctx, ctx.Org.Team.OrgID, ctx.Org.Team.ID, repo.ID) {
|
||||
ctx.NotFound()
|
||||
return
|
||||
}
|
||||
|
||||
access, err := models.AccessLevel(ctx.Doer, repo)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "GetTeamRepos", err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, convert.ToRepo(repo, access))
|
||||
}
|
||||
|
||||
// getRepositoryByParams get repository by a team's organization ID and repo name
|
||||
func getRepositoryByParams(ctx *context.APIContext) *repo_model.Repository {
|
||||
repo, err := repo_model.GetRepositoryByName(ctx.Org.Team.OrgID, ctx.Params(":reponame"))
|
||||
@@ -599,14 +655,14 @@ func AddTeamRepository(ctx *context.APIContext) {
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
if access, err := models.AccessLevel(ctx.User, repo); err != nil {
|
||||
if access, err := models.AccessLevel(ctx.Doer, repo); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "AccessLevel", err)
|
||||
return
|
||||
} else if access < perm.AccessModeAdmin {
|
||||
ctx.Error(http.StatusForbidden, "", "Must have admin-level access to the repository")
|
||||
return
|
||||
}
|
||||
if err := ctx.Org.Team.AddRepository(repo); err != nil {
|
||||
if err := models.AddRepository(ctx.Org.Team, repo); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "AddRepository", err)
|
||||
return
|
||||
}
|
||||
@@ -649,14 +705,14 @@ func RemoveTeamRepository(ctx *context.APIContext) {
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
if access, err := models.AccessLevel(ctx.User, repo); err != nil {
|
||||
if access, err := models.AccessLevel(ctx.Doer, repo); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "AccessLevel", err)
|
||||
return
|
||||
} else if access < perm.AccessModeAdmin {
|
||||
ctx.Error(http.StatusForbidden, "", "Must have admin-level access to the repository")
|
||||
return
|
||||
}
|
||||
if err := ctx.Org.Team.RemoveRepository(repo.ID); err != nil {
|
||||
if err := models.RemoveRepository(ctx.Org.Team, repo.ID); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "RemoveRepository", err)
|
||||
return
|
||||
}
|
||||
@@ -707,14 +763,15 @@ func SearchTeam(ctx *context.APIContext) {
|
||||
|
||||
listOptions := utils.GetListOptions(ctx)
|
||||
|
||||
opts := &models.SearchOrgTeamOptions{
|
||||
opts := &organization.SearchTeamOptions{
|
||||
UserID: ctx.Doer.ID,
|
||||
Keyword: ctx.FormTrim("q"),
|
||||
OrgID: ctx.Org.Organization.ID,
|
||||
IncludeDesc: ctx.FormString("include_desc") == "" || ctx.FormBool("include_desc"),
|
||||
ListOptions: listOptions,
|
||||
}
|
||||
|
||||
teams, maxResults, err := models.SearchOrgTeams(opts)
|
||||
teams, maxResults, err := organization.SearchTeam(opts)
|
||||
if err != nil {
|
||||
log.Error("SearchTeam failed: %v", err)
|
||||
ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
// Copyright 2021 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 packages
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"code.gitea.io/gitea/models/packages"
|
||||
"code.gitea.io/gitea/modules/context"
|
||||
"code.gitea.io/gitea/modules/convert"
|
||||
api "code.gitea.io/gitea/modules/structs"
|
||||
"code.gitea.io/gitea/routers/api/v1/utils"
|
||||
packages_service "code.gitea.io/gitea/services/packages"
|
||||
)
|
||||
|
||||
// ListPackages gets all packages of an owner
|
||||
func ListPackages(ctx *context.APIContext) {
|
||||
// swagger:operation GET /packages/{owner} package listPackages
|
||||
// ---
|
||||
// summary: Gets all packages of an owner
|
||||
// produces:
|
||||
// - application/json
|
||||
// parameters:
|
||||
// - name: owner
|
||||
// in: path
|
||||
// description: owner of the packages
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: page
|
||||
// in: query
|
||||
// description: page number of results to return (1-based)
|
||||
// type: integer
|
||||
// - name: limit
|
||||
// in: query
|
||||
// description: page size of results
|
||||
// type: integer
|
||||
// - name: type
|
||||
// in: query
|
||||
// description: package type filter
|
||||
// type: string
|
||||
// enum: [composer, conan, container, generic, helm, maven, npm, nuget, pypi, rubygems]
|
||||
// - name: q
|
||||
// in: query
|
||||
// description: name filter
|
||||
// type: string
|
||||
// responses:
|
||||
// "200":
|
||||
// "$ref": "#/responses/PackageList"
|
||||
|
||||
listOptions := utils.GetListOptions(ctx)
|
||||
|
||||
packageType := ctx.FormTrim("type")
|
||||
query := ctx.FormTrim("q")
|
||||
|
||||
pvs, count, err := packages.SearchVersions(ctx, &packages.PackageSearchOptions{
|
||||
OwnerID: ctx.Package.Owner.ID,
|
||||
Type: packages.Type(packageType),
|
||||
Name: packages.SearchValue{Value: query},
|
||||
Paginator: &listOptions,
|
||||
})
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "SearchVersions", err)
|
||||
return
|
||||
}
|
||||
|
||||
pds, err := packages.GetPackageDescriptors(ctx, pvs)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "GetPackageDescriptors", err)
|
||||
return
|
||||
}
|
||||
|
||||
apiPackages := make([]*api.Package, 0, len(pds))
|
||||
for _, pd := range pds {
|
||||
apiPackage, err := convert.ToPackage(ctx, pd, ctx.Doer)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "Error converting package for api", err)
|
||||
return
|
||||
}
|
||||
apiPackages = append(apiPackages, apiPackage)
|
||||
}
|
||||
|
||||
ctx.SetLinkHeader(int(count), listOptions.PageSize)
|
||||
ctx.SetTotalCountHeader(count)
|
||||
ctx.JSON(http.StatusOK, apiPackages)
|
||||
}
|
||||
|
||||
// GetPackage gets a package
|
||||
func GetPackage(ctx *context.APIContext) {
|
||||
// swagger:operation GET /packages/{owner}/{type}/{name}/{version} package getPackage
|
||||
// ---
|
||||
// summary: Gets a package
|
||||
// produces:
|
||||
// - application/json
|
||||
// parameters:
|
||||
// - name: owner
|
||||
// in: path
|
||||
// description: owner of the package
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: type
|
||||
// in: path
|
||||
// description: type of the package
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: name
|
||||
// in: path
|
||||
// description: name of the package
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: version
|
||||
// in: path
|
||||
// description: version of the package
|
||||
// type: string
|
||||
// required: true
|
||||
// responses:
|
||||
// "200":
|
||||
// "$ref": "#/responses/Package"
|
||||
// "404":
|
||||
// "$ref": "#/responses/notFound"
|
||||
|
||||
apiPackage, err := convert.ToPackage(ctx, ctx.Package.Descriptor, ctx.Doer)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "Error converting package for api", err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, apiPackage)
|
||||
}
|
||||
|
||||
// DeletePackage deletes a package
|
||||
func DeletePackage(ctx *context.APIContext) {
|
||||
// swagger:operation DELETE /packages/{owner}/{type}/{name}/{version} package deletePackage
|
||||
// ---
|
||||
// summary: Delete a package
|
||||
// parameters:
|
||||
// - name: owner
|
||||
// in: path
|
||||
// description: owner of the package
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: type
|
||||
// in: path
|
||||
// description: type of the package
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: name
|
||||
// in: path
|
||||
// description: name of the package
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: version
|
||||
// in: path
|
||||
// description: version of the package
|
||||
// type: string
|
||||
// required: true
|
||||
// responses:
|
||||
// "204":
|
||||
// "$ref": "#/responses/empty"
|
||||
// "404":
|
||||
// "$ref": "#/responses/notFound"
|
||||
|
||||
err := packages_service.RemovePackageVersion(ctx.Doer, ctx.Package.Descriptor.Version)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "RemovePackageVersion", err)
|
||||
return
|
||||
}
|
||||
ctx.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// ListPackageFiles gets all files of a package
|
||||
func ListPackageFiles(ctx *context.APIContext) {
|
||||
// swagger:operation GET /packages/{owner}/{type}/{name}/{version}/files package listPackageFiles
|
||||
// ---
|
||||
// summary: Gets all files of a package
|
||||
// produces:
|
||||
// - application/json
|
||||
// parameters:
|
||||
// - name: owner
|
||||
// in: path
|
||||
// description: owner of the package
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: type
|
||||
// in: path
|
||||
// description: type of the package
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: name
|
||||
// in: path
|
||||
// description: name of the package
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: version
|
||||
// in: path
|
||||
// description: version of the package
|
||||
// type: string
|
||||
// required: true
|
||||
// responses:
|
||||
// "200":
|
||||
// "$ref": "#/responses/PackageFileList"
|
||||
// "404":
|
||||
// "$ref": "#/responses/notFound"
|
||||
|
||||
apiPackageFiles := make([]*api.PackageFile, 0, len(ctx.Package.Descriptor.Files))
|
||||
for _, pfd := range ctx.Package.Descriptor.Files {
|
||||
apiPackageFiles = append(apiPackageFiles, convert.ToPackageFile(pfd))
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, apiPackageFiles)
|
||||
}
|
||||
@@ -45,7 +45,8 @@ func GetBlob(ctx *context.APIContext) {
|
||||
ctx.Error(http.StatusBadRequest, "", "sha not provided")
|
||||
return
|
||||
}
|
||||
if blob, err := files_service.GetBlobBySHA(ctx, ctx.Repo.Repository, sha); err != nil {
|
||||
|
||||
if blob, err := files_service.GetBlobBySHA(ctx, ctx.Repo.Repository, ctx.Repo.GitRepo, sha); err != nil {
|
||||
ctx.Error(http.StatusBadRequest, "", err)
|
||||
} else {
|
||||
ctx.JSON(http.StatusOK, blob)
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"net/http"
|
||||
|
||||
"code.gitea.io/gitea/models"
|
||||
"code.gitea.io/gitea/models/organization"
|
||||
user_model "code.gitea.io/gitea/models/user"
|
||||
"code.gitea.io/gitea/modules/context"
|
||||
"code.gitea.io/gitea/modules/convert"
|
||||
@@ -75,7 +76,7 @@ func GetBranch(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
br, err := convert.ToBranch(ctx.Repo.Repository, branch, c, branchProtection, ctx.User, ctx.Repo.IsAdmin())
|
||||
br, err := convert.ToBranch(ctx.Repo.Repository, branch, c, branchProtection, ctx.Doer, ctx.Repo.IsAdmin())
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "convert.ToBranch", err)
|
||||
return
|
||||
@@ -117,7 +118,7 @@ func DeleteBranch(ctx *context.APIContext) {
|
||||
|
||||
branchName := ctx.Params("*")
|
||||
|
||||
if err := repo_service.DeleteBranch(ctx.User, ctx.Repo.Repository, ctx.Repo.GitRepo, branchName); err != nil {
|
||||
if err := repo_service.DeleteBranch(ctx.Doer, ctx.Repo.Repository, ctx.Repo.GitRepo, branchName); err != nil {
|
||||
switch {
|
||||
case git.IsErrBranchNotExist(err):
|
||||
ctx.NotFound(err)
|
||||
@@ -176,7 +177,7 @@ func CreateBranch(ctx *context.APIContext) {
|
||||
opt.OldBranchName = ctx.Repo.Repository.DefaultBranch
|
||||
}
|
||||
|
||||
err := repo_service.CreateNewBranch(ctx, ctx.User, ctx.Repo.Repository, opt.OldBranchName, opt.BranchName)
|
||||
err := repo_service.CreateNewBranch(ctx, ctx.Doer, ctx.Repo.Repository, opt.OldBranchName, opt.BranchName)
|
||||
if err != nil {
|
||||
if models.IsErrBranchDoesNotExist(err) {
|
||||
ctx.Error(http.StatusNotFound, "", "The old branch does not exist")
|
||||
@@ -211,7 +212,7 @@ func CreateBranch(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
br, err := convert.ToBranch(ctx.Repo.Repository, branch, commit, branchProtection, ctx.User, ctx.Repo.IsAdmin())
|
||||
br, err := convert.ToBranch(ctx.Repo.Repository, branch, commit, branchProtection, ctx.Doer, ctx.Repo.IsAdmin())
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "convert.ToBranch", err)
|
||||
return
|
||||
@@ -258,10 +259,15 @@ func ListBranches(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
apiBranches := make([]*api.Branch, len(branches))
|
||||
apiBranches := make([]*api.Branch, 0, len(branches))
|
||||
for i := range branches {
|
||||
c, err := branches[i].GetCommit()
|
||||
if err != nil {
|
||||
// Skip if this branch doesn't exist anymore.
|
||||
if git.IsErrNotExist(err) {
|
||||
totalNumOfBranches--
|
||||
continue
|
||||
}
|
||||
ctx.Error(http.StatusInternalServerError, "GetCommit", err)
|
||||
return
|
||||
}
|
||||
@@ -270,11 +276,12 @@ func ListBranches(ctx *context.APIContext) {
|
||||
ctx.Error(http.StatusInternalServerError, "GetBranchProtection", err)
|
||||
return
|
||||
}
|
||||
apiBranches[i], err = convert.ToBranch(ctx.Repo.Repository, branches[i], c, branchProtection, ctx.User, ctx.Repo.IsAdmin())
|
||||
apiBranch, err := convert.ToBranch(ctx.Repo.Repository, branches[i], c, branchProtection, ctx.Doer, ctx.Repo.IsAdmin())
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "convert.ToBranch", err)
|
||||
return
|
||||
}
|
||||
apiBranches = append(apiBranches, apiBranch)
|
||||
}
|
||||
|
||||
ctx.SetLinkHeader(totalNumOfBranches, listOptions.PageSize)
|
||||
@@ -448,27 +455,27 @@ func CreateBranchProtection(ctx *context.APIContext) {
|
||||
}
|
||||
var whitelistTeams, mergeWhitelistTeams, approvalsWhitelistTeams []int64
|
||||
if repo.Owner.IsOrganization() {
|
||||
whitelistTeams, err = models.GetTeamIDsByNames(repo.OwnerID, form.PushWhitelistTeams, false)
|
||||
whitelistTeams, err = organization.GetTeamIDsByNames(repo.OwnerID, form.PushWhitelistTeams, false)
|
||||
if err != nil {
|
||||
if models.IsErrTeamNotExist(err) {
|
||||
if organization.IsErrTeamNotExist(err) {
|
||||
ctx.Error(http.StatusUnprocessableEntity, "Team does not exist", err)
|
||||
return
|
||||
}
|
||||
ctx.Error(http.StatusInternalServerError, "GetTeamIDsByNames", err)
|
||||
return
|
||||
}
|
||||
mergeWhitelistTeams, err = models.GetTeamIDsByNames(repo.OwnerID, form.MergeWhitelistTeams, false)
|
||||
mergeWhitelistTeams, err = organization.GetTeamIDsByNames(repo.OwnerID, form.MergeWhitelistTeams, false)
|
||||
if err != nil {
|
||||
if models.IsErrTeamNotExist(err) {
|
||||
if organization.IsErrTeamNotExist(err) {
|
||||
ctx.Error(http.StatusUnprocessableEntity, "Team does not exist", err)
|
||||
return
|
||||
}
|
||||
ctx.Error(http.StatusInternalServerError, "GetTeamIDsByNames", err)
|
||||
return
|
||||
}
|
||||
approvalsWhitelistTeams, err = models.GetTeamIDsByNames(repo.OwnerID, form.ApprovalsWhitelistTeams, false)
|
||||
approvalsWhitelistTeams, err = organization.GetTeamIDsByNames(repo.OwnerID, form.ApprovalsWhitelistTeams, false)
|
||||
if err != nil {
|
||||
if models.IsErrTeamNotExist(err) {
|
||||
if organization.IsErrTeamNotExist(err) {
|
||||
ctx.Error(http.StatusUnprocessableEntity, "Team does not exist", err)
|
||||
return
|
||||
}
|
||||
@@ -497,7 +504,7 @@ func CreateBranchProtection(ctx *context.APIContext) {
|
||||
BlockOnOutdatedBranch: form.BlockOnOutdatedBranch,
|
||||
}
|
||||
|
||||
err = models.UpdateProtectBranch(ctx.Repo.Repository, protectBranch, models.WhitelistOptions{
|
||||
err = models.UpdateProtectBranch(ctx, ctx.Repo.Repository, protectBranch, models.WhitelistOptions{
|
||||
UserIDs: whitelistUsers,
|
||||
TeamIDs: whitelistTeams,
|
||||
MergeUserIDs: mergeWhitelistUsers,
|
||||
@@ -692,9 +699,9 @@ func EditBranchProtection(ctx *context.APIContext) {
|
||||
var whitelistTeams, mergeWhitelistTeams, approvalsWhitelistTeams []int64
|
||||
if repo.Owner.IsOrganization() {
|
||||
if form.PushWhitelistTeams != nil {
|
||||
whitelistTeams, err = models.GetTeamIDsByNames(repo.OwnerID, form.PushWhitelistTeams, false)
|
||||
whitelistTeams, err = organization.GetTeamIDsByNames(repo.OwnerID, form.PushWhitelistTeams, false)
|
||||
if err != nil {
|
||||
if models.IsErrTeamNotExist(err) {
|
||||
if organization.IsErrTeamNotExist(err) {
|
||||
ctx.Error(http.StatusUnprocessableEntity, "Team does not exist", err)
|
||||
return
|
||||
}
|
||||
@@ -705,9 +712,9 @@ func EditBranchProtection(ctx *context.APIContext) {
|
||||
whitelistTeams = protectBranch.WhitelistTeamIDs
|
||||
}
|
||||
if form.MergeWhitelistTeams != nil {
|
||||
mergeWhitelistTeams, err = models.GetTeamIDsByNames(repo.OwnerID, form.MergeWhitelistTeams, false)
|
||||
mergeWhitelistTeams, err = organization.GetTeamIDsByNames(repo.OwnerID, form.MergeWhitelistTeams, false)
|
||||
if err != nil {
|
||||
if models.IsErrTeamNotExist(err) {
|
||||
if organization.IsErrTeamNotExist(err) {
|
||||
ctx.Error(http.StatusUnprocessableEntity, "Team does not exist", err)
|
||||
return
|
||||
}
|
||||
@@ -718,9 +725,9 @@ func EditBranchProtection(ctx *context.APIContext) {
|
||||
mergeWhitelistTeams = protectBranch.MergeWhitelistTeamIDs
|
||||
}
|
||||
if form.ApprovalsWhitelistTeams != nil {
|
||||
approvalsWhitelistTeams, err = models.GetTeamIDsByNames(repo.OwnerID, form.ApprovalsWhitelistTeams, false)
|
||||
approvalsWhitelistTeams, err = organization.GetTeamIDsByNames(repo.OwnerID, form.ApprovalsWhitelistTeams, false)
|
||||
if err != nil {
|
||||
if models.IsErrTeamNotExist(err) {
|
||||
if organization.IsErrTeamNotExist(err) {
|
||||
ctx.Error(http.StatusUnprocessableEntity, "Team does not exist", err)
|
||||
return
|
||||
}
|
||||
@@ -732,7 +739,7 @@ func EditBranchProtection(ctx *context.APIContext) {
|
||||
}
|
||||
}
|
||||
|
||||
err = models.UpdateProtectBranch(ctx.Repo.Repository, protectBranch, models.WhitelistOptions{
|
||||
err = models.UpdateProtectBranch(ctx, ctx.Repo.Repository, protectBranch, models.WhitelistOptions{
|
||||
UserIDs: whitelistUsers,
|
||||
TeamIDs: whitelistTeams,
|
||||
MergeUserIDs: mergeWhitelistUsers,
|
||||
|
||||
@@ -63,7 +63,7 @@ func ListCollaborators(ctx *context.APIContext) {
|
||||
|
||||
users := make([]*api.User, len(collaborators))
|
||||
for i, collaborator := range collaborators {
|
||||
users[i] = convert.ToUser(collaborator.User, ctx.User)
|
||||
users[i] = convert.ToUser(collaborator.User, ctx.Doer)
|
||||
}
|
||||
|
||||
ctx.SetTotalCountHeader(count)
|
||||
@@ -233,6 +233,61 @@ func DeleteCollaborator(ctx *context.APIContext) {
|
||||
ctx.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// GetRepoPermissions gets repository permissions for a user
|
||||
func GetRepoPermissions(ctx *context.APIContext) {
|
||||
// swagger:operation GET /repos/{owner}/{repo}/collaborators/{collaborator}/permission repository repoGetRepoPermissions
|
||||
// ---
|
||||
// summary: Get repository permissions for a user
|
||||
// produces:
|
||||
// - application/json
|
||||
// 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: collaborator
|
||||
// in: path
|
||||
// description: username of the collaborator
|
||||
// type: string
|
||||
// required: true
|
||||
// responses:
|
||||
// "200":
|
||||
// "$ref": "#/responses/RepoCollaboratorPermission"
|
||||
// "404":
|
||||
// "$ref": "#/responses/notFound"
|
||||
// "403":
|
||||
// "$ref": "#/responses/forbidden"
|
||||
|
||||
if !ctx.Doer.IsAdmin && ctx.Doer.LoginName != ctx.Params(":collaborator") && !ctx.IsUserRepoAdmin() {
|
||||
ctx.Error(http.StatusForbidden, "User", "Only admins can query all permissions, repo admins can query all repo permissions, collaborators can query only their own")
|
||||
return
|
||||
}
|
||||
|
||||
collaborator, err := user_model.GetUserByName(ctx.Params(":collaborator"))
|
||||
if err != nil {
|
||||
if user_model.IsErrUserNotExist(err) {
|
||||
ctx.Error(http.StatusNotFound, "GetUserByName", err)
|
||||
} else {
|
||||
ctx.Error(http.StatusInternalServerError, "GetUserByName", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
permission, err := models.GetUserRepoPermission(ctx, ctx.Repo.Repository, collaborator)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "GetUserRepoPermission", err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, convert.ToUserAndPermission(collaborator, ctx.ContextUser, permission.AccessMode))
|
||||
}
|
||||
|
||||
// GetReviewers return all users that can be requested to review in this repo
|
||||
func GetReviewers(ctx *context.APIContext) {
|
||||
// swagger:operation GET /repos/{owner}/{repo}/reviewers repository repoGetReviewers
|
||||
@@ -255,12 +310,12 @@ func GetReviewers(ctx *context.APIContext) {
|
||||
// "200":
|
||||
// "$ref": "#/responses/UserList"
|
||||
|
||||
reviewers, err := models.GetReviewers(ctx.Repo.Repository, ctx.User.ID, 0)
|
||||
reviewers, err := models.GetReviewers(ctx.Repo.Repository, ctx.Doer.ID, 0)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "ListCollaborators", err)
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusOK, convert.ToUsers(ctx.User, reviewers))
|
||||
ctx.JSON(http.StatusOK, convert.ToUsers(ctx.Doer, reviewers))
|
||||
}
|
||||
|
||||
// GetAssignees return all users that have write access and can be assigned to issues
|
||||
@@ -290,5 +345,5 @@ func GetAssignees(ctx *context.APIContext) {
|
||||
ctx.Error(http.StatusInternalServerError, "ListCollaborators", err)
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusOK, convert.ToUsers(ctx.User, assignees))
|
||||
ctx.JSON(http.StatusOK, convert.ToUsers(ctx.Doer, assignees))
|
||||
}
|
||||
|
||||
@@ -11,7 +11,6 @@ import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
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"
|
||||
@@ -268,16 +267,12 @@ func DownloadCommitDiffOrPatch(ctx *context.APIContext) {
|
||||
// "$ref": "#/responses/string"
|
||||
// "404":
|
||||
// "$ref": "#/responses/notFound"
|
||||
repoPath := repo_model.RepoPath(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
|
||||
if err := git.GetRawDiff(
|
||||
ctx,
|
||||
repoPath,
|
||||
ctx.Params(":sha"),
|
||||
git.RawDiffType(ctx.Params(":diffType")),
|
||||
ctx.Resp,
|
||||
); err != nil {
|
||||
sha := ctx.Params(":sha")
|
||||
diffType := git.RawDiffType(ctx.Params(":diffType"))
|
||||
|
||||
if err := git.GetRawDiff(ctx.Repo.GitRepo, sha, diffType, ctx.Resp); err != nil {
|
||||
if git.IsErrNotExist(err) {
|
||||
ctx.NotFound(ctx.Params(":sha"))
|
||||
ctx.NotFound(sha)
|
||||
return
|
||||
}
|
||||
ctx.Error(http.StatusInternalServerError, "DownloadCommitDiffOrPatch", err)
|
||||
|
||||
+56
-32
@@ -9,13 +9,16 @@ import (
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"path"
|
||||
"time"
|
||||
|
||||
"code.gitea.io/gitea/models"
|
||||
repo_model "code.gitea.io/gitea/models/repo"
|
||||
"code.gitea.io/gitea/models/unit"
|
||||
"code.gitea.io/gitea/modules/cache"
|
||||
"code.gitea.io/gitea/modules/context"
|
||||
"code.gitea.io/gitea/modules/git"
|
||||
"code.gitea.io/gitea/modules/setting"
|
||||
api "code.gitea.io/gitea/modules/structs"
|
||||
"code.gitea.io/gitea/modules/web"
|
||||
"code.gitea.io/gitea/routers/common"
|
||||
@@ -53,7 +56,7 @@ func GetRawFile(ctx *context.APIContext) {
|
||||
// required: false
|
||||
// responses:
|
||||
// 200:
|
||||
// description: success
|
||||
// description: Returns raw file content.
|
||||
// "404":
|
||||
// "$ref": "#/responses/notFound"
|
||||
|
||||
@@ -62,33 +65,50 @@ func GetRawFile(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
commit := ctx.Repo.Commit
|
||||
|
||||
if ref := ctx.FormTrim("ref"); len(ref) > 0 {
|
||||
var err error
|
||||
commit, err = ctx.Repo.GitRepo.GetCommit(ref)
|
||||
if err != nil {
|
||||
if git.IsErrNotExist(err) {
|
||||
ctx.NotFound()
|
||||
} else {
|
||||
ctx.Error(http.StatusInternalServerError, "GetBlobByPath", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
blob, lastModified := getBlobForEntry(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
|
||||
blob, err := commit.GetBlobByPath(ctx.Repo.TreePath)
|
||||
if err := common.ServeBlob(ctx.Context, blob, lastModified); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "ServeBlob", err)
|
||||
}
|
||||
}
|
||||
|
||||
func getBlobForEntry(ctx *context.APIContext) (blob *git.Blob, lastModified time.Time) {
|
||||
entry, err := ctx.Repo.Commit.GetTreeEntryByPath(ctx.Repo.TreePath)
|
||||
if err != nil {
|
||||
if git.IsErrNotExist(err) {
|
||||
ctx.NotFound()
|
||||
} else {
|
||||
ctx.Error(http.StatusInternalServerError, "GetBlobByPath", err)
|
||||
ctx.Error(http.StatusInternalServerError, "GetTreeEntryByPath", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err = common.ServeBlob(ctx.Context, blob); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "ServeBlob", err)
|
||||
|
||||
if entry.IsDir() || entry.IsSubModule() {
|
||||
ctx.NotFound("getBlobForEntry", nil)
|
||||
return
|
||||
}
|
||||
|
||||
var c *git.LastCommitCache
|
||||
if setting.CacheService.LastCommit.Enabled && ctx.Repo.CommitsCount >= setting.CacheService.LastCommit.CommitsCount {
|
||||
c = git.NewLastCommitCache(ctx.Repo.Repository.FullName(), ctx.Repo.GitRepo, setting.LastCommitCacheTTLSeconds, cache.GetCache())
|
||||
}
|
||||
|
||||
info, _, err := git.Entries([]*git.TreeEntry{entry}).GetCommitsInfo(ctx, ctx.Repo.Commit, path.Dir("/" + ctx.Repo.TreePath)[1:], c)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "GetCommitsInfo", err)
|
||||
return
|
||||
}
|
||||
|
||||
if len(info) == 1 {
|
||||
// Not Modified
|
||||
lastModified = info[0].Commit.Committer.When
|
||||
}
|
||||
blob = entry.Blob()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// GetArchive get archive of a repository
|
||||
@@ -122,7 +142,7 @@ func GetArchive(ctx *context.APIContext) {
|
||||
|
||||
repoPath := repo_model.RepoPath(ctx.Params(":username"), ctx.Params(":reponame"))
|
||||
if ctx.Repo.GitRepo == nil {
|
||||
gitRepo, err := git.OpenRepositoryCtx(ctx, repoPath)
|
||||
gitRepo, err := git.OpenRepository(ctx, repoPath)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "OpenRepository", err)
|
||||
return
|
||||
@@ -157,13 +177,18 @@ func GetEditorconfig(ctx *context.APIContext) {
|
||||
// description: filepath of file to get
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: ref
|
||||
// in: query
|
||||
// description: "The name of the commit/branch/tag. Default the repository’s default branch (usually master)"
|
||||
// type: string
|
||||
// required: false
|
||||
// responses:
|
||||
// 200:
|
||||
// description: success
|
||||
// "404":
|
||||
// "$ref": "#/responses/notFound"
|
||||
|
||||
ec, err := ctx.Repo.GetEditorconfig()
|
||||
ec, err := ctx.Repo.GetEditorconfig(ctx.Repo.Commit)
|
||||
if err != nil {
|
||||
if git.IsErrNotExist(err) {
|
||||
ctx.NotFound(err)
|
||||
@@ -183,8 +208,10 @@ func GetEditorconfig(ctx *context.APIContext) {
|
||||
}
|
||||
|
||||
// canWriteFiles returns true if repository is editable and user has proper access level.
|
||||
func canWriteFiles(r *context.Repository) bool {
|
||||
return r.Permission.CanWrite(unit.TypeCode) && !r.Repository.IsMirror && !r.Repository.IsArchived
|
||||
func canWriteFiles(ctx *context.APIContext, branch string) bool {
|
||||
return ctx.Repo.Permission.CanWriteToBranch(ctx.Doer, branch) &&
|
||||
!ctx.Repo.Repository.IsMirror &&
|
||||
!ctx.Repo.Repository.IsArchived
|
||||
}
|
||||
|
||||
// canReadFiles returns true if repository is readable and user has proper access level.
|
||||
@@ -233,9 +260,6 @@ func CreateFile(ctx *context.APIContext) {
|
||||
// "$ref": "#/responses/error"
|
||||
|
||||
apiOpts := web.GetForm(ctx).(*api.CreateFileOptions)
|
||||
if ctx.Repo.Repository.IsEmpty {
|
||||
ctx.Error(http.StatusUnprocessableEntity, "RepoIsEmpty", fmt.Errorf("repo is empty"))
|
||||
}
|
||||
|
||||
if apiOpts.BranchName == "" {
|
||||
apiOpts.BranchName = ctx.Repo.Repository.DefaultBranch
|
||||
@@ -389,9 +413,9 @@ func handleCreateOrUpdateFileError(ctx *context.APIContext, err error) {
|
||||
|
||||
// Called from both CreateFile or UpdateFile to handle both
|
||||
func createOrUpdateFile(ctx *context.APIContext, opts *files_service.UpdateRepoFileOptions) (*api.FileResponse, error) {
|
||||
if !canWriteFiles(ctx.Repo) {
|
||||
if !canWriteFiles(ctx, opts.OldBranch) {
|
||||
return nil, models.ErrUserDoesNotHaveAccessToRepo{
|
||||
UserID: ctx.User.ID,
|
||||
UserID: ctx.Doer.ID,
|
||||
RepoName: ctx.Repo.Repository.LowerName,
|
||||
}
|
||||
}
|
||||
@@ -402,7 +426,7 @@ func createOrUpdateFile(ctx *context.APIContext, opts *files_service.UpdateRepoF
|
||||
}
|
||||
opts.Content = string(content)
|
||||
|
||||
return files_service.CreateOrUpdateRepoFile(ctx, ctx.Repo.Repository, ctx.User, opts)
|
||||
return files_service.CreateOrUpdateRepoFile(ctx, ctx.Repo.Repository, ctx.Doer, opts)
|
||||
}
|
||||
|
||||
// DeleteFile Delete a file in a repository
|
||||
@@ -446,9 +470,9 @@ func DeleteFile(ctx *context.APIContext) {
|
||||
// "$ref": "#/responses/error"
|
||||
|
||||
apiOpts := web.GetForm(ctx).(*api.DeleteFileOptions)
|
||||
if !canWriteFiles(ctx.Repo) {
|
||||
if !canWriteFiles(ctx, apiOpts.BranchName) {
|
||||
ctx.Error(http.StatusForbidden, "DeleteFile", models.ErrUserDoesNotHaveAccessToRepo{
|
||||
UserID: ctx.User.ID,
|
||||
UserID: ctx.Doer.ID,
|
||||
RepoName: ctx.Repo.Repository.LowerName,
|
||||
})
|
||||
return
|
||||
@@ -489,7 +513,7 @@ func DeleteFile(ctx *context.APIContext) {
|
||||
opts.Message = ctx.Tr("repo.editor.delete", opts.TreePath)
|
||||
}
|
||||
|
||||
if fileResponse, err := files_service.DeleteRepoFile(ctx, ctx.Repo.Repository, ctx.User, opts); err != nil {
|
||||
if fileResponse, err := files_service.DeleteRepoFile(ctx, ctx.Repo.Repository, ctx.Doer, opts); err != nil {
|
||||
if git.IsErrBranchNotExist(err) || models.IsErrRepoFileDoesNotExist(err) || git.IsErrNotExist(err) {
|
||||
ctx.Error(http.StatusNotFound, "DeleteFile", err)
|
||||
return
|
||||
@@ -546,7 +570,7 @@ func GetContents(ctx *context.APIContext) {
|
||||
|
||||
if !canReadFiles(ctx.Repo) {
|
||||
ctx.Error(http.StatusInternalServerError, "GetContentsOrList", models.ErrUserDoesNotHaveAccessToRepo{
|
||||
UserID: ctx.User.ID,
|
||||
UserID: ctx.Doer.ID,
|
||||
RepoName: ctx.Repo.Repository.LowerName,
|
||||
})
|
||||
return
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"net/http"
|
||||
|
||||
"code.gitea.io/gitea/models"
|
||||
"code.gitea.io/gitea/models/organization"
|
||||
"code.gitea.io/gitea/models/perm"
|
||||
repo_model "code.gitea.io/gitea/models/repo"
|
||||
user_model "code.gitea.io/gitea/models/user"
|
||||
@@ -58,7 +59,7 @@ func ListForks(ctx *context.APIContext) {
|
||||
}
|
||||
apiForks := make([]*api.Repository, len(forks))
|
||||
for i, fork := range forks {
|
||||
access, err := models.AccessLevel(ctx.User, fork)
|
||||
access, err := models.AccessLevel(ctx.Doer, fork)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "AccessLevel", err)
|
||||
return
|
||||
@@ -106,18 +107,18 @@ func CreateFork(ctx *context.APIContext) {
|
||||
repo := ctx.Repo.Repository
|
||||
var forker *user_model.User // user/org that will own the fork
|
||||
if form.Organization == nil {
|
||||
forker = ctx.User
|
||||
forker = ctx.Doer
|
||||
} else {
|
||||
org, err := models.GetOrgByName(*form.Organization)
|
||||
org, err := organization.GetOrgByName(*form.Organization)
|
||||
if err != nil {
|
||||
if models.IsErrOrgNotExist(err) {
|
||||
if organization.IsErrOrgNotExist(err) {
|
||||
ctx.Error(http.StatusUnprocessableEntity, "", err)
|
||||
} else {
|
||||
ctx.Error(http.StatusInternalServerError, "GetOrgByName", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
isMember, err := org.IsOrgMember(ctx.User.ID)
|
||||
isMember, err := org.IsOrgMember(ctx.Doer.ID)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "IsOrgMember", err)
|
||||
return
|
||||
@@ -135,7 +136,7 @@ func CreateFork(ctx *context.APIContext) {
|
||||
name = *form.Name
|
||||
}
|
||||
|
||||
fork, err := repo_service.ForkRepository(ctx.User, forker, repo_service.ForkRepoOptions{
|
||||
fork, err := repo_service.ForkRepository(ctx, ctx.Doer, forker, repo_service.ForkRepoOptions{
|
||||
BaseRepo: repo,
|
||||
Name: name,
|
||||
Description: repo.Description,
|
||||
|
||||
@@ -138,6 +138,11 @@ func TestHook(ctx *context.APIContext) {
|
||||
// type: integer
|
||||
// format: int64
|
||||
// required: true
|
||||
// - name: ref
|
||||
// in: query
|
||||
// description: "The name of the commit/branch/tag. Default the repository’s default branch (usually master)"
|
||||
// type: string
|
||||
// required: false
|
||||
// responses:
|
||||
// "204":
|
||||
// "$ref": "#/responses/empty"
|
||||
@@ -163,8 +168,8 @@ func TestHook(ctx *context.APIContext) {
|
||||
Commits: []*api.PayloadCommit{commit},
|
||||
HeadCommit: commit,
|
||||
Repo: convert.ToRepo(ctx.Repo.Repository, perm.AccessModeNone),
|
||||
Pusher: convert.ToUserWithAccessMode(ctx.User, perm.AccessModeNone),
|
||||
Sender: convert.ToUserWithAccessMode(ctx.User, perm.AccessModeNone),
|
||||
Pusher: convert.ToUserWithAccessMode(ctx.Doer, perm.AccessModeNone),
|
||||
Sender: convert.ToUserWithAccessMode(ctx.Doer, perm.AccessModeNone),
|
||||
}); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "PrepareWebhook: ", err)
|
||||
return
|
||||
|
||||
@@ -14,6 +14,8 @@ import (
|
||||
|
||||
"code.gitea.io/gitea/models"
|
||||
"code.gitea.io/gitea/models/db"
|
||||
issues_model "code.gitea.io/gitea/models/issues"
|
||||
"code.gitea.io/gitea/models/organization"
|
||||
"code.gitea.io/gitea/models/unit"
|
||||
user_model "code.gitea.io/gitea/models/user"
|
||||
"code.gitea.io/gitea/modules/context"
|
||||
@@ -110,7 +112,7 @@ func SearchIssues(ctx *context.APIContext) {
|
||||
// "200":
|
||||
// "$ref": "#/responses/IssueList"
|
||||
|
||||
before, since, err := utils.GetQueryBeforeSince(ctx)
|
||||
before, since, err := context.GetQueryBeforeSince(ctx.Context)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusUnprocessableEntity, "GetQueryBeforeSince", err)
|
||||
return
|
||||
@@ -135,7 +137,7 @@ func SearchIssues(ctx *context.APIContext) {
|
||||
// This needs to be a column that is not nil in fixtures or
|
||||
// MySQL will return different results when sorting by null in some cases
|
||||
OrderBy: db.SearchOrderByAlphabetically,
|
||||
Actor: ctx.User,
|
||||
Actor: ctx.Doer,
|
||||
}
|
||||
if ctx.IsSigned {
|
||||
opts.Private = true
|
||||
@@ -161,9 +163,9 @@ func SearchIssues(ctx *context.APIContext) {
|
||||
ctx.Error(http.StatusBadRequest, "", "Owner organisation is required for filtering on team")
|
||||
return
|
||||
}
|
||||
team, err := models.GetTeam(opts.OwnerID, ctx.FormString("team"))
|
||||
team, err := organization.GetTeam(opts.OwnerID, ctx.FormString("team"))
|
||||
if err != nil {
|
||||
if models.IsErrTeamNotExist(err) {
|
||||
if organization.IsErrTeamNotExist(err) {
|
||||
ctx.Error(http.StatusBadRequest, "Team not found", err)
|
||||
} else {
|
||||
ctx.Error(http.StatusInternalServerError, "GetUserByName", err)
|
||||
@@ -173,6 +175,7 @@ func SearchIssues(ctx *context.APIContext) {
|
||||
opts.TeamID = team.ID
|
||||
}
|
||||
|
||||
repoCond := models.SearchRepositoryCondition(opts)
|
||||
repoIDs, _, err := models.SearchRepositoryIDs(opts)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "SearchRepositoryByName", err)
|
||||
@@ -233,7 +236,7 @@ func SearchIssues(ctx *context.APIContext) {
|
||||
Page: ctx.FormInt("page"),
|
||||
PageSize: limit,
|
||||
},
|
||||
RepoIDs: repoIDs,
|
||||
RepoCond: repoCond,
|
||||
IsClosed: isClosed,
|
||||
IssueIDs: issueIDs,
|
||||
IncludedLabelNames: includedLabelNames,
|
||||
@@ -245,18 +248,23 @@ func SearchIssues(ctx *context.APIContext) {
|
||||
UpdatedAfterUnix: since,
|
||||
}
|
||||
|
||||
ctxUserID := int64(0)
|
||||
if ctx.IsSigned {
|
||||
ctxUserID = ctx.Doer.ID
|
||||
}
|
||||
|
||||
// Filter for: Created by User, Assigned to User, Mentioning User, Review of User Requested
|
||||
if ctx.FormBool("created") {
|
||||
issuesOpt.PosterID = ctx.User.ID
|
||||
issuesOpt.PosterID = ctxUserID
|
||||
}
|
||||
if ctx.FormBool("assigned") {
|
||||
issuesOpt.AssigneeID = ctx.User.ID
|
||||
issuesOpt.AssigneeID = ctxUserID
|
||||
}
|
||||
if ctx.FormBool("mentioned") {
|
||||
issuesOpt.MentionedID = ctx.User.ID
|
||||
issuesOpt.MentionedID = ctxUserID
|
||||
}
|
||||
if ctx.FormBool("review_requested") {
|
||||
issuesOpt.ReviewRequestedID = ctx.User.ID
|
||||
issuesOpt.ReviewRequestedID = ctxUserID
|
||||
}
|
||||
|
||||
if issues, err = models.Issues(issuesOpt); err != nil {
|
||||
@@ -353,7 +361,7 @@ func ListIssues(ctx *context.APIContext) {
|
||||
// responses:
|
||||
// "200":
|
||||
// "$ref": "#/responses/IssueList"
|
||||
before, since, err := utils.GetQueryBeforeSince(ctx)
|
||||
before, since, err := context.GetQueryBeforeSince(ctx.Context)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusUnprocessableEntity, "GetQueryBeforeSince", err)
|
||||
return
|
||||
@@ -399,12 +407,12 @@ func ListIssues(ctx *context.APIContext) {
|
||||
for i := range part {
|
||||
// uses names and fall back to ids
|
||||
// non existent milestones are discarded
|
||||
mile, err := models.GetMilestoneByRepoIDANDName(ctx.Repo.Repository.ID, part[i])
|
||||
mile, err := issues_model.GetMilestoneByRepoIDANDName(ctx.Repo.Repository.ID, part[i])
|
||||
if err == nil {
|
||||
mileIDs = append(mileIDs, mile.ID)
|
||||
continue
|
||||
}
|
||||
if !models.IsErrMilestoneNotExist(err) {
|
||||
if !issues_model.IsErrMilestoneNotExist(err) {
|
||||
ctx.Error(http.StatusInternalServerError, "GetMilestoneByRepoIDANDName", err)
|
||||
return
|
||||
}
|
||||
@@ -412,12 +420,12 @@ func ListIssues(ctx *context.APIContext) {
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
mile, err = models.GetMilestoneByRepoID(ctx.Repo.Repository.ID, id)
|
||||
mile, err = issues_model.GetMilestoneByRepoID(ctx, ctx.Repo.Repository.ID, id)
|
||||
if err == nil {
|
||||
mileIDs = append(mileIDs, mile.ID)
|
||||
continue
|
||||
}
|
||||
if models.IsErrMilestoneNotExist(err) {
|
||||
if issues_model.IsErrMilestoneNotExist(err) {
|
||||
continue
|
||||
}
|
||||
ctx.Error(http.StatusInternalServerError, "GetMilestoneByRepoID", err)
|
||||
@@ -455,7 +463,7 @@ func ListIssues(ctx *context.APIContext) {
|
||||
if len(keyword) == 0 || len(issueIDs) > 0 || len(labelIDs) > 0 {
|
||||
issuesOpt := &models.IssuesOptions{
|
||||
ListOptions: listOptions,
|
||||
RepoIDs: []int64{ctx.Repo.Repository.ID},
|
||||
RepoID: ctx.Repo.Repository.ID,
|
||||
IsClosed: isClosed,
|
||||
IssueIDs: issueIDs,
|
||||
LabelIDs: labelIDs,
|
||||
@@ -592,8 +600,8 @@ func CreateIssue(ctx *context.APIContext) {
|
||||
RepoID: ctx.Repo.Repository.ID,
|
||||
Repo: ctx.Repo.Repository,
|
||||
Title: form.Title,
|
||||
PosterID: ctx.User.ID,
|
||||
Poster: ctx.User,
|
||||
PosterID: ctx.Doer.ID,
|
||||
Poster: ctx.Doer,
|
||||
Content: form.Body,
|
||||
Ref: form.Ref,
|
||||
DeadlineUnix: deadlineUnix,
|
||||
@@ -646,7 +654,7 @@ func CreateIssue(ctx *context.APIContext) {
|
||||
}
|
||||
|
||||
if form.Closed {
|
||||
if err := issue_service.ChangeStatus(issue, ctx.User, true); err != nil {
|
||||
if err := issue_service.ChangeStatus(issue, ctx.Doer, true); err != nil {
|
||||
if models.IsErrDependenciesLeft(err) {
|
||||
ctx.Error(http.StatusPreconditionFailed, "DependenciesLeft", "cannot close this issue because it still has open dependencies")
|
||||
return
|
||||
@@ -724,7 +732,7 @@ func EditIssue(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
if !issue.IsPoster(ctx.User.ID) && !canWrite {
|
||||
if !issue.IsPoster(ctx.Doer.ID) && !canWrite {
|
||||
ctx.Status(http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
@@ -737,7 +745,7 @@ func EditIssue(ctx *context.APIContext) {
|
||||
issue.Content = *form.Body
|
||||
}
|
||||
if form.Ref != nil {
|
||||
err = issue_service.ChangeIssueRef(issue, ctx.User, *form.Ref)
|
||||
err = issue_service.ChangeIssueRef(issue, ctx.Doer, *form.Ref)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "UpdateRef", err)
|
||||
return
|
||||
@@ -754,7 +762,7 @@ func EditIssue(ctx *context.APIContext) {
|
||||
deadlineUnix = timeutil.TimeStamp(deadline.Unix())
|
||||
}
|
||||
|
||||
if err := models.UpdateIssueDeadline(issue, deadlineUnix, ctx.User); err != nil {
|
||||
if err := models.UpdateIssueDeadline(issue, deadlineUnix, ctx.Doer); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "UpdateIssueDeadline", err)
|
||||
return
|
||||
}
|
||||
@@ -775,7 +783,7 @@ func EditIssue(ctx *context.APIContext) {
|
||||
oneAssignee = *form.Assignee
|
||||
}
|
||||
|
||||
err = issue_service.UpdateAssignees(issue, oneAssignee, form.Assignees, ctx.User)
|
||||
err = issue_service.UpdateAssignees(issue, oneAssignee, form.Assignees, ctx.Doer)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "UpdateAssignees", err)
|
||||
return
|
||||
@@ -786,7 +794,7 @@ func EditIssue(ctx *context.APIContext) {
|
||||
issue.MilestoneID != *form.Milestone {
|
||||
oldMilestoneID := issue.MilestoneID
|
||||
issue.MilestoneID = *form.Milestone
|
||||
if err = issue_service.ChangeMilestoneAssign(issue, ctx.User, oldMilestoneID); err != nil {
|
||||
if err = issue_service.ChangeMilestoneAssign(issue, ctx.Doer, oldMilestoneID); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "ChangeMilestoneAssign", err)
|
||||
return
|
||||
}
|
||||
@@ -803,7 +811,7 @@ func EditIssue(ctx *context.APIContext) {
|
||||
}
|
||||
issue.IsClosed = api.StateClosed == api.StateType(*form.State)
|
||||
}
|
||||
statusChangeComment, titleChanged, err := models.UpdateIssueByAPI(issue, ctx.User)
|
||||
statusChangeComment, titleChanged, err := models.UpdateIssueByAPI(issue, ctx.Doer)
|
||||
if err != nil {
|
||||
if models.IsErrDependenciesLeft(err) {
|
||||
ctx.Error(http.StatusPreconditionFailed, "DependenciesLeft", "cannot close this issue because it still has open dependencies")
|
||||
@@ -814,11 +822,11 @@ func EditIssue(ctx *context.APIContext) {
|
||||
}
|
||||
|
||||
if titleChanged {
|
||||
notification.NotifyIssueChangeTitle(ctx.User, issue, oldTitle)
|
||||
notification.NotifyIssueChangeTitle(ctx.Doer, issue, oldTitle)
|
||||
}
|
||||
|
||||
if statusChangeComment != nil {
|
||||
notification.NotifyIssueChangeStatus(ctx.User, issue, statusChangeComment, issue.IsClosed)
|
||||
notification.NotifyIssueChangeStatus(ctx.Doer, issue, statusChangeComment, issue.IsClosed)
|
||||
}
|
||||
|
||||
// Refetch from database to assign some automatic values
|
||||
@@ -872,7 +880,7 @@ func DeleteIssue(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
if err = issue_service.DeleteIssue(ctx.User, ctx.Repo.GitRepo, issue); err != nil {
|
||||
if err = issue_service.DeleteIssue(ctx.Doer, ctx.Repo.GitRepo, issue); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "DeleteIssueByID", err)
|
||||
return
|
||||
}
|
||||
@@ -941,7 +949,7 @@ func UpdateIssueDeadline(ctx *context.APIContext) {
|
||||
deadlineUnix = timeutil.TimeStamp(deadline.Unix())
|
||||
}
|
||||
|
||||
if err := models.UpdateIssueDeadline(issue, deadlineUnix, ctx.User); err != nil {
|
||||
if err := models.UpdateIssueDeadline(issue, deadlineUnix, ctx.Doer); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "UpdateIssueDeadline", err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
package repo
|
||||
|
||||
import (
|
||||
stdCtx "context"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
@@ -58,7 +59,7 @@ func ListIssueComments(ctx *context.APIContext) {
|
||||
// "200":
|
||||
// "$ref": "#/responses/CommentList"
|
||||
|
||||
before, since, err := utils.GetQueryBeforeSince(ctx)
|
||||
before, since, err := context.GetQueryBeforeSince(ctx.Context)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusUnprocessableEntity, "GetQueryBeforeSince", err)
|
||||
return
|
||||
@@ -150,7 +151,7 @@ func ListIssueCommentsAndTimeline(ctx *context.APIContext) {
|
||||
// "200":
|
||||
// "$ref": "#/responses/TimelineList"
|
||||
|
||||
before, since, err := utils.GetQueryBeforeSince(ctx)
|
||||
before, since, err := context.GetQueryBeforeSince(ctx.Context)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusUnprocessableEntity, "GetQueryBeforeSince", err)
|
||||
return
|
||||
@@ -183,9 +184,9 @@ func ListIssueCommentsAndTimeline(ctx *context.APIContext) {
|
||||
|
||||
var apiComments []*api.TimelineComment
|
||||
for _, comment := range comments {
|
||||
if comment.Type != models.CommentTypeCode && isXRefCommentAccessible(ctx.User, comment, issue.RepoID) {
|
||||
if comment.Type != models.CommentTypeCode && isXRefCommentAccessible(ctx, ctx.Doer, comment, issue.RepoID) {
|
||||
comment.Issue = issue
|
||||
apiComments = append(apiComments, convert.ToTimelineComment(comment, ctx.User))
|
||||
apiComments = append(apiComments, convert.ToTimelineComment(comment, ctx.Doer))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -193,16 +194,16 @@ func ListIssueCommentsAndTimeline(ctx *context.APIContext) {
|
||||
ctx.JSON(http.StatusOK, &apiComments)
|
||||
}
|
||||
|
||||
func isXRefCommentAccessible(user *user_model.User, c *models.Comment, issueRepoID int64) bool {
|
||||
func isXRefCommentAccessible(ctx stdCtx.Context, user *user_model.User, c *models.Comment, issueRepoID int64) bool {
|
||||
// Remove comments that the user has no permissions to see
|
||||
if models.CommentTypeIsRef(c.Type) && c.RefRepoID != issueRepoID && c.RefRepoID != 0 {
|
||||
var err error
|
||||
// Set RefRepo for description in template
|
||||
c.RefRepo, err = repo_model.GetRepositoryByID(c.RefRepoID)
|
||||
c.RefRepo, err = repo_model.GetRepositoryByIDCtx(ctx, c.RefRepoID)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
perm, err := models.GetUserRepoPermission(c.RefRepo, user)
|
||||
perm, err := models.GetUserRepoPermission(ctx, c.RefRepo, user)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
@@ -253,7 +254,7 @@ func ListRepoIssueComments(ctx *context.APIContext) {
|
||||
// "200":
|
||||
// "$ref": "#/responses/CommentList"
|
||||
|
||||
before, since, err := utils.GetQueryBeforeSince(ctx)
|
||||
before, since, err := context.GetQueryBeforeSince(ctx.Context)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusUnprocessableEntity, "GetQueryBeforeSince", err)
|
||||
return
|
||||
@@ -347,12 +348,12 @@ func CreateIssueComment(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
if issue.IsLocked && !ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull) && !ctx.User.IsAdmin {
|
||||
if issue.IsLocked && !ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull) && !ctx.Doer.IsAdmin {
|
||||
ctx.Error(http.StatusForbidden, "CreateIssueComment", errors.New(ctx.Tr("repo.issues.comment_on_locked")))
|
||||
return
|
||||
}
|
||||
|
||||
comment, err := comment_service.CreateIssueComment(ctx.User, ctx.Repo.Repository, issue, form.Body, nil)
|
||||
comment, err := comment_service.CreateIssueComment(ctx.Doer, ctx.Repo.Repository, issue, form.Body, nil)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "CreateIssueComment", err)
|
||||
return
|
||||
@@ -534,7 +535,7 @@ func editIssueComment(ctx *context.APIContext, form api.EditIssueCommentOption)
|
||||
return
|
||||
}
|
||||
|
||||
if !ctx.IsSigned || (ctx.User.ID != comment.PosterID && !ctx.Repo.IsAdmin()) {
|
||||
if !ctx.IsSigned || (ctx.Doer.ID != comment.PosterID && !ctx.Repo.IsAdmin()) {
|
||||
ctx.Status(http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
@@ -546,7 +547,7 @@ func editIssueComment(ctx *context.APIContext, form api.EditIssueCommentOption)
|
||||
|
||||
oldContent := comment.Content
|
||||
comment.Content = form.Body
|
||||
if err := comment_service.UpdateComment(comment, ctx.User, oldContent); err != nil {
|
||||
if err := comment_service.UpdateComment(comment, ctx.Doer, oldContent); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "UpdateComment", err)
|
||||
return
|
||||
}
|
||||
@@ -637,7 +638,7 @@ func deleteIssueComment(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
if !ctx.IsSigned || (ctx.User.ID != comment.PosterID && !ctx.Repo.IsAdmin()) {
|
||||
if !ctx.IsSigned || (ctx.Doer.ID != comment.PosterID && !ctx.Repo.IsAdmin()) {
|
||||
ctx.Status(http.StatusForbidden)
|
||||
return
|
||||
} else if comment.Type != models.CommentTypeComment {
|
||||
@@ -645,7 +646,7 @@ func deleteIssueComment(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
if err = comment_service.DeleteComment(ctx.User, comment); err != nil {
|
||||
if err = comment_service.DeleteComment(ctx.Doer, comment); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "DeleteCommentByID", err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -106,7 +106,7 @@ func AddIssueLabels(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
if err = issue_service.AddLabels(issue, ctx.User, labels); err != nil {
|
||||
if err = issue_service.AddLabels(issue, ctx.Doer, labels); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "AddLabels", err)
|
||||
return
|
||||
}
|
||||
@@ -183,7 +183,7 @@ func DeleteIssueLabel(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := issue_service.RemoveLabel(issue, ctx.User, label); err != nil {
|
||||
if err := issue_service.RemoveLabel(issue, ctx.Doer, label); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "DeleteIssueLabel", err)
|
||||
return
|
||||
}
|
||||
@@ -232,7 +232,7 @@ func ReplaceIssueLabels(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := issue_service.ReplaceLabels(issue, ctx.User, labels); err != nil {
|
||||
if err := issue_service.ReplaceLabels(issue, ctx.Doer, labels); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "ReplaceLabels", err)
|
||||
return
|
||||
}
|
||||
@@ -291,7 +291,7 @@ func ClearIssueLabels(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := issue_service.ClearLabels(issue, ctx.User); err != nil {
|
||||
if err := issue_service.ClearLabels(issue, ctx.Doer); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "ClearLabels", err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"net/http"
|
||||
|
||||
"code.gitea.io/gitea/models"
|
||||
issues_model "code.gitea.io/gitea/models/issues"
|
||||
"code.gitea.io/gitea/modules/context"
|
||||
"code.gitea.io/gitea/modules/convert"
|
||||
api "code.gitea.io/gitea/modules/structs"
|
||||
@@ -67,12 +68,12 @@ func GetIssueCommentReactions(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
reactions, _, err := models.FindCommentReactions(comment)
|
||||
reactions, _, err := issues_model.FindCommentReactions(comment.IssueID, comment.ID)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "FindCommentReactions", err)
|
||||
return
|
||||
}
|
||||
_, err = reactions.LoadUsers(ctx.Repo.Repository)
|
||||
_, err = reactions.LoadUsers(ctx, ctx.Repo.Repository)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "ReactionList.LoadUsers()", err)
|
||||
return
|
||||
@@ -81,7 +82,7 @@ func GetIssueCommentReactions(ctx *context.APIContext) {
|
||||
var result []api.Reaction
|
||||
for _, r := range reactions {
|
||||
result = append(result, api.Reaction{
|
||||
User: convert.ToUser(r.User, ctx.User),
|
||||
User: convert.ToUser(r.User, ctx.Doer),
|
||||
Reaction: r.Type,
|
||||
Created: r.CreatedUnix.AsTime(),
|
||||
})
|
||||
@@ -197,13 +198,13 @@ func changeIssueCommentReaction(ctx *context.APIContext, form api.EditReactionOp
|
||||
|
||||
if isCreateType {
|
||||
// PostIssueCommentReaction part
|
||||
reaction, err := models.CreateCommentReaction(ctx.User, comment.Issue, comment, form.Reaction)
|
||||
reaction, err := issues_model.CreateCommentReaction(ctx.Doer.ID, comment.Issue.ID, comment.ID, form.Reaction)
|
||||
if err != nil {
|
||||
if models.IsErrForbiddenIssueReaction(err) {
|
||||
if issues_model.IsErrForbiddenIssueReaction(err) {
|
||||
ctx.Error(http.StatusForbidden, err.Error(), err)
|
||||
} else if models.IsErrReactionAlreadyExist(err) {
|
||||
} else if issues_model.IsErrReactionAlreadyExist(err) {
|
||||
ctx.JSON(http.StatusOK, api.Reaction{
|
||||
User: convert.ToUser(ctx.User, ctx.User),
|
||||
User: convert.ToUser(ctx.Doer, ctx.Doer),
|
||||
Reaction: reaction.Type,
|
||||
Created: reaction.CreatedUnix.AsTime(),
|
||||
})
|
||||
@@ -214,13 +215,13 @@ func changeIssueCommentReaction(ctx *context.APIContext, form api.EditReactionOp
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusCreated, api.Reaction{
|
||||
User: convert.ToUser(ctx.User, ctx.User),
|
||||
User: convert.ToUser(ctx.Doer, ctx.Doer),
|
||||
Reaction: reaction.Type,
|
||||
Created: reaction.CreatedUnix.AsTime(),
|
||||
})
|
||||
} else {
|
||||
// DeleteIssueCommentReaction part
|
||||
err = models.DeleteCommentReaction(ctx.User, comment.Issue, comment, form.Reaction)
|
||||
err = issues_model.DeleteCommentReaction(ctx.Doer.ID, comment.Issue.ID, comment.ID, form.Reaction)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "DeleteCommentReaction", err)
|
||||
return
|
||||
@@ -285,12 +286,12 @@ func GetIssueReactions(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
reactions, count, err := models.FindIssueReactions(issue, utils.GetListOptions(ctx))
|
||||
reactions, count, err := issues_model.FindIssueReactions(issue.ID, utils.GetListOptions(ctx))
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "FindIssueReactions", err)
|
||||
return
|
||||
}
|
||||
_, err = reactions.LoadUsers(ctx.Repo.Repository)
|
||||
_, err = reactions.LoadUsers(ctx, ctx.Repo.Repository)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "ReactionList.LoadUsers()", err)
|
||||
return
|
||||
@@ -299,7 +300,7 @@ func GetIssueReactions(ctx *context.APIContext) {
|
||||
var result []api.Reaction
|
||||
for _, r := range reactions {
|
||||
result = append(result, api.Reaction{
|
||||
User: convert.ToUser(r.User, ctx.User),
|
||||
User: convert.ToUser(r.User, ctx.Doer),
|
||||
Reaction: r.Type,
|
||||
Created: r.CreatedUnix.AsTime(),
|
||||
})
|
||||
@@ -407,13 +408,13 @@ func changeIssueReaction(ctx *context.APIContext, form api.EditReactionOption, i
|
||||
|
||||
if isCreateType {
|
||||
// PostIssueReaction part
|
||||
reaction, err := models.CreateIssueReaction(ctx.User, issue, form.Reaction)
|
||||
reaction, err := issues_model.CreateIssueReaction(ctx.Doer.ID, issue.ID, form.Reaction)
|
||||
if err != nil {
|
||||
if models.IsErrForbiddenIssueReaction(err) {
|
||||
if issues_model.IsErrForbiddenIssueReaction(err) {
|
||||
ctx.Error(http.StatusForbidden, err.Error(), err)
|
||||
} else if models.IsErrReactionAlreadyExist(err) {
|
||||
} else if issues_model.IsErrReactionAlreadyExist(err) {
|
||||
ctx.JSON(http.StatusOK, api.Reaction{
|
||||
User: convert.ToUser(ctx.User, ctx.User),
|
||||
User: convert.ToUser(ctx.Doer, ctx.Doer),
|
||||
Reaction: reaction.Type,
|
||||
Created: reaction.CreatedUnix.AsTime(),
|
||||
})
|
||||
@@ -424,13 +425,13 @@ func changeIssueReaction(ctx *context.APIContext, form api.EditReactionOption, i
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusCreated, api.Reaction{
|
||||
User: convert.ToUser(ctx.User, ctx.User),
|
||||
User: convert.ToUser(ctx.Doer, ctx.Doer),
|
||||
Reaction: reaction.Type,
|
||||
Created: reaction.CreatedUnix.AsTime(),
|
||||
})
|
||||
} else {
|
||||
// DeleteIssueReaction part
|
||||
err = models.DeleteIssueReaction(ctx.User, issue, form.Reaction)
|
||||
err = issues_model.DeleteIssueReaction(ctx.Doer.ID, issue.ID, form.Reaction)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "DeleteIssueReaction", err)
|
||||
return
|
||||
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
"net/http"
|
||||
|
||||
"code.gitea.io/gitea/models"
|
||||
"code.gitea.io/gitea/models/db"
|
||||
"code.gitea.io/gitea/modules/context"
|
||||
"code.gitea.io/gitea/modules/convert"
|
||||
"code.gitea.io/gitea/routers/api/v1/utils"
|
||||
@@ -56,7 +55,7 @@ func StartIssueStopwatch(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := models.CreateIssueStopwatch(db.DefaultContext, ctx.User, issue); err != nil {
|
||||
if err := models.CreateIssueStopwatch(ctx, ctx.Doer, issue); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "CreateOrStopIssueStopwatch", err)
|
||||
return
|
||||
}
|
||||
@@ -105,7 +104,7 @@ func StopIssueStopwatch(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := models.FinishIssueStopwatch(db.DefaultContext, ctx.User, issue); err != nil {
|
||||
if err := models.FinishIssueStopwatch(ctx, ctx.Doer, issue); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "CreateOrStopIssueStopwatch", err)
|
||||
return
|
||||
}
|
||||
@@ -154,7 +153,7 @@ func DeleteIssueStopwatch(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := models.CancelStopwatch(ctx.User, issue); err != nil {
|
||||
if err := models.CancelStopwatch(ctx.Doer, issue); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "CancelStopwatch", err)
|
||||
return
|
||||
}
|
||||
@@ -179,12 +178,12 @@ func prepareIssueStopwatch(ctx *context.APIContext, shouldExist bool) (*models.I
|
||||
return nil, errors.New("Unable to write to PRs")
|
||||
}
|
||||
|
||||
if !ctx.Repo.CanUseTimetracker(issue, ctx.User) {
|
||||
if !ctx.Repo.CanUseTimetracker(issue, ctx.Doer) {
|
||||
ctx.Status(http.StatusForbidden)
|
||||
return nil, errors.New("Cannot use time tracker")
|
||||
}
|
||||
|
||||
if models.StopwatchExists(ctx.User.ID, issue.ID) != shouldExist {
|
||||
if models.StopwatchExists(ctx.Doer.ID, issue.ID) != shouldExist {
|
||||
if shouldExist {
|
||||
ctx.Error(http.StatusConflict, "StopwatchExists", "cannot stop/cancel a non existent stopwatch")
|
||||
err = errors.New("cannot stop/cancel a non existent stopwatch")
|
||||
@@ -220,13 +219,13 @@ func GetStopwatches(ctx *context.APIContext) {
|
||||
// "200":
|
||||
// "$ref": "#/responses/StopWatchList"
|
||||
|
||||
sws, err := models.GetUserStopwatches(ctx.User.ID, utils.GetListOptions(ctx))
|
||||
sws, err := models.GetUserStopwatches(ctx.Doer.ID, utils.GetListOptions(ctx))
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "GetUserStopwatches", err)
|
||||
return
|
||||
}
|
||||
|
||||
count, err := models.CountUserStopwatches(ctx.User.ID)
|
||||
count, err := models.CountUserStopwatches(ctx.Doer.ID)
|
||||
if err != nil {
|
||||
ctx.InternalServerError(err)
|
||||
return
|
||||
|
||||
@@ -128,8 +128,8 @@ func setIssueSubscription(ctx *context.APIContext, watch bool) {
|
||||
}
|
||||
|
||||
// only admin and user for itself can change subscription
|
||||
if user.ID != ctx.User.ID && !ctx.User.IsAdmin {
|
||||
ctx.Error(http.StatusForbidden, "User", fmt.Errorf("%s is not permitted to change subscriptions for %s", ctx.User.Name, user.Name))
|
||||
if user.ID != ctx.Doer.ID && !ctx.Doer.IsAdmin {
|
||||
ctx.Error(http.StatusForbidden, "User", fmt.Errorf("%s is not permitted to change subscriptions for %s", ctx.Doer.Name, user.Name))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -197,7 +197,7 @@ func CheckIssueSubscription(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
watching, err := models.CheckIssueWatch(ctx.User, issue)
|
||||
watching, err := models.CheckIssueWatch(ctx.Doer, issue)
|
||||
if err != nil {
|
||||
ctx.InternalServerError(err)
|
||||
return
|
||||
@@ -281,7 +281,7 @@ func GetIssueSubscribers(ctx *context.APIContext) {
|
||||
}
|
||||
apiUsers := make([]*api.User, 0, len(users))
|
||||
for _, v := range users {
|
||||
apiUsers = append(apiUsers, convert.ToUser(v, ctx.User))
|
||||
apiUsers = append(apiUsers, convert.ToUser(v, ctx.Doer))
|
||||
}
|
||||
|
||||
count, err := models.CountIssueWatchers(issue.ID)
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"time"
|
||||
|
||||
"code.gitea.io/gitea/models"
|
||||
"code.gitea.io/gitea/models/db"
|
||||
"code.gitea.io/gitea/models/unit"
|
||||
user_model "code.gitea.io/gitea/models/user"
|
||||
"code.gitea.io/gitea/modules/context"
|
||||
@@ -103,18 +104,18 @@ func ListTrackedTimes(ctx *context.APIContext) {
|
||||
opts.UserID = user.ID
|
||||
}
|
||||
|
||||
if opts.CreatedBeforeUnix, opts.CreatedAfterUnix, err = utils.GetQueryBeforeSince(ctx); err != nil {
|
||||
if opts.CreatedBeforeUnix, opts.CreatedAfterUnix, err = context.GetQueryBeforeSince(ctx.Context); err != nil {
|
||||
ctx.Error(http.StatusUnprocessableEntity, "GetQueryBeforeSince", err)
|
||||
return
|
||||
}
|
||||
|
||||
cantSetUser := !ctx.User.IsAdmin &&
|
||||
opts.UserID != ctx.User.ID &&
|
||||
cantSetUser := !ctx.Doer.IsAdmin &&
|
||||
opts.UserID != ctx.Doer.ID &&
|
||||
!ctx.IsUserRepoWriter([]unit.Type{unit.TypeIssues})
|
||||
|
||||
if cantSetUser {
|
||||
if opts.UserID == 0 {
|
||||
opts.UserID = ctx.User.ID
|
||||
opts.UserID = ctx.Doer.ID
|
||||
} else {
|
||||
ctx.Error(http.StatusForbidden, "", fmt.Errorf("query by user not allowed; not enough rights"))
|
||||
return
|
||||
@@ -189,7 +190,7 @@ func AddTime(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
if !ctx.Repo.CanUseTimetracker(issue, ctx.User) {
|
||||
if !ctx.Repo.CanUseTimetracker(issue, ctx.Doer) {
|
||||
if !ctx.Repo.Repository.IsTimetrackerEnabled() {
|
||||
ctx.Error(http.StatusBadRequest, "", "time tracking disabled")
|
||||
return
|
||||
@@ -198,9 +199,9 @@ func AddTime(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
user := ctx.User
|
||||
user := ctx.Doer
|
||||
if form.User != "" {
|
||||
if (ctx.IsUserRepoAdmin() && ctx.User.Name != form.User) || ctx.User.IsAdmin {
|
||||
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)
|
||||
if err != nil {
|
||||
@@ -270,7 +271,7 @@ func ResetIssueTime(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
if !ctx.Repo.CanUseTimetracker(issue, ctx.User) {
|
||||
if !ctx.Repo.CanUseTimetracker(issue, ctx.Doer) {
|
||||
if !ctx.Repo.Repository.IsTimetrackerEnabled() {
|
||||
ctx.JSON(http.StatusBadRequest, struct{ Message string }{Message: "time tracking disabled"})
|
||||
return
|
||||
@@ -279,16 +280,16 @@ func ResetIssueTime(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
err = models.DeleteIssueUserTimes(issue, ctx.User)
|
||||
err = models.DeleteIssueUserTimes(issue, ctx.Doer)
|
||||
if err != nil {
|
||||
if models.IsErrNotExist(err) {
|
||||
if db.IsErrNotExist(err) {
|
||||
ctx.Error(http.StatusNotFound, "DeleteIssueUserTimes", err)
|
||||
} else {
|
||||
ctx.Error(http.StatusInternalServerError, "DeleteIssueUserTimes", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
ctx.Status(204)
|
||||
ctx.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// DeleteTime delete a specific time by id
|
||||
@@ -341,7 +342,7 @@ func DeleteTime(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
if !ctx.Repo.CanUseTimetracker(issue, ctx.User) {
|
||||
if !ctx.Repo.CanUseTimetracker(issue, ctx.Doer) {
|
||||
if !ctx.Repo.Repository.IsTimetrackerEnabled() {
|
||||
ctx.JSON(http.StatusBadRequest, struct{ Message string }{Message: "time tracking disabled"})
|
||||
return
|
||||
@@ -352,7 +353,7 @@ func DeleteTime(ctx *context.APIContext) {
|
||||
|
||||
time, err := models.GetTrackedTimeByID(ctx.ParamsInt64(":id"))
|
||||
if err != nil {
|
||||
if models.IsErrNotExist(err) {
|
||||
if db.IsErrNotExist(err) {
|
||||
ctx.NotFound(err)
|
||||
return
|
||||
}
|
||||
@@ -364,7 +365,7 @@ func DeleteTime(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
if !ctx.User.IsAdmin && time.UserID != ctx.User.ID {
|
||||
if !ctx.Doer.IsAdmin && time.UserID != ctx.Doer.ID {
|
||||
// Only Admin and User itself can delete their time
|
||||
ctx.Status(http.StatusForbidden)
|
||||
return
|
||||
@@ -428,7 +429,7 @@ func ListTrackedTimesByUser(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
if !ctx.IsUserRepoAdmin() && !ctx.User.IsAdmin && ctx.User.ID != user.ID {
|
||||
if !ctx.IsUserRepoAdmin() && !ctx.Doer.IsAdmin && ctx.Doer.ID != user.ID {
|
||||
ctx.Error(http.StatusForbidden, "", fmt.Errorf("query by user not allowed; not enough rights"))
|
||||
return
|
||||
}
|
||||
@@ -522,18 +523,18 @@ func ListTrackedTimesByRepository(ctx *context.APIContext) {
|
||||
}
|
||||
|
||||
var err error
|
||||
if opts.CreatedBeforeUnix, opts.CreatedAfterUnix, err = utils.GetQueryBeforeSince(ctx); err != nil {
|
||||
if opts.CreatedBeforeUnix, opts.CreatedAfterUnix, err = context.GetQueryBeforeSince(ctx.Context); err != nil {
|
||||
ctx.Error(http.StatusUnprocessableEntity, "GetQueryBeforeSince", err)
|
||||
return
|
||||
}
|
||||
|
||||
cantSetUser := !ctx.User.IsAdmin &&
|
||||
opts.UserID != ctx.User.ID &&
|
||||
cantSetUser := !ctx.Doer.IsAdmin &&
|
||||
opts.UserID != ctx.Doer.ID &&
|
||||
!ctx.IsUserRepoWriter([]unit.Type{unit.TypeIssues})
|
||||
|
||||
if cantSetUser {
|
||||
if opts.UserID == 0 {
|
||||
opts.UserID = ctx.User.ID
|
||||
opts.UserID = ctx.Doer.ID
|
||||
} else {
|
||||
ctx.Error(http.StatusForbidden, "", fmt.Errorf("query by user not allowed; not enough rights"))
|
||||
return
|
||||
@@ -593,11 +594,11 @@ func ListMyTrackedTimes(ctx *context.APIContext) {
|
||||
|
||||
opts := &models.FindTrackedTimesOptions{
|
||||
ListOptions: utils.GetListOptions(ctx),
|
||||
UserID: ctx.User.ID,
|
||||
UserID: ctx.Doer.ID,
|
||||
}
|
||||
|
||||
var err error
|
||||
if opts.CreatedBeforeUnix, opts.CreatedAfterUnix, err = utils.GetQueryBeforeSince(ctx); err != nil {
|
||||
if opts.CreatedBeforeUnix, opts.CreatedAfterUnix, err = context.GetQueryBeforeSince(ctx.Context); err != nil {
|
||||
ctx.Error(http.StatusUnprocessableEntity, "GetQueryBeforeSince", err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -87,7 +87,7 @@ func ListDeployKeys(ctx *context.APIContext) {
|
||||
Fingerprint: ctx.FormString("fingerprint"),
|
||||
}
|
||||
|
||||
keys, err := asymkey_model.ListDeployKeys(db.DefaultContext, opts)
|
||||
keys, err := asymkey_model.ListDeployKeys(ctx, opts)
|
||||
if err != nil {
|
||||
ctx.InternalServerError(err)
|
||||
return
|
||||
@@ -107,7 +107,7 @@ func ListDeployKeys(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
apiKeys[i] = convert.ToDeployKey(apiLink, keys[i])
|
||||
if ctx.User.IsAdmin || ((ctx.Repo.Repository.ID == keys[i].RepoID) && (ctx.User.ID == ctx.Repo.Owner.ID)) {
|
||||
if ctx.Doer.IsAdmin || ((ctx.Repo.Repository.ID == keys[i].RepoID) && (ctx.Doer.ID == ctx.Repo.Owner.ID)) {
|
||||
apiKeys[i], _ = appendPrivateInformation(apiKeys[i], keys[i], ctx.Repo.Repository)
|
||||
}
|
||||
}
|
||||
@@ -144,7 +144,7 @@ func GetDeployKey(ctx *context.APIContext) {
|
||||
// "200":
|
||||
// "$ref": "#/responses/DeployKey"
|
||||
|
||||
key, err := asymkey_model.GetDeployKeyByID(db.DefaultContext, ctx.ParamsInt64(":id"))
|
||||
key, err := asymkey_model.GetDeployKeyByID(ctx, ctx.ParamsInt64(":id"))
|
||||
if err != nil {
|
||||
if asymkey_model.IsErrDeployKeyNotExist(err) {
|
||||
ctx.NotFound()
|
||||
@@ -161,7 +161,7 @@ func GetDeployKey(ctx *context.APIContext) {
|
||||
|
||||
apiLink := composeDeployKeysAPILink(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
|
||||
apiKey := convert.ToDeployKey(apiLink, key)
|
||||
if ctx.User.IsAdmin || ((ctx.Repo.Repository.ID == key.RepoID) && (ctx.User.ID == ctx.Repo.Owner.ID)) {
|
||||
if ctx.Doer.IsAdmin || ((ctx.Repo.Repository.ID == key.RepoID) && (ctx.Doer.ID == ctx.Repo.Owner.ID)) {
|
||||
apiKey, _ = appendPrivateInformation(apiKey, key, ctx.Repo.Repository)
|
||||
}
|
||||
ctx.JSON(http.StatusOK, apiKey)
|
||||
@@ -270,7 +270,7 @@ func DeleteDeploykey(ctx *context.APIContext) {
|
||||
// "403":
|
||||
// "$ref": "#/responses/forbidden"
|
||||
|
||||
if err := asymkey_service.DeleteDeployKey(ctx.User, ctx.ParamsInt64(":id")); err != nil {
|
||||
if err := asymkey_service.DeleteDeployKey(ctx.Doer, ctx.ParamsInt64(":id")); err != nil {
|
||||
if asymkey_model.IsErrKeyAccessDenied(err) {
|
||||
ctx.Error(http.StatusForbidden, "", "You do not have access to this key")
|
||||
} else {
|
||||
|
||||
@@ -161,7 +161,7 @@ func CreateLabel(ctx *context.APIContext) {
|
||||
RepoID: ctx.Repo.Repository.ID,
|
||||
Description: form.Description,
|
||||
}
|
||||
if err := models.NewLabel(label); err != nil {
|
||||
if err := models.NewLabel(ctx, label); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "NewLabel", err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -76,9 +76,7 @@ func GetLanguages(ctx *context.APIContext) {
|
||||
}
|
||||
|
||||
resp := make(languageResponse, len(langs))
|
||||
for i, v := range langs {
|
||||
resp[i] = v
|
||||
}
|
||||
copy(resp, langs)
|
||||
|
||||
ctx.JSON(http.StatusOK, resp)
|
||||
}
|
||||
|
||||
@@ -9,8 +9,15 @@ import (
|
||||
"testing"
|
||||
|
||||
"code.gitea.io/gitea/models/unittest"
|
||||
"code.gitea.io/gitea/modules/setting"
|
||||
webhook_service "code.gitea.io/gitea/services/webhook"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
unittest.MainTest(m, filepath.Join("..", "..", "..", ".."))
|
||||
setting.LoadForTest()
|
||||
setting.NewQueueService()
|
||||
unittest.MainTest(m, &unittest.TestOptions{
|
||||
GiteaRootPath: filepath.Join("..", "..", "..", ".."),
|
||||
SetUp: webhook_service.Init,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
|
||||
"code.gitea.io/gitea/models"
|
||||
"code.gitea.io/gitea/models/db"
|
||||
"code.gitea.io/gitea/models/organization"
|
||||
"code.gitea.io/gitea/models/perm"
|
||||
repo_model "code.gitea.io/gitea/models/repo"
|
||||
user_model "code.gitea.io/gitea/models/user"
|
||||
@@ -51,6 +52,8 @@ func Migrate(ctx *context.APIContext) {
|
||||
// "$ref": "#/responses/Repository"
|
||||
// "403":
|
||||
// "$ref": "#/responses/forbidden"
|
||||
// "409":
|
||||
// description: The repository with the same name already exists.
|
||||
// "422":
|
||||
// "$ref": "#/responses/validationError"
|
||||
|
||||
@@ -66,7 +69,7 @@ func Migrate(ctx *context.APIContext) {
|
||||
} else if form.RepoOwnerID != 0 {
|
||||
repoOwner, err = user_model.GetUserByID(form.RepoOwnerID)
|
||||
} else {
|
||||
repoOwner = ctx.User
|
||||
repoOwner = ctx.Doer
|
||||
}
|
||||
if err != nil {
|
||||
if user_model.IsErrUserNotExist(err) {
|
||||
@@ -82,15 +85,15 @@ func Migrate(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
if !ctx.User.IsAdmin {
|
||||
if !repoOwner.IsOrganization() && ctx.User.ID != repoOwner.ID {
|
||||
if !ctx.Doer.IsAdmin {
|
||||
if !repoOwner.IsOrganization() && ctx.Doer.ID != repoOwner.ID {
|
||||
ctx.Error(http.StatusForbidden, "", "Given user is not an organization.")
|
||||
return
|
||||
}
|
||||
|
||||
if repoOwner.IsOrganization() {
|
||||
// Check ownership of organization.
|
||||
isOwner, err := models.OrgFromUser(repoOwner).IsOwnedBy(ctx.User.ID)
|
||||
isOwner, err := organization.OrgFromUser(repoOwner).IsOwnedBy(ctx.Doer.ID)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "IsOwnedBy", err)
|
||||
return
|
||||
@@ -103,7 +106,7 @@ func Migrate(ctx *context.APIContext) {
|
||||
|
||||
remoteAddr, err := forms.ParseRemoteAddr(form.CloneAddr, form.AuthUsername, form.AuthPassword)
|
||||
if err == nil {
|
||||
err = migrations.IsMigrateURLAllowed(remoteAddr, ctx.User)
|
||||
err = migrations.IsMigrateURLAllowed(remoteAddr, ctx.Doer)
|
||||
}
|
||||
if err != nil {
|
||||
handleRemoteAddrError(ctx, err)
|
||||
@@ -130,7 +133,7 @@ func Migrate(ctx *context.APIContext) {
|
||||
ctx.Error(http.StatusInternalServerError, "", ctx.Tr("repo.migrate.invalid_lfs_endpoint"))
|
||||
return
|
||||
}
|
||||
err = migrations.IsMigrateURLAllowed(ep.String(), ctx.User)
|
||||
err = migrations.IsMigrateURLAllowed(ep.String(), ctx.Doer)
|
||||
if err != nil {
|
||||
handleRemoteAddrError(ctx, err)
|
||||
return
|
||||
@@ -167,7 +170,7 @@ func Migrate(ctx *context.APIContext) {
|
||||
opts.Releases = false
|
||||
}
|
||||
|
||||
repo, err := repo_module.CreateRepository(ctx.User, repoOwner, models.CreateRepoOptions{
|
||||
repo, err := repo_module.CreateRepository(ctx.Doer, repoOwner, models.CreateRepoOptions{
|
||||
Name: opts.RepoName,
|
||||
Description: opts.Description,
|
||||
OriginalURL: form.CloneAddr,
|
||||
@@ -192,18 +195,18 @@ func Migrate(ctx *context.APIContext) {
|
||||
}
|
||||
|
||||
if err == nil {
|
||||
notification.NotifyMigrateRepository(ctx.User, repoOwner, repo)
|
||||
notification.NotifyMigrateRepository(ctx.Doer, repoOwner, repo)
|
||||
return
|
||||
}
|
||||
|
||||
if repo != nil {
|
||||
if errDelete := models.DeleteRepository(ctx.User, repoOwner.ID, repo.ID); errDelete != nil {
|
||||
if errDelete := models.DeleteRepository(ctx.Doer, repoOwner.ID, repo.ID); errDelete != nil {
|
||||
log.Error("DeleteRepository: %v", errDelete)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
if repo, err = migrations.MigrateRepository(graceful.GetManager().HammerContext(), ctx.User, repoOwner.Name, opts, nil); err != nil {
|
||||
if repo, err = migrations.MigrateRepository(graceful.GetManager().HammerContext(), ctx.Doer, repoOwner.Name, opts, nil); err != nil {
|
||||
handleMigrateError(ctx, repoOwner, remoteAddr, err)
|
||||
return
|
||||
}
|
||||
@@ -235,7 +238,7 @@ func handleMigrateError(ctx *context.APIContext, repoOwner *user_model.User, rem
|
||||
case base.IsErrNotSupported(err):
|
||||
ctx.Error(http.StatusUnprocessableEntity, "", err)
|
||||
default:
|
||||
err = util.NewStringURLSanitizedError(err, remoteAddr, true)
|
||||
err = util.SanitizeErrorCredentialURLs(err)
|
||||
if strings.Contains(err.Error(), "Authentication failed") ||
|
||||
strings.Contains(err.Error(), "Bad credentials") ||
|
||||
strings.Contains(err.Error(), "could not read Username") {
|
||||
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"code.gitea.io/gitea/models"
|
||||
issues_model "code.gitea.io/gitea/models/issues"
|
||||
"code.gitea.io/gitea/modules/context"
|
||||
"code.gitea.io/gitea/modules/convert"
|
||||
api "code.gitea.io/gitea/modules/structs"
|
||||
@@ -57,7 +57,7 @@ func ListMilestones(ctx *context.APIContext) {
|
||||
// "200":
|
||||
// "$ref": "#/responses/MilestoneList"
|
||||
|
||||
milestones, total, err := models.GetMilestones(models.GetMilestonesOption{
|
||||
milestones, total, err := issues_model.GetMilestones(issues_model.GetMilestonesOption{
|
||||
ListOptions: utils.GetListOptions(ctx),
|
||||
RepoID: ctx.Repo.Repository.ID,
|
||||
State: api.StateType(ctx.FormString("state")),
|
||||
@@ -146,7 +146,7 @@ func CreateMilestone(ctx *context.APIContext) {
|
||||
form.Deadline = &defaultDeadline
|
||||
}
|
||||
|
||||
milestone := &models.Milestone{
|
||||
milestone := &issues_model.Milestone{
|
||||
RepoID: ctx.Repo.Repository.ID,
|
||||
Name: form.Title,
|
||||
Content: form.Description,
|
||||
@@ -158,7 +158,7 @@ func CreateMilestone(ctx *context.APIContext) {
|
||||
milestone.ClosedDateUnix = timeutil.TimeStampNow()
|
||||
}
|
||||
|
||||
if err := models.NewMilestone(milestone); err != nil {
|
||||
if err := issues_model.NewMilestone(milestone); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "NewMilestone", err)
|
||||
return
|
||||
}
|
||||
@@ -218,7 +218,7 @@ func EditMilestone(ctx *context.APIContext) {
|
||||
milestone.IsClosed = *form.State == string(api.StateClosed)
|
||||
}
|
||||
|
||||
if err := models.UpdateMilestone(milestone, oldIsClosed); err != nil {
|
||||
if err := issues_model.UpdateMilestone(milestone, oldIsClosed); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "UpdateMilestone", err)
|
||||
return
|
||||
}
|
||||
@@ -255,7 +255,7 @@ func DeleteMilestone(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := models.DeleteMilestoneByRepoID(ctx.Repo.Repository.ID, m.ID); err != nil {
|
||||
if err := issues_model.DeleteMilestoneByRepoID(ctx.Repo.Repository.ID, m.ID); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "DeleteMilestoneByRepoID", err)
|
||||
return
|
||||
}
|
||||
@@ -263,23 +263,23 @@ func DeleteMilestone(ctx *context.APIContext) {
|
||||
}
|
||||
|
||||
// getMilestoneByIDOrName get milestone by ID and if not available by name
|
||||
func getMilestoneByIDOrName(ctx *context.APIContext) *models.Milestone {
|
||||
func getMilestoneByIDOrName(ctx *context.APIContext) *issues_model.Milestone {
|
||||
mile := ctx.Params(":id")
|
||||
mileID, _ := strconv.ParseInt(mile, 0, 64)
|
||||
|
||||
if mileID != 0 {
|
||||
milestone, err := models.GetMilestoneByRepoID(ctx.Repo.Repository.ID, mileID)
|
||||
milestone, err := issues_model.GetMilestoneByRepoID(ctx, ctx.Repo.Repository.ID, mileID)
|
||||
if err == nil {
|
||||
return milestone
|
||||
} else if !models.IsErrMilestoneNotExist(err) {
|
||||
} else if !issues_model.IsErrMilestoneNotExist(err) {
|
||||
ctx.Error(http.StatusInternalServerError, "GetMilestoneByRepoID", err)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
milestone, err := models.GetMilestoneByRepoIDANDName(ctx.Repo.Repository.ID, mile)
|
||||
milestone, err := issues_model.GetMilestoneByRepoIDANDName(ctx.Repo.Repository.ID, mile)
|
||||
if err != nil {
|
||||
if models.IsErrMilestoneNotExist(err) {
|
||||
if issues_model.IsErrMilestoneNotExist(err) {
|
||||
ctx.NotFound()
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -5,8 +5,10 @@
|
||||
package repo
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
repo_model "code.gitea.io/gitea/models/repo"
|
||||
"code.gitea.io/gitea/models/unit"
|
||||
"code.gitea.io/gitea/modules/context"
|
||||
"code.gitea.io/gitea/modules/setting"
|
||||
@@ -48,6 +50,15 @@ func MirrorSync(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := repo_model.GetMirrorByRepoID(repo.ID); err != nil {
|
||||
if errors.Is(err, repo_model.ErrMirrorNotExist) {
|
||||
ctx.Error(http.StatusBadRequest, "MirrorSync", "Repository is not a mirror")
|
||||
return
|
||||
}
|
||||
ctx.Error(http.StatusInternalServerError, "MirrorSync", err)
|
||||
return
|
||||
}
|
||||
|
||||
mirror_service.StartToMirror(repo.ID)
|
||||
|
||||
ctx.Status(http.StatusOK)
|
||||
|
||||
@@ -55,15 +55,13 @@ func GetNote(ctx *context.APIContext) {
|
||||
}
|
||||
|
||||
func getNote(ctx *context.APIContext, identifier string) {
|
||||
gitRepo, err := git.OpenRepositoryCtx(ctx, ctx.Repo.Repository.RepoPath())
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "OpenRepository", err)
|
||||
if ctx.Repo.GitRepo == nil {
|
||||
ctx.InternalServerError(fmt.Errorf("no open git repo"))
|
||||
return
|
||||
}
|
||||
defer gitRepo.Close()
|
||||
|
||||
var note git.Note
|
||||
err = git.GetNote(ctx, gitRepo, identifier, ¬e)
|
||||
if err != nil {
|
||||
if err := git.GetNote(ctx, ctx.Repo.GitRepo, identifier, ¬e); err != nil {
|
||||
if git.IsErrNotExist(err) {
|
||||
ctx.NotFound(identifier)
|
||||
return
|
||||
@@ -72,7 +70,7 @@ func getNote(ctx *context.APIContext, identifier string) {
|
||||
return
|
||||
}
|
||||
|
||||
cmt, err := convert.ToCommit(ctx.Repo.Repository, gitRepo, note.Commit, nil)
|
||||
cmt, err := convert.ToCommit(ctx.Repo.Repository, ctx.Repo.GitRepo, note.Commit, nil)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "ToCommit", err)
|
||||
return
|
||||
|
||||
@@ -77,15 +77,15 @@ func ApplyDiffPatch(ctx *context.APIContext) {
|
||||
opts.Message = "apply-patch"
|
||||
}
|
||||
|
||||
if !canWriteFiles(ctx.Repo) {
|
||||
if !canWriteFiles(ctx, apiOpts.BranchName) {
|
||||
ctx.Error(http.StatusInternalServerError, "ApplyPatch", models.ErrUserDoesNotHaveAccessToRepo{
|
||||
UserID: ctx.User.ID,
|
||||
UserID: ctx.Doer.ID,
|
||||
RepoName: ctx.Repo.Repository.LowerName,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
fileResponse, err := files.ApplyDiffPatch(ctx, ctx.Repo.Repository, ctx.User, opts)
|
||||
fileResponse, err := files.ApplyDiffPatch(ctx, ctx.Repo.Repository, ctx.Doer, opts)
|
||||
if err != nil {
|
||||
if models.IsErrUserCannotCommit(err) || models.IsErrFilePathProtected(err) {
|
||||
ctx.Error(http.StatusForbidden, "Access", err)
|
||||
|
||||
+176
-110
@@ -14,6 +14,8 @@ import (
|
||||
"time"
|
||||
|
||||
"code.gitea.io/gitea/models"
|
||||
issues_model "code.gitea.io/gitea/models/issues"
|
||||
pull_model "code.gitea.io/gitea/models/pull"
|
||||
repo_model "code.gitea.io/gitea/models/repo"
|
||||
"code.gitea.io/gitea/models/unit"
|
||||
user_model "code.gitea.io/gitea/models/user"
|
||||
@@ -27,6 +29,7 @@ import (
|
||||
"code.gitea.io/gitea/modules/web"
|
||||
"code.gitea.io/gitea/routers/api/v1/utils"
|
||||
asymkey_service "code.gitea.io/gitea/services/asymkey"
|
||||
"code.gitea.io/gitea/services/automerge"
|
||||
"code.gitea.io/gitea/services/forms"
|
||||
issue_service "code.gitea.io/gitea/services/issue"
|
||||
pull_service "code.gitea.io/gitea/services/pull"
|
||||
@@ -110,15 +113,15 @@ func ListPullRequests(ctx *context.APIContext) {
|
||||
ctx.Error(http.StatusInternalServerError, "LoadAttributes", err)
|
||||
return
|
||||
}
|
||||
if err = prs[i].LoadBaseRepo(); err != nil {
|
||||
if err = prs[i].LoadBaseRepoCtx(ctx); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "LoadBaseRepo", err)
|
||||
return
|
||||
}
|
||||
if err = prs[i].LoadHeadRepo(); err != nil {
|
||||
if err = prs[i].LoadHeadRepoCtx(ctx); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "LoadHeadRepo", err)
|
||||
return
|
||||
}
|
||||
apiPrs[i] = convert.ToAPIPullRequest(ctx, prs[i], ctx.User)
|
||||
apiPrs[i] = convert.ToAPIPullRequest(ctx, prs[i], ctx.Doer)
|
||||
}
|
||||
|
||||
ctx.SetLinkHeader(int(maxResults), listOptions.PageSize)
|
||||
@@ -166,15 +169,15 @@ func GetPullRequest(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
if err = pr.LoadBaseRepo(); err != nil {
|
||||
if err = pr.LoadBaseRepoCtx(ctx); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "LoadBaseRepo", err)
|
||||
return
|
||||
}
|
||||
if err = pr.LoadHeadRepo(); err != nil {
|
||||
if err = pr.LoadHeadRepoCtx(ctx); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "LoadHeadRepo", err)
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusOK, convert.ToAPIPullRequest(ctx, pr, ctx.User))
|
||||
ctx.JSON(http.StatusOK, convert.ToAPIPullRequest(ctx, pr, ctx.Doer))
|
||||
}
|
||||
|
||||
// DownloadPullDiffOrPatch render a pull's raw diff or patch
|
||||
@@ -342,9 +345,9 @@ func CreatePullRequest(ctx *context.APIContext) {
|
||||
}
|
||||
|
||||
if form.Milestone > 0 {
|
||||
milestone, err := models.GetMilestoneByRepoID(ctx.Repo.Repository.ID, form.Milestone)
|
||||
milestone, err := issues_model.GetMilestoneByRepoID(ctx, ctx.Repo.Repository.ID, form.Milestone)
|
||||
if err != nil {
|
||||
if models.IsErrMilestoneNotExist(err) {
|
||||
if issues_model.IsErrMilestoneNotExist(err) {
|
||||
ctx.NotFound()
|
||||
} else {
|
||||
ctx.Error(http.StatusInternalServerError, "GetMilestoneByRepoID", err)
|
||||
@@ -363,8 +366,8 @@ func CreatePullRequest(ctx *context.APIContext) {
|
||||
prIssue := &models.Issue{
|
||||
RepoID: repo.ID,
|
||||
Title: form.Title,
|
||||
PosterID: ctx.User.ID,
|
||||
Poster: ctx.User,
|
||||
PosterID: ctx.Doer.ID,
|
||||
Poster: ctx.Doer,
|
||||
MilestoneID: milestoneID,
|
||||
IsPull: true,
|
||||
Content: form.Body,
|
||||
@@ -420,7 +423,7 @@ func CreatePullRequest(ctx *context.APIContext) {
|
||||
}
|
||||
|
||||
log.Trace("Pull request created: %d/%d", repo.ID, prIssue.ID)
|
||||
ctx.JSON(http.StatusCreated, convert.ToAPIPullRequest(ctx, pr, ctx.User))
|
||||
ctx.JSON(http.StatusCreated, convert.ToAPIPullRequest(ctx, pr, ctx.Doer))
|
||||
}
|
||||
|
||||
// EditPullRequest does what it says
|
||||
@@ -484,7 +487,7 @@ func EditPullRequest(ctx *context.APIContext) {
|
||||
issue := pr.Issue
|
||||
issue.Repo = ctx.Repo.Repository
|
||||
|
||||
if !issue.IsPoster(ctx.User.ID) && !ctx.Repo.CanWrite(unit.TypePullRequests) {
|
||||
if !issue.IsPoster(ctx.Doer.ID) && !ctx.Repo.CanWrite(unit.TypePullRequests) {
|
||||
ctx.Status(http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
@@ -506,7 +509,7 @@ func EditPullRequest(ctx *context.APIContext) {
|
||||
deadlineUnix = timeutil.TimeStamp(deadline.Unix())
|
||||
}
|
||||
|
||||
if err := models.UpdateIssueDeadline(issue, deadlineUnix, ctx.User); err != nil {
|
||||
if err := models.UpdateIssueDeadline(issue, deadlineUnix, ctx.Doer); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "UpdateIssueDeadline", err)
|
||||
return
|
||||
}
|
||||
@@ -522,7 +525,7 @@ func EditPullRequest(ctx *context.APIContext) {
|
||||
// Send an empty array ([]) to clear all assignees from the Issue.
|
||||
|
||||
if ctx.Repo.CanWrite(unit.TypePullRequests) && (form.Assignees != nil || len(form.Assignee) > 0) {
|
||||
err = issue_service.UpdateAssignees(issue, form.Assignee, form.Assignees, ctx.User)
|
||||
err = issue_service.UpdateAssignees(issue, form.Assignee, form.Assignees, ctx.Doer)
|
||||
if err != nil {
|
||||
if user_model.IsErrUserNotExist(err) {
|
||||
ctx.Error(http.StatusUnprocessableEntity, "", fmt.Sprintf("Assignee does not exist: [name: %s]", err))
|
||||
@@ -537,7 +540,7 @@ func EditPullRequest(ctx *context.APIContext) {
|
||||
issue.MilestoneID != form.Milestone {
|
||||
oldMilestoneID := issue.MilestoneID
|
||||
issue.MilestoneID = form.Milestone
|
||||
if err = issue_service.ChangeMilestoneAssign(issue, ctx.User, oldMilestoneID); err != nil {
|
||||
if err = issue_service.ChangeMilestoneAssign(issue, ctx.Doer, oldMilestoneID); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "ChangeMilestoneAssign", err)
|
||||
return
|
||||
}
|
||||
@@ -560,7 +563,7 @@ func EditPullRequest(ctx *context.APIContext) {
|
||||
labels = append(labels, orgLabels...)
|
||||
}
|
||||
|
||||
if err = issue.ReplaceLabels(labels, ctx.User); err != nil {
|
||||
if err = models.ReplaceIssueLabels(issue, labels, ctx.Doer); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "ReplaceLabelsError", err)
|
||||
return
|
||||
}
|
||||
@@ -573,7 +576,7 @@ func EditPullRequest(ctx *context.APIContext) {
|
||||
}
|
||||
issue.IsClosed = api.StateClosed == api.StateType(*form.State)
|
||||
}
|
||||
statusChangeComment, titleChanged, err := models.UpdateIssueByAPI(issue, ctx.User)
|
||||
statusChangeComment, titleChanged, err := models.UpdateIssueByAPI(issue, ctx.Doer)
|
||||
if err != nil {
|
||||
if models.IsErrDependenciesLeft(err) {
|
||||
ctx.Error(http.StatusPreconditionFailed, "DependenciesLeft", "cannot close this pull request because it still has open dependencies")
|
||||
@@ -584,11 +587,11 @@ func EditPullRequest(ctx *context.APIContext) {
|
||||
}
|
||||
|
||||
if titleChanged {
|
||||
notification.NotifyIssueChangeTitle(ctx.User, issue, oldTitle)
|
||||
notification.NotifyIssueChangeTitle(ctx.Doer, issue, oldTitle)
|
||||
}
|
||||
|
||||
if statusChangeComment != nil {
|
||||
notification.NotifyIssueChangeStatus(ctx.User, issue, statusChangeComment, issue.IsClosed)
|
||||
notification.NotifyIssueChangeStatus(ctx.Doer, issue, statusChangeComment, issue.IsClosed)
|
||||
}
|
||||
|
||||
// change pull target branch
|
||||
@@ -597,7 +600,7 @@ func EditPullRequest(ctx *context.APIContext) {
|
||||
ctx.Error(http.StatusNotFound, "NewBaseBranchNotExist", fmt.Errorf("new base '%s' not exist", form.Base))
|
||||
return
|
||||
}
|
||||
if err := pull_service.ChangeTargetBranch(ctx, pr, ctx.User, form.Base); err != nil {
|
||||
if err := pull_service.ChangeTargetBranch(ctx, pr, ctx.Doer, form.Base); err != nil {
|
||||
if models.IsErrPullRequestAlreadyExists(err) {
|
||||
ctx.Error(http.StatusConflict, "IsErrPullRequestAlreadyExists", err)
|
||||
return
|
||||
@@ -612,7 +615,19 @@ func EditPullRequest(ctx *context.APIContext) {
|
||||
}
|
||||
return
|
||||
}
|
||||
notification.NotifyPullRequestChangeTargetBranch(ctx.User, pr, form.Base)
|
||||
notification.NotifyPullRequestChangeTargetBranch(ctx.Doer, pr, form.Base)
|
||||
}
|
||||
|
||||
// update allow edits
|
||||
if form.AllowMaintainerEdit != nil {
|
||||
if err := pull_service.SetAllowEdits(ctx, ctx.Doer, pr, *form.AllowMaintainerEdit); err != nil {
|
||||
if errors.Is(pull_service.ErrUserHasNoPermissionForAction, err) {
|
||||
ctx.Error(http.StatusForbidden, "SetAllowEdits", fmt.Sprintf("SetAllowEdits: %s", err))
|
||||
return
|
||||
}
|
||||
ctx.ServerError("SetAllowEdits", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Refetch from database
|
||||
@@ -627,7 +642,7 @@ func EditPullRequest(ctx *context.APIContext) {
|
||||
}
|
||||
|
||||
// TODO this should be 200, not 201
|
||||
ctx.JSON(http.StatusCreated, convert.ToAPIPullRequest(ctx, pr, ctx.User))
|
||||
ctx.JSON(http.StatusCreated, convert.ToAPIPullRequest(ctx, pr, ctx.Doer))
|
||||
}
|
||||
|
||||
// IsPullRequestMerged checks if a PR exists given an index
|
||||
@@ -713,7 +728,8 @@ func MergePullRequest(ctx *context.APIContext) {
|
||||
// "$ref": "#/responses/error"
|
||||
|
||||
form := web.GetForm(ctx).(*forms.MergePullRequestForm)
|
||||
pr, err := models.GetPullRequestByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
|
||||
|
||||
pr, err := models.GetPullRequestByIndexCtx(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
|
||||
if err != nil {
|
||||
if models.IsErrPullRequestNotExist(err) {
|
||||
ctx.NotFound("GetPullRequestByIndex", err)
|
||||
@@ -723,13 +739,12 @@ func MergePullRequest(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
if err = pr.LoadHeadRepo(); err != nil {
|
||||
if err := pr.LoadHeadRepoCtx(ctx); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "LoadHeadRepo", err)
|
||||
return
|
||||
}
|
||||
|
||||
err = pr.LoadIssue()
|
||||
if err != nil {
|
||||
if err := pr.LoadIssueCtx(ctx); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "LoadIssue", err)
|
||||
return
|
||||
}
|
||||
@@ -737,35 +752,40 @@ func MergePullRequest(ctx *context.APIContext) {
|
||||
|
||||
if ctx.IsSigned {
|
||||
// Update issue-user.
|
||||
if err = pr.Issue.ReadBy(ctx.User.ID); err != nil {
|
||||
if err = pr.Issue.ReadBy(ctx, ctx.Doer.ID); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "ReadBy", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if pr.Issue.IsClosed {
|
||||
ctx.NotFound()
|
||||
return
|
||||
}
|
||||
manuallMerge := repo_model.MergeStyle(form.Do) == repo_model.MergeStyleManuallyMerged
|
||||
force := form.ForceMerge != nil && *form.ForceMerge
|
||||
|
||||
allowedMerge, err := pull_service.IsUserAllowedToMerge(pr, ctx.Repo.Permission, ctx.User)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "IsUSerAllowedToMerge", err)
|
||||
return
|
||||
}
|
||||
if !allowedMerge {
|
||||
ctx.Error(http.StatusMethodNotAllowed, "Merge", "User not allowed to merge PR")
|
||||
return
|
||||
}
|
||||
|
||||
if pr.HasMerged {
|
||||
ctx.Error(http.StatusMethodNotAllowed, "PR already merged", "")
|
||||
// start with merging by checking
|
||||
if err := pull_service.CheckPullMergable(ctx, ctx.Doer, &ctx.Repo.Permission, pr, manuallMerge, force); err != nil {
|
||||
if errors.Is(err, pull_service.ErrIsClosed) {
|
||||
ctx.NotFound()
|
||||
} else if errors.Is(err, pull_service.ErrUserNotAllowedToMerge) {
|
||||
ctx.Error(http.StatusMethodNotAllowed, "Merge", "User not allowed to merge PR")
|
||||
} else if errors.Is(err, pull_service.ErrHasMerged) {
|
||||
ctx.Error(http.StatusMethodNotAllowed, "PR already merged", "")
|
||||
} else if errors.Is(err, pull_service.ErrIsWorkInProgress) {
|
||||
ctx.Error(http.StatusMethodNotAllowed, "PR is a work in progress", "Work in progress PRs cannot be merged")
|
||||
} else if errors.Is(err, pull_service.ErrNotMergableState) {
|
||||
ctx.Error(http.StatusMethodNotAllowed, "PR not in mergeable state", "Please try again later")
|
||||
} else if models.IsErrDisallowedToMerge(err) {
|
||||
ctx.Error(http.StatusMethodNotAllowed, "PR is not ready to be merged", err)
|
||||
} else if asymkey_service.IsErrWontSign(err) {
|
||||
ctx.Error(http.StatusMethodNotAllowed, fmt.Sprintf("Protected branch %s requires signed commits but this merge would not be signed", pr.BaseBranch), err)
|
||||
} else {
|
||||
ctx.InternalServerError(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// handle manually-merged mark
|
||||
if repo_model.MergeStyle(form.Do) == repo_model.MergeStyleManuallyMerged {
|
||||
if err = pull_service.MergedManually(pr, ctx.User, ctx.Repo.GitRepo, form.MergeCommitID); err != nil {
|
||||
if manuallMerge {
|
||||
if err := pull_service.MergedManually(pr, ctx.Doer, ctx.Repo.GitRepo, form.MergeCommitID); err != nil {
|
||||
if models.IsErrInvalidMergeStyle(err) {
|
||||
ctx.Error(http.StatusMethodNotAllowed, "Invalid merge style", fmt.Errorf("%s is not allowed an allowed merge style for this repository", repo_model.MergeStyle(form.Do)))
|
||||
return
|
||||
@@ -781,54 +801,16 @@ func MergePullRequest(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
if !pr.CanAutoMerge() {
|
||||
ctx.Error(http.StatusMethodNotAllowed, "PR not in mergeable state", "Please try again later")
|
||||
return
|
||||
}
|
||||
|
||||
if pr.IsWorkInProgress() {
|
||||
ctx.Error(http.StatusMethodNotAllowed, "PR is a work in progress", "Work in progress PRs cannot be merged")
|
||||
return
|
||||
}
|
||||
|
||||
if err := pull_service.CheckPRReadyToMerge(ctx, pr, false); err != nil {
|
||||
if !models.IsErrNotAllowedToMerge(err) {
|
||||
ctx.Error(http.StatusInternalServerError, "CheckPRReadyToMerge", err)
|
||||
return
|
||||
}
|
||||
if form.ForceMerge != nil && *form.ForceMerge {
|
||||
if isRepoAdmin, err := models.IsUserRepoAdmin(pr.BaseRepo, ctx.User); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "IsUserRepoAdmin", err)
|
||||
return
|
||||
} else if !isRepoAdmin {
|
||||
ctx.Error(http.StatusMethodNotAllowed, "Merge", "Only repository admin can merge if not all checks are ok (force merge)")
|
||||
}
|
||||
} else {
|
||||
ctx.Error(http.StatusMethodNotAllowed, "PR is not ready to be merged", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if _, err := pull_service.IsSignedIfRequired(ctx, pr, ctx.User); err != nil {
|
||||
if !asymkey_service.IsErrWontSign(err) {
|
||||
ctx.Error(http.StatusInternalServerError, "IsSignedIfRequired", err)
|
||||
return
|
||||
}
|
||||
ctx.Error(http.StatusMethodNotAllowed, fmt.Sprintf("Protected branch %s requires signed commits but this merge would not be signed", pr.BaseBranch), err)
|
||||
return
|
||||
}
|
||||
|
||||
if len(form.Do) == 0 {
|
||||
form.Do = string(repo_model.MergeStyleMerge)
|
||||
}
|
||||
|
||||
message := strings.TrimSpace(form.MergeTitleField)
|
||||
if len(message) == 0 {
|
||||
if repo_model.MergeStyle(form.Do) == repo_model.MergeStyleMerge {
|
||||
message = pr.GetDefaultMergeMessage()
|
||||
}
|
||||
if repo_model.MergeStyle(form.Do) == repo_model.MergeStyleSquash {
|
||||
message = pr.GetDefaultSquashMessage()
|
||||
message, err = pull_service.GetDefaultMergeMessage(ctx.Repo.GitRepo, pr, repo_model.MergeStyle(form.Do))
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "GetDefaultMergeMessage", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -837,10 +819,25 @@ func MergePullRequest(ctx *context.APIContext) {
|
||||
message += "\n\n" + form.MergeMessageField
|
||||
}
|
||||
|
||||
if err := pull_service.Merge(ctx, pr, ctx.User, ctx.Repo.GitRepo, repo_model.MergeStyle(form.Do), form.HeadCommitID, message); err != nil {
|
||||
if form.MergeWhenChecksSucceed {
|
||||
scheduled, err := automerge.ScheduleAutoMerge(ctx, ctx.Doer, pr, repo_model.MergeStyle(form.Do), message)
|
||||
if err != nil {
|
||||
if pull_model.IsErrAlreadyScheduledToAutoMerge(err) {
|
||||
ctx.Error(http.StatusConflict, "ScheduleAutoMerge", err)
|
||||
return
|
||||
}
|
||||
ctx.Error(http.StatusInternalServerError, "ScheduleAutoMerge", err)
|
||||
return
|
||||
} else if scheduled {
|
||||
// nothing more to do ...
|
||||
ctx.Status(http.StatusCreated)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if err := pull_service.Merge(ctx, pr, ctx.Doer, ctx.Repo.GitRepo, repo_model.MergeStyle(form.Do), form.HeadCommitID, message); err != nil {
|
||||
if models.IsErrInvalidMergeStyle(err) {
|
||||
ctx.Error(http.StatusMethodNotAllowed, "Invalid merge style", fmt.Errorf("%s is not allowed an allowed merge style for this repository", repo_model.MergeStyle(form.Do)))
|
||||
return
|
||||
} else if models.IsErrMergeConflicts(err) {
|
||||
conflictError := err.(models.ErrMergeConflicts)
|
||||
ctx.JSON(http.StatusConflict, conflictError)
|
||||
@@ -852,28 +849,25 @@ func MergePullRequest(ctx *context.APIContext) {
|
||||
ctx.JSON(http.StatusConflict, conflictError)
|
||||
} else if git.IsErrPushOutOfDate(err) {
|
||||
ctx.Error(http.StatusConflict, "Merge", "merge push out of date")
|
||||
return
|
||||
} else if models.IsErrSHADoesNotMatch(err) {
|
||||
ctx.Error(http.StatusConflict, "Merge", "head out of date")
|
||||
return
|
||||
} else if git.IsErrPushRejected(err) {
|
||||
errPushRej := err.(*git.ErrPushRejected)
|
||||
if len(errPushRej.Message) == 0 {
|
||||
ctx.Error(http.StatusConflict, "Merge", "PushRejected without remote error message")
|
||||
return
|
||||
} else {
|
||||
ctx.Error(http.StatusConflict, "Merge", "PushRejected with remote message: "+errPushRej.Message)
|
||||
}
|
||||
ctx.Error(http.StatusConflict, "Merge", "PushRejected with remote message: "+errPushRej.Message)
|
||||
return
|
||||
} else {
|
||||
ctx.Error(http.StatusInternalServerError, "Merge", err)
|
||||
}
|
||||
ctx.Error(http.StatusInternalServerError, "Merge", err)
|
||||
return
|
||||
}
|
||||
|
||||
log.Trace("Pull request merged: %d", pr.ID)
|
||||
|
||||
if form.DeleteBranchAfterMerge {
|
||||
// Don't cleanup when there are other PR's that use this branch as head branch.
|
||||
exist, err := models.HasUnmergedPullRequestsByHeadInfo(pr.HeadRepoID, pr.HeadBranch)
|
||||
exist, err := models.HasUnmergedPullRequestsByHeadInfo(ctx, pr.HeadRepoID, pr.HeadBranch)
|
||||
if err != nil {
|
||||
ctx.ServerError("HasUnmergedPullRequestsByHeadInfo", err)
|
||||
return
|
||||
@@ -887,14 +881,14 @@ func MergePullRequest(ctx *context.APIContext) {
|
||||
if ctx.Repo != nil && ctx.Repo.Repository != nil && ctx.Repo.Repository.ID == pr.HeadRepoID && ctx.Repo.GitRepo != nil {
|
||||
headRepo = ctx.Repo.GitRepo
|
||||
} else {
|
||||
headRepo, err = git.OpenRepositoryCtx(ctx, pr.HeadRepo.RepoPath())
|
||||
headRepo, err = git.OpenRepository(ctx, pr.HeadRepo.RepoPath())
|
||||
if err != nil {
|
||||
ctx.ServerError(fmt.Sprintf("OpenRepository[%s]", pr.HeadRepo.RepoPath()), err)
|
||||
return
|
||||
}
|
||||
defer headRepo.Close()
|
||||
}
|
||||
if err := repo_service.DeleteBranch(ctx.User, pr.HeadRepo, headRepo, pr.HeadBranch); err != nil {
|
||||
if err := repo_service.DeleteBranch(ctx.Doer, pr.HeadRepo, headRepo, pr.HeadBranch); err != nil {
|
||||
switch {
|
||||
case git.IsErrBranchNotExist(err):
|
||||
ctx.NotFound(err)
|
||||
@@ -907,7 +901,7 @@ func MergePullRequest(ctx *context.APIContext) {
|
||||
}
|
||||
return
|
||||
}
|
||||
if err := models.AddDeletePRBranchComment(ctx.User, pr.BaseRepo, pr.Issue.ID, pr.HeadBranch); err != nil {
|
||||
if err := models.AddDeletePRBranchComment(ctx, ctx.Doer, pr.BaseRepo, pr.Issue.ID, pr.HeadBranch); err != nil {
|
||||
// Do not fail here as branch has already been deleted
|
||||
log.Error("DeleteBranch: %v", err)
|
||||
}
|
||||
@@ -981,7 +975,7 @@ func parseCompareInfo(ctx *context.APIContext, form api.CreatePullRequestOption)
|
||||
headRepo = ctx.Repo.Repository
|
||||
headGitRepo = ctx.Repo.GitRepo
|
||||
} else {
|
||||
headGitRepo, err = git.OpenRepositoryCtx(ctx, repo_model.RepoPath(headUser.Name, headRepo.Name))
|
||||
headGitRepo, err = git.OpenRepository(ctx, repo_model.RepoPath(headUser.Name, headRepo.Name))
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "OpenRepository", err)
|
||||
return nil, nil, nil, nil, "", ""
|
||||
@@ -989,7 +983,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(baseRepo, ctx.User)
|
||||
permBase, err := models.GetUserRepoPermission(ctx, baseRepo, ctx.Doer)
|
||||
if err != nil {
|
||||
headGitRepo.Close()
|
||||
ctx.Error(http.StatusInternalServerError, "GetUserRepoPermission", err)
|
||||
@@ -998,7 +992,7 @@ func parseCompareInfo(ctx *context.APIContext, form api.CreatePullRequestOption)
|
||||
if !permBase.CanReadIssuesOrPulls(true) || !permBase.CanRead(unit.TypeCode) {
|
||||
if log.IsTrace() {
|
||||
log.Trace("Permission Denied: User %-v cannot create/read pull requests or cannot read code in Repo %-v\nUser in baseRepo has Permissions: %-+v",
|
||||
ctx.User,
|
||||
ctx.Doer,
|
||||
baseRepo,
|
||||
permBase)
|
||||
}
|
||||
@@ -1008,7 +1002,7 @@ func parseCompareInfo(ctx *context.APIContext, form api.CreatePullRequestOption)
|
||||
}
|
||||
|
||||
// user should have permission to read headrepo's codes
|
||||
permHead, err := models.GetUserRepoPermission(headRepo, ctx.User)
|
||||
permHead, err := models.GetUserRepoPermission(ctx, headRepo, ctx.Doer)
|
||||
if err != nil {
|
||||
headGitRepo.Close()
|
||||
ctx.Error(http.StatusInternalServerError, "GetUserRepoPermission", err)
|
||||
@@ -1017,7 +1011,7 @@ func parseCompareInfo(ctx *context.APIContext, form api.CreatePullRequestOption)
|
||||
if !permHead.CanRead(unit.TypeCode) {
|
||||
if log.IsTrace() {
|
||||
log.Trace("Permission Denied: User: %-v cannot read code in Repo: %-v\nUser in headRepo has Permissions: %-+v",
|
||||
ctx.User,
|
||||
ctx.Doer,
|
||||
headRepo,
|
||||
permHead)
|
||||
}
|
||||
@@ -1109,18 +1103,18 @@ func UpdatePullRequest(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
if err = pr.LoadBaseRepo(); err != nil {
|
||||
if err = pr.LoadBaseRepoCtx(ctx); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "LoadBaseRepo", err)
|
||||
return
|
||||
}
|
||||
if err = pr.LoadHeadRepo(); err != nil {
|
||||
if err = pr.LoadHeadRepoCtx(ctx); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "LoadHeadRepo", err)
|
||||
return
|
||||
}
|
||||
|
||||
rebase := ctx.FormString("style") == "rebase"
|
||||
|
||||
allowedUpdateByMerge, allowedUpdateByRebase, err := pull_service.IsUserAllowedToUpdate(pr, ctx.User)
|
||||
allowedUpdateByMerge, allowedUpdateByRebase, err := pull_service.IsUserAllowedToUpdate(ctx, pr, ctx.Doer)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "IsUserAllowedToMerge", err)
|
||||
return
|
||||
@@ -1134,7 +1128,7 @@ func UpdatePullRequest(ctx *context.APIContext) {
|
||||
// default merge commit message
|
||||
message := fmt.Sprintf("Merge branch '%s' into %s", pr.BaseBranch, pr.HeadBranch)
|
||||
|
||||
if err = pull_service.Update(ctx, pr, ctx.User, message, rebase); err != nil {
|
||||
if err = pull_service.Update(ctx, pr, ctx.Doer, message, rebase); err != nil {
|
||||
if models.IsErrMergeConflicts(err) {
|
||||
ctx.Error(http.StatusConflict, "Update", "merge failed because of conflict")
|
||||
return
|
||||
@@ -1149,6 +1143,78 @@ func UpdatePullRequest(ctx *context.APIContext) {
|
||||
ctx.Status(http.StatusOK)
|
||||
}
|
||||
|
||||
// MergePullRequest cancel an auto merge scheduled for a given PullRequest by index
|
||||
func CancelScheduledAutoMerge(ctx *context.APIContext) {
|
||||
// swagger:operation DELETE /repos/{owner}/{repo}/pulls/{index}/merge repository repoCancelScheduledAutoMerge
|
||||
// ---
|
||||
// summary: Cancel the scheduled auto merge for the given pull request
|
||||
// produces:
|
||||
// - application/json
|
||||
// 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: index
|
||||
// in: path
|
||||
// description: index of the pull request to merge
|
||||
// type: integer
|
||||
// format: int64
|
||||
// required: true
|
||||
// responses:
|
||||
// "204":
|
||||
// "$ref": "#/responses/empty"
|
||||
// "403":
|
||||
// "$ref": "#/responses/forbidden"
|
||||
// "404":
|
||||
// "$ref": "#/responses/notFound"
|
||||
|
||||
pullIndex := ctx.ParamsInt64(":index")
|
||||
pull, err := models.GetPullRequestByIndex(ctx.Repo.Repository.ID, pullIndex)
|
||||
if err != nil {
|
||||
if models.IsErrPullRequestNotExist(err) {
|
||||
ctx.NotFound()
|
||||
return
|
||||
}
|
||||
ctx.InternalServerError(err)
|
||||
return
|
||||
}
|
||||
|
||||
exist, autoMerge, err := pull_model.GetScheduledMergeByPullID(ctx, pull.ID)
|
||||
if err != nil {
|
||||
ctx.InternalServerError(err)
|
||||
return
|
||||
}
|
||||
if !exist {
|
||||
ctx.NotFound()
|
||||
return
|
||||
}
|
||||
|
||||
if ctx.Doer.ID != autoMerge.DoerID {
|
||||
allowed, err := models.IsUserRepoAdminCtx(ctx, ctx.Repo.Repository, ctx.Doer)
|
||||
if err != nil {
|
||||
ctx.InternalServerError(err)
|
||||
return
|
||||
}
|
||||
if !allowed {
|
||||
ctx.Error(http.StatusForbidden, "No permission to cancel", "user has no permission to cancel the scheduled auto merge")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if err := automerge.RemoveScheduledAutoMerge(ctx, ctx.Doer, pull); err != nil {
|
||||
ctx.InternalServerError(err)
|
||||
} else {
|
||||
ctx.Status(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
// GetPullRequestCommits gets all commits associated with a given PR
|
||||
func GetPullRequestCommits(ctx *context.APIContext) {
|
||||
// swagger:operation GET /repos/{owner}/{repo}/pulls/{index}/commits repository repoGetPullRequestCommits
|
||||
@@ -1197,7 +1263,7 @@ func GetPullRequestCommits(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := pr.LoadBaseRepo(); err != nil {
|
||||
if err := pr.LoadBaseRepoCtx(ctx); err != nil {
|
||||
ctx.InternalServerError(err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"code.gitea.io/gitea/models"
|
||||
"code.gitea.io/gitea/models/organization"
|
||||
user_model "code.gitea.io/gitea/models/user"
|
||||
"code.gitea.io/gitea/modules/context"
|
||||
"code.gitea.io/gitea/modules/convert"
|
||||
@@ -74,7 +75,7 @@ func ListPullReviews(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
if err = pr.Issue.LoadRepo(); err != nil {
|
||||
if err = pr.Issue.LoadRepo(ctx); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "LoadRepo", err)
|
||||
return
|
||||
}
|
||||
@@ -97,7 +98,7 @@ func ListPullReviews(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
apiReviews, err := convert.ToPullReviewList(ctx, allReviews, ctx.User)
|
||||
apiReviews, err := convert.ToPullReviewList(ctx, allReviews, ctx.Doer)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "convertToPullReviewList", err)
|
||||
return
|
||||
@@ -148,7 +149,7 @@ func GetPullReview(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
apiReview, err := convert.ToPullReview(ctx, review, ctx.User)
|
||||
apiReview, err := convert.ToPullReview(ctx, review, ctx.Doer)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "convertToPullReview", err)
|
||||
return
|
||||
@@ -198,7 +199,7 @@ func GetPullReviewComments(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
apiComments, err := convert.ToPullReviewCommentList(ctx, review, ctx.User)
|
||||
apiComments, err := convert.ToPullReviewCommentList(ctx, review, ctx.Doer)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "convertToPullReviewCommentList", err)
|
||||
return
|
||||
@@ -250,11 +251,11 @@ func DeletePullReview(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
if ctx.User == nil {
|
||||
if ctx.Doer == nil {
|
||||
ctx.NotFound()
|
||||
return
|
||||
}
|
||||
if !ctx.User.IsAdmin && ctx.User.ID != review.ReviewerID {
|
||||
if !ctx.Doer.IsAdmin && ctx.Doer.ID != review.ReviewerID {
|
||||
ctx.Error(http.StatusForbidden, "only admin and user itself can delete a review", nil)
|
||||
return
|
||||
}
|
||||
@@ -321,7 +322,7 @@ func CreatePullReview(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := pr.Issue.LoadRepo(); err != nil {
|
||||
if err := pr.Issue.LoadRepo(ctx); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "pr.Issue.LoadRepo", err)
|
||||
return
|
||||
}
|
||||
@@ -353,7 +354,7 @@ func CreatePullReview(ctx *context.APIContext) {
|
||||
}
|
||||
|
||||
if _, err := pull_service.CreateCodeComment(ctx,
|
||||
ctx.User,
|
||||
ctx.Doer,
|
||||
ctx.Repo.GitRepo,
|
||||
pr.Issue,
|
||||
line,
|
||||
@@ -369,14 +370,14 @@ func CreatePullReview(ctx *context.APIContext) {
|
||||
}
|
||||
|
||||
// create review and associate all pending review comments
|
||||
review, _, err := pull_service.SubmitReview(ctx, ctx.User, ctx.Repo.GitRepo, pr.Issue, reviewType, opts.Body, opts.CommitID, nil)
|
||||
review, _, err := pull_service.SubmitReview(ctx, ctx.Doer, ctx.Repo.GitRepo, pr.Issue, reviewType, opts.Body, opts.CommitID, nil)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "SubmitReview", err)
|
||||
return
|
||||
}
|
||||
|
||||
// convert response
|
||||
apiReview, err := convert.ToPullReview(ctx, review, ctx.User)
|
||||
apiReview, err := convert.ToPullReview(ctx, review, ctx.Doer)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "convertToPullReview", err)
|
||||
return
|
||||
@@ -457,14 +458,14 @@ func SubmitPullReview(ctx *context.APIContext) {
|
||||
}
|
||||
|
||||
// create review and associate all pending review comments
|
||||
review, _, err = pull_service.SubmitReview(ctx, ctx.User, ctx.Repo.GitRepo, pr.Issue, reviewType, opts.Body, headCommitID, nil)
|
||||
review, _, err = pull_service.SubmitReview(ctx, ctx.Doer, ctx.Repo.GitRepo, pr.Issue, reviewType, opts.Body, headCommitID, nil)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "SubmitReview", err)
|
||||
return
|
||||
}
|
||||
|
||||
// convert response
|
||||
apiReview, err := convert.ToPullReview(ctx, review, ctx.User)
|
||||
apiReview, err := convert.ToPullReview(ctx, review, ctx.Doer)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "convertToPullReview", err)
|
||||
return
|
||||
@@ -486,7 +487,7 @@ func preparePullReviewType(ctx *context.APIContext, pr *models.PullRequest, even
|
||||
switch event {
|
||||
case api.ReviewStateApproved:
|
||||
// can not approve your own PR
|
||||
if pr.Issue.IsPoster(ctx.User.ID) {
|
||||
if pr.Issue.IsPoster(ctx.Doer.ID) {
|
||||
ctx.Error(http.StatusUnprocessableEntity, "", fmt.Errorf("approve your own pull is not allowed"))
|
||||
return -1, true
|
||||
}
|
||||
@@ -495,7 +496,7 @@ func preparePullReviewType(ctx *context.APIContext, pr *models.PullRequest, even
|
||||
|
||||
case api.ReviewStateRequestChanges:
|
||||
// can not reject your own PR
|
||||
if pr.Issue.IsPoster(ctx.User.ID) {
|
||||
if pr.Issue.IsPoster(ctx.Doer.ID) {
|
||||
ctx.Error(http.StatusUnprocessableEntity, "", fmt.Errorf("reject your own pull is not allowed"))
|
||||
return -1, true
|
||||
}
|
||||
@@ -551,7 +552,7 @@ func prepareSingleReview(ctx *context.APIContext) (*models.Review, *models.PullR
|
||||
}
|
||||
|
||||
// make sure that the user has access to this review if it is pending
|
||||
if review.Type == models.ReviewTypePending && review.ReviewerID != ctx.User.ID && !ctx.User.IsAdmin {
|
||||
if review.Type == models.ReviewTypePending && review.ReviewerID != ctx.Doer.ID && !ctx.Doer.IsAdmin {
|
||||
ctx.NotFound("GetReviewByID")
|
||||
return nil, nil, true
|
||||
}
|
||||
@@ -656,14 +657,14 @@ func apiReviewRequest(ctx *context.APIContext, opts api.PullReviewRequestOptions
|
||||
return
|
||||
}
|
||||
|
||||
if err := pr.Issue.LoadRepo(); err != nil {
|
||||
if err := pr.Issue.LoadRepo(ctx); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "pr.Issue.LoadRepo", err)
|
||||
return
|
||||
}
|
||||
|
||||
reviewers := make([]*user_model.User, 0, len(opts.Reviewers))
|
||||
|
||||
permDoer, err := models.GetUserRepoPermission(pr.Issue.Repo, ctx.User)
|
||||
permDoer, err := models.GetUserRepoPermission(ctx, pr.Issue.Repo, ctx.Doer)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "GetUserRepoPermission", err)
|
||||
return
|
||||
@@ -686,7 +687,7 @@ func apiReviewRequest(ctx *context.APIContext, opts api.PullReviewRequestOptions
|
||||
return
|
||||
}
|
||||
|
||||
err = issue_service.IsValidReviewRequest(reviewer, ctx.User, isAdd, pr.Issue, &permDoer)
|
||||
err = issue_service.IsValidReviewRequest(ctx, reviewer, ctx.Doer, isAdd, pr.Issue, &permDoer)
|
||||
if err != nil {
|
||||
if models.IsErrNotValidReviewRequest(err) {
|
||||
ctx.Error(http.StatusUnprocessableEntity, "NotValidReviewRequest", err)
|
||||
@@ -705,7 +706,7 @@ func apiReviewRequest(ctx *context.APIContext, opts api.PullReviewRequestOptions
|
||||
}
|
||||
|
||||
for _, reviewer := range reviewers {
|
||||
comment, err := issue_service.ReviewRequest(pr.Issue, ctx.User, reviewer, isAdd)
|
||||
comment, err := issue_service.ReviewRequest(pr.Issue, ctx.Doer, reviewer, isAdd)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "ReviewRequest", err)
|
||||
return
|
||||
@@ -722,12 +723,12 @@ func apiReviewRequest(ctx *context.APIContext, opts api.PullReviewRequestOptions
|
||||
|
||||
if ctx.Repo.Repository.Owner.IsOrganization() && len(opts.TeamReviewers) > 0 {
|
||||
|
||||
teamReviewers := make([]*models.Team, 0, len(opts.TeamReviewers))
|
||||
teamReviewers := make([]*organization.Team, 0, len(opts.TeamReviewers))
|
||||
for _, t := range opts.TeamReviewers {
|
||||
var teamReviewer *models.Team
|
||||
teamReviewer, err = models.GetTeam(ctx.Repo.Owner.ID, t)
|
||||
var teamReviewer *organization.Team
|
||||
teamReviewer, err = organization.GetTeam(ctx.Repo.Owner.ID, t)
|
||||
if err != nil {
|
||||
if models.IsErrTeamNotExist(err) {
|
||||
if organization.IsErrTeamNotExist(err) {
|
||||
ctx.NotFound("TeamNotExist", fmt.Sprintf("Team '%s' not exist", t))
|
||||
return
|
||||
}
|
||||
@@ -735,7 +736,7 @@ func apiReviewRequest(ctx *context.APIContext, opts api.PullReviewRequestOptions
|
||||
return
|
||||
}
|
||||
|
||||
err = issue_service.IsValidTeamReviewRequest(teamReviewer, ctx.User, isAdd, pr.Issue)
|
||||
err = issue_service.IsValidTeamReviewRequest(ctx, teamReviewer, ctx.Doer, isAdd, pr.Issue)
|
||||
if err != nil {
|
||||
if models.IsErrNotValidReviewRequest(err) {
|
||||
ctx.Error(http.StatusUnprocessableEntity, "NotValidReviewRequest", err)
|
||||
@@ -749,7 +750,7 @@ func apiReviewRequest(ctx *context.APIContext, opts api.PullReviewRequestOptions
|
||||
}
|
||||
|
||||
for _, teamReviewer := range teamReviewers {
|
||||
comment, err := issue_service.TeamReviewRequest(pr.Issue, ctx.User, teamReviewer, isAdd)
|
||||
comment, err := issue_service.TeamReviewRequest(pr.Issue, ctx.Doer, teamReviewer, isAdd)
|
||||
if err != nil {
|
||||
ctx.ServerError("TeamReviewRequest", err)
|
||||
return
|
||||
@@ -766,7 +767,7 @@ func apiReviewRequest(ctx *context.APIContext, opts api.PullReviewRequestOptions
|
||||
}
|
||||
|
||||
if isAdd {
|
||||
apiReviews, err := convert.ToPullReviewList(ctx, reviews, ctx.User)
|
||||
apiReviews, err := convert.ToPullReviewList(ctx, reviews, ctx.Doer)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "convertToPullReviewList", err)
|
||||
return
|
||||
@@ -884,7 +885,7 @@ func dismissReview(ctx *context.APIContext, msg string, isDismiss bool) {
|
||||
return
|
||||
}
|
||||
|
||||
_, err := pull_service.DismissReview(ctx, review.ID, msg, ctx.User, isDismiss)
|
||||
_, err := pull_service.DismissReview(ctx, review.ID, msg, ctx.Doer, isDismiss)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "pull_service.DismissReview", err)
|
||||
return
|
||||
@@ -896,7 +897,7 @@ func dismissReview(ctx *context.APIContext, msg string, isDismiss bool) {
|
||||
}
|
||||
|
||||
// convert response
|
||||
apiReview, err := convert.ToPullReview(ctx, review, ctx.User)
|
||||
apiReview, err := convert.ToPullReview(ctx, review, ctx.Doer)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "convertToPullReview", err)
|
||||
return
|
||||
|
||||
@@ -191,8 +191,8 @@ func CreateRelease(ctx *context.APIContext) {
|
||||
}
|
||||
rel = &models.Release{
|
||||
RepoID: ctx.Repo.Repository.ID,
|
||||
PublisherID: ctx.User.ID,
|
||||
Publisher: ctx.User,
|
||||
PublisherID: ctx.Doer.ID,
|
||||
Publisher: ctx.Doer,
|
||||
TagName: form.TagName,
|
||||
Target: form.Target,
|
||||
Title: form.Title,
|
||||
@@ -220,12 +220,12 @@ func CreateRelease(ctx *context.APIContext) {
|
||||
rel.Note = form.Note
|
||||
rel.IsDraft = form.IsDraft
|
||||
rel.IsPrerelease = form.IsPrerelease
|
||||
rel.PublisherID = ctx.User.ID
|
||||
rel.PublisherID = ctx.Doer.ID
|
||||
rel.IsTag = false
|
||||
rel.Repo = ctx.Repo.Repository
|
||||
rel.Publisher = ctx.User
|
||||
rel.Publisher = ctx.Doer
|
||||
|
||||
if err = releaseservice.UpdateRelease(ctx.User, ctx.Repo.GitRepo, rel, nil, nil, nil); err != nil {
|
||||
if err = releaseservice.UpdateRelease(ctx.Doer, ctx.Repo.GitRepo, rel, nil, nil, nil); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "UpdateRelease", err)
|
||||
return
|
||||
}
|
||||
@@ -300,7 +300,7 @@ func EditRelease(ctx *context.APIContext) {
|
||||
if form.IsPrerelease != nil {
|
||||
rel.IsPrerelease = *form.IsPrerelease
|
||||
}
|
||||
if err := releaseservice.UpdateRelease(ctx.User, ctx.Repo.GitRepo, rel, nil, nil, nil); err != nil {
|
||||
if err := releaseservice.UpdateRelease(ctx.Doer, ctx.Repo.GitRepo, rel, nil, nil, nil); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "UpdateRelease", err)
|
||||
return
|
||||
}
|
||||
@@ -356,7 +356,7 @@ func DeleteRelease(ctx *context.APIContext) {
|
||||
ctx.NotFound()
|
||||
return
|
||||
}
|
||||
if err := releaseservice.DeleteReleaseByID(ctx, id, ctx.User, false); err != nil {
|
||||
if err := releaseservice.DeleteReleaseByID(ctx, id, ctx.Doer, false); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "DeleteReleaseByID", err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -184,7 +184,7 @@ func CreateReleaseAttachment(ctx *context.APIContext) {
|
||||
}
|
||||
|
||||
// Create a new attachment and save the file
|
||||
attach, err := attachment.UploadAttachment(file, ctx.User.ID, release.RepoID, releaseID, filename, setting.Repository.Release.AllowedTypes)
|
||||
attach, err := attachment.UploadAttachment(file, ctx.Doer.ID, release.RepoID, releaseID, filename, setting.Repository.Release.AllowedTypes)
|
||||
if err != nil {
|
||||
if upload.IsErrFileTypeForbidden(err) {
|
||||
ctx.Error(http.StatusBadRequest, "DetectContentType", err)
|
||||
|
||||
@@ -110,7 +110,7 @@ func DeleteReleaseByTag(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
if err = releaseservice.DeleteReleaseByID(ctx, release.ID, ctx.User, false); err != nil {
|
||||
if err = releaseservice.DeleteReleaseByID(ctx, release.ID, ctx.Doer, false); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "DeleteReleaseByID", err)
|
||||
}
|
||||
|
||||
|
||||
+91
-75
@@ -13,6 +13,7 @@ import (
|
||||
|
||||
"code.gitea.io/gitea/models"
|
||||
"code.gitea.io/gitea/models/db"
|
||||
"code.gitea.io/gitea/models/organization"
|
||||
"code.gitea.io/gitea/models/perm"
|
||||
repo_model "code.gitea.io/gitea/models/repo"
|
||||
unit_model "code.gitea.io/gitea/models/unit"
|
||||
@@ -21,6 +22,7 @@ import (
|
||||
"code.gitea.io/gitea/modules/convert"
|
||||
"code.gitea.io/gitea/modules/git"
|
||||
"code.gitea.io/gitea/modules/log"
|
||||
repo_module "code.gitea.io/gitea/modules/repository"
|
||||
"code.gitea.io/gitea/modules/setting"
|
||||
api "code.gitea.io/gitea/modules/structs"
|
||||
"code.gitea.io/gitea/modules/util"
|
||||
@@ -30,23 +32,6 @@ import (
|
||||
repo_service "code.gitea.io/gitea/services/repository"
|
||||
)
|
||||
|
||||
var searchOrderByMap = map[string]map[string]db.SearchOrderBy{
|
||||
"asc": {
|
||||
"alpha": db.SearchOrderByAlphabetically,
|
||||
"created": db.SearchOrderByOldest,
|
||||
"updated": db.SearchOrderByLeastUpdated,
|
||||
"size": db.SearchOrderBySize,
|
||||
"id": db.SearchOrderByID,
|
||||
},
|
||||
"desc": {
|
||||
"alpha": db.SearchOrderByAlphabeticallyReverse,
|
||||
"created": db.SearchOrderByNewest,
|
||||
"updated": db.SearchOrderByRecentUpdated,
|
||||
"size": db.SearchOrderBySizeReverse,
|
||||
"id": db.SearchOrderByIDReverse,
|
||||
},
|
||||
}
|
||||
|
||||
// Search repositories via options
|
||||
func Search(ctx *context.APIContext) {
|
||||
// swagger:operation GET /repos/search repository repoSearch
|
||||
@@ -139,7 +124,7 @@ func Search(ctx *context.APIContext) {
|
||||
|
||||
opts := &models.SearchRepoOptions{
|
||||
ListOptions: utils.GetListOptions(ctx),
|
||||
Actor: ctx.User,
|
||||
Actor: ctx.Doer,
|
||||
Keyword: ctx.FormTrim("q"),
|
||||
OwnerID: ctx.FormInt64("uid"),
|
||||
PriorityOwnerID: ctx.FormInt64("priority_owner_id"),
|
||||
@@ -192,7 +177,7 @@ func Search(ctx *context.APIContext) {
|
||||
if len(sortOrder) == 0 {
|
||||
sortOrder = "asc"
|
||||
}
|
||||
if searchModeMap, ok := searchOrderByMap[sortOrder]; ok {
|
||||
if searchModeMap, ok := context.SearchOrderByMap[sortOrder]; ok {
|
||||
if orderBy, ok := searchModeMap[sortMode]; ok {
|
||||
opts.OrderBy = orderBy
|
||||
} else {
|
||||
@@ -217,14 +202,14 @@ func Search(ctx *context.APIContext) {
|
||||
|
||||
results := make([]*api.Repository, len(repos))
|
||||
for i, repo := range repos {
|
||||
if err = repo.GetOwner(db.DefaultContext); err != nil {
|
||||
if err = repo.GetOwner(ctx); err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, api.SearchError{
|
||||
OK: false,
|
||||
Error: err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
accessMode, err := models.AccessLevel(ctx.User, repo)
|
||||
accessMode, err := models.AccessLevel(ctx.Doer, repo)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, api.SearchError{
|
||||
OK: false,
|
||||
@@ -233,7 +218,6 @@ func Search(ctx *context.APIContext) {
|
||||
}
|
||||
results[i] = convert.ToRepo(repo, accessMode)
|
||||
}
|
||||
|
||||
ctx.SetLinkHeader(int(count), opts.PageSize)
|
||||
ctx.SetTotalCountHeader(count)
|
||||
ctx.JSON(http.StatusOK, api.SearchResults{
|
||||
@@ -247,7 +231,7 @@ func CreateUserRepo(ctx *context.APIContext, owner *user_model.User, opt api.Cre
|
||||
if opt.AutoInit && opt.Readme == "" {
|
||||
opt.Readme = "Default"
|
||||
}
|
||||
repo, err := repo_service.CreateRepository(ctx.User, owner, models.CreateRepoOptions{
|
||||
repo, err := repo_service.CreateRepository(ctx.Doer, owner, models.CreateRepoOptions{
|
||||
Name: opt.Name,
|
||||
Description: opt.Description,
|
||||
IssueLabels: opt.IssueLabels,
|
||||
@@ -264,7 +248,8 @@ func CreateUserRepo(ctx *context.APIContext, owner *user_model.User, opt api.Cre
|
||||
if repo_model.IsErrRepoAlreadyExist(err) {
|
||||
ctx.Error(http.StatusConflict, "", "The repository with the same name already exists.")
|
||||
} else if db.IsErrNameReserved(err) ||
|
||||
db.IsErrNamePatternNotAllowed(err) {
|
||||
db.IsErrNamePatternNotAllowed(err) ||
|
||||
repo_module.IsErrIssueLabelTemplateLoad(err) {
|
||||
ctx.Error(http.StatusUnprocessableEntity, "", err)
|
||||
} else {
|
||||
ctx.Error(http.StatusInternalServerError, "CreateRepository", err)
|
||||
@@ -303,12 +288,12 @@ func Create(ctx *context.APIContext) {
|
||||
// "422":
|
||||
// "$ref": "#/responses/validationError"
|
||||
opt := web.GetForm(ctx).(*api.CreateRepoOption)
|
||||
if ctx.User.IsOrganization() {
|
||||
if ctx.Doer.IsOrganization() {
|
||||
// Shouldn't reach this condition, but just in case.
|
||||
ctx.Error(http.StatusUnprocessableEntity, "", "not allowed creating repository for organization")
|
||||
return
|
||||
}
|
||||
CreateUserRepo(ctx, ctx.User, *opt)
|
||||
CreateUserRepo(ctx, ctx.Doer, *opt)
|
||||
}
|
||||
|
||||
// Generate Create a repository using a template
|
||||
@@ -353,21 +338,22 @@ func Generate(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
if ctx.User.IsOrganization() {
|
||||
if ctx.Doer.IsOrganization() {
|
||||
ctx.Error(http.StatusUnprocessableEntity, "", "not allowed creating repository for organization")
|
||||
return
|
||||
}
|
||||
|
||||
opts := models.GenerateRepoOptions{
|
||||
Name: form.Name,
|
||||
Description: form.Description,
|
||||
Private: form.Private,
|
||||
GitContent: form.GitContent,
|
||||
Topics: form.Topics,
|
||||
GitHooks: form.GitHooks,
|
||||
Webhooks: form.Webhooks,
|
||||
Avatar: form.Avatar,
|
||||
IssueLabels: form.Labels,
|
||||
Name: form.Name,
|
||||
DefaultBranch: form.DefaultBranch,
|
||||
Description: form.Description,
|
||||
Private: form.Private,
|
||||
GitContent: form.GitContent,
|
||||
Topics: form.Topics,
|
||||
GitHooks: form.GitHooks,
|
||||
Webhooks: form.Webhooks,
|
||||
Avatar: form.Avatar,
|
||||
IssueLabels: form.Labels,
|
||||
}
|
||||
|
||||
if !opts.IsValid() {
|
||||
@@ -375,7 +361,7 @@ func Generate(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
ctxUser := ctx.User
|
||||
ctxUser := ctx.Doer
|
||||
var err error
|
||||
if form.Owner != ctxUser.Name {
|
||||
ctxUser, err = user_model.GetUserByName(form.Owner)
|
||||
@@ -391,13 +377,13 @@ func Generate(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
if !ctx.User.IsAdmin && !ctxUser.IsOrganization() {
|
||||
if !ctx.Doer.IsAdmin && !ctxUser.IsOrganization() {
|
||||
ctx.Error(http.StatusForbidden, "", "Only admin can generate repository for other user.")
|
||||
return
|
||||
}
|
||||
|
||||
if !ctx.User.IsAdmin {
|
||||
canCreate, err := models.OrgFromUser(ctxUser).CanCreateOrgRepo(ctx.User.ID)
|
||||
if !ctx.Doer.IsAdmin {
|
||||
canCreate, err := organization.OrgFromUser(ctxUser).CanCreateOrgRepo(ctx.Doer.ID)
|
||||
if err != nil {
|
||||
ctx.ServerError("CanCreateOrgRepo", err)
|
||||
return
|
||||
@@ -408,7 +394,7 @@ func Generate(ctx *context.APIContext) {
|
||||
}
|
||||
}
|
||||
|
||||
repo, err := repo_service.GenerateRepository(ctx.User, ctxUser, ctx.Repo.Repository, opts)
|
||||
repo, err := repo_service.GenerateRepository(ctx.Doer, ctxUser, ctx.Repo.Repository, opts)
|
||||
if err != nil {
|
||||
if repo_model.IsErrRepoAlreadyExist(err) {
|
||||
ctx.Error(http.StatusConflict, "", "The repository with the same name already exists.")
|
||||
@@ -483,9 +469,9 @@ func CreateOrgRepo(ctx *context.APIContext) {
|
||||
// "403":
|
||||
// "$ref": "#/responses/forbidden"
|
||||
opt := web.GetForm(ctx).(*api.CreateRepoOption)
|
||||
org, err := models.GetOrgByName(ctx.Params(":org"))
|
||||
org, err := organization.GetOrgByName(ctx.Params(":org"))
|
||||
if err != nil {
|
||||
if models.IsErrOrgNotExist(err) {
|
||||
if organization.IsErrOrgNotExist(err) {
|
||||
ctx.Error(http.StatusUnprocessableEntity, "", err)
|
||||
} else {
|
||||
ctx.Error(http.StatusInternalServerError, "GetOrgByName", err)
|
||||
@@ -493,13 +479,13 @@ func CreateOrgRepo(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
if !models.HasOrgOrUserVisible(org.AsUser(), ctx.User) {
|
||||
if !organization.HasOrgOrUserVisible(ctx, org.AsUser(), ctx.Doer) {
|
||||
ctx.NotFound("HasOrgOrUserVisible", nil)
|
||||
return
|
||||
}
|
||||
|
||||
if !ctx.User.IsAdmin {
|
||||
canCreate, err := org.CanCreateOrgRepo(ctx.User.ID)
|
||||
if !ctx.Doer.IsAdmin {
|
||||
canCreate, err := org.CanCreateOrgRepo(ctx.Doer.ID)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "CanCreateOrgRepo", err)
|
||||
return
|
||||
@@ -569,7 +555,7 @@ func GetByID(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
perm, err := models.GetUserRepoPermission(repo, ctx.User)
|
||||
perm, err := models.GetUserRepoPermission(ctx, repo, ctx.Doer)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "AccessLevel", err)
|
||||
return
|
||||
@@ -629,7 +615,7 @@ func Edit(ctx *context.APIContext) {
|
||||
}
|
||||
|
||||
if opts.MirrorInterval != nil {
|
||||
if err := updateMirrorInterval(ctx, opts); err != nil {
|
||||
if err := updateMirror(ctx, opts); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -653,7 +639,7 @@ func updateBasicProperties(ctx *context.APIContext, opts api.EditRepoOption) err
|
||||
}
|
||||
// Check if repository name has been changed and not just a case change
|
||||
if repo.LowerName != strings.ToLower(newRepoName) {
|
||||
if err := repo_service.ChangeRepositoryName(ctx.User, repo, newRepoName); err != nil {
|
||||
if err := repo_service.ChangeRepositoryName(ctx.Doer, repo, newRepoName); err != nil {
|
||||
switch {
|
||||
case repo_model.IsErrRepoAlreadyExist(err):
|
||||
ctx.Error(http.StatusUnprocessableEntity, fmt.Sprintf("repo name is already taken [name: %s]", newRepoName), err)
|
||||
@@ -694,7 +680,7 @@ func updateBasicProperties(ctx *context.APIContext, opts api.EditRepoOption) err
|
||||
|
||||
visibilityChanged = repo.IsPrivate != *opts.Private
|
||||
// when ForcePrivate enabled, you could change public repo to private, but only admin users can change private to public
|
||||
if visibilityChanged && setting.Repository.ForcePrivate && !*opts.Private && !ctx.User.IsAdmin {
|
||||
if visibilityChanged && setting.Repository.ForcePrivate && !*opts.Private && !ctx.Doer.IsAdmin {
|
||||
err := fmt.Errorf("cannot change private repository to public")
|
||||
ctx.Error(http.StatusUnprocessableEntity, "Force Private enabled", err)
|
||||
return err
|
||||
@@ -709,7 +695,7 @@ func updateBasicProperties(ctx *context.APIContext, opts api.EditRepoOption) err
|
||||
|
||||
if ctx.Repo.GitRepo == nil && !repo.IsEmpty {
|
||||
var err error
|
||||
ctx.Repo.GitRepo, err = git.OpenRepositoryCtx(ctx, ctx.Repo.Repository.RepoPath())
|
||||
ctx.Repo.GitRepo, err = git.OpenRepository(ctx, ctx.Repo.Repository.RepoPath())
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "Unable to OpenRepository", err)
|
||||
return err
|
||||
@@ -958,37 +944,67 @@ func updateRepoArchivedState(ctx *context.APIContext, opts api.EditRepoOption) e
|
||||
return nil
|
||||
}
|
||||
|
||||
// updateMirrorInterval updates the repo's mirror Interval
|
||||
func updateMirrorInterval(ctx *context.APIContext, opts api.EditRepoOption) error {
|
||||
// updateMirror updates a repo's mirror Interval and EnablePrune
|
||||
func updateMirror(ctx *context.APIContext, opts api.EditRepoOption) error {
|
||||
repo := ctx.Repo.Repository
|
||||
|
||||
// only update mirror if interval or enable prune are provided
|
||||
if opts.MirrorInterval == nil && opts.EnablePrune == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
// these values only make sense if the repo is a mirror
|
||||
if !repo.IsMirror {
|
||||
err := fmt.Errorf("repo is not a mirror, can not change mirror interval")
|
||||
ctx.Error(http.StatusUnprocessableEntity, err.Error(), err)
|
||||
return err
|
||||
}
|
||||
|
||||
// get the mirror from the repo
|
||||
mirror, err := repo_model.GetMirrorByRepoID(repo.ID)
|
||||
if err != nil {
|
||||
log.Error("Failed to get mirror: %s", err)
|
||||
ctx.Error(http.StatusInternalServerError, "MirrorInterval", err)
|
||||
return err
|
||||
}
|
||||
|
||||
// update MirrorInterval
|
||||
if opts.MirrorInterval != nil {
|
||||
if !repo.IsMirror {
|
||||
err := fmt.Errorf("repo is not a mirror, can not change mirror interval")
|
||||
ctx.Error(http.StatusUnprocessableEntity, err.Error(), err)
|
||||
return err
|
||||
}
|
||||
mirror, err := repo_model.GetMirrorByRepoID(repo.ID)
|
||||
|
||||
// MirrorInterval should be a duration
|
||||
interval, err := time.ParseDuration(*opts.MirrorInterval)
|
||||
if err != nil {
|
||||
log.Error("Failed to get mirror: %s", err)
|
||||
ctx.Error(http.StatusInternalServerError, "MirrorInterval", err)
|
||||
return err
|
||||
}
|
||||
if interval, err := time.ParseDuration(*opts.MirrorInterval); err == nil {
|
||||
mirror.Interval = interval
|
||||
mirror.Repo = repo
|
||||
if err := repo_model.UpdateMirror(mirror); err != nil {
|
||||
log.Error("Failed to Set Mirror Interval: %s", err)
|
||||
ctx.Error(http.StatusUnprocessableEntity, "MirrorInterval", err)
|
||||
return err
|
||||
}
|
||||
log.Trace("Repository %s/%s Mirror Interval was Updated to %s", ctx.Repo.Owner.Name, repo.Name, interval)
|
||||
} else {
|
||||
log.Error("Wrong format for MirrorInternal Sent: %s", err)
|
||||
ctx.Error(http.StatusUnprocessableEntity, "MirrorInterval", err)
|
||||
return err
|
||||
}
|
||||
|
||||
// Ensure the provided duration is not too short
|
||||
if interval != 0 && interval < setting.Mirror.MinInterval {
|
||||
err := fmt.Errorf("invalid mirror interval: %s is below minimum interval: %s", interval, setting.Mirror.MinInterval)
|
||||
ctx.Error(http.StatusUnprocessableEntity, "MirrorInterval", err)
|
||||
return err
|
||||
}
|
||||
|
||||
mirror.Interval = interval
|
||||
mirror.Repo = repo
|
||||
mirror.ScheduleNextUpdate()
|
||||
log.Trace("Repository %s Mirror[%d] Set Interval: %s NextUpdateUnix: %s", repo.FullName(), mirror.ID, interval, mirror.NextUpdateUnix)
|
||||
}
|
||||
|
||||
// update EnablePrune
|
||||
if opts.EnablePrune != nil {
|
||||
mirror.EnablePrune = *opts.EnablePrune
|
||||
log.Trace("Repository %s Mirror[%d] Set EnablePrune: %t", repo.FullName(), mirror.ID, mirror.EnablePrune)
|
||||
}
|
||||
|
||||
// finally update the mirror in the DB
|
||||
if err := repo_model.UpdateMirror(mirror); err != nil {
|
||||
log.Error("Failed to Set Mirror Interval: %s", err)
|
||||
ctx.Error(http.StatusUnprocessableEntity, "MirrorInterval", err)
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1019,7 +1035,7 @@ func Delete(ctx *context.APIContext) {
|
||||
owner := ctx.Repo.Owner
|
||||
repo := ctx.Repo.Repository
|
||||
|
||||
canDelete, err := models.CanUserDelete(repo, ctx.User)
|
||||
canDelete, err := models.CanUserDelete(repo, ctx.Doer)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "CanUserDelete", err)
|
||||
return
|
||||
@@ -1032,7 +1048,7 @@ func Delete(ctx *context.APIContext) {
|
||||
ctx.Repo.GitRepo.Close()
|
||||
}
|
||||
|
||||
if err := repo_service.DeleteRepository(ctx, ctx.User, repo, true); err != nil {
|
||||
if err := repo_service.DeleteRepository(ctx, ctx.Doer, repo, true); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "DeleteRepository", err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ func TestRepoEdit(t *testing.T) {
|
||||
ctx := test.MockContext(t, "user2/repo1")
|
||||
test.LoadRepo(t, ctx, 1)
|
||||
test.LoadUser(t, ctx, 2)
|
||||
ctx.Repo.Owner = ctx.User
|
||||
ctx.Repo.Owner = ctx.Doer
|
||||
description := "new description"
|
||||
website := "http://wwww.newwebsite.com"
|
||||
private := true
|
||||
@@ -71,7 +71,7 @@ func TestRepoEditNameChange(t *testing.T) {
|
||||
ctx := test.MockContext(t, "user2/repo1")
|
||||
test.LoadRepo(t, ctx, 1)
|
||||
test.LoadUser(t, ctx, 2)
|
||||
ctx.Repo.Owner = ctx.User
|
||||
ctx.Repo.Owner = ctx.Doer
|
||||
name := "newname"
|
||||
opts := api.EditRepoOption{
|
||||
Name: &name,
|
||||
|
||||
@@ -51,7 +51,7 @@ func ListStargazers(ctx *context.APIContext) {
|
||||
}
|
||||
users := make([]*api.User, len(stargazers))
|
||||
for i, stargazer := range stargazers {
|
||||
users[i] = convert.ToUser(stargazer, ctx.User)
|
||||
users[i] = convert.ToUser(stargazer, ctx.Doer)
|
||||
}
|
||||
|
||||
ctx.SetTotalCountHeader(int64(ctx.Repo.Repository.NumStars))
|
||||
|
||||
@@ -62,7 +62,7 @@ func NewCommitStatus(ctx *context.APIContext) {
|
||||
Description: form.Description,
|
||||
Context: form.Context,
|
||||
}
|
||||
if err := files_service.CreateCommitStatus(ctx, ctx.Repo.Repository, ctx.User, sha, status); err != nil {
|
||||
if err := files_service.CreateCommitStatus(ctx, ctx.Repo.Repository, ctx.Doer, sha, status); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "CreateCommitStatus", err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -51,7 +51,7 @@ func ListSubscribers(ctx *context.APIContext) {
|
||||
}
|
||||
users := make([]*api.User, len(subscribers))
|
||||
for i, subscriber := range subscribers {
|
||||
users[i] = convert.ToUser(subscriber, ctx.User)
|
||||
users[i] = convert.ToUser(subscriber, ctx.Doer)
|
||||
}
|
||||
|
||||
ctx.SetTotalCountHeader(int64(ctx.Repo.Repository.NumWatches))
|
||||
|
||||
@@ -191,7 +191,7 @@ func CreateTag(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := releaseservice.CreateNewTag(ctx, ctx.User, ctx.Repo.Repository, commit.ID.String(), form.TagName, form.Message); err != nil {
|
||||
if err := releaseservice.CreateNewTag(ctx, ctx.Doer, ctx.Repo.Repository, commit.ID.String(), form.TagName, form.Message); err != nil {
|
||||
if models.IsErrTagAlreadyExists(err) {
|
||||
ctx.Error(http.StatusConflict, "tag exist", err)
|
||||
return
|
||||
@@ -255,7 +255,7 @@ func DeleteTag(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
if err = releaseservice.DeleteReleaseByID(ctx, tag.ID, ctx.User, true); err != nil {
|
||||
if err = releaseservice.DeleteReleaseByID(ctx, tag.ID, ctx.Doer, true); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "DeleteReleaseByID", err)
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"net/http"
|
||||
|
||||
"code.gitea.io/gitea/models"
|
||||
"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"
|
||||
@@ -41,7 +42,7 @@ func ListTeams(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
teams, err := models.GetRepoTeams(ctx.Repo.Repository)
|
||||
teams, err := organization.GetRepoTeams(ctx.Repo.Repository)
|
||||
if err != nil {
|
||||
ctx.InternalServerError(err)
|
||||
return
|
||||
@@ -101,7 +102,7 @@ func IsTeam(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
if team.HasRepository(ctx.Repo.Repository.ID) {
|
||||
if models.HasRepository(team, ctx.Repo.Repository.ID) {
|
||||
if err := team.GetUnits(); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "GetUnits", err)
|
||||
return
|
||||
@@ -196,20 +197,20 @@ func changeRepoTeam(ctx *context.APIContext, add bool) {
|
||||
return
|
||||
}
|
||||
|
||||
repoHasTeam := team.HasRepository(ctx.Repo.Repository.ID)
|
||||
repoHasTeam := models.HasRepository(team, ctx.Repo.Repository.ID)
|
||||
var err error
|
||||
if add {
|
||||
if repoHasTeam {
|
||||
ctx.Error(http.StatusUnprocessableEntity, "alreadyAdded", fmt.Errorf("team '%s' is already added to repo", team.Name))
|
||||
return
|
||||
}
|
||||
err = team.AddRepository(ctx.Repo.Repository)
|
||||
err = models.AddRepository(team, ctx.Repo.Repository)
|
||||
} else {
|
||||
if !repoHasTeam {
|
||||
ctx.Error(http.StatusUnprocessableEntity, "notAdded", fmt.Errorf("team '%s' was not added to repo", team.Name))
|
||||
return
|
||||
}
|
||||
err = team.RemoveRepository(ctx.Repo.Repository.ID)
|
||||
err = models.RemoveRepository(team, ctx.Repo.Repository.ID)
|
||||
}
|
||||
if err != nil {
|
||||
ctx.InternalServerError(err)
|
||||
@@ -219,10 +220,10 @@ func changeRepoTeam(ctx *context.APIContext, add bool) {
|
||||
ctx.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func getTeamByParam(ctx *context.APIContext) *models.Team {
|
||||
team, err := models.GetTeam(ctx.Repo.Owner.ID, ctx.Params(":team"))
|
||||
func getTeamByParam(ctx *context.APIContext) *organization.Team {
|
||||
team, err := organization.GetTeam(ctx.Repo.Owner.ID, ctx.Params(":team"))
|
||||
if err != nil {
|
||||
if models.IsErrTeamNotExist(err) {
|
||||
if organization.IsErrTeamNotExist(err) {
|
||||
ctx.Error(http.StatusNotFound, "TeamNotExit", err)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"net/http"
|
||||
|
||||
"code.gitea.io/gitea/models"
|
||||
"code.gitea.io/gitea/models/organization"
|
||||
"code.gitea.io/gitea/models/perm"
|
||||
repo_model "code.gitea.io/gitea/models/repo"
|
||||
user_model "code.gitea.io/gitea/models/user"
|
||||
@@ -67,23 +68,23 @@ func Transfer(ctx *context.APIContext) {
|
||||
}
|
||||
|
||||
if newOwner.Type == user_model.UserTypeOrganization {
|
||||
if !ctx.User.IsAdmin && newOwner.Visibility == api.VisibleTypePrivate && !models.OrgFromUser(newOwner).HasMemberWithUserID(ctx.User.ID) {
|
||||
if !ctx.Doer.IsAdmin && newOwner.Visibility == api.VisibleTypePrivate && !organization.OrgFromUser(newOwner).HasMemberWithUserID(ctx.Doer.ID) {
|
||||
// The user shouldn't know about this organization
|
||||
ctx.Error(http.StatusNotFound, "", "The new owner does not exist or cannot be found")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
var teams []*models.Team
|
||||
var teams []*organization.Team
|
||||
if opts.TeamIDs != nil {
|
||||
if !newOwner.IsOrganization() {
|
||||
ctx.Error(http.StatusUnprocessableEntity, "repoTransfer", "Teams can only be added to organization-owned repositories")
|
||||
return
|
||||
}
|
||||
|
||||
org := convert.ToOrganization(models.OrgFromUser(newOwner))
|
||||
org := convert.ToOrganization(organization.OrgFromUser(newOwner))
|
||||
for _, tID := range *opts.TeamIDs {
|
||||
team, err := models.GetTeamByID(tID)
|
||||
team, err := organization.GetTeamByID(tID)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusUnprocessableEntity, "team", fmt.Errorf("team %d not found", tID))
|
||||
return
|
||||
@@ -103,14 +104,16 @@ func Transfer(ctx *context.APIContext) {
|
||||
ctx.Repo.GitRepo = nil
|
||||
}
|
||||
|
||||
if err := repo_service.StartRepositoryTransfer(ctx.User, newOwner, ctx.Repo.Repository, teams); err != nil {
|
||||
oldFullname := ctx.Repo.Repository.FullName()
|
||||
|
||||
if err := repo_service.StartRepositoryTransfer(ctx.Doer, newOwner, ctx.Repo.Repository, teams); err != nil {
|
||||
if models.IsErrRepoTransferInProgress(err) {
|
||||
ctx.Error(http.StatusConflict, "CreatePendingRepositoryTransfer", err)
|
||||
ctx.Error(http.StatusConflict, "StartRepositoryTransfer", err)
|
||||
return
|
||||
}
|
||||
|
||||
if repo_model.IsErrRepoAlreadyExist(err) {
|
||||
ctx.Error(http.StatusUnprocessableEntity, "CreatePendingRepositoryTransfer", err)
|
||||
ctx.Error(http.StatusUnprocessableEntity, "StartRepositoryTransfer", err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -119,12 +122,12 @@ func Transfer(ctx *context.APIContext) {
|
||||
}
|
||||
|
||||
if ctx.Repo.Repository.Status == repo_model.RepositoryPendingTransfer {
|
||||
log.Trace("Repository transfer initiated: %s -> %s", ctx.Repo.Repository.FullName(), newOwner.Name)
|
||||
log.Trace("Repository transfer initiated: %s -> %s", oldFullname, ctx.Repo.Repository.FullName())
|
||||
ctx.JSON(http.StatusCreated, convert.ToRepo(ctx.Repo.Repository, perm.AccessModeAdmin))
|
||||
return
|
||||
}
|
||||
|
||||
log.Trace("Repository transferred: %s -> %s", ctx.Repo.Repository.FullName(), newOwner.Name)
|
||||
log.Trace("Repository transferred: %s -> %s", oldFullname, ctx.Repo.Repository.FullName())
|
||||
ctx.JSON(http.StatusAccepted, convert.ToRepo(ctx.Repo.Repository, perm.AccessModeAdmin))
|
||||
}
|
||||
|
||||
@@ -218,7 +221,7 @@ func acceptOrRejectRepoTransfer(ctx *context.APIContext, accept bool) error {
|
||||
return err
|
||||
}
|
||||
|
||||
if !repoTransfer.CanUserAcceptTransfer(ctx.User) {
|
||||
if !repoTransfer.CanUserAcceptTransfer(ctx.Doer) {
|
||||
ctx.Error(http.StatusForbidden, "CanUserAcceptTransfer", nil)
|
||||
return fmt.Errorf("user does not have permissions to do this")
|
||||
}
|
||||
|
||||
@@ -71,7 +71,7 @@ func NewWikiPage(ctx *context.APIContext) {
|
||||
}
|
||||
form.ContentBase64 = string(content)
|
||||
|
||||
if err := wiki_service.AddWikiPage(ctx, ctx.User, ctx.Repo.Repository, wikiName, form.ContentBase64, form.Message); err != nil {
|
||||
if err := wiki_service.AddWikiPage(ctx, ctx.Doer, ctx.Repo.Repository, wikiName, form.ContentBase64, form.Message); err != nil {
|
||||
if models.IsErrWikiReservedName(err) {
|
||||
ctx.Error(http.StatusBadRequest, "IsErrWikiReservedName", err)
|
||||
} else if models.IsErrWikiAlreadyExist(err) {
|
||||
@@ -144,7 +144,7 @@ func EditWikiPage(ctx *context.APIContext) {
|
||||
}
|
||||
form.ContentBase64 = string(content)
|
||||
|
||||
if err := wiki_service.EditWikiPage(ctx, ctx.User, ctx.Repo.Repository, oldWikiName, newWikiName, form.ContentBase64, form.Message); err != nil {
|
||||
if err := wiki_service.EditWikiPage(ctx, ctx.Doer, ctx.Repo.Repository, oldWikiName, newWikiName, form.ContentBase64, form.Message); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "EditWikiPage", err)
|
||||
return
|
||||
}
|
||||
@@ -233,7 +233,7 @@ func DeleteWikiPage(ctx *context.APIContext) {
|
||||
|
||||
wikiName := wiki_service.NormalizeWikiName(ctx.Params(":pageName"))
|
||||
|
||||
if err := wiki_service.DeleteWikiPage(ctx, ctx.User, ctx.Repo.Repository, wikiName); err != nil {
|
||||
if err := wiki_service.DeleteWikiPage(ctx, ctx.Doer, ctx.Repo.Repository, wikiName); err != nil {
|
||||
if err.Error() == "file does not exist" {
|
||||
ctx.NotFound(err)
|
||||
return
|
||||
@@ -458,7 +458,7 @@ func findEntryForFile(commit *git.Commit, target string) (*git.TreeEntry, error)
|
||||
// findWikiRepoCommit opens the wiki repo and returns the latest commit, writing to context on error.
|
||||
// The caller is responsible for closing the returned repo again
|
||||
func findWikiRepoCommit(ctx *context.APIContext) (*git.Repository, *git.Commit) {
|
||||
wikiRepo, err := git.OpenRepositoryCtx(ctx, ctx.Repo.Repository.WikiPath())
|
||||
wikiRepo, err := git.OpenRepository(ctx, ctx.Repo.Repository.WikiPath())
|
||||
if err != nil {
|
||||
|
||||
if git.IsErrNotExist(err) || err.Error() == "no such file or directory" {
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
// 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 swagger
|
||||
|
||||
import (
|
||||
api "code.gitea.io/gitea/modules/structs"
|
||||
)
|
||||
|
||||
// Package
|
||||
// swagger:response Package
|
||||
type swaggerResponsePackage struct {
|
||||
// in:body
|
||||
Body api.Package `json:"body"`
|
||||
}
|
||||
|
||||
// PackageList
|
||||
// swagger:response PackageList
|
||||
type swaggerResponsePackageList struct {
|
||||
// in:body
|
||||
Body []api.Package `json:"body"`
|
||||
}
|
||||
|
||||
// PackageFileList
|
||||
// swagger:response PackageFileList
|
||||
type swaggerResponsePackageFileList struct {
|
||||
// in:body
|
||||
Body []api.PackageFile `json:"body"`
|
||||
}
|
||||
@@ -344,3 +344,10 @@ type swaggerWikiCommitList struct {
|
||||
// in:body
|
||||
Body api.WikiCommitList `json:"body"`
|
||||
}
|
||||
|
||||
// RepoCollaboratorPermission
|
||||
// swagger:response RepoCollaboratorPermission
|
||||
type swaggerRepoCollaboratorPermission struct {
|
||||
// in:body
|
||||
Body api.RepoCollaboratorPermission `json:"body"`
|
||||
}
|
||||
|
||||
@@ -45,7 +45,7 @@ func ListAccessTokens(ctx *context.APIContext) {
|
||||
// "200":
|
||||
// "$ref": "#/responses/AccessTokenList"
|
||||
|
||||
opts := models.ListAccessTokensOptions{UserID: ctx.User.ID, ListOptions: utils.GetListOptions(ctx)}
|
||||
opts := models.ListAccessTokensOptions{UserID: ctx.Doer.ID, ListOptions: utils.GetListOptions(ctx)}
|
||||
|
||||
count, err := models.CountAccessTokens(opts)
|
||||
if err != nil {
|
||||
@@ -99,7 +99,7 @@ func CreateAccessToken(ctx *context.APIContext) {
|
||||
form := web.GetForm(ctx).(*api.CreateAccessTokenOption)
|
||||
|
||||
t := &models.AccessToken{
|
||||
UID: ctx.User.ID,
|
||||
UID: ctx.Doer.ID,
|
||||
Name: form.Name,
|
||||
}
|
||||
|
||||
@@ -157,7 +157,7 @@ func DeleteAccessToken(ctx *context.APIContext) {
|
||||
if tokenID == 0 {
|
||||
tokens, err := models.ListAccessTokens(models.ListAccessTokensOptions{
|
||||
Name: token,
|
||||
UserID: ctx.User.ID,
|
||||
UserID: ctx.Doer.ID,
|
||||
})
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "ListAccessTokens", err)
|
||||
@@ -180,7 +180,7 @@ func DeleteAccessToken(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := models.DeleteAccessTokenByID(tokenID, ctx.User.ID); err != nil {
|
||||
if err := models.DeleteAccessTokenByID(tokenID, ctx.Doer.ID); err != nil {
|
||||
if models.IsErrAccessTokenNotExist(err) {
|
||||
ctx.NotFound()
|
||||
} else {
|
||||
@@ -215,7 +215,7 @@ func CreateOauth2Application(ctx *context.APIContext) {
|
||||
|
||||
app, err := auth.CreateOAuth2Application(auth.CreateOAuth2ApplicationOptions{
|
||||
Name: data.Name,
|
||||
UserID: ctx.User.ID,
|
||||
UserID: ctx.Doer.ID,
|
||||
RedirectURIs: data.RedirectURIs,
|
||||
})
|
||||
if err != nil {
|
||||
@@ -252,7 +252,7 @@ func ListOauth2Applications(ctx *context.APIContext) {
|
||||
// "200":
|
||||
// "$ref": "#/responses/OAuth2ApplicationList"
|
||||
|
||||
apps, total, err := auth.ListOAuth2Applications(ctx.User.ID, utils.GetListOptions(ctx))
|
||||
apps, total, err := auth.ListOAuth2Applications(ctx.Doer.ID, utils.GetListOptions(ctx))
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "ListOAuth2Applications", err)
|
||||
return
|
||||
@@ -288,7 +288,7 @@ func DeleteOauth2Application(ctx *context.APIContext) {
|
||||
// "404":
|
||||
// "$ref": "#/responses/notFound"
|
||||
appID := ctx.ParamsInt64(":id")
|
||||
if err := auth.DeleteOAuth2Application(appID, ctx.User.ID); err != nil {
|
||||
if err := auth.DeleteOAuth2Application(appID, ctx.Doer.ID); err != nil {
|
||||
if auth.IsErrOAuthApplicationNotFound(err) {
|
||||
ctx.NotFound()
|
||||
} else {
|
||||
@@ -365,7 +365,7 @@ func UpdateOauth2Application(ctx *context.APIContext) {
|
||||
|
||||
app, err := auth.UpdateOAuth2Application(auth.UpdateOAuth2ApplicationOptions{
|
||||
Name: data.Name,
|
||||
UserID: ctx.User.ID,
|
||||
UserID: ctx.Doer.ID,
|
||||
ID: appID,
|
||||
RedirectURIs: data.RedirectURIs,
|
||||
})
|
||||
|
||||
@@ -28,7 +28,7 @@ func ListEmails(ctx *context.APIContext) {
|
||||
// "200":
|
||||
// "$ref": "#/responses/EmailList"
|
||||
|
||||
emails, err := user_model.GetEmailAddresses(ctx.User.ID)
|
||||
emails, err := user_model.GetEmailAddresses(ctx.Doer.ID)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "GetEmailAddresses", err)
|
||||
return
|
||||
@@ -71,7 +71,7 @@ func AddEmail(ctx *context.APIContext) {
|
||||
emails := make([]*user_model.EmailAddress, len(form.Emails))
|
||||
for i := range form.Emails {
|
||||
emails[i] = &user_model.EmailAddress{
|
||||
UID: ctx.User.ID,
|
||||
UID: ctx.Doer.ID,
|
||||
Email: form.Emails[i],
|
||||
IsActivated: !setting.Service.RegisterEmailConfirm,
|
||||
}
|
||||
@@ -80,8 +80,16 @@ func AddEmail(ctx *context.APIContext) {
|
||||
if err := user_model.AddEmailAddresses(emails); err != nil {
|
||||
if user_model.IsErrEmailAlreadyUsed(err) {
|
||||
ctx.Error(http.StatusUnprocessableEntity, "", "Email address has been used: "+err.(user_model.ErrEmailAlreadyUsed).Email)
|
||||
} else if user_model.IsErrEmailInvalid(err) {
|
||||
errMsg := fmt.Sprintf("Email address %s invalid", err.(user_model.ErrEmailInvalid).Email)
|
||||
} else if user_model.IsErrEmailCharIsNotSupported(err) || user_model.IsErrEmailInvalid(err) {
|
||||
email := ""
|
||||
if typedError, ok := err.(user_model.ErrEmailInvalid); ok {
|
||||
email = typedError.Email
|
||||
}
|
||||
if typedError, ok := err.(user_model.ErrEmailCharIsNotSupported); ok {
|
||||
email = typedError.Email
|
||||
}
|
||||
|
||||
errMsg := fmt.Sprintf("Email address %q invalid", email)
|
||||
ctx.Error(http.StatusUnprocessableEntity, "", errMsg)
|
||||
} else {
|
||||
ctx.Error(http.StatusInternalServerError, "AddEmailAddresses", err)
|
||||
@@ -123,7 +131,7 @@ func DeleteEmail(ctx *context.APIContext) {
|
||||
for i := range form.Emails {
|
||||
emails[i] = &user_model.EmailAddress{
|
||||
Email: form.Emails[i],
|
||||
UID: ctx.User.ID,
|
||||
UID: ctx.Doer.ID,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ import (
|
||||
func responseAPIUsers(ctx *context.APIContext, users []*user_model.User) {
|
||||
apiUsers := make([]*api.User, len(users))
|
||||
for i := range users {
|
||||
apiUsers[i] = convert.ToUser(users[i], ctx.User)
|
||||
apiUsers[i] = convert.ToUser(users[i], ctx.Doer)
|
||||
}
|
||||
ctx.JSON(http.StatusOK, &apiUsers)
|
||||
}
|
||||
@@ -54,7 +54,7 @@ func ListMyFollowers(ctx *context.APIContext) {
|
||||
// "200":
|
||||
// "$ref": "#/responses/UserList"
|
||||
|
||||
listUserFollowers(ctx, ctx.User)
|
||||
listUserFollowers(ctx, ctx.Doer)
|
||||
}
|
||||
|
||||
// ListFollowers list the given user's followers
|
||||
@@ -82,11 +82,7 @@ func ListFollowers(ctx *context.APIContext) {
|
||||
// "200":
|
||||
// "$ref": "#/responses/UserList"
|
||||
|
||||
u := GetUserByParams(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
listUserFollowers(ctx, u)
|
||||
listUserFollowers(ctx, ctx.ContextUser)
|
||||
}
|
||||
|
||||
func listUserFollowing(ctx *context.APIContext, u *user_model.User) {
|
||||
@@ -120,7 +116,7 @@ func ListMyFollowing(ctx *context.APIContext) {
|
||||
// "200":
|
||||
// "$ref": "#/responses/UserList"
|
||||
|
||||
listUserFollowing(ctx, ctx.User)
|
||||
listUserFollowing(ctx, ctx.Doer)
|
||||
}
|
||||
|
||||
// ListFollowing list the users that the given user is following
|
||||
@@ -148,11 +144,7 @@ func ListFollowing(ctx *context.APIContext) {
|
||||
// "200":
|
||||
// "$ref": "#/responses/UserList"
|
||||
|
||||
u := GetUserByParams(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
listUserFollowing(ctx, u)
|
||||
listUserFollowing(ctx, ctx.ContextUser)
|
||||
}
|
||||
|
||||
func checkUserFollowing(ctx *context.APIContext, u *user_model.User, followID int64) {
|
||||
@@ -180,25 +172,21 @@ func CheckMyFollowing(ctx *context.APIContext) {
|
||||
// "404":
|
||||
// "$ref": "#/responses/notFound"
|
||||
|
||||
target := GetUserByParams(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
checkUserFollowing(ctx, ctx.User, target.ID)
|
||||
checkUserFollowing(ctx, ctx.Doer, ctx.ContextUser.ID)
|
||||
}
|
||||
|
||||
// CheckFollowing check if one user is following another user
|
||||
func CheckFollowing(ctx *context.APIContext) {
|
||||
// swagger:operation GET /users/{follower}/following/{followee} user userCheckFollowing
|
||||
// swagger:operation GET /users/{username}/following/{target} user userCheckFollowing
|
||||
// ---
|
||||
// summary: Check if one user is following another user
|
||||
// parameters:
|
||||
// - name: follower
|
||||
// - name: username
|
||||
// in: path
|
||||
// description: username of following user
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: followee
|
||||
// - name: target
|
||||
// in: path
|
||||
// description: username of followed user
|
||||
// type: string
|
||||
@@ -209,15 +197,11 @@ func CheckFollowing(ctx *context.APIContext) {
|
||||
// "404":
|
||||
// "$ref": "#/responses/notFound"
|
||||
|
||||
u := GetUserByParams(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
target := GetUserByParamsName(ctx, ":target")
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
checkUserFollowing(ctx, u, target.ID)
|
||||
checkUserFollowing(ctx, ctx.ContextUser, target.ID)
|
||||
}
|
||||
|
||||
// Follow follow a user
|
||||
@@ -235,11 +219,7 @@ func Follow(ctx *context.APIContext) {
|
||||
// "204":
|
||||
// "$ref": "#/responses/empty"
|
||||
|
||||
target := GetUserByParams(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
if err := user_model.FollowUser(ctx.User.ID, target.ID); err != nil {
|
||||
if err := user_model.FollowUser(ctx.Doer.ID, ctx.ContextUser.ID); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "FollowUser", err)
|
||||
return
|
||||
}
|
||||
@@ -261,11 +241,7 @@ func Unfollow(ctx *context.APIContext) {
|
||||
// "204":
|
||||
// "$ref": "#/responses/empty"
|
||||
|
||||
target := GetUserByParams(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
if err := user_model.UnfollowUser(ctx.User.ID, target.ID); err != nil {
|
||||
if err := user_model.UnfollowUser(ctx.Doer.ID, ctx.ContextUser.ID); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "UnfollowUser", err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ import (
|
||||
)
|
||||
|
||||
func listGPGKeys(ctx *context.APIContext, uid int64, listOptions db.ListOptions) {
|
||||
keys, err := asymkey_model.ListGPGKeys(db.DefaultContext, uid, listOptions)
|
||||
keys, err := asymkey_model.ListGPGKeys(ctx, uid, listOptions)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "ListGPGKeys", err)
|
||||
return
|
||||
@@ -64,11 +64,7 @@ func ListGPGKeys(ctx *context.APIContext) {
|
||||
// "200":
|
||||
// "$ref": "#/responses/GPGKeyList"
|
||||
|
||||
user := GetUserByParams(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
listGPGKeys(ctx, user.ID, utils.GetListOptions(ctx))
|
||||
listGPGKeys(ctx, ctx.ContextUser.ID, utils.GetListOptions(ctx))
|
||||
}
|
||||
|
||||
// ListMyGPGKeys get the GPG key list of the authenticated user
|
||||
@@ -91,7 +87,7 @@ func ListMyGPGKeys(ctx *context.APIContext) {
|
||||
// "200":
|
||||
// "$ref": "#/responses/GPGKeyList"
|
||||
|
||||
listGPGKeys(ctx, ctx.User.ID, utils.GetListOptions(ctx))
|
||||
listGPGKeys(ctx, ctx.Doer.ID, utils.GetListOptions(ctx))
|
||||
}
|
||||
|
||||
// GetGPGKey get the GPG key based on a id
|
||||
@@ -128,8 +124,8 @@ func GetGPGKey(ctx *context.APIContext) {
|
||||
|
||||
// CreateUserGPGKey creates new GPG key to given user by ID.
|
||||
func CreateUserGPGKey(ctx *context.APIContext, form api.CreateGPGKeyOption, uid int64) {
|
||||
token := asymkey_model.VerificationToken(ctx.User, 1)
|
||||
lastToken := asymkey_model.VerificationToken(ctx.User, 0)
|
||||
token := asymkey_model.VerificationToken(ctx.Doer, 1)
|
||||
lastToken := asymkey_model.VerificationToken(ctx.Doer, 0)
|
||||
|
||||
keys, err := asymkey_model.AddGPGKey(uid, form.ArmoredKey, token, form.Signature)
|
||||
if err != nil && asymkey_model.IsErrGPGInvalidTokenSignature(err) {
|
||||
@@ -156,7 +152,7 @@ func GetVerificationToken(ctx *context.APIContext) {
|
||||
// "404":
|
||||
// "$ref": "#/responses/notFound"
|
||||
|
||||
token := asymkey_model.VerificationToken(ctx.User, 1)
|
||||
token := asymkey_model.VerificationToken(ctx.Doer, 1)
|
||||
ctx.PlainText(http.StatusOK, token)
|
||||
}
|
||||
|
||||
@@ -178,12 +174,12 @@ func VerifyUserGPGKey(ctx *context.APIContext) {
|
||||
// "$ref": "#/responses/validationError"
|
||||
|
||||
form := web.GetForm(ctx).(*api.VerifyGPGKeyOption)
|
||||
token := asymkey_model.VerificationToken(ctx.User, 1)
|
||||
lastToken := asymkey_model.VerificationToken(ctx.User, 0)
|
||||
token := asymkey_model.VerificationToken(ctx.Doer, 1)
|
||||
lastToken := asymkey_model.VerificationToken(ctx.Doer, 0)
|
||||
|
||||
_, err := asymkey_model.VerifyGPGKey(ctx.User.ID, form.KeyID, token, form.Signature)
|
||||
_, err := asymkey_model.VerifyGPGKey(ctx.Doer.ID, form.KeyID, token, form.Signature)
|
||||
if err != nil && asymkey_model.IsErrGPGInvalidTokenSignature(err) {
|
||||
_, err = asymkey_model.VerifyGPGKey(ctx.User.ID, form.KeyID, lastToken, form.Signature)
|
||||
_, err = asymkey_model.VerifyGPGKey(ctx.Doer.ID, form.KeyID, lastToken, form.Signature)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
@@ -230,7 +226,7 @@ func CreateGPGKey(ctx *context.APIContext) {
|
||||
// "$ref": "#/responses/validationError"
|
||||
|
||||
form := web.GetForm(ctx).(*api.CreateGPGKeyOption)
|
||||
CreateUserGPGKey(ctx, *form, ctx.User.ID)
|
||||
CreateUserGPGKey(ctx, *form, ctx.Doer.ID)
|
||||
}
|
||||
|
||||
// DeleteGPGKey remove a GPG key belonging to the authenticated user
|
||||
@@ -255,7 +251,7 @@ func DeleteGPGKey(ctx *context.APIContext) {
|
||||
// "404":
|
||||
// "$ref": "#/responses/notFound"
|
||||
|
||||
if err := asymkey_model.DeleteGPGKey(ctx.User, ctx.ParamsInt64(":id")); err != nil {
|
||||
if err := asymkey_model.DeleteGPGKey(ctx.Doer, ctx.ParamsInt64(":id")); err != nil {
|
||||
if asymkey_model.IsErrGPGKeyAccessDenied(err) {
|
||||
ctx.Error(http.StatusForbidden, "", "You do not have access to this key")
|
||||
} else {
|
||||
|
||||
+21
-20
@@ -86,7 +86,7 @@ func listPublicKeys(ctx *context.APIContext, user *user_model.User) {
|
||||
apiKeys := make([]*api.PublicKey, len(keys))
|
||||
for i := range keys {
|
||||
apiKeys[i] = convert.ToPublicKey(apiLink, keys[i])
|
||||
if ctx.User.IsAdmin || ctx.User.ID == keys[i].OwnerID {
|
||||
if ctx.Doer.IsAdmin || ctx.Doer.ID == keys[i].OwnerID {
|
||||
apiKeys[i], _ = appendPrivateInformation(apiKeys[i], keys[i], user)
|
||||
}
|
||||
}
|
||||
@@ -119,7 +119,7 @@ func ListMyPublicKeys(ctx *context.APIContext) {
|
||||
// "200":
|
||||
// "$ref": "#/responses/PublicKeyList"
|
||||
|
||||
listPublicKeys(ctx, ctx.User)
|
||||
listPublicKeys(ctx, ctx.Doer)
|
||||
}
|
||||
|
||||
// ListPublicKeys list the given user's public keys
|
||||
@@ -151,11 +151,7 @@ func ListPublicKeys(ctx *context.APIContext) {
|
||||
// "200":
|
||||
// "$ref": "#/responses/PublicKeyList"
|
||||
|
||||
user := GetUserByParams(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
listPublicKeys(ctx, user)
|
||||
listPublicKeys(ctx, ctx.ContextUser)
|
||||
}
|
||||
|
||||
// GetPublicKey get a public key
|
||||
@@ -190,8 +186,8 @@ func GetPublicKey(ctx *context.APIContext) {
|
||||
|
||||
apiLink := composePublicKeysAPILink()
|
||||
apiKey := convert.ToPublicKey(apiLink, key)
|
||||
if ctx.User.IsAdmin || ctx.User.ID == key.OwnerID {
|
||||
apiKey, _ = appendPrivateInformation(apiKey, key, ctx.User)
|
||||
if ctx.Doer.IsAdmin || ctx.Doer.ID == key.OwnerID {
|
||||
apiKey, _ = appendPrivateInformation(apiKey, key, ctx.Doer)
|
||||
}
|
||||
ctx.JSON(http.StatusOK, apiKey)
|
||||
}
|
||||
@@ -211,8 +207,8 @@ func CreateUserPublicKey(ctx *context.APIContext, form api.CreateKeyOption, uid
|
||||
}
|
||||
apiLink := composePublicKeysAPILink()
|
||||
apiKey := convert.ToPublicKey(apiLink, key)
|
||||
if ctx.User.IsAdmin || ctx.User.ID == key.OwnerID {
|
||||
apiKey, _ = appendPrivateInformation(apiKey, key, ctx.User)
|
||||
if ctx.Doer.IsAdmin || ctx.Doer.ID == key.OwnerID {
|
||||
apiKey, _ = appendPrivateInformation(apiKey, key, ctx.Doer)
|
||||
}
|
||||
ctx.JSON(http.StatusCreated, apiKey)
|
||||
}
|
||||
@@ -238,7 +234,7 @@ func CreatePublicKey(ctx *context.APIContext) {
|
||||
// "$ref": "#/responses/validationError"
|
||||
|
||||
form := web.GetForm(ctx).(*api.CreateKeyOption)
|
||||
CreateUserPublicKey(ctx, *form, ctx.User.ID)
|
||||
CreateUserPublicKey(ctx, *form, ctx.Doer.ID)
|
||||
}
|
||||
|
||||
// DeletePublicKey delete one public key
|
||||
@@ -266,16 +262,21 @@ func DeletePublicKey(ctx *context.APIContext) {
|
||||
id := ctx.ParamsInt64(":id")
|
||||
externallyManaged, err := asymkey_model.PublicKeyIsExternallyManaged(id)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "PublicKeyIsExternallyManaged", err)
|
||||
}
|
||||
if externallyManaged {
|
||||
ctx.Error(http.StatusForbidden, "", "SSH Key is externally managed for this user")
|
||||
}
|
||||
|
||||
if err := asymkey_service.DeletePublicKey(ctx.User, id); err != nil {
|
||||
if asymkey_model.IsErrKeyNotExist(err) {
|
||||
ctx.NotFound()
|
||||
} else if asymkey_model.IsErrKeyAccessDenied(err) {
|
||||
} else {
|
||||
ctx.Error(http.StatusInternalServerError, "PublicKeyIsExternallyManaged", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if externallyManaged {
|
||||
ctx.Error(http.StatusForbidden, "", "SSH Key is externally managed for this user")
|
||||
return
|
||||
}
|
||||
|
||||
if err := asymkey_service.DeletePublicKey(ctx.Doer, id); err != nil {
|
||||
if asymkey_model.IsErrKeyAccessDenied(err) {
|
||||
ctx.Error(http.StatusForbidden, "", "You do not have access to this key")
|
||||
} else {
|
||||
ctx.Error(http.StatusInternalServerError, "DeletePublicKey", err)
|
||||
|
||||
@@ -8,7 +8,6 @@ import (
|
||||
"net/http"
|
||||
|
||||
"code.gitea.io/gitea/models"
|
||||
"code.gitea.io/gitea/models/db"
|
||||
"code.gitea.io/gitea/models/perm"
|
||||
user_model "code.gitea.io/gitea/models/user"
|
||||
"code.gitea.io/gitea/modules/context"
|
||||
@@ -39,12 +38,12 @@ 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.User, repos[i])
|
||||
access, err := models.AccessLevel(ctx.Doer, repos[i])
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "AccessLevel", err)
|
||||
return
|
||||
}
|
||||
if ctx.IsSigned && ctx.User.IsAdmin || access >= perm.AccessModeRead {
|
||||
if ctx.IsSigned && ctx.Doer.IsAdmin || access >= perm.AccessModeRead {
|
||||
apiRepos = append(apiRepos, convert.ToRepo(repos[i], access))
|
||||
}
|
||||
}
|
||||
@@ -79,12 +78,8 @@ func ListUserRepos(ctx *context.APIContext) {
|
||||
// "200":
|
||||
// "$ref": "#/responses/RepositoryList"
|
||||
|
||||
user := GetUserByParams(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
private := ctx.IsSigned
|
||||
listUserRepos(ctx, user, private)
|
||||
listUserRepos(ctx, ctx.ContextUser, private)
|
||||
}
|
||||
|
||||
// ListMyRepos - list the repositories you own or have access to.
|
||||
@@ -109,8 +104,8 @@ func ListMyRepos(ctx *context.APIContext) {
|
||||
|
||||
opts := &models.SearchRepoOptions{
|
||||
ListOptions: utils.GetListOptions(ctx),
|
||||
Actor: ctx.User,
|
||||
OwnerID: ctx.User.ID,
|
||||
Actor: ctx.Doer,
|
||||
OwnerID: ctx.Doer.ID,
|
||||
Private: ctx.IsSigned,
|
||||
IncludeDescription: true,
|
||||
}
|
||||
@@ -124,11 +119,11 @@ func ListMyRepos(ctx *context.APIContext) {
|
||||
|
||||
results := make([]*api.Repository, len(repos))
|
||||
for i, repo := range repos {
|
||||
if err = repo.GetOwner(db.DefaultContext); err != nil {
|
||||
if err = repo.GetOwner(ctx); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "GetOwner", err)
|
||||
return
|
||||
}
|
||||
accessMode, err := models.AccessLevel(ctx.User, repo)
|
||||
accessMode, err := models.AccessLevel(ctx.Doer, repo)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "AccessLevel", err)
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ func GetUserSettings(ctx *context.APIContext) {
|
||||
// responses:
|
||||
// "200":
|
||||
// "$ref": "#/responses/UserSettings"
|
||||
ctx.JSON(http.StatusOK, convert.User2UserSettings(ctx.User))
|
||||
ctx.JSON(http.StatusOK, convert.User2UserSettings(ctx.Doer))
|
||||
}
|
||||
|
||||
// UpdateUserSettings returns user settings
|
||||
@@ -46,38 +46,38 @@ func UpdateUserSettings(ctx *context.APIContext) {
|
||||
form := web.GetForm(ctx).(*api.UserSettingsOptions)
|
||||
|
||||
if form.FullName != nil {
|
||||
ctx.User.FullName = *form.FullName
|
||||
ctx.Doer.FullName = *form.FullName
|
||||
}
|
||||
if form.Description != nil {
|
||||
ctx.User.Description = *form.Description
|
||||
ctx.Doer.Description = *form.Description
|
||||
}
|
||||
if form.Website != nil {
|
||||
ctx.User.Website = *form.Website
|
||||
ctx.Doer.Website = *form.Website
|
||||
}
|
||||
if form.Location != nil {
|
||||
ctx.User.Location = *form.Location
|
||||
ctx.Doer.Location = *form.Location
|
||||
}
|
||||
if form.Language != nil {
|
||||
ctx.User.Language = *form.Language
|
||||
ctx.Doer.Language = *form.Language
|
||||
}
|
||||
if form.Theme != nil {
|
||||
ctx.User.Theme = *form.Theme
|
||||
ctx.Doer.Theme = *form.Theme
|
||||
}
|
||||
if form.DiffViewStyle != nil {
|
||||
ctx.User.DiffViewStyle = *form.DiffViewStyle
|
||||
ctx.Doer.DiffViewStyle = *form.DiffViewStyle
|
||||
}
|
||||
|
||||
if form.HideEmail != nil {
|
||||
ctx.User.KeepEmailPrivate = *form.HideEmail
|
||||
ctx.Doer.KeepEmailPrivate = *form.HideEmail
|
||||
}
|
||||
if form.HideActivity != nil {
|
||||
ctx.User.KeepActivityPrivate = *form.HideActivity
|
||||
ctx.Doer.KeepActivityPrivate = *form.HideActivity
|
||||
}
|
||||
|
||||
if err := user_model.UpdateUser(ctx.User, false); err != nil {
|
||||
if err := user_model.UpdateUser(ctx.Doer, false); err != nil {
|
||||
ctx.InternalServerError(err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, convert.User2UserSettings(ctx.User))
|
||||
ctx.JSON(http.StatusOK, convert.User2UserSettings(ctx.Doer))
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ import (
|
||||
// getStarredRepos returns the repos that the user with the specified userID has
|
||||
// starred
|
||||
func getStarredRepos(user *user_model.User, private bool, listOptions db.ListOptions) ([]*api.Repository, error) {
|
||||
starredRepos, err := models.GetStarredRepos(user.ID, private, listOptions)
|
||||
starredRepos, err := repo_model.GetStarredRepos(user.ID, private, listOptions)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -62,15 +62,14 @@ func GetStarredRepos(ctx *context.APIContext) {
|
||||
// "200":
|
||||
// "$ref": "#/responses/RepositoryList"
|
||||
|
||||
user := GetUserByParams(ctx)
|
||||
private := user.ID == ctx.User.ID
|
||||
repos, err := getStarredRepos(user, private, utils.GetListOptions(ctx))
|
||||
private := ctx.ContextUser.ID == ctx.Doer.ID
|
||||
repos, err := getStarredRepos(ctx.ContextUser, private, utils.GetListOptions(ctx))
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "getStarredRepos", err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.SetTotalCountHeader(int64(user.NumStars))
|
||||
ctx.SetTotalCountHeader(int64(ctx.ContextUser.NumStars))
|
||||
ctx.JSON(http.StatusOK, &repos)
|
||||
}
|
||||
|
||||
@@ -94,12 +93,12 @@ func GetMyStarredRepos(ctx *context.APIContext) {
|
||||
// "200":
|
||||
// "$ref": "#/responses/RepositoryList"
|
||||
|
||||
repos, err := getStarredRepos(ctx.User, true, utils.GetListOptions(ctx))
|
||||
repos, err := getStarredRepos(ctx.Doer, true, utils.GetListOptions(ctx))
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "getStarredRepos", err)
|
||||
}
|
||||
|
||||
ctx.SetTotalCountHeader(int64(ctx.User.NumStars))
|
||||
ctx.SetTotalCountHeader(int64(ctx.Doer.NumStars))
|
||||
ctx.JSON(http.StatusOK, &repos)
|
||||
}
|
||||
|
||||
@@ -125,7 +124,7 @@ func IsStarring(ctx *context.APIContext) {
|
||||
// "404":
|
||||
// "$ref": "#/responses/notFound"
|
||||
|
||||
if repo_model.IsStaring(ctx.User.ID, ctx.Repo.Repository.ID) {
|
||||
if repo_model.IsStaring(ctx.Doer.ID, ctx.Repo.Repository.ID) {
|
||||
ctx.Status(http.StatusNoContent)
|
||||
} else {
|
||||
ctx.NotFound()
|
||||
@@ -152,7 +151,7 @@ func Star(ctx *context.APIContext) {
|
||||
// "204":
|
||||
// "$ref": "#/responses/empty"
|
||||
|
||||
err := repo_model.StarRepo(ctx.User.ID, ctx.Repo.Repository.ID, true)
|
||||
err := repo_model.StarRepo(ctx.Doer.ID, ctx.Repo.Repository.ID, true)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "StarRepo", err)
|
||||
return
|
||||
@@ -180,7 +179,7 @@ func Unstar(ctx *context.APIContext) {
|
||||
// "204":
|
||||
// "$ref": "#/responses/empty"
|
||||
|
||||
err := repo_model.StarRepo(ctx.User.ID, ctx.Repo.Repository.ID, false)
|
||||
err := repo_model.StarRepo(ctx.Doer.ID, ctx.Repo.Repository.ID, false)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "StarRepo", err)
|
||||
return
|
||||
|
||||
@@ -56,7 +56,7 @@ func Search(ctx *context.APIContext) {
|
||||
listOptions := utils.GetListOptions(ctx)
|
||||
|
||||
users, maxResults, err := user_model.SearchUsers(&user_model.SearchUserOptions{
|
||||
Actor: ctx.User,
|
||||
Actor: ctx.Doer,
|
||||
Keyword: ctx.FormTrim("q"),
|
||||
UID: ctx.FormInt64("uid"),
|
||||
Type: user_model.UserTypeIndividual,
|
||||
@@ -75,7 +75,7 @@ func Search(ctx *context.APIContext) {
|
||||
|
||||
ctx.JSON(http.StatusOK, map[string]interface{}{
|
||||
"ok": true,
|
||||
"data": convert.ToUsers(ctx.User, users),
|
||||
"data": convert.ToUsers(ctx.Doer, users),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -98,18 +98,12 @@ func GetInfo(ctx *context.APIContext) {
|
||||
// "404":
|
||||
// "$ref": "#/responses/notFound"
|
||||
|
||||
u := GetUserByParams(ctx)
|
||||
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
|
||||
if !models.IsUserVisibleToViewer(u, ctx.User) {
|
||||
if !user_model.IsUserVisibleToViewer(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
|
||||
}
|
||||
ctx.JSON(http.StatusOK, convert.ToUser(u, ctx.User))
|
||||
ctx.JSON(http.StatusOK, convert.ToUser(ctx.ContextUser, ctx.Doer))
|
||||
}
|
||||
|
||||
// GetAuthenticatedUser get current user's information
|
||||
@@ -123,7 +117,7 @@ func GetAuthenticatedUser(ctx *context.APIContext) {
|
||||
// "200":
|
||||
// "$ref": "#/responses/User"
|
||||
|
||||
ctx.JSON(http.StatusOK, convert.ToUser(ctx.User, ctx.User))
|
||||
ctx.JSON(http.StatusOK, convert.ToUser(ctx.Doer, ctx.Doer))
|
||||
}
|
||||
|
||||
// GetUserHeatmapData is the handler to get a users heatmap
|
||||
@@ -145,12 +139,7 @@ func GetUserHeatmapData(ctx *context.APIContext) {
|
||||
// "404":
|
||||
// "$ref": "#/responses/notFound"
|
||||
|
||||
user := GetUserByParams(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
|
||||
heatmap, err := models.GetUserHeatmapDataByUser(user, ctx.User)
|
||||
heatmap, err := models.GetUserHeatmapDataByUser(ctx.ContextUser, ctx.Doer)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "GetUserHeatmapDataByUser", err)
|
||||
return
|
||||
|
||||
@@ -19,7 +19,7 @@ import (
|
||||
|
||||
// getWatchedRepos returns the repos that the user with the specified userID is watching
|
||||
func getWatchedRepos(user *user_model.User, private bool, listOptions db.ListOptions) ([]*api.Repository, int64, error) {
|
||||
watchedRepos, total, err := models.GetWatchedRepos(user.ID, private, listOptions)
|
||||
watchedRepos, total, err := repo_model.GetWatchedRepos(user.ID, private, listOptions)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
@@ -60,9 +60,8 @@ func GetWatchedRepos(ctx *context.APIContext) {
|
||||
// "200":
|
||||
// "$ref": "#/responses/RepositoryList"
|
||||
|
||||
user := GetUserByParams(ctx)
|
||||
private := user.ID == ctx.User.ID
|
||||
repos, total, err := getWatchedRepos(user, private, utils.GetListOptions(ctx))
|
||||
private := ctx.ContextUser.ID == ctx.Doer.ID
|
||||
repos, total, err := getWatchedRepos(ctx.ContextUser, private, utils.GetListOptions(ctx))
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "getWatchedRepos", err)
|
||||
}
|
||||
@@ -91,7 +90,7 @@ func GetMyWatchedRepos(ctx *context.APIContext) {
|
||||
// "200":
|
||||
// "$ref": "#/responses/RepositoryList"
|
||||
|
||||
repos, total, err := getWatchedRepos(ctx.User, true, utils.GetListOptions(ctx))
|
||||
repos, total, err := getWatchedRepos(ctx.Doer, true, utils.GetListOptions(ctx))
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "getWatchedRepos", err)
|
||||
}
|
||||
@@ -123,7 +122,7 @@ func IsWatching(ctx *context.APIContext) {
|
||||
// "404":
|
||||
// description: User is not watching this repo or repo do not exist
|
||||
|
||||
if repo_model.IsWatching(ctx.User.ID, ctx.Repo.Repository.ID) {
|
||||
if repo_model.IsWatching(ctx.Doer.ID, ctx.Repo.Repository.ID) {
|
||||
ctx.JSON(http.StatusOK, api.WatchInfo{
|
||||
Subscribed: true,
|
||||
Ignored: false,
|
||||
@@ -157,7 +156,7 @@ func Watch(ctx *context.APIContext) {
|
||||
// "200":
|
||||
// "$ref": "#/responses/WatchInfo"
|
||||
|
||||
err := repo_model.WatchRepo(ctx.User.ID, ctx.Repo.Repository.ID, true)
|
||||
err := repo_model.WatchRepo(ctx.Doer.ID, ctx.Repo.Repository.ID, true)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "WatchRepo", err)
|
||||
return
|
||||
@@ -192,7 +191,7 @@ func Unwatch(ctx *context.APIContext) {
|
||||
// "204":
|
||||
// "$ref": "#/responses/empty"
|
||||
|
||||
err := repo_model.WatchRepo(ctx.User.ID, ctx.Repo.Repository.ID, false)
|
||||
err := repo_model.WatchRepo(ctx.Doer.ID, ctx.Repo.Repository.ID, false)
|
||||
if err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "UnwatchRepo", err)
|
||||
return
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"code.gitea.io/gitea/modules/context"
|
||||
@@ -35,12 +36,7 @@ func ResolveRefOrSha(ctx *context.APIContext, ref string) string {
|
||||
// GetGitRefs return git references based on filter
|
||||
func GetGitRefs(ctx *context.APIContext, filter string) ([]*git.Reference, string, error) {
|
||||
if ctx.Repo.GitRepo == nil {
|
||||
var err error
|
||||
ctx.Repo.GitRepo, err = git.OpenRepositoryCtx(ctx, ctx.Repo.Repository.RepoPath())
|
||||
if err != nil {
|
||||
return nil, "OpenRepository", err
|
||||
}
|
||||
defer ctx.Repo.GitRepo.Close()
|
||||
return nil, "", fmt.Errorf("no open git repo found in context")
|
||||
}
|
||||
if len(filter) > 0 {
|
||||
filter = "refs/" + filter
|
||||
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"code.gitea.io/gitea/models/db"
|
||||
"code.gitea.io/gitea/models/webhook"
|
||||
"code.gitea.io/gitea/modules/context"
|
||||
"code.gitea.io/gitea/modules/convert"
|
||||
@@ -164,7 +163,7 @@ func addHook(ctx *context.APIContext, form *api.CreateHookOption, orgID, repoID
|
||||
if err := w.UpdateEvent(); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "UpdateEvent", err)
|
||||
return nil, false
|
||||
} else if err := webhook.CreateWebhook(db.DefaultContext, w); err != nil {
|
||||
} else if err := webhook.CreateWebhook(ctx, w); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "CreateWebhook", err)
|
||||
return nil, false
|
||||
}
|
||||
@@ -246,18 +245,29 @@ func editHook(ctx *context.APIContext, form *api.EditHookOption, w *webhook.Webh
|
||||
w.ChooseEvents = true
|
||||
w.Create = util.IsStringInSlice(string(webhook.HookEventCreate), form.Events, true)
|
||||
w.Push = util.IsStringInSlice(string(webhook.HookEventPush), form.Events, true)
|
||||
w.PullRequest = util.IsStringInSlice(string(webhook.HookEventPullRequest), form.Events, true)
|
||||
w.Create = util.IsStringInSlice(string(webhook.HookEventCreate), form.Events, true)
|
||||
w.Delete = util.IsStringInSlice(string(webhook.HookEventDelete), form.Events, true)
|
||||
w.Fork = util.IsStringInSlice(string(webhook.HookEventFork), form.Events, true)
|
||||
w.Issues = util.IsStringInSlice(string(webhook.HookEventIssues), form.Events, true)
|
||||
w.IssueComment = util.IsStringInSlice(string(webhook.HookEventIssueComment), form.Events, true)
|
||||
w.Push = util.IsStringInSlice(string(webhook.HookEventPush), form.Events, true)
|
||||
w.PullRequest = util.IsStringInSlice(string(webhook.HookEventPullRequest), form.Events, true)
|
||||
w.Repository = util.IsStringInSlice(string(webhook.HookEventRepository), form.Events, true)
|
||||
w.Release = util.IsStringInSlice(string(webhook.HookEventRelease), form.Events, true)
|
||||
w.BranchFilter = form.BranchFilter
|
||||
|
||||
// Issues
|
||||
w.Issues = issuesHook(form.Events, "issues_only")
|
||||
w.IssueAssign = issuesHook(form.Events, string(webhook.HookEventIssueAssign))
|
||||
w.IssueLabel = issuesHook(form.Events, string(webhook.HookEventIssueLabel))
|
||||
w.IssueMilestone = issuesHook(form.Events, string(webhook.HookEventIssueMilestone))
|
||||
w.IssueComment = issuesHook(form.Events, string(webhook.HookEventIssueComment))
|
||||
|
||||
// Pull requests
|
||||
w.PullRequest = pullHook(form.Events, "pull_request_only")
|
||||
w.PullRequestAssign = pullHook(form.Events, string(webhook.HookEventPullRequestAssign))
|
||||
w.PullRequestLabel = pullHook(form.Events, string(webhook.HookEventPullRequestLabel))
|
||||
w.PullRequestMilestone = pullHook(form.Events, string(webhook.HookEventPullRequestMilestone))
|
||||
w.PullRequestComment = pullHook(form.Events, string(webhook.HookEventPullRequestComment))
|
||||
w.PullRequestReview = pullHook(form.Events, "pull_request_review")
|
||||
w.PullRequestSync = pullHook(form.Events, string(webhook.HookEventPullRequestSync))
|
||||
|
||||
if err := w.UpdateEvent(); err != nil {
|
||||
ctx.Error(http.StatusInternalServerError, "UpdateEvent", err)
|
||||
return false
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
// Copyright 2017 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 utils
|
||||
|
||||
import (
|
||||
"code.gitea.io/gitea/models/db"
|
||||
"code.gitea.io/gitea/modules/context"
|
||||
"code.gitea.io/gitea/modules/convert"
|
||||
)
|
||||
|
||||
// GetListOptions returns list options using the page and limit parameters
|
||||
func GetListOptions(ctx *context.APIContext) db.ListOptions {
|
||||
return db.ListOptions{
|
||||
Page: ctx.FormInt("page"),
|
||||
PageSize: convert.ToCorrectPageSize(ctx.FormInt("limit")),
|
||||
}
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
// Copyright 2017 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 utils
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"code.gitea.io/gitea/models/db"
|
||||
"code.gitea.io/gitea/modules/context"
|
||||
"code.gitea.io/gitea/modules/convert"
|
||||
)
|
||||
|
||||
// GetQueryBeforeSince return parsed time (unix format) from URL query's before and since
|
||||
func GetQueryBeforeSince(ctx *context.APIContext) (before, since int64, err error) {
|
||||
qCreatedBefore, err := prepareQueryArg(ctx, "before")
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
|
||||
qCreatedSince, err := prepareQueryArg(ctx, "since")
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
|
||||
before, err = parseTime(qCreatedBefore)
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
|
||||
since, err = parseTime(qCreatedSince)
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
return before, since, nil
|
||||
}
|
||||
|
||||
// parseTime parse time and return unix timestamp
|
||||
func parseTime(value string) (int64, error) {
|
||||
if len(value) != 0 {
|
||||
t, err := time.Parse(time.RFC3339, value)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if !t.IsZero() {
|
||||
return t.Unix(), nil
|
||||
}
|
||||
}
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
// prepareQueryArg unescape and trim a query arg
|
||||
func prepareQueryArg(ctx *context.APIContext, name string) (value string, err error) {
|
||||
value, err = url.PathUnescape(ctx.FormString(name))
|
||||
value = strings.TrimSpace(value)
|
||||
return
|
||||
}
|
||||
|
||||
// GetListOptions returns list options using the page and limit parameters
|
||||
func GetListOptions(ctx *context.APIContext) db.ListOptions {
|
||||
return db.ListOptions{
|
||||
Page: ctx.FormInt("page"),
|
||||
PageSize: convert.ToCorrectPageSize(ctx.FormInt("limit")),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user