初始提交: Gitea 项目代码
This commit is contained in:
@@ -0,0 +1,191 @@
|
||||
// Copyright 2025 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package setting
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"gitea.dev/models/actions"
|
||||
repo_model "gitea.dev/models/repo"
|
||||
unit_model "gitea.dev/models/unit"
|
||||
user_model "gitea.dev/models/user"
|
||||
"gitea.dev/modules/templates"
|
||||
"gitea.dev/modules/util"
|
||||
shared_actions "gitea.dev/routers/web/shared/actions"
|
||||
"gitea.dev/services/context"
|
||||
repo_service "gitea.dev/services/repository"
|
||||
)
|
||||
|
||||
const tplRepoActionsGeneralSettings templates.TplName = "repo/settings/actions"
|
||||
|
||||
func ActionsGeneralSettings(ctx *context.Context) {
|
||||
ctx.Data["Title"] = ctx.Tr("actions.general")
|
||||
ctx.Data["PageType"] = "general"
|
||||
ctx.Data["PageIsActionsSettingsGeneral"] = true
|
||||
|
||||
actionsUnit, err := ctx.Repo.Repository.GetUnit(ctx, unit_model.TypeActions)
|
||||
if err != nil && !repo_model.IsErrUnitTypeNotExist(err) {
|
||||
ctx.ServerError("GetUnit", err)
|
||||
return
|
||||
}
|
||||
if actionsUnit == nil { // no actions unit
|
||||
ctx.HTML(http.StatusOK, tplRepoActionsGeneralSettings)
|
||||
return
|
||||
}
|
||||
|
||||
actionsCfg := actionsUnit.ActionsConfig()
|
||||
|
||||
// Token permission settings
|
||||
ctx.Data["TokenPermissionModePermissive"] = repo_model.ActionsTokenPermissionModePermissive
|
||||
ctx.Data["TokenPermissionModeRestricted"] = repo_model.ActionsTokenPermissionModeRestricted
|
||||
|
||||
// Follow owner config (only for repos in orgs)
|
||||
ctx.Data["OverrideOwnerConfig"] = actionsCfg.OverrideOwnerConfig
|
||||
if actionsCfg.OverrideOwnerConfig {
|
||||
ctx.Data["MaxTokenPermissions"] = actionsCfg.GetMaxTokenPermissions()
|
||||
ctx.Data["TokenPermissionMode"] = actionsCfg.TokenPermissionMode
|
||||
ctx.Data["EnableMaxTokenPermissions"] = actionsCfg.MaxTokenPermissions != nil
|
||||
} else {
|
||||
ownerActionsConfig, err := actions.GetOwnerActionsConfig(ctx, ctx.Repo.Repository.OwnerID)
|
||||
if err != nil {
|
||||
ctx.ServerError("GetOwnerActionsConfig", err)
|
||||
return
|
||||
}
|
||||
ctx.Data["MaxTokenPermissions"] = ownerActionsConfig.GetMaxTokenPermissions()
|
||||
ctx.Data["TokenPermissionMode"] = ownerActionsConfig.TokenPermissionMode
|
||||
ctx.Data["EnableMaxTokenPermissions"] = ownerActionsConfig.MaxTokenPermissions != nil
|
||||
}
|
||||
|
||||
if ctx.Repo.Repository.IsPrivate {
|
||||
collaborativeOwnerIDs := actionsCfg.CollaborativeOwnerIDs
|
||||
collaborativeOwners, err := user_model.GetUsersByIDs(ctx, collaborativeOwnerIDs)
|
||||
if err != nil {
|
||||
ctx.ServerError("GetUsersByIDs", err)
|
||||
return
|
||||
}
|
||||
ctx.Data["CollaborativeOwners"] = collaborativeOwners
|
||||
}
|
||||
|
||||
ctx.HTML(http.StatusOK, tplRepoActionsGeneralSettings)
|
||||
}
|
||||
|
||||
func ActionsUnitPost(ctx *context.Context) {
|
||||
redirectURL := ctx.Repo.RepoLink + "/settings/actions/general"
|
||||
enableActionsUnit := ctx.FormBool("enable_actions")
|
||||
repo := ctx.Repo.Repository
|
||||
|
||||
var err error
|
||||
if enableActionsUnit && !unit_model.TypeActions.UnitGlobalDisabled() {
|
||||
err = repo_service.UpdateRepositoryUnits(ctx, repo, []repo_model.RepoUnit{newRepoUnit(repo, unit_model.TypeActions, nil)}, nil)
|
||||
} else if !unit_model.TypeActions.UnitGlobalDisabled() {
|
||||
err = repo_service.UpdateRepositoryUnits(ctx, repo, nil, []unit_model.Type{unit_model.TypeActions})
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
ctx.ServerError("UpdateRepositoryUnits", err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success"))
|
||||
ctx.Redirect(redirectURL)
|
||||
}
|
||||
|
||||
func AddCollaborativeOwner(ctx *context.Context) {
|
||||
collUser, err := user_model.GetUserByName(ctx, ctx.FormString("collaborative_owner"))
|
||||
if err != nil {
|
||||
if errors.Is(err, util.ErrNotExist) {
|
||||
ctx.JSONError(ctx.Tr("form.user_not_exist"))
|
||||
} else {
|
||||
ctx.ServerError("GetUserByName", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
actionsUnit, err := ctx.Repo.Repository.GetUnit(ctx, unit_model.TypeActions)
|
||||
if err != nil {
|
||||
ctx.ServerError("GetUnit", err)
|
||||
return
|
||||
}
|
||||
actionsCfg := actionsUnit.ActionsConfig()
|
||||
actionsCfg.AddCollaborativeOwner(collUser.ID)
|
||||
if err := repo_model.UpdateRepoUnitConfig(ctx, actionsUnit); err != nil {
|
||||
ctx.ServerError("UpdateRepoUnitConfig", err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSONOK()
|
||||
}
|
||||
|
||||
func DeleteCollaborativeOwner(ctx *context.Context) {
|
||||
ownerID := ctx.FormInt64("id")
|
||||
|
||||
actionsUnit, err := ctx.Repo.Repository.GetUnit(ctx, unit_model.TypeActions)
|
||||
if err != nil {
|
||||
ctx.ServerError("GetUnit", err)
|
||||
return
|
||||
}
|
||||
actionsCfg := actionsUnit.ActionsConfig()
|
||||
if !actionsCfg.IsCollaborativeOwner(ownerID) {
|
||||
ctx.Flash.Error(ctx.Tr("actions.general.collaborative_owner_not_exist"))
|
||||
ctx.JSONErrorNotFound()
|
||||
return
|
||||
}
|
||||
actionsCfg.RemoveCollaborativeOwner(ownerID)
|
||||
if err := repo_model.UpdateRepoUnitConfig(ctx, actionsUnit); err != nil {
|
||||
ctx.ServerError("UpdateRepoUnitConfig", err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSONOK()
|
||||
}
|
||||
|
||||
// UpdateTokenPermissions updates the token permission settings for the repository
|
||||
func UpdateTokenPermissions(ctx *context.Context) {
|
||||
redirectURL := ctx.Repo.RepoLink + "/settings/actions/general"
|
||||
|
||||
actionsUnit, err := ctx.Repo.Repository.GetUnit(ctx, unit_model.TypeActions)
|
||||
if err != nil {
|
||||
ctx.ServerError("GetUnit", err)
|
||||
return
|
||||
}
|
||||
|
||||
actionsCfg := actionsUnit.ActionsConfig()
|
||||
|
||||
// Update Override Owner Config (for repos in orgs)
|
||||
// If checked, it means we WANT to override (opt-out of following)
|
||||
actionsCfg.OverrideOwnerConfig = ctx.FormBool("override_owner_config")
|
||||
|
||||
// Update permission mode (only if overriding owner config)
|
||||
shouldUpdate := actionsCfg.OverrideOwnerConfig
|
||||
|
||||
if shouldUpdate {
|
||||
permissionMode, permissionModeValid := util.EnumValue(repo_model.ActionsTokenPermissionMode(ctx.FormString("token_permission_mode")))
|
||||
if !permissionModeValid {
|
||||
ctx.Flash.Error("Invalid token permission mode")
|
||||
ctx.Redirect(redirectURL)
|
||||
return
|
||||
}
|
||||
actionsCfg.TokenPermissionMode = permissionMode
|
||||
}
|
||||
|
||||
// Update Maximum Permissions (radio buttons: none/read/write)
|
||||
enableMaxPermissions := ctx.FormBool("enable_max_permissions")
|
||||
if shouldUpdate {
|
||||
if enableMaxPermissions {
|
||||
actionsCfg.MaxTokenPermissions = shared_actions.ParseMaxTokenPermissions(ctx)
|
||||
} else {
|
||||
// If not enabled, ensure any sent permissions are ignored and set to nil
|
||||
actionsCfg.MaxTokenPermissions = nil
|
||||
}
|
||||
}
|
||||
|
||||
if err := repo_model.UpdateRepoUnitConfig(ctx, actionsUnit); err != nil {
|
||||
ctx.ServerError("UpdateRepoUnitConfig", err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success"))
|
||||
ctx.Redirect(redirectURL)
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
// Copyright 2023 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package setting
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"gitea.dev/modules/log"
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/modules/typesniffer"
|
||||
"gitea.dev/modules/web"
|
||||
"gitea.dev/services/context"
|
||||
"gitea.dev/services/forms"
|
||||
repo_service "gitea.dev/services/repository"
|
||||
)
|
||||
|
||||
// UpdateAvatarSetting update repo's avatar
|
||||
func UpdateAvatarSetting(ctx *context.Context, form forms.AvatarForm) error {
|
||||
ctxRepo := ctx.Repo.Repository
|
||||
|
||||
if form.Avatar == nil {
|
||||
// No avatar is uploaded and we not removing it here.
|
||||
// No random avatar generated here.
|
||||
// Just exit, no action.
|
||||
if ctxRepo.CustomAvatarRelativePath() == "" {
|
||||
log.Trace("No avatar was uploaded for repo: %d. Default icon will appear instead.", ctxRepo.ID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
r, err := form.Avatar.Open()
|
||||
if err != nil {
|
||||
return fmt.Errorf("Avatar.Open: %w", err)
|
||||
}
|
||||
defer r.Close()
|
||||
|
||||
if form.Avatar.Size > setting.Avatar.MaxFileSize {
|
||||
return errors.New(ctx.Locale.TrString("settings.uploaded_avatar_is_too_big", form.Avatar.Size/1024, setting.Avatar.MaxFileSize/1024))
|
||||
}
|
||||
|
||||
data, err := io.ReadAll(r)
|
||||
if err != nil {
|
||||
return fmt.Errorf("io.ReadAll: %w", err)
|
||||
}
|
||||
st := typesniffer.DetectContentType(data)
|
||||
if !(st.IsImage() && !st.IsSvgImage()) {
|
||||
return errors.New(ctx.Locale.TrString("settings.uploaded_avatar_not_a_image"))
|
||||
}
|
||||
if err = repo_service.UploadAvatar(ctx, ctxRepo, data); err != nil {
|
||||
return fmt.Errorf("UploadAvatar: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SettingsAvatar save new POSTed repository avatar
|
||||
func SettingsAvatar(ctx *context.Context) {
|
||||
form := web.GetForm(ctx).(*forms.AvatarForm)
|
||||
form.Source = forms.AvatarLocal
|
||||
if err := UpdateAvatarSetting(ctx, *form); err != nil {
|
||||
ctx.Flash.Error(err.Error())
|
||||
} else {
|
||||
ctx.Flash.Success(ctx.Tr("repo.settings.update_avatar_success"))
|
||||
}
|
||||
ctx.Redirect(ctx.Repo.RepoLink + "/settings")
|
||||
}
|
||||
|
||||
// SettingsDeleteAvatar delete repository avatar
|
||||
func SettingsDeleteAvatar(ctx *context.Context) {
|
||||
if err := repo_service.DeleteAvatar(ctx, ctx.Repo.Repository); err != nil {
|
||||
ctx.Flash.Error(fmt.Sprintf("DeleteAvatar: %v", err))
|
||||
}
|
||||
ctx.JSONRedirect(ctx.Repo.RepoLink + "/settings")
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
// Copyright 2023 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package setting
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"gitea.dev/models/organization"
|
||||
"gitea.dev/models/perm"
|
||||
repo_model "gitea.dev/models/repo"
|
||||
unit_model "gitea.dev/models/unit"
|
||||
user_model "gitea.dev/models/user"
|
||||
"gitea.dev/modules/log"
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/services/context"
|
||||
"gitea.dev/services/mailer"
|
||||
repo_service "gitea.dev/services/repository"
|
||||
)
|
||||
|
||||
// Collaboration render a repository's collaboration page
|
||||
func Collaboration(ctx *context.Context) {
|
||||
ctx.Data["Title"] = ctx.Tr("repo.settings.collaboration")
|
||||
ctx.Data["PageIsSettingsCollaboration"] = true
|
||||
|
||||
users, _, err := repo_model.GetCollaborators(ctx, &repo_model.FindCollaborationOptions{RepoID: ctx.Repo.Repository.ID})
|
||||
if err != nil {
|
||||
ctx.ServerError("GetCollaborators", err)
|
||||
return
|
||||
}
|
||||
ctx.Data["Collaborators"] = users
|
||||
|
||||
teams, err := organization.GetRepoTeams(ctx, ctx.Repo.Repository.OwnerID, ctx.Repo.Repository.ID)
|
||||
if err != nil {
|
||||
ctx.ServerError("GetRepoTeams", err)
|
||||
return
|
||||
}
|
||||
ctx.Data["Teams"] = teams
|
||||
ctx.Data["Repo"] = ctx.Repo.Repository
|
||||
ctx.Data["OrgID"] = ctx.Repo.Repository.OwnerID
|
||||
ctx.Data["OrgName"] = ctx.Repo.Repository.OwnerName
|
||||
ctx.Data["Org"] = ctx.Repo.Repository.Owner
|
||||
ctx.Data["Units"] = unit_model.Units
|
||||
|
||||
ctx.HTML(http.StatusOK, tplCollaboration)
|
||||
}
|
||||
|
||||
// CollaborationPost response for actions for a collaboration of a repository
|
||||
func CollaborationPost(ctx *context.Context) {
|
||||
name := strings.ToLower(ctx.FormString("collaborator"))
|
||||
if len(name) == 0 || ctx.Repo.Owner.LowerName == name {
|
||||
ctx.Redirect(setting.AppSubURL + ctx.Req.URL.EscapedPath())
|
||||
return
|
||||
}
|
||||
|
||||
u, err := user_model.GetUserByName(ctx, name)
|
||||
if err != nil {
|
||||
if user_model.IsErrUserNotExist(err) {
|
||||
ctx.Flash.Error(ctx.Tr("form.user_not_exist"))
|
||||
ctx.Redirect(setting.AppSubURL + ctx.Req.URL.EscapedPath())
|
||||
} else {
|
||||
ctx.ServerError("GetUserByName", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if !u.IsActive {
|
||||
ctx.Flash.Error(ctx.Tr("repo.settings.add_collaborator_inactive_user"))
|
||||
ctx.Redirect(setting.AppSubURL + ctx.Req.URL.EscapedPath())
|
||||
return
|
||||
}
|
||||
|
||||
// Organization is not allowed to be added as a collaborator.
|
||||
if u.IsOrganization() {
|
||||
ctx.Flash.Error(ctx.Tr("repo.settings.org_not_allowed_to_be_collaborator"))
|
||||
ctx.Redirect(setting.AppSubURL + ctx.Req.URL.EscapedPath())
|
||||
return
|
||||
}
|
||||
|
||||
if got, err := repo_model.IsCollaborator(ctx, ctx.Repo.Repository.ID, u.ID); err == nil && got {
|
||||
ctx.Flash.Error(ctx.Tr("repo.settings.add_collaborator_duplicate"))
|
||||
ctx.Redirect(ctx.Repo.RepoLink + "/settings/collaboration")
|
||||
return
|
||||
}
|
||||
|
||||
// find the owner team of the organization the repo belongs too and
|
||||
// check if the user we're trying to add is an owner.
|
||||
if ctx.Repo.Repository.Owner.IsOrganization() {
|
||||
if isOwner, err := organization.IsOrganizationOwner(ctx, ctx.Repo.Repository.Owner.ID, u.ID); err != nil {
|
||||
ctx.ServerError("IsOrganizationOwner", err)
|
||||
return
|
||||
} else if isOwner {
|
||||
ctx.Flash.Error(ctx.Tr("repo.settings.add_collaborator_owner"))
|
||||
ctx.Redirect(setting.AppSubURL + ctx.Req.URL.EscapedPath())
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if err = repo_service.AddOrUpdateCollaborator(ctx, ctx.Repo.Repository, u, perm.AccessModeWrite); err != nil {
|
||||
if errors.Is(err, user_model.ErrBlockedUser) {
|
||||
ctx.Flash.Error(ctx.Tr("repo.settings.add_collaborator.blocked_user"))
|
||||
ctx.Redirect(ctx.Repo.RepoLink + "/settings/collaboration")
|
||||
} else {
|
||||
ctx.ServerError("AddOrUpdateCollaborator", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if setting.Service.EnableNotifyMail {
|
||||
mailer.SendCollaboratorMail(u, ctx.Doer, ctx.Repo.Repository)
|
||||
}
|
||||
|
||||
ctx.Flash.Success(ctx.Tr("repo.settings.add_collaborator_success"))
|
||||
ctx.Redirect(setting.AppSubURL + ctx.Req.URL.EscapedPath())
|
||||
}
|
||||
|
||||
// ChangeCollaborationAccessMode response for changing access of a collaboration
|
||||
func ChangeCollaborationAccessMode(ctx *context.Context) {
|
||||
if err := repo_model.ChangeCollaborationAccessMode(
|
||||
ctx,
|
||||
ctx.Repo.Repository,
|
||||
ctx.FormInt64("uid"),
|
||||
perm.AccessMode(ctx.FormInt("mode"))); err != nil {
|
||||
log.Error("ChangeCollaborationAccessMode: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// DeleteCollaboration delete a collaboration for a repository
|
||||
func DeleteCollaboration(ctx *context.Context) {
|
||||
if collaborator, err := user_model.GetUserByID(ctx, ctx.FormInt64("id")); err != nil {
|
||||
if user_model.IsErrUserNotExist(err) {
|
||||
ctx.Flash.Error(ctx.Tr("form.user_not_exist"))
|
||||
} else {
|
||||
ctx.ServerError("GetUserByName", err)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
if err := repo_service.DeleteCollaboration(ctx, ctx.Repo.Repository, collaborator); err != nil {
|
||||
ctx.Flash.Error("DeleteCollaboration: " + err.Error())
|
||||
} else {
|
||||
ctx.Flash.Success(ctx.Tr("repo.settings.remove_collaborator_success"))
|
||||
}
|
||||
}
|
||||
|
||||
ctx.JSONRedirect(ctx.Repo.RepoLink + "/settings/collaboration")
|
||||
}
|
||||
|
||||
// AddTeamPost response for adding a team to a repository
|
||||
func AddTeamPost(ctx *context.Context) {
|
||||
if !ctx.Repo.Owner.RepoAdminChangeTeamAccess && !ctx.Repo.Permission.IsOwner() {
|
||||
ctx.Flash.Error(ctx.Tr("repo.settings.change_team_access_not_allowed"))
|
||||
ctx.Redirect(ctx.Repo.RepoLink + "/settings/collaboration")
|
||||
return
|
||||
}
|
||||
|
||||
name := strings.ToLower(ctx.FormString("team"))
|
||||
if len(name) == 0 {
|
||||
ctx.Redirect(ctx.Repo.RepoLink + "/settings/collaboration")
|
||||
return
|
||||
}
|
||||
|
||||
team, err := organization.OrgFromUser(ctx.Repo.Owner).GetTeam(ctx, name)
|
||||
if err != nil {
|
||||
if organization.IsErrTeamNotExist(err) {
|
||||
ctx.Flash.Error(ctx.Tr("form.team_not_exist"))
|
||||
ctx.Redirect(ctx.Repo.RepoLink + "/settings/collaboration")
|
||||
} else {
|
||||
ctx.ServerError("GetTeam", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if team.OrgID != ctx.Repo.Repository.OwnerID {
|
||||
ctx.Flash.Error(ctx.Tr("repo.settings.team_not_in_organization"))
|
||||
ctx.Redirect(ctx.Repo.RepoLink + "/settings/collaboration")
|
||||
return
|
||||
}
|
||||
|
||||
if organization.HasTeamRepo(ctx, ctx.Repo.Repository.OwnerID, team.ID, ctx.Repo.Repository.ID) {
|
||||
ctx.Flash.Error(ctx.Tr("repo.settings.add_team_duplicate"))
|
||||
ctx.Redirect(ctx.Repo.RepoLink + "/settings/collaboration")
|
||||
return
|
||||
}
|
||||
|
||||
if err = repo_service.TeamAddRepository(ctx, team, ctx.Repo.Repository); err != nil {
|
||||
ctx.ServerError("TeamAddRepository", err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Flash.Success(ctx.Tr("repo.settings.add_team_success"))
|
||||
ctx.Redirect(ctx.Repo.RepoLink + "/settings/collaboration")
|
||||
}
|
||||
|
||||
// DeleteTeam response for deleting a team from a repository
|
||||
func DeleteTeam(ctx *context.Context) {
|
||||
if !ctx.Repo.Owner.RepoAdminChangeTeamAccess && !ctx.Repo.Permission.IsOwner() {
|
||||
ctx.Flash.Error(ctx.Tr("repo.settings.change_team_access_not_allowed"))
|
||||
ctx.Redirect(ctx.Repo.RepoLink + "/settings/collaboration")
|
||||
return
|
||||
}
|
||||
|
||||
team, err := organization.GetTeamByID(ctx, ctx.FormInt64("id"))
|
||||
if err != nil {
|
||||
ctx.ServerError("GetTeamByID", err)
|
||||
return
|
||||
}
|
||||
|
||||
if err = repo_service.RemoveRepositoryFromTeam(ctx, team, ctx.Repo.Repository.ID); err != nil {
|
||||
ctx.ServerError("team.RemoveRepositories", err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Flash.Success(ctx.Tr("repo.settings.remove_team_success"))
|
||||
ctx.JSONRedirect(ctx.Repo.RepoLink + "/settings/collaboration")
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
// Copyright 2023 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package setting
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
git_model "gitea.dev/models/git"
|
||||
"gitea.dev/modules/log"
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/routers/web/repo"
|
||||
"gitea.dev/services/context"
|
||||
repo_service "gitea.dev/services/repository"
|
||||
)
|
||||
|
||||
// SetDefaultBranchPost set default branch
|
||||
func SetDefaultBranchPost(ctx *context.Context) {
|
||||
ctx.Data["Title"] = ctx.Tr("repo.settings.branches.update_default_branch")
|
||||
ctx.Data["PageIsSettingsBranches"] = true
|
||||
|
||||
repo.PrepareBranchList(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
|
||||
repo := ctx.Repo.Repository
|
||||
|
||||
switch ctx.FormString("action") {
|
||||
case "default_branch":
|
||||
if ctx.HasError() {
|
||||
ctx.HTML(http.StatusOK, tplBranches)
|
||||
return
|
||||
}
|
||||
|
||||
branch := ctx.FormString("branch")
|
||||
if err := repo_service.SetRepoDefaultBranch(ctx, ctx.Repo.Repository, branch); err != nil {
|
||||
switch {
|
||||
case git_model.IsErrBranchNotExist(err):
|
||||
ctx.Status(http.StatusNotFound)
|
||||
default:
|
||||
ctx.ServerError("SetDefaultBranch", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
log.Trace("Repository basic settings updated: %s/%s", ctx.Repo.Owner.Name, repo.Name)
|
||||
|
||||
ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success"))
|
||||
ctx.Redirect(setting.AppSubURL + ctx.Req.URL.EscapedPath())
|
||||
default:
|
||||
ctx.NotFound(nil)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
// Copyright 2023 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package setting
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
asymkey_model "gitea.dev/models/asymkey"
|
||||
"gitea.dev/models/db"
|
||||
"gitea.dev/modules/log"
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/modules/web"
|
||||
asymkey_service "gitea.dev/services/asymkey"
|
||||
"gitea.dev/services/context"
|
||||
"gitea.dev/services/forms"
|
||||
)
|
||||
|
||||
// DeployKeys render the deploy keys list of a repository page
|
||||
func DeployKeys(ctx *context.Context) {
|
||||
ctx.Data["Title"] = ctx.Tr("repo.settings.deploy_keys") + " / " + ctx.Tr("secrets.secrets")
|
||||
ctx.Data["PageIsSettingsKeys"] = true
|
||||
ctx.Data["DisableSSH"] = setting.SSH.Disabled
|
||||
|
||||
keys, err := db.Find[asymkey_model.DeployKey](ctx, asymkey_model.ListDeployKeysOptions{RepoID: ctx.Repo.Repository.ID})
|
||||
if err != nil {
|
||||
ctx.ServerError("ListDeployKeys", err)
|
||||
return
|
||||
}
|
||||
ctx.Data["Deploykeys"] = keys
|
||||
|
||||
ctx.HTML(http.StatusOK, tplDeployKeys)
|
||||
}
|
||||
|
||||
// DeployKeysPost response for adding a deploy key of a repository
|
||||
func DeployKeysPost(ctx *context.Context) {
|
||||
form := web.GetForm(ctx).(*forms.AddKeyForm)
|
||||
ctx.Data["Title"] = ctx.Tr("repo.settings.deploy_keys")
|
||||
ctx.Data["PageIsSettingsKeys"] = true
|
||||
ctx.Data["DisableSSH"] = setting.SSH.Disabled
|
||||
|
||||
keys, err := db.Find[asymkey_model.DeployKey](ctx, asymkey_model.ListDeployKeysOptions{RepoID: ctx.Repo.Repository.ID})
|
||||
if err != nil {
|
||||
ctx.ServerError("ListDeployKeys", err)
|
||||
return
|
||||
}
|
||||
ctx.Data["Deploykeys"] = keys
|
||||
|
||||
if ctx.HasError() {
|
||||
ctx.HTML(http.StatusOK, tplDeployKeys)
|
||||
return
|
||||
}
|
||||
|
||||
content, err := asymkey_model.CheckPublicKeyString(form.Content)
|
||||
if err != nil {
|
||||
if db.IsErrSSHDisabled(err) {
|
||||
ctx.Flash.Info(ctx.Tr("settings.ssh_disabled"))
|
||||
} else if asymkey_model.IsErrKeyUnableVerify(err) {
|
||||
ctx.Flash.Info(ctx.Tr("form.unable_verify_ssh_key"))
|
||||
} else if err == asymkey_model.ErrKeyIsPrivate {
|
||||
ctx.Data["HasError"] = true
|
||||
ctx.Data["Err_Content"] = true
|
||||
ctx.Flash.Error(ctx.Tr("form.must_use_public_key"))
|
||||
} else {
|
||||
ctx.Data["HasError"] = true
|
||||
ctx.Data["Err_Content"] = true
|
||||
ctx.Flash.Error(ctx.Tr("form.invalid_ssh_key", err.Error()))
|
||||
}
|
||||
ctx.Redirect(ctx.Repo.RepoLink + "/settings/keys")
|
||||
return
|
||||
}
|
||||
|
||||
key, err := asymkey_model.AddDeployKey(ctx, ctx.Repo.Repository.ID, form.Title, content, !form.IsWritable)
|
||||
if err != nil {
|
||||
ctx.Data["HasError"] = true
|
||||
switch {
|
||||
case asymkey_model.IsErrDeployKeyAlreadyExist(err):
|
||||
ctx.Data["Err_Content"] = true
|
||||
ctx.RenderWithErrDeprecated(ctx.Tr("repo.settings.key_been_used"), tplDeployKeys, &form)
|
||||
case asymkey_model.IsErrKeyAlreadyExist(err):
|
||||
ctx.Data["Err_Content"] = true
|
||||
ctx.RenderWithErrDeprecated(ctx.Tr("settings.ssh_key_been_used"), tplDeployKeys, &form)
|
||||
case asymkey_model.IsErrKeyNameAlreadyUsed(err):
|
||||
ctx.Data["Err_Title"] = true
|
||||
ctx.RenderWithErrDeprecated(ctx.Tr("repo.settings.key_name_used"), tplDeployKeys, &form)
|
||||
case asymkey_model.IsErrDeployKeyNameAlreadyUsed(err):
|
||||
ctx.Data["Err_Title"] = true
|
||||
ctx.RenderWithErrDeprecated(ctx.Tr("repo.settings.key_name_used"), tplDeployKeys, &form)
|
||||
default:
|
||||
ctx.ServerError("AddDeployKey", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
log.Trace("Deploy key added: %d", ctx.Repo.Repository.ID)
|
||||
ctx.Flash.Success(ctx.Tr("repo.settings.add_key_success", key.Name))
|
||||
ctx.Redirect(ctx.Repo.RepoLink + "/settings/keys")
|
||||
}
|
||||
|
||||
// DeleteDeployKey response for deleting a deploy key
|
||||
func DeleteDeployKey(ctx *context.Context) {
|
||||
if err := asymkey_service.DeleteDeployKey(ctx, ctx.Repo.Repository, ctx.FormInt64("id")); err != nil {
|
||||
ctx.Flash.Error("DeleteDeployKey: " + err.Error())
|
||||
} else {
|
||||
ctx.Flash.Success(ctx.Tr("repo.settings.deploy_key_deletion_success"))
|
||||
}
|
||||
|
||||
ctx.JSONRedirect(ctx.Repo.RepoLink + "/settings/keys")
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
// Copyright 2023 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package setting
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"gitea.dev/modules/git"
|
||||
"gitea.dev/routers/web/repo"
|
||||
"gitea.dev/services/context"
|
||||
)
|
||||
|
||||
// GitHooks hooks of a repository
|
||||
func GitHooks(ctx *context.Context) {
|
||||
ctx.Data["Title"] = ctx.Tr("repo.settings.githooks")
|
||||
ctx.Data["PageIsSettingsGitHooks"] = true
|
||||
|
||||
hooks, err := ctx.Repo.GitRepo.Hooks()
|
||||
if err != nil {
|
||||
ctx.ServerError("Hooks", err)
|
||||
return
|
||||
}
|
||||
ctx.Data["Hooks"] = hooks
|
||||
|
||||
ctx.HTML(http.StatusOK, tplGithooks)
|
||||
}
|
||||
|
||||
// GitHooksEdit render for editing a hook of repository page
|
||||
func GitHooksEdit(ctx *context.Context) {
|
||||
ctx.Data["Title"] = ctx.Tr("repo.settings.githooks")
|
||||
ctx.Data["PageIsSettingsGitHooks"] = true
|
||||
|
||||
name := ctx.PathParam("name")
|
||||
hook, err := ctx.Repo.GitRepo.GetHook(name)
|
||||
if err != nil {
|
||||
if err == git.ErrNotValidHook {
|
||||
ctx.NotFound(err)
|
||||
} else {
|
||||
ctx.ServerError("GetHook", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
ctx.Data["Hook"] = hook
|
||||
ctx.Data["CodeEditorConfig"] = repo.CodeEditorConfig{Filename: name + ".sh", IndentStyle: "tab", TabWidth: 4}
|
||||
ctx.HTML(http.StatusOK, tplGithookEdit)
|
||||
}
|
||||
|
||||
// GitHooksEditPost response for editing a git hook of a repository
|
||||
func GitHooksEditPost(ctx *context.Context) {
|
||||
name := ctx.PathParam("name")
|
||||
hook, err := ctx.Repo.GitRepo.GetHook(name)
|
||||
if err != nil {
|
||||
if err == git.ErrNotValidHook {
|
||||
ctx.NotFound(err)
|
||||
} else {
|
||||
ctx.ServerError("GetHook", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
hook.Content = ctx.FormString("content")
|
||||
if err = hook.Update(); err != nil {
|
||||
ctx.ServerError("hook.Update", err)
|
||||
return
|
||||
}
|
||||
ctx.Redirect(ctx.Repo.RepoLink + "/settings/hooks/git")
|
||||
}
|
||||
@@ -0,0 +1,535 @@
|
||||
// Copyright 2019 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package setting
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
gotemplate "html/template"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
git_model "gitea.dev/models/git"
|
||||
"gitea.dev/modules/charset"
|
||||
"gitea.dev/modules/container"
|
||||
"gitea.dev/modules/git"
|
||||
"gitea.dev/modules/git/attribute"
|
||||
"gitea.dev/modules/git/pipeline"
|
||||
"gitea.dev/modules/gitrepo"
|
||||
"gitea.dev/modules/lfs"
|
||||
"gitea.dev/modules/log"
|
||||
repo_module "gitea.dev/modules/repository"
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/modules/storage"
|
||||
"gitea.dev/modules/templates"
|
||||
"gitea.dev/modules/typesniffer"
|
||||
"gitea.dev/modules/util"
|
||||
"gitea.dev/services/context"
|
||||
)
|
||||
|
||||
const (
|
||||
tplSettingsLFS templates.TplName = "repo/settings/lfs"
|
||||
tplSettingsLFSLocks templates.TplName = "repo/settings/lfs_locks"
|
||||
tplSettingsLFSFile templates.TplName = "repo/settings/lfs_file"
|
||||
tplSettingsLFSFileFind templates.TplName = "repo/settings/lfs_file_find"
|
||||
tplSettingsLFSPointers templates.TplName = "repo/settings/lfs_pointers"
|
||||
)
|
||||
|
||||
// LFSFiles shows a repository's LFS files
|
||||
func LFSFiles(ctx *context.Context) {
|
||||
if !setting.LFS.StartServer {
|
||||
ctx.NotFound(nil)
|
||||
return
|
||||
}
|
||||
page := max(ctx.FormInt("page"), 1)
|
||||
total, err := git_model.CountLFSMetaObjects(ctx, ctx.Repo.Repository.ID)
|
||||
if err != nil {
|
||||
ctx.ServerError("LFSFiles", err)
|
||||
return
|
||||
}
|
||||
ctx.Data["Total"] = total
|
||||
|
||||
pager := context.NewPagination(total, setting.UI.ExplorePagingNum, page, 5)
|
||||
ctx.Data["Title"] = ctx.Tr("repo.settings.lfs")
|
||||
ctx.Data["PageIsSettingsLFS"] = true
|
||||
lfsMetaObjects, err := git_model.GetLFSMetaObjects(ctx, ctx.Repo.Repository.ID, pager.Paginater.Current(), setting.UI.ExplorePagingNum)
|
||||
if err != nil {
|
||||
ctx.ServerError("LFSFiles", err)
|
||||
return
|
||||
}
|
||||
ctx.Data["LFSFiles"] = lfsMetaObjects
|
||||
ctx.Data["Page"] = pager
|
||||
ctx.HTML(http.StatusOK, tplSettingsLFS)
|
||||
}
|
||||
|
||||
// LFSLocks shows a repository's LFS locks
|
||||
func LFSLocks(ctx *context.Context) {
|
||||
if !setting.LFS.StartServer {
|
||||
ctx.NotFound(nil)
|
||||
return
|
||||
}
|
||||
ctx.Data["LFSFilesLink"] = ctx.Repo.RepoLink + "/settings/lfs"
|
||||
|
||||
page := max(ctx.FormInt("page"), 1)
|
||||
total, err := git_model.CountLFSLockByRepoID(ctx, ctx.Repo.Repository.ID)
|
||||
if err != nil {
|
||||
ctx.ServerError("LFSLocks", err)
|
||||
return
|
||||
}
|
||||
ctx.Data["Total"] = total
|
||||
|
||||
pager := context.NewPagination(total, setting.UI.ExplorePagingNum, page, 5)
|
||||
ctx.Data["Title"] = ctx.Tr("repo.settings.lfs_locks")
|
||||
ctx.Data["PageIsSettingsLFS"] = true
|
||||
lfsLocks, err := git_model.GetLFSLockByRepoID(ctx, ctx.Repo.Repository.ID, pager.Paginater.Current(), setting.UI.ExplorePagingNum)
|
||||
if err != nil {
|
||||
ctx.ServerError("LFSLocks", err)
|
||||
return
|
||||
}
|
||||
if err := lfsLocks.LoadAttributes(ctx); err != nil {
|
||||
ctx.ServerError("LFSLocks", err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Data["LFSLocks"] = lfsLocks
|
||||
|
||||
if len(lfsLocks) == 0 {
|
||||
ctx.Data["Page"] = pager
|
||||
ctx.HTML(http.StatusOK, tplSettingsLFSLocks)
|
||||
return
|
||||
}
|
||||
|
||||
// Clone base repo.
|
||||
tmpBasePath, cleanup, err := repo_module.CreateTemporaryPath("locks")
|
||||
if err != nil {
|
||||
log.Error("Failed to create temporary path: %v", err)
|
||||
ctx.ServerError("LFSLocks", err)
|
||||
return
|
||||
}
|
||||
defer cleanup()
|
||||
|
||||
if err := gitrepo.CloneRepoToLocal(ctx, ctx.Repo.Repository, tmpBasePath, git.CloneRepoOptions{
|
||||
Bare: true,
|
||||
Shared: true,
|
||||
}); err != nil {
|
||||
log.Error("Failed to clone repository: %s (%v)", ctx.Repo.Repository.FullName(), err)
|
||||
ctx.ServerError("LFSLocks", fmt.Errorf("failed to clone repository: %s (%w)", ctx.Repo.Repository.FullName(), err))
|
||||
return
|
||||
}
|
||||
|
||||
gitRepo, err := git.OpenRepository(ctx, tmpBasePath)
|
||||
if err != nil {
|
||||
log.Error("Unable to open temporary repository: %s (%v)", tmpBasePath, err)
|
||||
ctx.ServerError("LFSLocks", fmt.Errorf("failed to open new temporary repository in: %s %w", tmpBasePath, err))
|
||||
return
|
||||
}
|
||||
defer gitRepo.Close()
|
||||
|
||||
checker, err := attribute.NewBatchChecker(gitRepo, ctx.Repo.Repository.DefaultBranch, []string{attribute.Lockable})
|
||||
if err != nil {
|
||||
log.Error("Unable to check attributes in %s (%v)", tmpBasePath, err)
|
||||
ctx.ServerError("LFSLocks", err)
|
||||
return
|
||||
}
|
||||
defer checker.Close()
|
||||
|
||||
lockables := make([]bool, len(lfsLocks))
|
||||
filenames := make([]string, len(lfsLocks))
|
||||
for i, lock := range lfsLocks {
|
||||
filenames[i] = lock.Path
|
||||
attrs, err := checker.CheckPath(lock.Path)
|
||||
if err != nil {
|
||||
log.Error("Unable to check attributes in %s: %s (%v)", tmpBasePath, lock.Path, err)
|
||||
continue
|
||||
}
|
||||
lockables[i] = attrs.Get(attribute.Lockable).ToBool().Value()
|
||||
}
|
||||
ctx.Data["Lockables"] = lockables
|
||||
|
||||
filelist, err := gitRepo.LsFiles(filenames...)
|
||||
if err != nil {
|
||||
log.Error("Unable to lsfiles in %s (%v)", tmpBasePath, err)
|
||||
ctx.ServerError("LFSLocks", err)
|
||||
return
|
||||
}
|
||||
|
||||
fileset := make(container.Set[string], len(filelist))
|
||||
fileset.AddMultiple(filelist...)
|
||||
|
||||
linkable := make([]bool, len(lfsLocks))
|
||||
for i, lock := range lfsLocks {
|
||||
linkable[i] = fileset.Contains(lock.Path)
|
||||
}
|
||||
ctx.Data["Linkable"] = linkable
|
||||
|
||||
ctx.Data["Page"] = pager
|
||||
ctx.HTML(http.StatusOK, tplSettingsLFSLocks)
|
||||
}
|
||||
|
||||
// LFSLockFile locks a file
|
||||
func LFSLockFile(ctx *context.Context) {
|
||||
if !setting.LFS.StartServer {
|
||||
ctx.NotFound(nil)
|
||||
return
|
||||
}
|
||||
originalPath := ctx.FormString("path")
|
||||
lockPath := originalPath
|
||||
if len(lockPath) == 0 {
|
||||
ctx.Flash.Error(ctx.Tr("repo.settings.lfs_invalid_locking_path", originalPath))
|
||||
ctx.Redirect(ctx.Repo.RepoLink + "/settings/lfs/locks")
|
||||
return
|
||||
}
|
||||
if lockPath[len(lockPath)-1] == '/' {
|
||||
ctx.Flash.Error(ctx.Tr("repo.settings.lfs_invalid_lock_directory", originalPath))
|
||||
ctx.Redirect(ctx.Repo.RepoLink + "/settings/lfs/locks")
|
||||
return
|
||||
}
|
||||
lockPath = util.PathJoinRel(lockPath)
|
||||
if len(lockPath) == 0 {
|
||||
ctx.Flash.Error(ctx.Tr("repo.settings.lfs_invalid_locking_path", originalPath))
|
||||
ctx.Redirect(ctx.Repo.RepoLink + "/settings/lfs/locks")
|
||||
return
|
||||
}
|
||||
|
||||
_, err := git_model.CreateLFSLock(ctx, ctx.Repo.Repository, &git_model.LFSLock{
|
||||
Path: lockPath,
|
||||
OwnerID: ctx.Doer.ID,
|
||||
})
|
||||
if err != nil {
|
||||
if git_model.IsErrLFSLockAlreadyExist(err) {
|
||||
ctx.Flash.Error(ctx.Tr("repo.settings.lfs_lock_already_exists", originalPath))
|
||||
ctx.Redirect(ctx.Repo.RepoLink + "/settings/lfs/locks")
|
||||
return
|
||||
}
|
||||
ctx.ServerError("LFSLockFile", err)
|
||||
return
|
||||
}
|
||||
ctx.Redirect(ctx.Repo.RepoLink + "/settings/lfs/locks")
|
||||
}
|
||||
|
||||
// LFSUnlock forcibly unlocks an LFS lock
|
||||
func LFSUnlock(ctx *context.Context) {
|
||||
if !setting.LFS.StartServer {
|
||||
ctx.NotFound(nil)
|
||||
return
|
||||
}
|
||||
_, err := git_model.DeleteLFSLockByID(ctx, ctx.PathParamInt64("lid"), ctx.Repo.Repository, ctx.Doer, true)
|
||||
if err != nil {
|
||||
ctx.ServerError("LFSUnlock", err)
|
||||
return
|
||||
}
|
||||
ctx.Redirect(ctx.Repo.RepoLink + "/settings/lfs/locks")
|
||||
}
|
||||
|
||||
// LFSFileGet serves a single LFS file
|
||||
func LFSFileGet(ctx *context.Context) {
|
||||
if !setting.LFS.StartServer {
|
||||
ctx.NotFound(nil)
|
||||
return
|
||||
}
|
||||
ctx.Data["LFSFilesLink"] = ctx.Repo.RepoLink + "/settings/lfs"
|
||||
oid := ctx.PathParam("oid")
|
||||
|
||||
p := lfs.Pointer{Oid: oid}
|
||||
if !p.IsValid() {
|
||||
ctx.NotFound(nil)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Data["Title"] = oid
|
||||
ctx.Data["PageIsSettingsLFS"] = true
|
||||
meta, err := git_model.GetLFSMetaObjectByOid(ctx, ctx.Repo.Repository.ID, oid)
|
||||
if err != nil {
|
||||
if err == git_model.ErrLFSObjectNotExist {
|
||||
ctx.NotFound(nil)
|
||||
return
|
||||
}
|
||||
ctx.ServerError("LFSFileGet", err)
|
||||
return
|
||||
}
|
||||
ctx.Data["LFSFile"] = meta
|
||||
dataRc, err := lfs.ReadMetaObject(meta.Pointer)
|
||||
if err != nil {
|
||||
ctx.ServerError("LFSFileGet", err)
|
||||
return
|
||||
}
|
||||
defer dataRc.Close()
|
||||
buf := make([]byte, 1024)
|
||||
n, err := util.ReadAtMost(dataRc, buf)
|
||||
if err != nil {
|
||||
ctx.ServerError("Data", err)
|
||||
return
|
||||
}
|
||||
buf = buf[:n]
|
||||
|
||||
st := typesniffer.DetectContentType(buf)
|
||||
// FIXME: there is no IsPlainText set, but template uses it
|
||||
ctx.Data["IsTextFile"] = st.IsText()
|
||||
ctx.Data["FileSize"] = meta.Size
|
||||
ctx.Data["RawFileLink"] = fmt.Sprintf("%s/%s/%s.git/info/lfs/objects/%s", setting.AppSubURL, url.PathEscape(ctx.Repo.Repository.OwnerName), url.PathEscape(ctx.Repo.Repository.Name), url.PathEscape(meta.Oid))
|
||||
switch {
|
||||
case st.IsRepresentableAsText():
|
||||
if meta.Size >= setting.UI.MaxDisplayFileSize {
|
||||
ctx.Data["IsFileTooLarge"] = true
|
||||
break
|
||||
}
|
||||
|
||||
if st.IsSvgImage() {
|
||||
ctx.Data["IsImageFile"] = true
|
||||
}
|
||||
|
||||
rd := charset.ToUTF8WithFallbackReader(io.MultiReader(bytes.NewReader(buf), dataRc), charset.ConvertOpts{})
|
||||
|
||||
// Building code view blocks with line number on server side.
|
||||
// FIXME: the logic is not right here: it first calls EscapeControlReader then calls HTMLEscapeString: double-escaping
|
||||
escapedContent := &bytes.Buffer{}
|
||||
ctx.Data["EscapeStatus"], _ = charset.EscapeControlReader(rd, escapedContent, ctx.Locale)
|
||||
|
||||
var output bytes.Buffer
|
||||
lines := strings.Split(escapedContent.String(), "\n")
|
||||
// Remove blank line at the end of file
|
||||
if len(lines) > 0 && lines[len(lines)-1] == "" {
|
||||
lines = lines[:len(lines)-1]
|
||||
}
|
||||
for index, line := range lines {
|
||||
line = gotemplate.HTMLEscapeString(line)
|
||||
if index != len(lines)-1 {
|
||||
line += "\n"
|
||||
}
|
||||
fmt.Fprintf(&output, `<li class="L%d" rel="L%d">%s</li>`, index+1, index+1, line)
|
||||
}
|
||||
ctx.Data["FileContent"] = gotemplate.HTML(output.String())
|
||||
|
||||
output.Reset()
|
||||
for i := 0; i < len(lines); i++ {
|
||||
fmt.Fprintf(&output, `<span id="L%d">%d</span>`, i+1, i+1)
|
||||
}
|
||||
ctx.Data["LineNums"] = gotemplate.HTML(output.String())
|
||||
|
||||
case st.IsVideo():
|
||||
ctx.Data["IsVideoFile"] = true
|
||||
case st.IsAudio():
|
||||
ctx.Data["IsAudioFile"] = true
|
||||
case st.IsImage() && (setting.UI.SVG.Enabled || !st.IsSvgImage()):
|
||||
ctx.Data["IsImageFile"] = true
|
||||
default:
|
||||
// TODO: the logic is not the same as "renderFile" in "view.go"
|
||||
}
|
||||
ctx.HTML(http.StatusOK, tplSettingsLFSFile)
|
||||
}
|
||||
|
||||
// LFSDelete disassociates the provided oid from the repository and if the lfs file is no longer associated with any repositories - deletes it
|
||||
func LFSDelete(ctx *context.Context) {
|
||||
if !setting.LFS.StartServer {
|
||||
ctx.NotFound(nil)
|
||||
return
|
||||
}
|
||||
oid := ctx.PathParam("oid")
|
||||
p := lfs.Pointer{Oid: oid}
|
||||
if !p.IsValid() {
|
||||
ctx.NotFound(nil)
|
||||
return
|
||||
}
|
||||
|
||||
count, err := git_model.RemoveLFSMetaObjectByOid(ctx, ctx.Repo.Repository.ID, oid)
|
||||
if err != nil {
|
||||
ctx.ServerError("LFSDelete", err)
|
||||
return
|
||||
}
|
||||
// FIXME: Warning: the LFS store is not locked - and can't be locked - there could be a race condition here
|
||||
// Please note a similar condition happens in models/repo.go DeleteRepository
|
||||
if count == 0 {
|
||||
oidPath := path.Join(oid[0:2], oid[2:4], oid[4:])
|
||||
err = storage.LFS.Delete(oidPath)
|
||||
if err != nil {
|
||||
ctx.ServerError("LFSDelete", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
ctx.Redirect(ctx.Repo.RepoLink + "/settings/lfs")
|
||||
}
|
||||
|
||||
// LFSFileFind guesses a sha for the provided oid (or uses the provided sha) and then finds the commits that contain this sha
|
||||
func LFSFileFind(ctx *context.Context) {
|
||||
if !setting.LFS.StartServer {
|
||||
ctx.NotFound(nil)
|
||||
return
|
||||
}
|
||||
oid := ctx.FormString("oid")
|
||||
size := ctx.FormInt64("size")
|
||||
if len(oid) == 0 || size == 0 {
|
||||
ctx.NotFound(nil)
|
||||
return
|
||||
}
|
||||
sha := ctx.FormString("sha")
|
||||
ctx.Data["Title"] = oid
|
||||
ctx.Data["PageIsSettingsLFS"] = true
|
||||
objectFormat := ctx.Repo.GetObjectFormat()
|
||||
var objectID git.ObjectID
|
||||
if len(sha) == 0 {
|
||||
pointer := lfs.Pointer{Oid: oid, Size: size}
|
||||
objectID = git.ComputeBlobHash(objectFormat, []byte(pointer.StringContent()))
|
||||
sha = objectID.String()
|
||||
} else {
|
||||
objectID = git.MustIDFromString(sha)
|
||||
}
|
||||
ctx.Data["LFSFilesLink"] = ctx.Repo.RepoLink + "/settings/lfs"
|
||||
ctx.Data["Oid"] = oid
|
||||
ctx.Data["Size"] = size
|
||||
ctx.Data["SHA"] = sha
|
||||
|
||||
results, err := pipeline.FindLFSFile(ctx.Repo.GitRepo, objectID)
|
||||
if err != nil && err != io.EOF {
|
||||
log.Error("Failure in FindLFSFile: %v", err)
|
||||
ctx.ServerError("LFSFind: FindLFSFile.", err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Data["Results"] = results
|
||||
ctx.HTML(http.StatusOK, tplSettingsLFSFileFind)
|
||||
}
|
||||
|
||||
// LFSPointerFiles will search the repository for pointer files and report which are missing LFS files in the content store
|
||||
func LFSPointerFiles(ctx *context.Context) {
|
||||
if !setting.LFS.StartServer {
|
||||
ctx.NotFound(nil)
|
||||
return
|
||||
}
|
||||
ctx.Data["PageIsSettingsLFS"] = true
|
||||
ctx.Data["LFSFilesLink"] = ctx.Repo.RepoLink + "/settings/lfs"
|
||||
|
||||
var err error
|
||||
err = func() error {
|
||||
pointerChan := make(chan lfs.PointerBlob)
|
||||
errChan := make(chan error, 1)
|
||||
go func() {
|
||||
errChan <- lfs.SearchPointerBlobs(ctx, ctx.Repo.GitRepo, pointerChan)
|
||||
}()
|
||||
|
||||
numPointers := 0
|
||||
var numAssociated, numNoExist, numAssociatable int
|
||||
|
||||
type pointerResult struct {
|
||||
SHA string
|
||||
Oid string
|
||||
Size int64
|
||||
InRepo bool
|
||||
Exists bool
|
||||
Accessible bool
|
||||
Associatable bool
|
||||
}
|
||||
|
||||
results := []pointerResult{}
|
||||
|
||||
contentStore := lfs.NewContentStore()
|
||||
repo := ctx.Repo.Repository
|
||||
|
||||
for pointerBlob := range pointerChan {
|
||||
numPointers++
|
||||
|
||||
result := pointerResult{
|
||||
SHA: pointerBlob.Hash,
|
||||
Oid: pointerBlob.Oid,
|
||||
Size: pointerBlob.Size,
|
||||
}
|
||||
|
||||
if _, err := git_model.GetLFSMetaObjectByOid(ctx, repo.ID, pointerBlob.Oid); err != nil {
|
||||
if err != git_model.ErrLFSObjectNotExist {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
result.InRepo = true
|
||||
}
|
||||
|
||||
result.Exists, err = contentStore.Exists(pointerBlob.Pointer)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if result.Exists {
|
||||
if !result.InRepo {
|
||||
// Can we fix?
|
||||
// OK well that's "simple"
|
||||
// - we need to check whether current user has access to a repo that has access to the file
|
||||
result.Associatable, err = git_model.LFSObjectAccessible(ctx, ctx.Doer, pointerBlob.Oid)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !result.Associatable {
|
||||
associated, err := git_model.ExistsLFSObject(ctx, pointerBlob.Oid)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
result.Associatable = !associated
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
result.Accessible = result.InRepo || result.Associatable
|
||||
|
||||
if result.InRepo {
|
||||
numAssociated++
|
||||
}
|
||||
if !result.Exists {
|
||||
numNoExist++
|
||||
}
|
||||
if result.Associatable {
|
||||
numAssociatable++
|
||||
}
|
||||
|
||||
results = append(results, result)
|
||||
}
|
||||
|
||||
ctx.Data["Pointers"] = results
|
||||
ctx.Data["NumPointers"] = numPointers
|
||||
ctx.Data["NumAssociated"] = numAssociated
|
||||
ctx.Data["NumAssociatable"] = numAssociatable
|
||||
ctx.Data["NumNoExist"] = numNoExist
|
||||
ctx.Data["NumNotAssociated"] = numPointers - numAssociated
|
||||
|
||||
err := <-errChan
|
||||
return err
|
||||
}()
|
||||
if err != nil {
|
||||
ctx.ServerError("LFSPointerFiles", err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.HTML(http.StatusOK, tplSettingsLFSPointers)
|
||||
}
|
||||
|
||||
// LFSAutoAssociate auto associates accessible lfs files
|
||||
func LFSAutoAssociate(ctx *context.Context) {
|
||||
if !setting.LFS.StartServer {
|
||||
ctx.NotFound(nil)
|
||||
return
|
||||
}
|
||||
oids := ctx.FormStrings("oid")
|
||||
metas := make([]*git_model.LFSMetaObject, len(oids))
|
||||
for i, oid := range oids {
|
||||
idx := strings.IndexRune(oid, ' ')
|
||||
if idx < 0 || idx+1 > len(oid) {
|
||||
ctx.ServerError("LFSAutoAssociate", fmt.Errorf("illegal oid input: %s", oid))
|
||||
return
|
||||
}
|
||||
var err error
|
||||
metas[i] = &git_model.LFSMetaObject{}
|
||||
metas[i].Size, err = strconv.ParseInt(oid[idx+1:], 10, 64)
|
||||
if err != nil {
|
||||
ctx.ServerError("LFSAutoAssociate", fmt.Errorf("illegal oid input: %s %w", oid, err))
|
||||
return
|
||||
}
|
||||
metas[i].Oid = oid[:idx]
|
||||
// metas[i].RepositoryID = ctx.Repo.Repository.ID
|
||||
}
|
||||
if err := git_model.LFSAutoAssociate(ctx, metas, ctx.Doer, ctx.Repo.Repository.ID); err != nil {
|
||||
ctx.ServerError("LFSAutoAssociate", err)
|
||||
return
|
||||
}
|
||||
ctx.Redirect(ctx.Repo.RepoLink + "/settings/lfs")
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// Copyright 2017 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package setting
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"gitea.dev/models/unittest"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
unittest.MainTest(m)
|
||||
}
|
||||
@@ -0,0 +1,390 @@
|
||||
// Copyright 2017 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package setting
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
git_model "gitea.dev/models/git"
|
||||
"gitea.dev/models/organization"
|
||||
"gitea.dev/models/perm"
|
||||
access_model "gitea.dev/models/perm/access"
|
||||
repo_model "gitea.dev/models/repo"
|
||||
"gitea.dev/models/unit"
|
||||
"gitea.dev/modules/base"
|
||||
"gitea.dev/modules/glob"
|
||||
"gitea.dev/modules/json"
|
||||
"gitea.dev/modules/templates"
|
||||
"gitea.dev/modules/web"
|
||||
"gitea.dev/routers/web/repo"
|
||||
"gitea.dev/services/context"
|
||||
"gitea.dev/services/forms"
|
||||
pull_service "gitea.dev/services/pull"
|
||||
"gitea.dev/services/repository"
|
||||
)
|
||||
|
||||
const (
|
||||
tplProtectedBranch templates.TplName = "repo/settings/protected_branch"
|
||||
)
|
||||
|
||||
// ProtectedBranchRules render the page to protect the repository
|
||||
func ProtectedBranchRules(ctx *context.Context) {
|
||||
ctx.Data["Title"] = ctx.Tr("repo.settings.branches")
|
||||
ctx.Data["PageIsSettingsBranches"] = true
|
||||
|
||||
rules, err := git_model.FindRepoProtectedBranchRules(ctx, ctx.Repo.Repository.ID)
|
||||
if err != nil {
|
||||
ctx.ServerError("GetProtectedBranches", err)
|
||||
return
|
||||
}
|
||||
ctx.Data["ProtectedBranches"] = rules
|
||||
|
||||
repo.PrepareBranchList(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
|
||||
ctx.HTML(http.StatusOK, tplBranches)
|
||||
}
|
||||
|
||||
// SettingsProtectedBranch renders the protected branch setting page
|
||||
func SettingsProtectedBranch(c *context.Context) {
|
||||
ruleName := c.FormString("rule_name")
|
||||
var rule *git_model.ProtectedBranch
|
||||
if ruleName != "" {
|
||||
var err error
|
||||
rule, err = git_model.GetProtectedBranchRuleByName(c, c.Repo.Repository.ID, ruleName)
|
||||
if err != nil {
|
||||
c.ServerError("GetProtectBranchOfRepoByName", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if rule == nil {
|
||||
// No options found, create defaults.
|
||||
rule = &git_model.ProtectedBranch{}
|
||||
}
|
||||
|
||||
c.Data["PageIsSettingsBranches"] = true
|
||||
c.Data["Title"] = c.Locale.TrString("repo.settings.protected_branch") + " - " + rule.RuleName
|
||||
users, err := access_model.GetUsersWithUnitAccess(c, c.Repo.Repository, perm.AccessModeRead, unit.TypePullRequests)
|
||||
if err != nil {
|
||||
c.ServerError("GetUsersWithUnitAccess", err)
|
||||
return
|
||||
}
|
||||
c.Data["Users"] = users
|
||||
c.Data["whitelist_users"] = strings.Join(base.Int64sToStrings(rule.WhitelistUserIDs), ",")
|
||||
c.Data["force_push_allowlist_users"] = strings.Join(base.Int64sToStrings(rule.ForcePushAllowlistUserIDs), ",")
|
||||
c.Data["merge_whitelist_users"] = strings.Join(base.Int64sToStrings(rule.MergeWhitelistUserIDs), ",")
|
||||
c.Data["bypass_allowlist_users"] = strings.Join(base.Int64sToStrings(rule.BypassAllowlistUserIDs), ",")
|
||||
c.Data["approvals_whitelist_users"] = strings.Join(base.Int64sToStrings(rule.ApprovalsWhitelistUserIDs), ",")
|
||||
c.Data["status_check_contexts"] = strings.Join(rule.StatusCheckContexts, "\n")
|
||||
contexts, _ := git_model.FindRepoRecentCommitStatusContexts(c, c.Repo.Repository.ID, 7*24*time.Hour) // Find last week status check contexts
|
||||
c.Data["recent_status_checks"] = contexts
|
||||
|
||||
if c.Repo.Owner.IsOrganization() {
|
||||
teams, err := organization.GetTeamsWithAccessToAnyRepoUnit(c, c.Repo.Owner.ID, c.Repo.Repository.ID, perm.AccessModeRead, unit.TypeCode, unit.TypePullRequests)
|
||||
if err != nil {
|
||||
c.ServerError("Repo.Owner.TeamsWithAccessToRepo", err)
|
||||
return
|
||||
}
|
||||
c.Data["Teams"] = teams
|
||||
c.Data["whitelist_teams"] = strings.Join(base.Int64sToStrings(rule.WhitelistTeamIDs), ",")
|
||||
c.Data["force_push_allowlist_teams"] = strings.Join(base.Int64sToStrings(rule.ForcePushAllowlistTeamIDs), ",")
|
||||
c.Data["merge_whitelist_teams"] = strings.Join(base.Int64sToStrings(rule.MergeWhitelistTeamIDs), ",")
|
||||
c.Data["bypass_allowlist_teams"] = strings.Join(base.Int64sToStrings(rule.BypassAllowlistTeamIDs), ",")
|
||||
c.Data["approvals_whitelist_teams"] = strings.Join(base.Int64sToStrings(rule.ApprovalsWhitelistTeamIDs), ",")
|
||||
}
|
||||
|
||||
c.Data["Rule"] = rule
|
||||
c.HTML(http.StatusOK, tplProtectedBranch)
|
||||
}
|
||||
|
||||
// SettingsProtectedBranchPost updates the protected branch settings
|
||||
func SettingsProtectedBranchPost(ctx *context.Context) {
|
||||
f := web.GetForm(ctx).(*forms.ProtectBranchForm)
|
||||
var protectBranch *git_model.ProtectedBranch
|
||||
if f.RuleName == "" {
|
||||
ctx.Flash.Error(ctx.Tr("repo.settings.protected_branch_required_rule_name"))
|
||||
ctx.Redirect(ctx.Repo.RepoLink + "/settings/branches/edit")
|
||||
return
|
||||
}
|
||||
|
||||
var err error
|
||||
if f.RuleID > 0 {
|
||||
// If the RuleID isn't 0, it must be an edit operation. So we get rule by id.
|
||||
protectBranch, err = git_model.GetProtectedBranchRuleByID(ctx, ctx.Repo.Repository.ID, f.RuleID)
|
||||
if err != nil {
|
||||
ctx.ServerError("GetProtectBranchOfRepoByID", err)
|
||||
return
|
||||
}
|
||||
if protectBranch != nil && protectBranch.RuleName != f.RuleName {
|
||||
// RuleName changed. We need to check if there is a rule with the same name.
|
||||
// If a rule with the same name exists, an error should be returned.
|
||||
sameNameProtectBranch, err := git_model.GetProtectedBranchRuleByName(ctx, ctx.Repo.Repository.ID, f.RuleName)
|
||||
if err != nil {
|
||||
ctx.ServerError("GetProtectBranchOfRepoByName", err)
|
||||
return
|
||||
}
|
||||
if sameNameProtectBranch != nil {
|
||||
ctx.Flash.Error(ctx.Tr("repo.settings.protected_branch_duplicate_rule_name"))
|
||||
ctx.Redirect(fmt.Sprintf("%s/settings/branches/edit?rule_name=%s", ctx.Repo.RepoLink, protectBranch.RuleName))
|
||||
return
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// FIXME: If a new ProtectBranch has a duplicate RuleName, an error should be returned.
|
||||
// Currently, if a new ProtectBranch with a duplicate RuleName is created, the existing ProtectBranch will be updated.
|
||||
// But we cannot modify this logic now because many unit tests rely on it.
|
||||
protectBranch, err = git_model.GetProtectedBranchRuleByName(ctx, ctx.Repo.Repository.ID, f.RuleName)
|
||||
if err != nil {
|
||||
ctx.ServerError("GetProtectBranchOfRepoByName", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
if protectBranch == nil {
|
||||
// No options found, create defaults.
|
||||
protectBranch = &git_model.ProtectedBranch{
|
||||
RepoID: ctx.Repo.Repository.ID,
|
||||
RuleName: f.RuleName,
|
||||
}
|
||||
}
|
||||
|
||||
var whitelistUsers, whitelistTeams, forcePushAllowlistUsers, forcePushAllowlistTeams, mergeWhitelistUsers, mergeWhitelistTeams, approvalsWhitelistUsers, approvalsWhitelistTeams, bypassAllowlistUsers, bypassAllowlistTeams []int64
|
||||
protectBranch.RuleName = f.RuleName
|
||||
if f.RequiredApprovals < 0 {
|
||||
ctx.Flash.Error(ctx.Tr("repo.settings.protected_branch_required_approvals_min"))
|
||||
ctx.Redirect(fmt.Sprintf("%s/settings/branches/edit?rule_name=%s", ctx.Repo.RepoLink, f.RuleName))
|
||||
return
|
||||
}
|
||||
|
||||
switch f.EnablePush {
|
||||
case "all":
|
||||
protectBranch.CanPush = true
|
||||
protectBranch.EnableWhitelist = false
|
||||
protectBranch.WhitelistDeployKeys = false
|
||||
case "whitelist":
|
||||
protectBranch.CanPush = true
|
||||
protectBranch.EnableWhitelist = true
|
||||
protectBranch.WhitelistDeployKeys = f.WhitelistDeployKeys
|
||||
if strings.TrimSpace(f.WhitelistUsers) != "" {
|
||||
whitelistUsers, _ = base.StringsToInt64s(strings.Split(f.WhitelistUsers, ","))
|
||||
}
|
||||
if strings.TrimSpace(f.WhitelistTeams) != "" {
|
||||
whitelistTeams, _ = base.StringsToInt64s(strings.Split(f.WhitelistTeams, ","))
|
||||
}
|
||||
default:
|
||||
protectBranch.CanPush = false
|
||||
protectBranch.EnableWhitelist = false
|
||||
protectBranch.WhitelistDeployKeys = false
|
||||
}
|
||||
|
||||
switch f.EnableForcePush {
|
||||
case "all":
|
||||
protectBranch.CanForcePush = true
|
||||
protectBranch.EnableForcePushAllowlist = false
|
||||
protectBranch.ForcePushAllowlistDeployKeys = false
|
||||
case "whitelist":
|
||||
protectBranch.CanForcePush = true
|
||||
protectBranch.EnableForcePushAllowlist = true
|
||||
protectBranch.ForcePushAllowlistDeployKeys = f.ForcePushAllowlistDeployKeys
|
||||
if strings.TrimSpace(f.ForcePushAllowlistUsers) != "" {
|
||||
forcePushAllowlistUsers, _ = base.StringsToInt64s(strings.Split(f.ForcePushAllowlistUsers, ","))
|
||||
}
|
||||
if strings.TrimSpace(f.ForcePushAllowlistTeams) != "" {
|
||||
forcePushAllowlistTeams, _ = base.StringsToInt64s(strings.Split(f.ForcePushAllowlistTeams, ","))
|
||||
}
|
||||
default:
|
||||
protectBranch.CanForcePush = false
|
||||
protectBranch.EnableForcePushAllowlist = false
|
||||
protectBranch.ForcePushAllowlistDeployKeys = false
|
||||
}
|
||||
|
||||
protectBranch.EnableMergeWhitelist = f.EnableMergeWhitelist
|
||||
if f.EnableMergeWhitelist {
|
||||
if strings.TrimSpace(f.MergeWhitelistUsers) != "" {
|
||||
mergeWhitelistUsers, _ = base.StringsToInt64s(strings.Split(f.MergeWhitelistUsers, ","))
|
||||
}
|
||||
if strings.TrimSpace(f.MergeWhitelistTeams) != "" {
|
||||
mergeWhitelistTeams, _ = base.StringsToInt64s(strings.Split(f.MergeWhitelistTeams, ","))
|
||||
}
|
||||
}
|
||||
|
||||
protectBranch.EnableBypassAllowlist = f.EnableBypassAllowlist
|
||||
if f.EnableBypassAllowlist {
|
||||
if strings.TrimSpace(f.BypassAllowlistUsers) != "" {
|
||||
bypassAllowlistUsers, _ = base.StringsToInt64s(strings.Split(f.BypassAllowlistUsers, ","))
|
||||
}
|
||||
if strings.TrimSpace(f.BypassAllowlistTeams) != "" {
|
||||
bypassAllowlistTeams, _ = base.StringsToInt64s(strings.Split(f.BypassAllowlistTeams, ","))
|
||||
}
|
||||
}
|
||||
|
||||
protectBranch.EnableStatusCheck = f.EnableStatusCheck
|
||||
if f.EnableStatusCheck {
|
||||
patterns := strings.Split(strings.ReplaceAll(f.StatusCheckContexts, "\r", "\n"), "\n")
|
||||
validPatterns := make([]string, 0, len(patterns))
|
||||
for _, pattern := range patterns {
|
||||
trimmed := strings.TrimSpace(pattern)
|
||||
if trimmed == "" {
|
||||
continue
|
||||
}
|
||||
if _, err := glob.Compile(trimmed); err != nil {
|
||||
ctx.Flash.Error(ctx.Tr("repo.settings.protect_invalid_status_check_pattern", pattern))
|
||||
ctx.Redirect(fmt.Sprintf("%s/settings/branches/edit?rule_name=%s", ctx.Repo.RepoLink, url.QueryEscape(protectBranch.RuleName)))
|
||||
return
|
||||
}
|
||||
validPatterns = append(validPatterns, trimmed)
|
||||
}
|
||||
if len(validPatterns) == 0 {
|
||||
// if status check is enabled, patterns slice is not allowed to be empty
|
||||
ctx.Flash.Error(ctx.Tr("repo.settings.protect_no_valid_status_check_patterns"))
|
||||
ctx.Redirect(fmt.Sprintf("%s/settings/branches/edit?rule_name=%s", ctx.Repo.RepoLink, url.QueryEscape(protectBranch.RuleName)))
|
||||
return
|
||||
}
|
||||
protectBranch.StatusCheckContexts = validPatterns
|
||||
} else {
|
||||
protectBranch.StatusCheckContexts = nil
|
||||
}
|
||||
|
||||
protectBranch.RequiredApprovals = f.RequiredApprovals
|
||||
protectBranch.EnableApprovalsWhitelist = f.EnableApprovalsWhitelist
|
||||
if f.EnableApprovalsWhitelist {
|
||||
if strings.TrimSpace(f.ApprovalsWhitelistUsers) != "" {
|
||||
approvalsWhitelistUsers, _ = base.StringsToInt64s(strings.Split(f.ApprovalsWhitelistUsers, ","))
|
||||
}
|
||||
if strings.TrimSpace(f.ApprovalsWhitelistTeams) != "" {
|
||||
approvalsWhitelistTeams, _ = base.StringsToInt64s(strings.Split(f.ApprovalsWhitelistTeams, ","))
|
||||
}
|
||||
}
|
||||
protectBranch.BlockOnRejectedReviews = f.BlockOnRejectedReviews
|
||||
protectBranch.BlockOnOfficialReviewRequests = f.BlockOnOfficialReviewRequests
|
||||
protectBranch.DismissStaleApprovals = f.DismissStaleApprovals
|
||||
protectBranch.IgnoreStaleApprovals = f.IgnoreStaleApprovals
|
||||
protectBranch.RequireSignedCommits = f.RequireSignedCommits
|
||||
protectBranch.ProtectedFilePatterns = f.ProtectedFilePatterns
|
||||
protectBranch.UnprotectedFilePatterns = f.UnprotectedFilePatterns
|
||||
protectBranch.BlockOnOutdatedBranch = f.BlockOnOutdatedBranch
|
||||
protectBranch.BlockAdminMergeOverride = f.BlockAdminMergeOverride
|
||||
|
||||
if err = pull_service.CreateOrUpdateProtectedBranch(ctx, ctx.Repo.Repository, protectBranch, git_model.WhitelistOptions{
|
||||
UserIDs: whitelistUsers,
|
||||
TeamIDs: whitelistTeams,
|
||||
ForcePushUserIDs: forcePushAllowlistUsers,
|
||||
ForcePushTeamIDs: forcePushAllowlistTeams,
|
||||
MergeUserIDs: mergeWhitelistUsers,
|
||||
MergeTeamIDs: mergeWhitelistTeams,
|
||||
ApprovalsUserIDs: approvalsWhitelistUsers,
|
||||
ApprovalsTeamIDs: approvalsWhitelistTeams,
|
||||
BypassUserIDs: bypassAllowlistUsers,
|
||||
BypassTeamIDs: bypassAllowlistTeams,
|
||||
}); err != nil {
|
||||
ctx.ServerError("CreateOrUpdateProtectedBranch", err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Flash.Success(ctx.Tr("repo.settings.update_protect_branch_success", protectBranch.RuleName))
|
||||
ctx.Redirect(fmt.Sprintf("%s/settings/branches?rule_name=%s", ctx.Repo.RepoLink, protectBranch.RuleName))
|
||||
}
|
||||
|
||||
// DeleteProtectedBranchRulePost delete protected branch rule by id
|
||||
func DeleteProtectedBranchRulePost(ctx *context.Context) {
|
||||
ruleID := ctx.PathParamInt64("id")
|
||||
if ruleID <= 0 {
|
||||
ctx.Flash.Error(ctx.Tr("repo.settings.remove_protected_branch_failed", strconv.FormatInt(ruleID, 10)))
|
||||
ctx.JSONRedirect(ctx.Repo.RepoLink + "/settings/branches")
|
||||
return
|
||||
}
|
||||
|
||||
rule, err := git_model.GetProtectedBranchRuleByID(ctx, ctx.Repo.Repository.ID, ruleID)
|
||||
if err != nil {
|
||||
ctx.Flash.Error(ctx.Tr("repo.settings.remove_protected_branch_failed", strconv.FormatInt(ruleID, 10)))
|
||||
ctx.JSONRedirect(ctx.Repo.RepoLink + "/settings/branches")
|
||||
return
|
||||
}
|
||||
|
||||
if rule == nil {
|
||||
ctx.Flash.Error(ctx.Tr("repo.settings.remove_protected_branch_failed", strconv.FormatInt(ruleID, 10)))
|
||||
ctx.JSONRedirect(ctx.Repo.RepoLink + "/settings/branches")
|
||||
return
|
||||
}
|
||||
|
||||
if err := git_model.DeleteProtectedBranch(ctx, ctx.Repo.Repository, ruleID); err != nil {
|
||||
ctx.Flash.Error(ctx.Tr("repo.settings.remove_protected_branch_failed", rule.RuleName))
|
||||
ctx.JSONRedirect(ctx.Repo.RepoLink + "/settings/branches")
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Flash.Success(ctx.Tr("repo.settings.remove_protected_branch_success", rule.RuleName))
|
||||
ctx.JSONRedirect(ctx.Repo.RepoLink + "/settings/branches")
|
||||
}
|
||||
|
||||
func UpdateBranchProtectionPriories(ctx *context.Context) {
|
||||
var form struct {
|
||||
IDs []int64 `json:"ids"`
|
||||
}
|
||||
if err := json.NewDecoder(ctx.Req.Body).Decode(&form); err != nil {
|
||||
ctx.JSONError("invalid argument")
|
||||
return
|
||||
}
|
||||
if err := git_model.UpdateProtectBranchPriorities(ctx, ctx.Repo.Repository, form.IDs); err != nil {
|
||||
ctx.ServerError("UpdateProtectBranchPriorities", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// RenameBranchPost responses for rename a branch
|
||||
func RenameBranchPost(ctx *context.Context) {
|
||||
form := web.GetForm(ctx).(*forms.RenameBranchForm)
|
||||
|
||||
if !ctx.Repo.CanCreateBranch() {
|
||||
ctx.NotFound(nil)
|
||||
return
|
||||
}
|
||||
|
||||
if ctx.HasError() {
|
||||
ctx.Flash.Error(ctx.GetErrMsg())
|
||||
ctx.Redirect(ctx.Repo.RepoLink + "/branches")
|
||||
return
|
||||
}
|
||||
|
||||
msg, err := repository.RenameBranch(ctx, ctx.Repo.Repository, ctx.Doer, form.From, form.To)
|
||||
if err != nil {
|
||||
switch {
|
||||
case repo_model.IsErrUserDoesNotHaveAccessToRepo(err):
|
||||
ctx.Flash.Error(ctx.Tr("repo.branch.rename_default_or_protected_branch_error"))
|
||||
ctx.Redirect(ctx.Repo.RepoLink + "/branches")
|
||||
case git_model.IsErrBranchAlreadyExists(err):
|
||||
ctx.Flash.Error(ctx.Tr("repo.branch.branch_already_exists", form.To))
|
||||
ctx.Redirect(ctx.Repo.RepoLink + "/branches")
|
||||
case errors.Is(err, git_model.ErrBranchIsProtected):
|
||||
ctx.Flash.Error(ctx.Tr("repo.branch.rename_protected_branch_failed"))
|
||||
ctx.Redirect(ctx.Repo.RepoLink + "/branches")
|
||||
default:
|
||||
ctx.ServerError("RenameBranch", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if msg == "target_exist" {
|
||||
ctx.Flash.Error(ctx.Tr("repo.settings.rename_branch_failed_exist", form.To))
|
||||
ctx.Redirect(ctx.Repo.RepoLink + "/branches")
|
||||
return
|
||||
}
|
||||
|
||||
if msg == "from_not_exist" {
|
||||
ctx.Flash.Error(ctx.Tr("repo.settings.rename_branch_failed_not_exist", form.From))
|
||||
ctx.Redirect(ctx.Repo.RepoLink + "/branches")
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Flash.Success(ctx.Tr("repo.settings.rename_branch_success", form.From, form.To))
|
||||
ctx.Redirect(ctx.Repo.RepoLink + "/branches")
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
// Copyright 2021 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package setting
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
git_model "gitea.dev/models/git"
|
||||
"gitea.dev/models/organization"
|
||||
"gitea.dev/models/perm"
|
||||
access_model "gitea.dev/models/perm/access"
|
||||
"gitea.dev/models/unit"
|
||||
"gitea.dev/modules/base"
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/modules/templates"
|
||||
"gitea.dev/modules/web"
|
||||
"gitea.dev/services/context"
|
||||
"gitea.dev/services/forms"
|
||||
)
|
||||
|
||||
const (
|
||||
tplTags templates.TplName = "repo/settings/tags"
|
||||
)
|
||||
|
||||
// Tags render the page to protect tags
|
||||
func ProtectedTags(ctx *context.Context) {
|
||||
if setTagsContext(ctx) != nil {
|
||||
return
|
||||
}
|
||||
|
||||
ctx.HTML(http.StatusOK, tplTags)
|
||||
}
|
||||
|
||||
// NewProtectedTagPost handles creation of a protect tag
|
||||
func NewProtectedTagPost(ctx *context.Context) {
|
||||
if setTagsContext(ctx) != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if ctx.HasError() {
|
||||
ctx.HTML(http.StatusOK, tplTags)
|
||||
return
|
||||
}
|
||||
|
||||
repo := ctx.Repo.Repository
|
||||
form := web.GetForm(ctx).(*forms.ProtectTagForm)
|
||||
|
||||
pt := &git_model.ProtectedTag{
|
||||
RepoID: repo.ID,
|
||||
NamePattern: strings.TrimSpace(form.NamePattern),
|
||||
}
|
||||
|
||||
if strings.TrimSpace(form.AllowlistUsers) != "" {
|
||||
pt.AllowlistUserIDs, _ = base.StringsToInt64s(strings.Split(form.AllowlistUsers, ","))
|
||||
}
|
||||
if strings.TrimSpace(form.AllowlistTeams) != "" {
|
||||
pt.AllowlistTeamIDs, _ = base.StringsToInt64s(strings.Split(form.AllowlistTeams, ","))
|
||||
}
|
||||
|
||||
if err := git_model.InsertProtectedTag(ctx, pt); err != nil {
|
||||
ctx.ServerError("InsertProtectedTag", err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success"))
|
||||
ctx.Redirect(setting.AppSubURL + ctx.Req.URL.EscapedPath())
|
||||
}
|
||||
|
||||
// EditProtectedTag render the page to edit a protect tag
|
||||
func EditProtectedTag(ctx *context.Context) {
|
||||
if setTagsContext(ctx) != nil {
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Data["PageIsEditProtectedTag"] = true
|
||||
|
||||
pt := selectProtectedTagByContext(ctx)
|
||||
if pt == nil {
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Data["name_pattern"] = pt.NamePattern
|
||||
ctx.Data["allowlist_users"] = strings.Join(base.Int64sToStrings(pt.AllowlistUserIDs), ",")
|
||||
ctx.Data["allowlist_teams"] = strings.Join(base.Int64sToStrings(pt.AllowlistTeamIDs), ",")
|
||||
|
||||
ctx.HTML(http.StatusOK, tplTags)
|
||||
}
|
||||
|
||||
// EditProtectedTagPost handles creation of a protect tag
|
||||
func EditProtectedTagPost(ctx *context.Context) {
|
||||
if setTagsContext(ctx) != nil {
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Data["PageIsEditProtectedTag"] = true
|
||||
|
||||
if ctx.HasError() {
|
||||
ctx.HTML(http.StatusOK, tplTags)
|
||||
return
|
||||
}
|
||||
|
||||
pt := selectProtectedTagByContext(ctx)
|
||||
if pt == nil {
|
||||
return
|
||||
}
|
||||
|
||||
form := web.GetForm(ctx).(*forms.ProtectTagForm)
|
||||
|
||||
pt.NamePattern = strings.TrimSpace(form.NamePattern)
|
||||
pt.AllowlistUserIDs, _ = base.StringsToInt64s(strings.Split(form.AllowlistUsers, ","))
|
||||
pt.AllowlistTeamIDs, _ = base.StringsToInt64s(strings.Split(form.AllowlistTeams, ","))
|
||||
|
||||
if err := git_model.UpdateProtectedTag(ctx, pt); err != nil {
|
||||
ctx.ServerError("UpdateProtectedTag", err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success"))
|
||||
ctx.Redirect(ctx.Repo.Repository.Link() + "/settings/tags")
|
||||
}
|
||||
|
||||
// DeleteProtectedTagPost handles deletion of a protected tag
|
||||
func DeleteProtectedTagPost(ctx *context.Context) {
|
||||
pt := selectProtectedTagByContext(ctx)
|
||||
if pt == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if err := git_model.DeleteProtectedTag(ctx, pt); err != nil {
|
||||
ctx.ServerError("DeleteProtectedTag", err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success"))
|
||||
ctx.Redirect(ctx.Repo.Repository.Link() + "/settings/tags")
|
||||
}
|
||||
|
||||
func setTagsContext(ctx *context.Context) error {
|
||||
ctx.Data["Title"] = ctx.Tr("repo.settings.tags")
|
||||
ctx.Data["PageIsSettingsTags"] = true
|
||||
|
||||
protectedTags, err := git_model.GetProtectedTags(ctx, ctx.Repo.Repository.ID)
|
||||
if err != nil {
|
||||
ctx.ServerError("GetProtectedTags", err)
|
||||
return err
|
||||
}
|
||||
ctx.Data["ProtectedTags"] = protectedTags
|
||||
|
||||
users, err := access_model.GetUsersWithUnitAccess(ctx, ctx.Repo.Repository, perm.AccessModeRead, unit.TypePullRequests)
|
||||
if err != nil {
|
||||
ctx.ServerError("GetUsersWithUnitAccess", err)
|
||||
return err
|
||||
}
|
||||
ctx.Data["Users"] = users
|
||||
|
||||
if ctx.Repo.Owner.IsOrganization() {
|
||||
teams, err := organization.GetTeamsWithAccessToAnyRepoUnit(ctx, ctx.Repo.Owner.ID, ctx.Repo.Repository.ID, perm.AccessModeRead, unit.TypeCode, unit.TypePullRequests)
|
||||
if err != nil {
|
||||
ctx.ServerError("Repo.Owner.TeamsWithAccessToRepo", err)
|
||||
return err
|
||||
}
|
||||
ctx.Data["Teams"] = teams
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func selectProtectedTagByContext(ctx *context.Context) *git_model.ProtectedTag {
|
||||
id := ctx.FormInt64("id")
|
||||
if id == 0 {
|
||||
id = ctx.PathParamInt64("id")
|
||||
}
|
||||
|
||||
tag, err := git_model.GetProtectedTagByID(ctx, id)
|
||||
if err != nil {
|
||||
ctx.ServerError("GetProtectedTagByID", err)
|
||||
return nil
|
||||
}
|
||||
|
||||
if tag != nil && tag.RepoID == ctx.Repo.Repository.ID {
|
||||
return tag
|
||||
}
|
||||
|
||||
ctx.NotFound(fmt.Errorf("ProtectedTag[%v] not associated to repository %v", id, ctx.Repo.Repository))
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
// Copyright 2025 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package setting
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"slices"
|
||||
"strconv"
|
||||
|
||||
"gitea.dev/models/perm"
|
||||
"gitea.dev/models/repo"
|
||||
"gitea.dev/models/unit"
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/modules/templates"
|
||||
"gitea.dev/services/context"
|
||||
)
|
||||
|
||||
const tplRepoSettingsPublicAccess templates.TplName = "repo/settings/public_access"
|
||||
|
||||
func parsePublicAccessMode(permission string, allowed []string) (ret struct {
|
||||
AnonymousAccessMode, EveryoneAccessMode perm.AccessMode
|
||||
},
|
||||
) {
|
||||
ret.AnonymousAccessMode = perm.AccessModeNone
|
||||
ret.EveryoneAccessMode = perm.AccessModeNone
|
||||
|
||||
// if site admin forces repositories to be private, then do not allow any other access mode,
|
||||
// otherwise the "force private" setting would be bypassed
|
||||
if setting.Repository.ForcePrivate {
|
||||
return ret
|
||||
}
|
||||
if !slices.Contains(allowed, permission) {
|
||||
return ret
|
||||
}
|
||||
switch permission {
|
||||
case paAnonymousRead:
|
||||
ret.AnonymousAccessMode = perm.AccessModeRead
|
||||
case paEveryoneRead:
|
||||
ret.EveryoneAccessMode = perm.AccessModeRead
|
||||
case paEveryoneWrite:
|
||||
ret.EveryoneAccessMode = perm.AccessModeWrite
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
||||
const (
|
||||
paNotSet = "not-set"
|
||||
paAnonymousRead = "anonymous-read"
|
||||
paEveryoneRead = "everyone-read"
|
||||
paEveryoneWrite = "everyone-write"
|
||||
)
|
||||
|
||||
type repoUnitPublicAccess struct {
|
||||
UnitType unit.Type
|
||||
FormKey string
|
||||
DisplayName string
|
||||
PublicAccessTypes []string
|
||||
UnitPublicAccess string
|
||||
}
|
||||
|
||||
func repoUnitPublicAccesses(ctx *context.Context) []*repoUnitPublicAccess {
|
||||
accesses := []*repoUnitPublicAccess{
|
||||
{
|
||||
UnitType: unit.TypeCode,
|
||||
DisplayName: ctx.Locale.TrString("repo.code"),
|
||||
PublicAccessTypes: []string{paAnonymousRead, paEveryoneRead},
|
||||
},
|
||||
{
|
||||
UnitType: unit.TypeIssues,
|
||||
DisplayName: ctx.Locale.TrString("issues"),
|
||||
PublicAccessTypes: []string{paAnonymousRead, paEveryoneRead},
|
||||
},
|
||||
{
|
||||
UnitType: unit.TypePullRequests,
|
||||
DisplayName: ctx.Locale.TrString("pull_requests"),
|
||||
PublicAccessTypes: []string{paAnonymousRead, paEveryoneRead},
|
||||
},
|
||||
{
|
||||
UnitType: unit.TypeReleases,
|
||||
DisplayName: ctx.Locale.TrString("repo.releases"),
|
||||
PublicAccessTypes: []string{paAnonymousRead, paEveryoneRead},
|
||||
},
|
||||
{
|
||||
UnitType: unit.TypeWiki,
|
||||
DisplayName: ctx.Locale.TrString("repo.wiki"),
|
||||
PublicAccessTypes: []string{paAnonymousRead, paEveryoneRead, paEveryoneWrite},
|
||||
},
|
||||
{
|
||||
UnitType: unit.TypeProjects,
|
||||
DisplayName: ctx.Locale.TrString("repo.projects"),
|
||||
PublicAccessTypes: []string{paAnonymousRead, paEveryoneRead},
|
||||
},
|
||||
{
|
||||
UnitType: unit.TypePackages,
|
||||
DisplayName: ctx.Locale.TrString("repo.packages"),
|
||||
PublicAccessTypes: []string{paAnonymousRead, paEveryoneRead},
|
||||
},
|
||||
{
|
||||
UnitType: unit.TypeActions,
|
||||
DisplayName: ctx.Locale.TrString("repo.actions"),
|
||||
PublicAccessTypes: []string{paAnonymousRead, paEveryoneRead},
|
||||
},
|
||||
}
|
||||
for _, ua := range accesses {
|
||||
ua.FormKey = "repo-unit-access-" + strconv.Itoa(int(ua.UnitType))
|
||||
for _, u := range ctx.Repo.Repository.Units {
|
||||
if u.Type == ua.UnitType {
|
||||
ua.UnitPublicAccess = paNotSet
|
||||
switch {
|
||||
case u.EveryoneAccessMode == perm.AccessModeWrite:
|
||||
ua.UnitPublicAccess = paEveryoneWrite
|
||||
case u.EveryoneAccessMode == perm.AccessModeRead:
|
||||
ua.UnitPublicAccess = paEveryoneRead
|
||||
case u.AnonymousAccessMode == perm.AccessModeRead:
|
||||
ua.UnitPublicAccess = paAnonymousRead
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return slices.DeleteFunc(accesses, func(ua *repoUnitPublicAccess) bool {
|
||||
return ua.UnitPublicAccess == ""
|
||||
})
|
||||
}
|
||||
|
||||
func PublicAccess(ctx *context.Context) {
|
||||
ctx.Data["PageIsSettingsPublicAccess"] = true
|
||||
ctx.Data["RepoUnitPublicAccesses"] = repoUnitPublicAccesses(ctx)
|
||||
ctx.Data["GlobalForcePrivate"] = setting.Repository.ForcePrivate
|
||||
if setting.Repository.ForcePrivate {
|
||||
ctx.Flash.Error(ctx.Tr("form.repository_force_private"), true)
|
||||
}
|
||||
ctx.HTML(http.StatusOK, tplRepoSettingsPublicAccess)
|
||||
}
|
||||
|
||||
func PublicAccessPost(ctx *context.Context) {
|
||||
accesses := repoUnitPublicAccesses(ctx)
|
||||
for _, ua := range accesses {
|
||||
formVal := ctx.FormString(ua.FormKey)
|
||||
parsed := parsePublicAccessMode(formVal, ua.PublicAccessTypes)
|
||||
err := repo.UpdateRepoUnitPublicAccess(ctx, &repo.RepoUnit{
|
||||
RepoID: ctx.Repo.Repository.ID,
|
||||
Type: ua.UnitType,
|
||||
AnonymousAccessMode: parsed.AnonymousAccessMode,
|
||||
EveryoneAccessMode: parsed.EveryoneAccessMode,
|
||||
})
|
||||
if err != nil {
|
||||
ctx.ServerError("UpdateRepoUnitPublicAccess", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success"))
|
||||
ctx.Redirect(ctx.Repo.Repository.Link() + "/settings/public_access")
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
// Copyright 2022 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package setting
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/modules/templates"
|
||||
shared "gitea.dev/routers/web/shared/secrets"
|
||||
shared_user "gitea.dev/routers/web/shared/user"
|
||||
"gitea.dev/services/context"
|
||||
)
|
||||
|
||||
const (
|
||||
// TODO: Separate secrets from runners when layout is ready
|
||||
tplRepoSecrets templates.TplName = "repo/settings/actions"
|
||||
tplOrgSecrets templates.TplName = "org/settings/actions"
|
||||
tplUserSecrets templates.TplName = "user/settings/actions"
|
||||
)
|
||||
|
||||
type secretsCtx struct {
|
||||
OwnerID int64
|
||||
RepoID int64
|
||||
IsRepo bool
|
||||
IsOrg bool
|
||||
IsUser bool
|
||||
SecretsTemplate templates.TplName
|
||||
RedirectLink string
|
||||
}
|
||||
|
||||
func getSecretsCtx(ctx *context.Context) (*secretsCtx, error) {
|
||||
if ctx.Data["PageIsRepoSettings"] == true {
|
||||
return &secretsCtx{
|
||||
OwnerID: 0,
|
||||
RepoID: ctx.Repo.Repository.ID,
|
||||
IsRepo: true,
|
||||
SecretsTemplate: tplRepoSecrets,
|
||||
RedirectLink: ctx.Repo.RepoLink + "/settings/actions/secrets",
|
||||
}, nil
|
||||
}
|
||||
|
||||
if ctx.Data["PageIsOrgSettings"] == true {
|
||||
if _, err := shared_user.RenderUserOrgHeader(ctx); err != nil {
|
||||
ctx.ServerError("RenderUserOrgHeader", err)
|
||||
return nil, nil //nolint:nilnil // error is already handled by ctx.ServerError
|
||||
}
|
||||
return &secretsCtx{
|
||||
OwnerID: ctx.ContextUser.ID,
|
||||
RepoID: 0,
|
||||
IsOrg: true,
|
||||
SecretsTemplate: tplOrgSecrets,
|
||||
RedirectLink: ctx.Org.OrgLink + "/settings/actions/secrets",
|
||||
}, nil
|
||||
}
|
||||
|
||||
if ctx.Data["PageIsUserSettings"] == true {
|
||||
return &secretsCtx{
|
||||
OwnerID: ctx.Doer.ID,
|
||||
RepoID: 0,
|
||||
IsUser: true,
|
||||
SecretsTemplate: tplUserSecrets,
|
||||
RedirectLink: setting.AppSubURL + "/user/settings/actions/secrets",
|
||||
}, nil
|
||||
}
|
||||
|
||||
return nil, errors.New("unable to set Secrets context")
|
||||
}
|
||||
|
||||
func Secrets(ctx *context.Context) {
|
||||
ctx.Data["Title"] = ctx.Tr("actions.actions")
|
||||
ctx.Data["PageType"] = "secrets"
|
||||
ctx.Data["PageIsSharedSettingsSecrets"] = true
|
||||
|
||||
sCtx, err := getSecretsCtx(ctx)
|
||||
if err != nil {
|
||||
ctx.ServerError("getSecretsCtx", err)
|
||||
return
|
||||
}
|
||||
|
||||
if sCtx.IsRepo {
|
||||
ctx.Data["DisableSSH"] = setting.SSH.Disabled
|
||||
}
|
||||
|
||||
shared.SetSecretsContext(ctx, sCtx.OwnerID, sCtx.RepoID)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
ctx.HTML(http.StatusOK, sCtx.SecretsTemplate)
|
||||
}
|
||||
|
||||
func SecretsPost(ctx *context.Context) {
|
||||
sCtx, err := getSecretsCtx(ctx)
|
||||
if err != nil {
|
||||
ctx.ServerError("getSecretsCtx", err)
|
||||
return
|
||||
}
|
||||
|
||||
if ctx.HasError() {
|
||||
ctx.JSONError(ctx.GetErrMsg())
|
||||
return
|
||||
}
|
||||
|
||||
shared.PerformSecretsPost(
|
||||
ctx,
|
||||
sCtx.OwnerID,
|
||||
sCtx.RepoID,
|
||||
sCtx.RedirectLink,
|
||||
)
|
||||
}
|
||||
|
||||
func SecretsDelete(ctx *context.Context) {
|
||||
sCtx, err := getSecretsCtx(ctx)
|
||||
if err != nil {
|
||||
ctx.ServerError("getSecretsCtx", err)
|
||||
return
|
||||
}
|
||||
shared.PerformSecretsDelete(
|
||||
ctx,
|
||||
sCtx.OwnerID,
|
||||
sCtx.RepoID,
|
||||
sCtx.RedirectLink,
|
||||
)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,433 @@
|
||||
// Copyright 2017 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package setting
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
asymkey_model "gitea.dev/models/asymkey"
|
||||
"gitea.dev/models/organization"
|
||||
"gitea.dev/models/perm"
|
||||
repo_model "gitea.dev/models/repo"
|
||||
"gitea.dev/models/unittest"
|
||||
user_model "gitea.dev/models/user"
|
||||
"gitea.dev/modules/gitrepo"
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/modules/test"
|
||||
"gitea.dev/modules/web"
|
||||
"gitea.dev/services/context"
|
||||
"gitea.dev/services/contexttest"
|
||||
"gitea.dev/services/forms"
|
||||
mirror_service "gitea.dev/services/mirror"
|
||||
repo_service "gitea.dev/services/repository"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestAddReadOnlyDeployKey(t *testing.T) {
|
||||
defer test.MockVariableValue(&setting.SSH.RootPath, t.TempDir())()
|
||||
unittest.PrepareTestEnv(t)
|
||||
|
||||
ctx, _ := contexttest.MockContext(t, "user2/repo1/settings/keys")
|
||||
|
||||
contexttest.LoadUser(t, ctx, 2)
|
||||
contexttest.LoadRepo(t, ctx, 2)
|
||||
|
||||
addKeyForm := forms.AddKeyForm{
|
||||
Title: "read-only",
|
||||
Content: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC4cn+iXnA4KvcQYSV88vGn0Yi91vG47t1P7okprVmhNTkipNRIHWr6WdCO4VDr/cvsRkuVJAsLO2enwjGWWueOO6BodiBgyAOZ/5t5nJNMCNuLGT5UIo/RI1b0WRQwxEZTRjt6mFNw6lH14wRd8ulsr9toSWBPMOGWoYs1PDeDL0JuTjL+tr1SZi/EyxCngpYszKdXllJEHyI79KQgeD0Vt3pTrkbNVTOEcCNqZePSVmUH8X8Vhugz3bnE0/iE9Pb5fkWO9c4AnM1FgI/8Bvp27Fw2ShryIXuR6kKvUqhVMTuOSDHwu6A8jLE5Owt3GAYugDpDYuwTVNGrHLXKpPzrGGPE/jPmaLCMZcsdkec95dYeU3zKODEm8UQZFhmJmDeWVJ36nGrGZHL4J5aTTaeFUJmmXDaJYiJ+K2/ioKgXqnXvltu0A9R8/LGy4nrTJRr4JMLuJFoUXvGm1gXQ70w2LSpk6yl71RNC0hCtsBe8BP8IhYCM0EP5jh7eCMQZNvM= nocomment\n",
|
||||
}
|
||||
web.SetForm(ctx, &addKeyForm)
|
||||
DeployKeysPost(ctx)
|
||||
assert.Equal(t, http.StatusSeeOther, ctx.Resp.WrittenStatus())
|
||||
|
||||
unittest.AssertExistsAndLoadBean(t, &asymkey_model.DeployKey{
|
||||
Name: addKeyForm.Title,
|
||||
Content: addKeyForm.Content,
|
||||
Mode: perm.AccessModeRead,
|
||||
})
|
||||
}
|
||||
|
||||
func TestAddReadWriteOnlyDeployKey(t *testing.T) {
|
||||
defer test.MockVariableValue(&setting.SSH.RootPath, t.TempDir())()
|
||||
|
||||
unittest.PrepareTestEnv(t)
|
||||
|
||||
ctx, _ := contexttest.MockContext(t, "user2/repo1/settings/keys")
|
||||
|
||||
contexttest.LoadUser(t, ctx, 2)
|
||||
contexttest.LoadRepo(t, ctx, 2)
|
||||
|
||||
addKeyForm := forms.AddKeyForm{
|
||||
Title: "read-write",
|
||||
Content: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC4cn+iXnA4KvcQYSV88vGn0Yi91vG47t1P7okprVmhNTkipNRIHWr6WdCO4VDr/cvsRkuVJAsLO2enwjGWWueOO6BodiBgyAOZ/5t5nJNMCNuLGT5UIo/RI1b0WRQwxEZTRjt6mFNw6lH14wRd8ulsr9toSWBPMOGWoYs1PDeDL0JuTjL+tr1SZi/EyxCngpYszKdXllJEHyI79KQgeD0Vt3pTrkbNVTOEcCNqZePSVmUH8X8Vhugz3bnE0/iE9Pb5fkWO9c4AnM1FgI/8Bvp27Fw2ShryIXuR6kKvUqhVMTuOSDHwu6A8jLE5Owt3GAYugDpDYuwTVNGrHLXKpPzrGGPE/jPmaLCMZcsdkec95dYeU3zKODEm8UQZFhmJmDeWVJ36nGrGZHL4J5aTTaeFUJmmXDaJYiJ+K2/ioKgXqnXvltu0A9R8/LGy4nrTJRr4JMLuJFoUXvGm1gXQ70w2LSpk6yl71RNC0hCtsBe8BP8IhYCM0EP5jh7eCMQZNvM= nocomment\n",
|
||||
IsWritable: true,
|
||||
}
|
||||
web.SetForm(ctx, &addKeyForm)
|
||||
DeployKeysPost(ctx)
|
||||
assert.Equal(t, http.StatusSeeOther, ctx.Resp.WrittenStatus())
|
||||
|
||||
unittest.AssertExistsAndLoadBean(t, &asymkey_model.DeployKey{
|
||||
Name: addKeyForm.Title,
|
||||
Content: addKeyForm.Content,
|
||||
Mode: perm.AccessModeWrite,
|
||||
})
|
||||
}
|
||||
|
||||
func TestCollaborationPost(t *testing.T) {
|
||||
unittest.PrepareTestEnv(t)
|
||||
ctx, _ := contexttest.MockContext(t, "user2/repo1/issues/labels")
|
||||
contexttest.LoadUser(t, ctx, 2)
|
||||
contexttest.LoadUser(t, ctx, 4)
|
||||
contexttest.LoadRepo(t, ctx, 1)
|
||||
|
||||
ctx.Req.Form.Set("collaborator", "user4")
|
||||
|
||||
u := &user_model.User{
|
||||
LowerName: "user2",
|
||||
Type: user_model.UserTypeIndividual,
|
||||
}
|
||||
|
||||
re := &repo_model.Repository{
|
||||
ID: 2,
|
||||
Owner: u,
|
||||
}
|
||||
|
||||
repo := &context.Repository{
|
||||
Owner: u,
|
||||
Repository: re,
|
||||
}
|
||||
|
||||
ctx.Repo = repo
|
||||
|
||||
CollaborationPost(ctx)
|
||||
|
||||
assert.Equal(t, http.StatusSeeOther, ctx.Resp.WrittenStatus())
|
||||
|
||||
exists, err := repo_model.IsCollaborator(ctx, re.ID, 4)
|
||||
assert.NoError(t, err)
|
||||
assert.True(t, exists)
|
||||
}
|
||||
|
||||
func TestCollaborationPost_InactiveUser(t *testing.T) {
|
||||
unittest.PrepareTestEnv(t)
|
||||
ctx, _ := contexttest.MockContext(t, "user2/repo1/issues/labels")
|
||||
contexttest.LoadUser(t, ctx, 2)
|
||||
contexttest.LoadUser(t, ctx, 9)
|
||||
contexttest.LoadRepo(t, ctx, 1)
|
||||
|
||||
ctx.Req.Form.Set("collaborator", "user9")
|
||||
|
||||
repo := &context.Repository{
|
||||
Owner: &user_model.User{
|
||||
LowerName: "user2",
|
||||
},
|
||||
}
|
||||
|
||||
ctx.Repo = repo
|
||||
|
||||
CollaborationPost(ctx)
|
||||
|
||||
assert.Equal(t, http.StatusSeeOther, ctx.Resp.WrittenStatus())
|
||||
assert.NotEmpty(t, ctx.Flash.ErrorMsg)
|
||||
}
|
||||
|
||||
func TestCollaborationPost_AddCollaboratorTwice(t *testing.T) {
|
||||
unittest.PrepareTestEnv(t)
|
||||
ctx, _ := contexttest.MockContext(t, "user2/repo1/issues/labels")
|
||||
contexttest.LoadUser(t, ctx, 2)
|
||||
contexttest.LoadUser(t, ctx, 4)
|
||||
contexttest.LoadRepo(t, ctx, 1)
|
||||
|
||||
ctx.Req.Form.Set("collaborator", "user4")
|
||||
|
||||
u := &user_model.User{
|
||||
LowerName: "user2",
|
||||
Type: user_model.UserTypeIndividual,
|
||||
}
|
||||
|
||||
re := &repo_model.Repository{
|
||||
ID: 2,
|
||||
Owner: u,
|
||||
}
|
||||
|
||||
repo := &context.Repository{
|
||||
Owner: u,
|
||||
Repository: re,
|
||||
}
|
||||
|
||||
ctx.Repo = repo
|
||||
|
||||
CollaborationPost(ctx)
|
||||
|
||||
assert.Equal(t, http.StatusSeeOther, ctx.Resp.WrittenStatus())
|
||||
|
||||
exists, err := repo_model.IsCollaborator(ctx, re.ID, 4)
|
||||
assert.NoError(t, err)
|
||||
assert.True(t, exists)
|
||||
|
||||
// Try adding the same collaborator again
|
||||
CollaborationPost(ctx)
|
||||
|
||||
assert.Equal(t, http.StatusSeeOther, ctx.Resp.WrittenStatus())
|
||||
assert.NotEmpty(t, ctx.Flash.ErrorMsg)
|
||||
}
|
||||
|
||||
func TestCollaborationPost_NonExistentUser(t *testing.T) {
|
||||
unittest.PrepareTestEnv(t)
|
||||
ctx, _ := contexttest.MockContext(t, "user2/repo1/issues/labels")
|
||||
contexttest.LoadUser(t, ctx, 2)
|
||||
contexttest.LoadRepo(t, ctx, 1)
|
||||
|
||||
ctx.Req.Form.Set("collaborator", "user34")
|
||||
|
||||
repo := &context.Repository{
|
||||
Owner: &user_model.User{
|
||||
LowerName: "user2",
|
||||
},
|
||||
}
|
||||
|
||||
ctx.Repo = repo
|
||||
|
||||
CollaborationPost(ctx)
|
||||
|
||||
assert.Equal(t, http.StatusSeeOther, ctx.Resp.WrittenStatus())
|
||||
assert.NotEmpty(t, ctx.Flash.ErrorMsg)
|
||||
}
|
||||
|
||||
func TestAddTeamPost(t *testing.T) {
|
||||
unittest.PrepareTestEnv(t)
|
||||
ctx, _ := contexttest.MockContext(t, "org26/repo43")
|
||||
|
||||
ctx.Req.Form.Set("team", "team11")
|
||||
|
||||
org := &user_model.User{
|
||||
LowerName: "org26",
|
||||
Type: user_model.UserTypeOrganization,
|
||||
}
|
||||
|
||||
team := &organization.Team{
|
||||
ID: 11,
|
||||
OrgID: 26,
|
||||
}
|
||||
|
||||
re := &repo_model.Repository{
|
||||
ID: 43,
|
||||
Owner: org,
|
||||
OwnerID: 26,
|
||||
}
|
||||
|
||||
repo := &context.Repository{
|
||||
Owner: &user_model.User{
|
||||
ID: 26,
|
||||
LowerName: "org26",
|
||||
RepoAdminChangeTeamAccess: true,
|
||||
},
|
||||
Repository: re,
|
||||
}
|
||||
|
||||
ctx.Repo = repo
|
||||
|
||||
AddTeamPost(ctx)
|
||||
|
||||
assert.True(t, repo_service.HasRepository(t.Context(), team, re.ID))
|
||||
assert.Equal(t, http.StatusSeeOther, ctx.Resp.WrittenStatus())
|
||||
assert.Empty(t, ctx.Flash.ErrorMsg)
|
||||
}
|
||||
|
||||
func TestAddTeamPost_NotAllowed(t *testing.T) {
|
||||
unittest.PrepareTestEnv(t)
|
||||
ctx, _ := contexttest.MockContext(t, "org26/repo43")
|
||||
|
||||
ctx.Req.Form.Set("team", "team11")
|
||||
|
||||
org := &user_model.User{
|
||||
LowerName: "org26",
|
||||
Type: user_model.UserTypeOrganization,
|
||||
}
|
||||
|
||||
team := &organization.Team{
|
||||
ID: 11,
|
||||
OrgID: 26,
|
||||
}
|
||||
|
||||
re := &repo_model.Repository{
|
||||
ID: 43,
|
||||
Owner: org,
|
||||
OwnerID: 26,
|
||||
}
|
||||
|
||||
repo := &context.Repository{
|
||||
Owner: &user_model.User{
|
||||
ID: 26,
|
||||
LowerName: "org26",
|
||||
RepoAdminChangeTeamAccess: false,
|
||||
},
|
||||
Repository: re,
|
||||
}
|
||||
|
||||
ctx.Repo = repo
|
||||
|
||||
AddTeamPost(ctx)
|
||||
|
||||
assert.False(t, repo_service.HasRepository(t.Context(), team, re.ID))
|
||||
assert.Equal(t, http.StatusSeeOther, ctx.Resp.WrittenStatus())
|
||||
assert.NotEmpty(t, ctx.Flash.ErrorMsg)
|
||||
}
|
||||
|
||||
func TestAddTeamPost_AddTeamTwice(t *testing.T) {
|
||||
unittest.PrepareTestEnv(t)
|
||||
ctx, _ := contexttest.MockContext(t, "org26/repo43")
|
||||
|
||||
ctx.Req.Form.Set("team", "team11")
|
||||
|
||||
org := &user_model.User{
|
||||
LowerName: "org26",
|
||||
Type: user_model.UserTypeOrganization,
|
||||
}
|
||||
|
||||
team := &organization.Team{
|
||||
ID: 11,
|
||||
OrgID: 26,
|
||||
}
|
||||
|
||||
re := &repo_model.Repository{
|
||||
ID: 43,
|
||||
Owner: org,
|
||||
OwnerID: 26,
|
||||
}
|
||||
|
||||
repo := &context.Repository{
|
||||
Owner: &user_model.User{
|
||||
ID: 26,
|
||||
LowerName: "org26",
|
||||
RepoAdminChangeTeamAccess: true,
|
||||
},
|
||||
Repository: re,
|
||||
}
|
||||
|
||||
ctx.Repo = repo
|
||||
|
||||
AddTeamPost(ctx)
|
||||
|
||||
AddTeamPost(ctx)
|
||||
assert.True(t, repo_service.HasRepository(t.Context(), team, re.ID))
|
||||
assert.Equal(t, http.StatusSeeOther, ctx.Resp.WrittenStatus())
|
||||
assert.NotEmpty(t, ctx.Flash.ErrorMsg)
|
||||
}
|
||||
|
||||
func TestAddTeamPost_NonExistentTeam(t *testing.T) {
|
||||
unittest.PrepareTestEnv(t)
|
||||
ctx, _ := contexttest.MockContext(t, "org26/repo43")
|
||||
|
||||
ctx.Req.Form.Set("team", "team-non-existent")
|
||||
|
||||
org := &user_model.User{
|
||||
LowerName: "org26",
|
||||
Type: user_model.UserTypeOrganization,
|
||||
}
|
||||
|
||||
re := &repo_model.Repository{
|
||||
ID: 43,
|
||||
Owner: org,
|
||||
OwnerID: 26,
|
||||
}
|
||||
|
||||
repo := &context.Repository{
|
||||
Owner: &user_model.User{
|
||||
ID: 26,
|
||||
LowerName: "org26",
|
||||
RepoAdminChangeTeamAccess: true,
|
||||
},
|
||||
Repository: re,
|
||||
}
|
||||
|
||||
ctx.Repo = repo
|
||||
|
||||
AddTeamPost(ctx)
|
||||
assert.Equal(t, http.StatusSeeOther, ctx.Resp.WrittenStatus())
|
||||
assert.NotEmpty(t, ctx.Flash.ErrorMsg)
|
||||
}
|
||||
|
||||
func TestDeleteTeam(t *testing.T) {
|
||||
unittest.PrepareTestEnv(t)
|
||||
ctx, _ := contexttest.MockContext(t, "org3/team1/repo3")
|
||||
|
||||
ctx.Req.Form.Set("id", "2")
|
||||
|
||||
org := &user_model.User{
|
||||
LowerName: "org3",
|
||||
Type: user_model.UserTypeOrganization,
|
||||
}
|
||||
|
||||
team := &organization.Team{
|
||||
ID: 2,
|
||||
OrgID: 3,
|
||||
}
|
||||
|
||||
re := &repo_model.Repository{
|
||||
ID: 3,
|
||||
Owner: org,
|
||||
OwnerID: 3,
|
||||
}
|
||||
|
||||
repo := &context.Repository{
|
||||
Owner: &user_model.User{
|
||||
ID: 3,
|
||||
LowerName: "org3",
|
||||
RepoAdminChangeTeamAccess: true,
|
||||
},
|
||||
Repository: re,
|
||||
}
|
||||
|
||||
ctx.Repo = repo
|
||||
|
||||
DeleteTeam(ctx)
|
||||
|
||||
assert.False(t, repo_service.HasRepository(t.Context(), team, re.ID))
|
||||
}
|
||||
|
||||
func TestHandleSettingsPostMirrorPreservesExistingUsername(t *testing.T) {
|
||||
defer test.MockVariableValue(&setting.Mirror.Enabled, true)()
|
||||
|
||||
unittest.PrepareTestEnv(t)
|
||||
|
||||
// Use the existing fixture mirror repo (org3/repo5) which has a git repo on disk.
|
||||
mirrorRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 5})
|
||||
mirror := unittest.AssertExistsAndLoadBean(t, &repo_model.Mirror{RepoID: 5})
|
||||
|
||||
require.NoError(t, mirror_service.UpdateAddress(t.Context(), mirror, "https://existing-user:existing-password@example.com/user2/repo1.git"))
|
||||
|
||||
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
||||
|
||||
ctx, _ := contexttest.MockContext(t, mirrorRepo.Link()+"/settings")
|
||||
contexttest.LoadUser(t, ctx, user.ID)
|
||||
contexttest.LoadRepo(t, ctx, mirrorRepo.ID)
|
||||
|
||||
web.SetForm(ctx, &forms.RepoSettingForm{
|
||||
Interval: "8h",
|
||||
MirrorAddress: "https://example.com/user2/repo1.git",
|
||||
MirrorPassword: "updated-password",
|
||||
})
|
||||
|
||||
handleSettingsPostMirror(ctx)
|
||||
|
||||
assert.Equal(t, http.StatusSeeOther, ctx.Resp.WrittenStatus())
|
||||
|
||||
updatedMirror := unittest.AssertExistsAndLoadBean(t, &repo_model.Mirror{RepoID: mirrorRepo.ID})
|
||||
assert.Equal(t, "https://example.com/user2/repo1.git", updatedMirror.RemoteAddress)
|
||||
|
||||
updatedRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: mirrorRepo.ID})
|
||||
assert.Equal(t, "https://example.com/user2/repo1.git", updatedRepo.OriginalURL)
|
||||
|
||||
remoteURL, err := gitrepo.GitRemoteGetURL(t.Context(), updatedRepo, updatedMirror.GetRemoteName())
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, remoteURL.User)
|
||||
assert.Equal(t, "existing-user", remoteURL.User.Username())
|
||||
password, ok := remoteURL.User.Password()
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, "updated-password", password)
|
||||
}
|
||||
@@ -0,0 +1,751 @@
|
||||
// Copyright 2015 The Gogs Authors. All rights reserved.
|
||||
// Copyright 2017 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package setting
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path"
|
||||
"strings"
|
||||
|
||||
"gitea.dev/models/db"
|
||||
"gitea.dev/models/perm"
|
||||
access_model "gitea.dev/models/perm/access"
|
||||
user_model "gitea.dev/models/user"
|
||||
"gitea.dev/models/webhook"
|
||||
"gitea.dev/modules/git"
|
||||
"gitea.dev/modules/json"
|
||||
"gitea.dev/modules/setting"
|
||||
api "gitea.dev/modules/structs"
|
||||
"gitea.dev/modules/templates"
|
||||
"gitea.dev/modules/util"
|
||||
"gitea.dev/modules/web"
|
||||
webhook_module "gitea.dev/modules/webhook"
|
||||
"gitea.dev/services/context"
|
||||
"gitea.dev/services/convert"
|
||||
"gitea.dev/services/forms"
|
||||
webhook_service "gitea.dev/services/webhook"
|
||||
)
|
||||
|
||||
const (
|
||||
tplHooks templates.TplName = "repo/settings/webhook/base"
|
||||
tplHookNew templates.TplName = "repo/settings/webhook/new"
|
||||
tplOrgHookNew templates.TplName = "org/settings/hook_new"
|
||||
tplUserHookNew templates.TplName = "user/settings/hook_new"
|
||||
tplAdminHookNew templates.TplName = "admin/hook_new"
|
||||
)
|
||||
|
||||
// Webhooks render web hooks list page
|
||||
func Webhooks(ctx *context.Context) {
|
||||
ctx.Data["Title"] = ctx.Tr("repo.settings.hooks")
|
||||
ctx.Data["PageIsSettingsHooks"] = true
|
||||
ctx.Data["BaseLink"] = ctx.Repo.RepoLink + "/settings/hooks"
|
||||
ctx.Data["BaseLinkNew"] = ctx.Repo.RepoLink + "/settings/hooks"
|
||||
ctx.Data["Description"] = ctx.Tr("repo.settings.hooks_desc", "https://docs.gitea.com/usage/webhooks")
|
||||
|
||||
ws, err := db.Find[webhook.Webhook](ctx, webhook.ListWebhookOptions{RepoID: ctx.Repo.Repository.ID})
|
||||
if err != nil {
|
||||
ctx.ServerError("GetWebhooksByRepoID", err)
|
||||
return
|
||||
}
|
||||
ctx.Data["Webhooks"] = ws
|
||||
|
||||
ctx.HTML(http.StatusOK, tplHooks)
|
||||
}
|
||||
|
||||
type ownerRepoCtx struct {
|
||||
OwnerID int64
|
||||
RepoID int64
|
||||
IsAdmin bool
|
||||
IsSystemWebhook bool
|
||||
Link string
|
||||
LinkNew string
|
||||
NewTemplate templates.TplName
|
||||
}
|
||||
|
||||
// getOwnerRepoCtx determines whether this is a repo, owner, or admin (both default and system) context.
|
||||
func getOwnerRepoCtx(ctx *context.Context) (*ownerRepoCtx, error) {
|
||||
if ctx.Data["PageIsRepoSettings"] == true {
|
||||
return &ownerRepoCtx{
|
||||
RepoID: ctx.Repo.Repository.ID,
|
||||
Link: path.Join(ctx.Repo.RepoLink, "settings/hooks"),
|
||||
LinkNew: path.Join(ctx.Repo.RepoLink, "settings/hooks"),
|
||||
NewTemplate: tplHookNew,
|
||||
}, nil
|
||||
}
|
||||
|
||||
if ctx.Data["PageIsOrgSettings"] == true {
|
||||
return &ownerRepoCtx{
|
||||
OwnerID: ctx.ContextUser.ID,
|
||||
Link: path.Join(ctx.Org.OrgLink, "settings/hooks"),
|
||||
LinkNew: path.Join(ctx.Org.OrgLink, "settings/hooks"),
|
||||
NewTemplate: tplOrgHookNew,
|
||||
}, nil
|
||||
}
|
||||
|
||||
if ctx.Data["PageIsUserSettings"] == true {
|
||||
return &ownerRepoCtx{
|
||||
OwnerID: ctx.Doer.ID,
|
||||
Link: path.Join(setting.AppSubURL, "/user/settings/hooks"),
|
||||
LinkNew: path.Join(setting.AppSubURL, "/user/settings/hooks"),
|
||||
NewTemplate: tplUserHookNew,
|
||||
}, nil
|
||||
}
|
||||
|
||||
if ctx.Data["PageIsAdmin"] == true {
|
||||
return &ownerRepoCtx{
|
||||
IsAdmin: true,
|
||||
IsSystemWebhook: ctx.PathParam("configType") == "system-hooks",
|
||||
Link: path.Join(setting.AppSubURL, "/-/admin/hooks"),
|
||||
LinkNew: path.Join(setting.AppSubURL, "/-/admin/", ctx.PathParam("configType")),
|
||||
NewTemplate: tplAdminHookNew,
|
||||
}, nil
|
||||
}
|
||||
|
||||
return nil, errors.New("unable to set OwnerRepo context")
|
||||
}
|
||||
|
||||
func checkHookType(ctx *context.Context) string {
|
||||
hookType := strings.ToLower(ctx.PathParam("type"))
|
||||
if !util.SliceContainsString(setting.Webhook.Types, hookType, true) {
|
||||
ctx.NotFound(nil)
|
||||
return ""
|
||||
}
|
||||
return hookType
|
||||
}
|
||||
|
||||
// WebhooksNew render creating webhook page
|
||||
func WebhooksNew(ctx *context.Context) {
|
||||
ctx.Data["Title"] = ctx.Tr("repo.settings.add_webhook")
|
||||
ctx.Data["Webhook"] = webhook.Webhook{HookEvent: &webhook_module.HookEvent{}}
|
||||
|
||||
orCtx, err := getOwnerRepoCtx(ctx)
|
||||
if err != nil {
|
||||
ctx.ServerError("getOwnerRepoCtx", err)
|
||||
return
|
||||
}
|
||||
|
||||
if orCtx.IsAdmin && orCtx.IsSystemWebhook {
|
||||
ctx.Data["PageIsAdminSystemHooks"] = true
|
||||
ctx.Data["PageIsAdminSystemHooksNew"] = true
|
||||
} else if orCtx.IsAdmin {
|
||||
ctx.Data["PageIsAdminDefaultHooks"] = true
|
||||
ctx.Data["PageIsAdminDefaultHooksNew"] = true
|
||||
} else {
|
||||
ctx.Data["PageIsSettingsHooks"] = true
|
||||
ctx.Data["PageIsSettingsHooksNew"] = true
|
||||
}
|
||||
|
||||
hookType := checkHookType(ctx)
|
||||
ctx.Data["HookType"] = hookType
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
if hookType == "discord" {
|
||||
ctx.Data["DiscordHook"] = map[string]any{
|
||||
"Username": "Gitea",
|
||||
}
|
||||
}
|
||||
ctx.Data["BaseLink"] = orCtx.LinkNew
|
||||
ctx.Data["BaseLinkNew"] = orCtx.LinkNew
|
||||
|
||||
ctx.HTML(http.StatusOK, orCtx.NewTemplate)
|
||||
}
|
||||
|
||||
// ParseHookEvent convert web form content to webhook.HookEvent
|
||||
func ParseHookEvent(form forms.WebhookForm) *webhook_module.HookEvent {
|
||||
return &webhook_module.HookEvent{
|
||||
PushOnly: form.PushOnly(),
|
||||
SendEverything: form.SendEverything(),
|
||||
ChooseEvents: form.ChooseEvents(),
|
||||
HookEvents: webhook_module.HookEvents{
|
||||
webhook_module.HookEventCreate: form.Create,
|
||||
webhook_module.HookEventDelete: form.Delete,
|
||||
webhook_module.HookEventFork: form.Fork,
|
||||
webhook_module.HookEventIssues: form.Issues,
|
||||
webhook_module.HookEventIssueAssign: form.IssueAssign,
|
||||
webhook_module.HookEventIssueLabel: form.IssueLabel,
|
||||
webhook_module.HookEventIssueMilestone: form.IssueMilestone,
|
||||
webhook_module.HookEventIssueComment: form.IssueComment,
|
||||
webhook_module.HookEventRelease: form.Release,
|
||||
webhook_module.HookEventPush: form.Push,
|
||||
webhook_module.HookEventPullRequest: form.PullRequest,
|
||||
webhook_module.HookEventPullRequestAssign: form.PullRequestAssign,
|
||||
webhook_module.HookEventPullRequestLabel: form.PullRequestLabel,
|
||||
webhook_module.HookEventPullRequestMilestone: form.PullRequestMilestone,
|
||||
webhook_module.HookEventPullRequestComment: form.PullRequestComment,
|
||||
webhook_module.HookEventPullRequestReview: form.PullRequestReview,
|
||||
webhook_module.HookEventPullRequestSync: form.PullRequestSync,
|
||||
webhook_module.HookEventPullRequestReviewRequest: form.PullRequestReviewRequest,
|
||||
webhook_module.HookEventWiki: form.Wiki,
|
||||
webhook_module.HookEventRepository: form.Repository,
|
||||
webhook_module.HookEventPackage: form.Package,
|
||||
webhook_module.HookEventStatus: form.Status,
|
||||
webhook_module.HookEventWorkflowRun: form.WorkflowRun,
|
||||
webhook_module.HookEventWorkflowJob: form.WorkflowJob,
|
||||
},
|
||||
BranchFilter: form.BranchFilter,
|
||||
}
|
||||
}
|
||||
|
||||
type webhookParams struct {
|
||||
// Type should be imported from webhook package (webhook.XXX)
|
||||
Type string
|
||||
|
||||
URL string
|
||||
ContentType webhook.HookContentType
|
||||
HTTPMethod string
|
||||
WebhookForm forms.WebhookForm
|
||||
Meta any
|
||||
}
|
||||
|
||||
func createWebhook(ctx *context.Context, params webhookParams) {
|
||||
ctx.Data["Title"] = ctx.Tr("repo.settings.add_webhook")
|
||||
ctx.Data["PageIsSettingsHooks"] = true
|
||||
ctx.Data["PageIsSettingsHooksNew"] = true
|
||||
ctx.Data["Webhook"] = webhook.Webhook{HookEvent: &webhook_module.HookEvent{}}
|
||||
ctx.Data["HookType"] = params.Type
|
||||
|
||||
orCtx, err := getOwnerRepoCtx(ctx)
|
||||
if err != nil {
|
||||
ctx.ServerError("getOwnerRepoCtx", err)
|
||||
return
|
||||
}
|
||||
ctx.Data["BaseLink"] = orCtx.LinkNew
|
||||
|
||||
if ctx.HasError() {
|
||||
ctx.HTML(http.StatusOK, orCtx.NewTemplate)
|
||||
return
|
||||
}
|
||||
|
||||
var meta []byte
|
||||
if params.Meta != nil {
|
||||
meta, err = json.Marshal(params.Meta)
|
||||
if err != nil {
|
||||
ctx.ServerError("Marshal", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
w := &webhook.Webhook{
|
||||
RepoID: orCtx.RepoID,
|
||||
URL: params.URL,
|
||||
Name: strings.TrimSpace(params.WebhookForm.Name),
|
||||
HTTPMethod: params.HTTPMethod,
|
||||
ContentType: params.ContentType,
|
||||
Secret: params.WebhookForm.Secret,
|
||||
HookEvent: ParseHookEvent(params.WebhookForm),
|
||||
IsActive: params.WebhookForm.Active,
|
||||
Type: params.Type,
|
||||
Meta: string(meta),
|
||||
OwnerID: orCtx.OwnerID,
|
||||
IsSystemWebhook: orCtx.IsSystemWebhook,
|
||||
}
|
||||
err = w.SetHeaderAuthorization(params.WebhookForm.AuthorizationHeader)
|
||||
if err != nil {
|
||||
ctx.ServerError("SetHeaderAuthorization", err)
|
||||
return
|
||||
}
|
||||
if err := w.UpdateEvent(); err != nil {
|
||||
ctx.ServerError("UpdateEvent", err)
|
||||
return
|
||||
} else if err := webhook.CreateWebhook(ctx, w); err != nil {
|
||||
ctx.ServerError("CreateWebhook", err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Flash.Success(ctx.Tr("repo.settings.add_hook_success"))
|
||||
ctx.Redirect(orCtx.Link)
|
||||
}
|
||||
|
||||
func editWebhook(ctx *context.Context, params webhookParams) {
|
||||
ctx.Data["Title"] = ctx.Tr("repo.settings.update_webhook")
|
||||
ctx.Data["PageIsSettingsHooks"] = true
|
||||
ctx.Data["PageIsSettingsHooksEdit"] = true
|
||||
|
||||
orCtx, w := checkWebhook(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
ctx.Data["Webhook"] = w
|
||||
|
||||
if ctx.HasError() {
|
||||
ctx.HTML(http.StatusOK, orCtx.NewTemplate)
|
||||
return
|
||||
}
|
||||
|
||||
var meta []byte
|
||||
var err error
|
||||
if params.Meta != nil {
|
||||
meta, err = json.Marshal(params.Meta)
|
||||
if err != nil {
|
||||
ctx.ServerError("Marshal", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
w.URL = params.URL
|
||||
w.Name = strings.TrimSpace(params.WebhookForm.Name)
|
||||
w.ContentType = params.ContentType
|
||||
w.Secret = params.WebhookForm.Secret
|
||||
w.HookEvent = ParseHookEvent(params.WebhookForm)
|
||||
w.IsActive = params.WebhookForm.Active
|
||||
w.HTTPMethod = params.HTTPMethod
|
||||
w.Meta = string(meta)
|
||||
|
||||
err = w.SetHeaderAuthorization(params.WebhookForm.AuthorizationHeader)
|
||||
if err != nil {
|
||||
ctx.ServerError("SetHeaderAuthorization", err)
|
||||
return
|
||||
}
|
||||
|
||||
if err := w.UpdateEvent(); err != nil {
|
||||
ctx.ServerError("UpdateEvent", err)
|
||||
return
|
||||
} else if err := webhook.UpdateWebhook(ctx, w); err != nil {
|
||||
ctx.ServerError("UpdateWebhook", err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Flash.Success(ctx.Tr("repo.settings.update_hook_success"))
|
||||
ctx.Redirect(fmt.Sprintf("%s/%d", orCtx.Link, w.ID))
|
||||
}
|
||||
|
||||
// GiteaHooksNewPost response for creating Gitea webhook
|
||||
func GiteaHooksNewPost(ctx *context.Context) {
|
||||
createWebhook(ctx, giteaHookParams(ctx))
|
||||
}
|
||||
|
||||
// GiteaHooksEditPost response for editing Gitea webhook
|
||||
func GiteaHooksEditPost(ctx *context.Context) {
|
||||
editWebhook(ctx, giteaHookParams(ctx))
|
||||
}
|
||||
|
||||
func giteaHookParams(ctx *context.Context) webhookParams {
|
||||
form := web.GetForm(ctx).(*forms.NewWebhookForm)
|
||||
|
||||
contentType := webhook.ContentTypeJSON
|
||||
if webhook.HookContentType(form.ContentType) == webhook.ContentTypeForm {
|
||||
contentType = webhook.ContentTypeForm
|
||||
}
|
||||
|
||||
return webhookParams{
|
||||
Type: webhook_module.GITEA,
|
||||
URL: form.PayloadURL,
|
||||
ContentType: contentType,
|
||||
HTTPMethod: form.HTTPMethod,
|
||||
WebhookForm: form.WebhookForm,
|
||||
}
|
||||
}
|
||||
|
||||
// GogsHooksNewPost response for creating Gogs webhook
|
||||
func GogsHooksNewPost(ctx *context.Context) {
|
||||
createWebhook(ctx, gogsHookParams(ctx))
|
||||
}
|
||||
|
||||
// GogsHooksEditPost response for editing Gogs webhook
|
||||
func GogsHooksEditPost(ctx *context.Context) {
|
||||
editWebhook(ctx, gogsHookParams(ctx))
|
||||
}
|
||||
|
||||
func gogsHookParams(ctx *context.Context) webhookParams {
|
||||
form := web.GetForm(ctx).(*forms.NewGogshookForm)
|
||||
|
||||
contentType := webhook.ContentTypeJSON
|
||||
if webhook.HookContentType(form.ContentType) == webhook.ContentTypeForm {
|
||||
contentType = webhook.ContentTypeForm
|
||||
}
|
||||
|
||||
return webhookParams{
|
||||
Type: webhook_module.GOGS,
|
||||
URL: form.PayloadURL,
|
||||
ContentType: contentType,
|
||||
WebhookForm: form.WebhookForm,
|
||||
}
|
||||
}
|
||||
|
||||
// DiscordHooksNewPost response for creating Discord webhook
|
||||
func DiscordHooksNewPost(ctx *context.Context) {
|
||||
createWebhook(ctx, discordHookParams(ctx))
|
||||
}
|
||||
|
||||
// DiscordHooksEditPost response for editing Discord webhook
|
||||
func DiscordHooksEditPost(ctx *context.Context) {
|
||||
editWebhook(ctx, discordHookParams(ctx))
|
||||
}
|
||||
|
||||
func discordHookParams(ctx *context.Context) webhookParams {
|
||||
form := web.GetForm(ctx).(*forms.NewDiscordHookForm)
|
||||
|
||||
return webhookParams{
|
||||
Type: webhook_module.DISCORD,
|
||||
URL: form.PayloadURL,
|
||||
ContentType: webhook.ContentTypeJSON,
|
||||
WebhookForm: form.WebhookForm,
|
||||
Meta: &webhook_service.DiscordMeta{
|
||||
Username: form.Username,
|
||||
IconURL: form.IconURL,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// DingtalkHooksNewPost response for creating Dingtalk webhook
|
||||
func DingtalkHooksNewPost(ctx *context.Context) {
|
||||
createWebhook(ctx, dingtalkHookParams(ctx))
|
||||
}
|
||||
|
||||
// DingtalkHooksEditPost response for editing Dingtalk webhook
|
||||
func DingtalkHooksEditPost(ctx *context.Context) {
|
||||
editWebhook(ctx, dingtalkHookParams(ctx))
|
||||
}
|
||||
|
||||
func dingtalkHookParams(ctx *context.Context) webhookParams {
|
||||
form := web.GetForm(ctx).(*forms.NewDingtalkHookForm)
|
||||
|
||||
return webhookParams{
|
||||
Type: webhook_module.DINGTALK,
|
||||
URL: form.PayloadURL,
|
||||
ContentType: webhook.ContentTypeJSON,
|
||||
WebhookForm: form.WebhookForm,
|
||||
}
|
||||
}
|
||||
|
||||
// TelegramHooksNewPost response for creating Telegram webhook
|
||||
func TelegramHooksNewPost(ctx *context.Context) {
|
||||
createWebhook(ctx, telegramHookParams(ctx))
|
||||
}
|
||||
|
||||
// TelegramHooksEditPost response for editing Telegram webhook
|
||||
func TelegramHooksEditPost(ctx *context.Context) {
|
||||
editWebhook(ctx, telegramHookParams(ctx))
|
||||
}
|
||||
|
||||
func telegramHookParams(ctx *context.Context) webhookParams {
|
||||
form := web.GetForm(ctx).(*forms.NewTelegramHookForm)
|
||||
|
||||
return webhookParams{
|
||||
Type: webhook_module.TELEGRAM,
|
||||
URL: fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage?chat_id=%s&message_thread_id=%s", url.PathEscape(form.BotToken), url.QueryEscape(form.ChatID), url.QueryEscape(form.ThreadID)),
|
||||
ContentType: webhook.ContentTypeJSON,
|
||||
WebhookForm: form.WebhookForm,
|
||||
Meta: &webhook_service.TelegramMeta{
|
||||
BotToken: form.BotToken,
|
||||
ChatID: form.ChatID,
|
||||
ThreadID: form.ThreadID,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// MatrixHooksNewPost response for creating Matrix webhook
|
||||
func MatrixHooksNewPost(ctx *context.Context) {
|
||||
createWebhook(ctx, matrixHookParams(ctx))
|
||||
}
|
||||
|
||||
// MatrixHooksEditPost response for editing Matrix webhook
|
||||
func MatrixHooksEditPost(ctx *context.Context) {
|
||||
editWebhook(ctx, matrixHookParams(ctx))
|
||||
}
|
||||
|
||||
func matrixRoomIDEncode(roomID string) string {
|
||||
// See https://spec.matrix.org/latest/appendices/#room-ids
|
||||
// Some (unrelated) demo links: https://spec.matrix.org/latest/appendices/#matrixto-navigation
|
||||
// API spec: https://spec.matrix.org/v1.18/client-server-api/#sending-events-to-a-room
|
||||
// Some of their examples show links like: "PUT /rooms/!roomid:domain/state/m.example.event"
|
||||
return strings.NewReplacer("%21", "!", "%3A", ":").Replace(url.PathEscape(roomID))
|
||||
}
|
||||
|
||||
func matrixHookParams(ctx *context.Context) webhookParams {
|
||||
form := web.GetForm(ctx).(*forms.NewMatrixHookForm)
|
||||
|
||||
// TODO: need to migrate to the latest (v3) API: https://spec.matrix.org/v1.18/client-server-api/
|
||||
return webhookParams{
|
||||
Type: webhook_module.MATRIX,
|
||||
URL: fmt.Sprintf("%s/_matrix/client/r0/rooms/%s/send/m.room.message", form.HomeserverURL, matrixRoomIDEncode(form.RoomID)),
|
||||
ContentType: webhook.ContentTypeJSON,
|
||||
HTTPMethod: http.MethodPut,
|
||||
WebhookForm: form.WebhookForm,
|
||||
Meta: &webhook_service.MatrixMeta{
|
||||
HomeserverURL: form.HomeserverURL,
|
||||
Room: form.RoomID,
|
||||
MessageType: form.MessageType,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// MSTeamsHooksNewPost response for creating MSTeams webhook
|
||||
func MSTeamsHooksNewPost(ctx *context.Context) {
|
||||
createWebhook(ctx, mSTeamsHookParams(ctx))
|
||||
}
|
||||
|
||||
// MSTeamsHooksEditPost response for editing MSTeams webhook
|
||||
func MSTeamsHooksEditPost(ctx *context.Context) {
|
||||
editWebhook(ctx, mSTeamsHookParams(ctx))
|
||||
}
|
||||
|
||||
func mSTeamsHookParams(ctx *context.Context) webhookParams {
|
||||
form := web.GetForm(ctx).(*forms.NewMSTeamsHookForm)
|
||||
|
||||
return webhookParams{
|
||||
Type: webhook_module.MSTEAMS,
|
||||
URL: form.PayloadURL,
|
||||
ContentType: webhook.ContentTypeJSON,
|
||||
WebhookForm: form.WebhookForm,
|
||||
}
|
||||
}
|
||||
|
||||
// SlackHooksNewPost response for creating Slack webhook
|
||||
func SlackHooksNewPost(ctx *context.Context) {
|
||||
createWebhook(ctx, slackHookParams(ctx))
|
||||
}
|
||||
|
||||
// SlackHooksEditPost response for editing Slack webhook
|
||||
func SlackHooksEditPost(ctx *context.Context) {
|
||||
editWebhook(ctx, slackHookParams(ctx))
|
||||
}
|
||||
|
||||
func slackHookParams(ctx *context.Context) webhookParams {
|
||||
form := web.GetForm(ctx).(*forms.NewSlackHookForm)
|
||||
|
||||
return webhookParams{
|
||||
Type: webhook_module.SLACK,
|
||||
URL: form.PayloadURL,
|
||||
ContentType: webhook.ContentTypeJSON,
|
||||
WebhookForm: form.WebhookForm,
|
||||
Meta: &webhook_service.SlackMeta{
|
||||
Channel: strings.TrimSpace(form.Channel),
|
||||
Username: form.Username,
|
||||
IconURL: form.IconURL,
|
||||
Color: form.Color,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// FeishuHooksNewPost response for creating Feishu webhook
|
||||
func FeishuHooksNewPost(ctx *context.Context) {
|
||||
createWebhook(ctx, feishuHookParams(ctx))
|
||||
}
|
||||
|
||||
// FeishuHooksEditPost response for editing Feishu webhook
|
||||
func FeishuHooksEditPost(ctx *context.Context) {
|
||||
editWebhook(ctx, feishuHookParams(ctx))
|
||||
}
|
||||
|
||||
func feishuHookParams(ctx *context.Context) webhookParams {
|
||||
form := web.GetForm(ctx).(*forms.NewFeishuHookForm)
|
||||
|
||||
return webhookParams{
|
||||
Type: webhook_module.FEISHU,
|
||||
URL: form.PayloadURL,
|
||||
ContentType: webhook.ContentTypeJSON,
|
||||
WebhookForm: form.WebhookForm,
|
||||
}
|
||||
}
|
||||
|
||||
// WechatworkHooksNewPost response for creating Wechatwork webhook
|
||||
func WechatworkHooksNewPost(ctx *context.Context) {
|
||||
createWebhook(ctx, wechatworkHookParams(ctx))
|
||||
}
|
||||
|
||||
// WechatworkHooksEditPost response for editing Wechatwork webhook
|
||||
func WechatworkHooksEditPost(ctx *context.Context) {
|
||||
editWebhook(ctx, wechatworkHookParams(ctx))
|
||||
}
|
||||
|
||||
func wechatworkHookParams(ctx *context.Context) webhookParams {
|
||||
form := web.GetForm(ctx).(*forms.NewWechatWorkHookForm)
|
||||
|
||||
return webhookParams{
|
||||
Type: webhook_module.WECHATWORK,
|
||||
URL: form.PayloadURL,
|
||||
ContentType: webhook.ContentTypeJSON,
|
||||
WebhookForm: form.WebhookForm,
|
||||
}
|
||||
}
|
||||
|
||||
// PackagistHooksNewPost response for creating Packagist webhook
|
||||
func PackagistHooksNewPost(ctx *context.Context) {
|
||||
createWebhook(ctx, packagistHookParams(ctx))
|
||||
}
|
||||
|
||||
// PackagistHooksEditPost response for editing Packagist webhook
|
||||
func PackagistHooksEditPost(ctx *context.Context) {
|
||||
editWebhook(ctx, packagistHookParams(ctx))
|
||||
}
|
||||
|
||||
func packagistHookParams(ctx *context.Context) webhookParams {
|
||||
form := web.GetForm(ctx).(*forms.NewPackagistHookForm)
|
||||
|
||||
return webhookParams{
|
||||
Type: webhook_module.PACKAGIST,
|
||||
URL: fmt.Sprintf("https://packagist.org/api/update-package?username=%s&apiToken=%s", url.QueryEscape(form.Username), url.QueryEscape(form.APIToken)),
|
||||
ContentType: webhook.ContentTypeJSON,
|
||||
WebhookForm: form.WebhookForm,
|
||||
Meta: &webhook_service.PackagistMeta{
|
||||
Username: form.Username,
|
||||
APIToken: form.APIToken,
|
||||
PackageURL: form.PackageURL,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func checkWebhook(ctx *context.Context) (*ownerRepoCtx, *webhook.Webhook) {
|
||||
orCtx, err := getOwnerRepoCtx(ctx)
|
||||
if err != nil {
|
||||
ctx.ServerError("getOwnerRepoCtx", err)
|
||||
return nil, nil
|
||||
}
|
||||
ctx.Data["BaseLink"] = orCtx.Link
|
||||
ctx.Data["BaseLinkNew"] = orCtx.LinkNew
|
||||
|
||||
var w *webhook.Webhook
|
||||
if orCtx.RepoID > 0 {
|
||||
w, err = webhook.GetWebhookByRepoID(ctx, orCtx.RepoID, ctx.PathParamInt64("id"))
|
||||
} else if orCtx.OwnerID > 0 {
|
||||
w, err = webhook.GetWebhookByOwnerID(ctx, orCtx.OwnerID, ctx.PathParamInt64("id"))
|
||||
} else if orCtx.IsAdmin {
|
||||
w, err = webhook.GetSystemOrDefaultWebhook(ctx, ctx.PathParamInt64("id"))
|
||||
}
|
||||
if err != nil || w == nil {
|
||||
if webhook.IsErrWebhookNotExist(err) {
|
||||
ctx.NotFound(nil)
|
||||
} else {
|
||||
ctx.ServerError("GetWebhookByID", err)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
ctx.Data["HookType"] = w.Type
|
||||
switch w.Type {
|
||||
case webhook_module.SLACK:
|
||||
ctx.Data["SlackHook"] = webhook_service.GetSlackHook(w)
|
||||
case webhook_module.DISCORD:
|
||||
ctx.Data["DiscordHook"] = webhook_service.GetDiscordHook(w)
|
||||
case webhook_module.TELEGRAM:
|
||||
ctx.Data["TelegramHook"] = webhook_service.GetTelegramHook(w)
|
||||
case webhook_module.MATRIX:
|
||||
ctx.Data["MatrixHook"] = webhook_service.GetMatrixHook(w)
|
||||
case webhook_module.PACKAGIST:
|
||||
ctx.Data["PackagistHook"] = webhook_service.GetPackagistHook(w)
|
||||
}
|
||||
|
||||
ctx.Data["History"], err = w.History(ctx, 1)
|
||||
if err != nil {
|
||||
ctx.ServerError("History", err)
|
||||
}
|
||||
return orCtx, w
|
||||
}
|
||||
|
||||
// WebHooksEdit render editing web hook page
|
||||
func WebHooksEdit(ctx *context.Context) {
|
||||
ctx.Data["Title"] = ctx.Tr("repo.settings.update_webhook")
|
||||
ctx.Data["PageIsSettingsHooks"] = true
|
||||
ctx.Data["PageIsSettingsHooksEdit"] = true
|
||||
|
||||
orCtx, w := checkWebhook(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
ctx.Data["Webhook"] = w
|
||||
|
||||
ctx.HTML(http.StatusOK, orCtx.NewTemplate)
|
||||
}
|
||||
|
||||
// TestWebhook test if web hook is work fine
|
||||
func TestWebhook(ctx *context.Context) {
|
||||
hookID := ctx.PathParamInt64("id")
|
||||
w, err := webhook.GetWebhookByRepoID(ctx, ctx.Repo.Repository.ID, hookID)
|
||||
if err != nil {
|
||||
ctx.Flash.Error("GetWebhookByRepoID: " + err.Error())
|
||||
ctx.Status(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
// Grab latest commit or fake one if it's empty repository.
|
||||
// Note: in old code, the "ctx.Repo.Commit" is the last commit of the default branch.
|
||||
// New code doesn't set that commit, so it always uses the fake commit to test webhook.
|
||||
commit := ctx.Repo.Commit
|
||||
if commit == nil {
|
||||
ghost := user_model.NewGhostUser()
|
||||
objectFormat := git.ObjectFormatFromName(ctx.Repo.Repository.ObjectFormatName)
|
||||
commit = &git.Commit{
|
||||
ID: objectFormat.EmptyObjectID(),
|
||||
Author: ghost.NewGitSig(),
|
||||
Committer: ghost.NewGitSig(),
|
||||
CommitMessage: git.CommitMessage{MessageRaw: "This is a fake commit"},
|
||||
}
|
||||
}
|
||||
|
||||
apiUser := convert.ToUserWithAccessMode(ctx, ctx.Doer, perm.AccessModeNone)
|
||||
|
||||
apiCommit := &api.PayloadCommit{
|
||||
ID: commit.ID.String(),
|
||||
Message: commit.MessageUTF8(),
|
||||
URL: ctx.Repo.Repository.HTMLURL() + "/commit/" + url.PathEscape(commit.ID.String()),
|
||||
Author: &api.PayloadUser{
|
||||
Name: commit.Author.Name,
|
||||
Email: commit.Author.Email,
|
||||
},
|
||||
Committer: &api.PayloadUser{
|
||||
Name: commit.Committer.Name,
|
||||
Email: commit.Committer.Email,
|
||||
},
|
||||
}
|
||||
|
||||
commitID := commit.ID.String()
|
||||
p := &api.PushPayload{
|
||||
Ref: git.BranchPrefix + ctx.Repo.Repository.DefaultBranch,
|
||||
Before: commitID,
|
||||
After: commitID,
|
||||
CompareURL: setting.AppURL + ctx.Repo.Repository.ComposeCompareURL(commitID, commitID),
|
||||
Commits: []*api.PayloadCommit{apiCommit},
|
||||
TotalCommits: 1,
|
||||
HeadCommit: apiCommit,
|
||||
Repo: convert.ToRepo(ctx, ctx.Repo.Repository, access_model.Permission{AccessMode: perm.AccessModeNone}),
|
||||
Pusher: apiUser,
|
||||
Sender: apiUser,
|
||||
}
|
||||
if err := webhook_service.PrepareWebhook(ctx, w, webhook_module.HookEventPush, p); err != nil {
|
||||
ctx.Flash.Error("PrepareWebhook: " + err.Error())
|
||||
ctx.Status(http.StatusInternalServerError)
|
||||
} else {
|
||||
ctx.Flash.Info(ctx.Tr("repo.settings.webhook.delivery.success"))
|
||||
ctx.Status(http.StatusOK)
|
||||
}
|
||||
}
|
||||
|
||||
// ReplayWebhook replays a webhook
|
||||
func ReplayWebhook(ctx *context.Context) {
|
||||
hookTaskUUID := ctx.PathParam("uuid")
|
||||
|
||||
orCtx, w := checkWebhook(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
|
||||
if err := webhook_service.ReplayHookTask(ctx, w, hookTaskUUID); err != nil {
|
||||
if webhook.IsErrHookTaskNotExist(err) {
|
||||
ctx.NotFound(nil)
|
||||
} else {
|
||||
ctx.ServerError("ReplayHookTask", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Flash.Success(ctx.Tr("repo.settings.webhook.delivery.success"))
|
||||
ctx.Redirect(fmt.Sprintf("%s/%d", orCtx.Link, w.ID))
|
||||
}
|
||||
|
||||
// DeleteWebhook delete a webhook
|
||||
func DeleteWebhook(ctx *context.Context) {
|
||||
if err := webhook.DeleteWebhookByRepoID(ctx, ctx.Repo.Repository.ID, ctx.FormInt64("id")); err != nil {
|
||||
ctx.Flash.Error("DeleteWebhookByRepoID: " + err.Error())
|
||||
} else {
|
||||
ctx.Flash.Success(ctx.Tr("repo.settings.webhook_deletion_success"))
|
||||
}
|
||||
|
||||
ctx.JSONRedirect(ctx.Repo.RepoLink + "/settings/hooks")
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package setting
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestWebhookMatrix(t *testing.T) {
|
||||
assert.Equal(t, "!roomid:domain", matrixRoomIDEncode("!roomid:domain"))
|
||||
assert.Equal(t, "!room%23id:domain", matrixRoomIDEncode("!room#id:domain")) // maybe it should never really happen in real world
|
||||
}
|
||||
Reference in New Issue
Block a user