Merge remote-tracking branch 'upstream/main' into limit-repo-size

This commit is contained in:
DmitryFrolovTri committed 2023-05-03 14:58:32 +00:00
commit 3592ae7600
495 files changed
+6917 -12240

No files matched your search

+20 -5
View File
@@ -92,6 +92,21 @@ func generateTaskContext(t *actions_model.ActionTask) *structpb.Struct {
event := map[string]interface{}{}
_ = json.Unmarshal([]byte(t.Job.Run.EventPayload), &event)
baseRef := ""
headRef := ""
if pullPayload, err := t.Job.Run.GetPullRequestEventPayload(); err == nil && pullPayload.PullRequest != nil && pullPayload.PullRequest.Base != nil && pullPayload.PullRequest.Head != nil {
baseRef = pullPayload.PullRequest.Base.Ref
headRef = pullPayload.PullRequest.Head.Ref
}
refPrefix, refName := git.SplitRefName(t.Job.Run.Ref)
refType := ""
switch refPrefix {
case git.BranchPrefix:
refType = "branch"
case git.TagPrefix:
refType = "tag"
}
taskContext, _ := structpb.NewStruct(map[string]interface{}{
// standard contexts, see https://docs.github.com/en/actions/learn-github-actions/contexts#github-context
"action": "", // string, The name of the action currently running, or the id of a step. GitHub removes special characters, and uses the name __run when the current step runs a script without an id. If you use the same action more than once in the same job, the name will include a suffix with the sequence number with underscore before it. For example, the first script you run will have the name __run, and the second script will be named __run_2. Similarly, the second invocation of actions/checkout will be actionscheckout2.
@@ -100,19 +115,19 @@ func generateTaskContext(t *actions_model.ActionTask) *structpb.Struct {
"action_repository": "", // string, For a step executing an action, this is the owner and repository name of the action. For example, actions/checkout.
"action_status": "", // string, For a composite action, the current result of the composite action.
"actor": t.Job.Run.TriggerUser.Name, // string, The username of the user that triggered the initial workflow run. If the workflow run is a re-run, this value may differ from github.triggering_actor. Any workflow re-runs will use the privileges of github.actor, even if the actor initiating the re-run (github.triggering_actor) has different privileges.
"api_url": "", // string, The URL of the GitHub REST API.
"base_ref": "", // string, The base_ref or target branch of the pull request in a workflow run. This property is only available when the event that triggers a workflow run is either pull_request or pull_request_target.
"api_url": setting.AppURL + "api/v1", // string, The URL of the GitHub REST API.
"base_ref": baseRef, // string, The base_ref or target branch of the pull request in a workflow run. This property is only available when the event that triggers a workflow run is either pull_request or pull_request_target.
"env": "", // string, Path on the runner to the file that sets environment variables from workflow commands. This file is unique to the current step and is a different file for each step in a job. For more information, see "Workflow commands for GitHub Actions."
"event": event, // object, The full event webhook payload. You can access individual properties of the event using this context. This object is identical to the webhook payload of the event that triggered the workflow run, and is different for each event. The webhooks for each GitHub Actions event is linked in "Events that trigger workflows." For example, for a workflow run triggered by the push event, this object contains the contents of the push webhook payload.
"event_name": t.Job.Run.Event.Event(), // string, The name of the event that triggered the workflow run.
"event_path": "", // string, The path to the file on the runner that contains the full event webhook payload.
"graphql_url": "", // string, The URL of the GitHub GraphQL API.
"head_ref": "", // string, The head_ref or source branch of the pull request in a workflow run. This property is only available when the event that triggers a workflow run is either pull_request or pull_request_target.
"head_ref": headRef, // string, The head_ref or source branch of the pull request in a workflow run. This property is only available when the event that triggers a workflow run is either pull_request or pull_request_target.
"job": fmt.Sprint(t.JobID), // string, The job_id of the current job.
"ref": t.Job.Run.Ref, // string, The fully-formed ref of the branch or tag that triggered the workflow run. For workflows triggered by push, this is the branch or tag ref that was pushed. For workflows triggered by pull_request, this is the pull request merge branch. For workflows triggered by release, this is the release tag created. For other triggers, this is the branch or tag ref that triggered the workflow run. This is only set if a branch or tag is available for the event type. The ref given is fully-formed, meaning that for branches the format is refs/heads/<branch_name>, for pull requests it is refs/pull/<pr_number>/merge, and for tags it is refs/tags/<tag_name>. For example, refs/heads/feature-branch-1.
"ref_name": git.RefEndName(t.Job.Run.Ref), // string, The short ref name of the branch or tag that triggered the workflow run. This value matches the branch or tag name shown on GitHub. For example, feature-branch-1.
"ref_name": refName, // string, The short ref name of the branch or tag that triggered the workflow run. This value matches the branch or tag name shown on GitHub. For example, feature-branch-1.
"ref_protected": false, // boolean, true if branch protections are configured for the ref that triggered the workflow run.
"ref_type": "", // string, The type of ref that triggered the workflow run. Valid values are branch or tag.
"ref_type": refType, // string, The type of ref that triggered the workflow run. Valid values are branch or tag.
"path": "", // string, Path on the runner to the file that sets system PATH variables from workflow commands. This file is unique to the current step and is a different file for each step in a job. For more information, see "Workflow commands for GitHub Actions."
"repository": t.Job.Run.Repo.OwnerName + "/" + t.Job.Run.Repo.Name, // string, The owner and repository name. For example, Codertocat/Hello-World.
"repository_owner": t.Job.Run.Repo.OwnerName, // string, The repository owner's name. For example, Codertocat.
+46
View File
@@ -9,6 +9,7 @@ import (
"regexp"
"strings"
auth_model "code.gitea.io/gitea/models/auth"
"code.gitea.io/gitea/models/perm"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/log"
@@ -20,6 +21,7 @@ import (
"code.gitea.io/gitea/routers/api/packages/conan"
"code.gitea.io/gitea/routers/api/packages/conda"
"code.gitea.io/gitea/routers/api/packages/container"
"code.gitea.io/gitea/routers/api/packages/debian"
"code.gitea.io/gitea/routers/api/packages/generic"
"code.gitea.io/gitea/routers/api/packages/helm"
"code.gitea.io/gitea/routers/api/packages/maven"
@@ -36,6 +38,32 @@ import (
func reqPackageAccess(accessMode perm.AccessMode) func(ctx *context.Context) {
return func(ctx *context.Context) {
if ctx.Data["IsApiToken"] == true {
scope, ok := ctx.Data["ApiTokenScope"].(auth_model.AccessTokenScope)
if ok { // it's a personal access token but not oauth2 token
scopeMatched := false
var err error
if accessMode == perm.AccessModeRead {
scopeMatched, err = scope.HasScope(auth_model.AccessTokenScopeReadPackage)
if err != nil {
ctx.Error(http.StatusInternalServerError, "HasScope", err.Error())
return
}
} else if accessMode == perm.AccessModeWrite {
scopeMatched, err = scope.HasScope(auth_model.AccessTokenScopeWritePackage)
if err != nil {
ctx.Error(http.StatusInternalServerError, "HasScope", err.Error())
return
}
}
if !scopeMatched {
ctx.Resp.Header().Set("WWW-Authenticate", `Basic realm="Gitea Package API"`)
ctx.Error(http.StatusUnauthorized, "reqPackageAccess", "user should have specific permission or be a site admin")
return
}
}
}
if ctx.Package.AccessMode < accessMode && !ctx.IsUserSiteAdmin() {
ctx.Resp.Header().Set("WWW-Authenticate", `Basic realm="Gitea Package API"`)
ctx.Error(http.StatusUnauthorized, "reqPackageAccess", "user should have specific permission or be a site admin")
@@ -245,6 +273,24 @@ func CommonRoutes(ctx gocontext.Context) *web.Route {
conda.UploadPackageFile(ctx)
})
}, reqPackageAccess(perm.AccessModeRead))
r.Group("/debian", func() {
r.Get("/repository.key", debian.GetRepositoryKey)
r.Group("/dists/{distribution}", func() {
r.Get("/{filename}", debian.GetRepositoryFile)
r.Get("/by-hash/{algorithm}/{hash}", debian.GetRepositoryFileByHash)
r.Group("/{component}/{architecture}", func() {
r.Get("/{filename}", debian.GetRepositoryFile)
r.Get("/by-hash/{algorithm}/{hash}", debian.GetRepositoryFileByHash)
})
})
r.Group("/pool/{distribution}/{component}", func() {
r.Get("/{name}_{version}_{architecture}.deb", debian.DownloadPackageFile)
r.Group("", func() {
r.Put("/upload", debian.UploadPackageFile)
r.Delete("/{name}/{version}/{architecture}", debian.DeletePackageFile)
}, reqPackageAccess(perm.AccessModeWrite))
})
}, reqPackageAccess(perm.AccessModeRead))
r.Group("/generic", func() {
r.Group("/{packagename}/{packageversion}", func() {
r.Delete("", reqPackageAccess(perm.AccessModeWrite), generic.DeletePackage)
+1 -1
View File
@@ -173,7 +173,7 @@ func UploadPackage(ctx *context.Context) {
return
}
buf, err := packages_module.CreateHashedBufferFromReader(cp.Content, 32*1024*1024)
buf, err := packages_module.CreateHashedBufferFromReader(cp.Content)
if err != nil {
apiError(ctx, http.StatusInternalServerError, err)
return
+1 -1
View File
@@ -263,7 +263,7 @@ func UploadPackage(ctx *context.Context) {
}
defer file.Close()
buf, err := packages_module.CreateHashedBufferFromReader(file, 32*1024*1024)
buf, err := packages_module.CreateHashedBufferFromReader(file)
if err != nil {
apiError(ctx, http.StatusInternalServerError, err)
return
+1 -1
View File
@@ -192,7 +192,7 @@ func DownloadPackageFile(ctx *context.Context) {
// UploadPackage creates a new package
func UploadPackage(ctx *context.Context) {
buf, err := packages_module.CreateHashedBufferFromReader(ctx.Req.Body, 32*1024*1024)
buf, err := packages_module.CreateHashedBufferFromReader(ctx.Req.Body)
if err != nil {
apiError(ctx, http.StatusInternalServerError, err)
return
+3 -10
View File
@@ -318,7 +318,7 @@ func uploadFile(ctx *context.Context, fileFilter container.Set[string], fileKey
defer upload.Close()
}
buf, err := packages_module.CreateHashedBufferFromReader(upload, 32*1024*1024)
buf, err := packages_module.CreateHashedBufferFromReader(upload)
if err != nil {
apiError(ctx, http.StatusInternalServerError, err)
return
@@ -648,10 +648,7 @@ func deleteRecipeOrPackage(apictx *context.Context, rref *conan_module.RecipeRef
}
for _, pf := range pfs {
if err := packages_model.DeleteAllProperties(ctx, packages_model.PropertyTypeFile, pf.ID); err != nil {
return err
}
if err := packages_model.DeleteFileByID(ctx, pf.ID); err != nil {
if err := packages_service.DeletePackageFile(ctx, pf); err != nil {
return err
}
}
@@ -664,11 +661,7 @@ func deleteRecipeOrPackage(apictx *context.Context, rref *conan_module.RecipeRef
if !has {
versionDeleted = true
if err := packages_model.DeleteAllProperties(ctx, packages_model.PropertyTypeVersion, pv.ID); err != nil {
return err
}
if err := packages_model.DeleteVersionByID(ctx, pv.ID); err != nil {
if err := packages_service.DeletePackageVersionAndReferences(ctx, pv); err != nil {
return err
}
}
+1 -1
View File
@@ -183,7 +183,7 @@ func UploadPackageFile(ctx *context.Context) {
defer upload.Close()
}
buf, err := packages_module.CreateHashedBufferFromReader(upload, 32*1024*1024)
buf, err := packages_module.CreateHashedBufferFromReader(upload)
if err != nil {
apiError(ctx, http.StatusInternalServerError, err)
return
+4 -4
View File
@@ -27,10 +27,6 @@ var uploadVersionMutex sync.Mutex
// saveAsPackageBlob creates a package blob from an upload
// The uploaded blob gets stored in a special upload version to link them to the package/image
func saveAsPackageBlob(hsr packages_module.HashedSizeReader, pci *packages_service.PackageCreationInfo) (*packages_model.PackageBlob, error) {
if err := packages_service.CheckSizeQuotaExceeded(db.DefaultContext, pci.Creator, pci.Owner, packages_model.TypeContainer, hsr.Size()); err != nil {
return nil, err
}
pb := packages_service.NewPackageBlob(hsr)
exists := false
@@ -43,6 +39,10 @@ func saveAsPackageBlob(hsr packages_module.HashedSizeReader, pci *packages_servi
}
err = db.WithTx(db.DefaultContext, func(ctx context.Context) error {
if err := packages_service.CheckSizeQuotaExceeded(ctx, pci.Creator, pci.Owner, packages_model.TypeContainer, hsr.Size()); err != nil {
return err
}
pb, exists, err = packages_model.GetOrInsertBlob(ctx, pb)
if err != nil {
log.Error("Error inserting package blob: %v", err)
+2 -2
View File
@@ -219,7 +219,7 @@ func InitiateUploadBlob(ctx *context.Context) {
digest := ctx.FormTrim("digest")
if digest != "" {
buf, err := packages_module.CreateHashedBufferFromReader(ctx.Req.Body, 32*1024*1024)
buf, err := packages_module.CreateHashedBufferFromReader(ctx.Req.Body)
if err != nil {
apiError(ctx, http.StatusInternalServerError, err)
return
@@ -538,7 +538,7 @@ func UploadManifest(ctx *context.Context) {
}
maxSize := maxManifestSize + 1
buf, err := packages_module.CreateHashedBufferFromReader(&io.LimitedReader{R: ctx.Req.Body, N: int64(maxSize)}, maxSize)
buf, err := packages_module.CreateHashedBufferFromReaderWithSize(&io.LimitedReader{R: ctx.Req.Body, N: int64(maxSize)}, maxSize)
if err != nil {
apiError(ctx, http.StatusInternalServerError, err)
return
+317
View File
@@ -0,0 +1,317 @@
// Copyright 2023 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package debian
import (
stdctx "context"
"errors"
"fmt"
"io"
"net/http"
"strings"
"code.gitea.io/gitea/models/db"
packages_model "code.gitea.io/gitea/models/packages"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/notification"
packages_module "code.gitea.io/gitea/modules/packages"
debian_module "code.gitea.io/gitea/modules/packages/debian"
"code.gitea.io/gitea/modules/util"
"code.gitea.io/gitea/routers/api/packages/helper"
packages_service "code.gitea.io/gitea/services/packages"
debian_service "code.gitea.io/gitea/services/packages/debian"
)
func apiError(ctx *context.Context, status int, obj interface{}) {
helper.LogAndProcessError(ctx, status, obj, func(message string) {
ctx.PlainText(status, message)
})
}
func GetRepositoryKey(ctx *context.Context) {
_, pub, err := debian_service.GetOrCreateKeyPair(ctx.Package.Owner.ID)
if err != nil {
apiError(ctx, http.StatusInternalServerError, err)
return
}
ctx.ServeContent(strings.NewReader(pub), &context.ServeHeaderOptions{
ContentType: "application/pgp-keys",
Filename: "repository.key",
})
}
// https://wiki.debian.org/DebianRepository/Format#A.22Release.22_files
// https://wiki.debian.org/DebianRepository/Format#A.22Packages.22_Indices
func GetRepositoryFile(ctx *context.Context) {
pv, err := debian_service.GetOrCreateRepositoryVersion(ctx.Package.Owner.ID)
if err != nil {
apiError(ctx, http.StatusInternalServerError, err)
return
}
key := ctx.Params("distribution")
component := ctx.Params("component")
architecture := strings.TrimPrefix(ctx.Params("architecture"), "binary-")
if component != "" && architecture != "" {
key += "|" + component + "|" + architecture
}
s, pf, err := packages_service.GetFileStreamByPackageVersion(
ctx,
pv,
&packages_service.PackageFileInfo{
Filename: ctx.Params("filename"),
CompositeKey: key,
},
)
if err != nil {
if err == packages_model.ErrPackageNotExist || err == packages_model.ErrPackageFileNotExist {
apiError(ctx, http.StatusNotFound, err)
} else {
apiError(ctx, http.StatusInternalServerError, err)
}
return
}
defer s.Close()
ctx.ServeContent(s, &context.ServeHeaderOptions{
Filename: pf.Name,
LastModified: pf.CreatedUnix.AsLocalTime(),
})
}
// https://wiki.debian.org/DebianRepository/Format#indices_acquisition_via_hashsums_.28by-hash.29
func GetRepositoryFileByHash(ctx *context.Context) {
pv, err := debian_service.GetOrCreateRepositoryVersion(ctx.Package.Owner.ID)
if err != nil {
apiError(ctx, http.StatusInternalServerError, err)
return
}
algorithm := strings.ToLower(ctx.Params("algorithm"))
if algorithm == "md5sum" {
algorithm = "md5"
}
pfs, _, err := packages_model.SearchFiles(ctx, &packages_model.PackageFileSearchOptions{
VersionID: pv.ID,
Hash: strings.ToLower(ctx.Params("hash")),
HashAlgorithm: algorithm,
})
if err != nil {
apiError(ctx, http.StatusInternalServerError, err)
return
}
if len(pfs) != 1 {
apiError(ctx, http.StatusNotFound, nil)
return
}
s, pf, err := packages_service.GetPackageFileStream(ctx, pfs[0])
if err != nil {
if errors.Is(err, util.ErrNotExist) {
apiError(ctx, http.StatusNotFound, err)
} else {
apiError(ctx, http.StatusInternalServerError, err)
}
return
}
defer s.Close()
ctx.ServeContent(s, &context.ServeHeaderOptions{
Filename: pf.Name,
LastModified: pf.CreatedUnix.AsLocalTime(),
})
}
func UploadPackageFile(ctx *context.Context) {
distribution := strings.TrimSpace(ctx.Params("distribution"))
component := strings.TrimSpace(ctx.Params("component"))
if distribution == "" || component == "" {
apiError(ctx, http.StatusBadRequest, "invalid distribution or component")
return
}
upload, close, err := ctx.UploadStream()
if err != nil {
apiError(ctx, http.StatusInternalServerError, err)
return
}
if close {
defer upload.Close()
}
buf, err := packages_module.CreateHashedBufferFromReader(upload)
if err != nil {
apiError(ctx, http.StatusInternalServerError, err)
return
}
defer buf.Close()
pck, err := debian_module.ParsePackage(buf)
if err != nil {
if errors.Is(err, util.ErrInvalidArgument) {
apiError(ctx, http.StatusBadRequest, err)
} else {
apiError(ctx, http.StatusInternalServerError, err)
}
return
}
if _, err := buf.Seek(0, io.SeekStart); err != nil {
apiError(ctx, http.StatusInternalServerError, err)
return
}
_, _, err = packages_service.CreatePackageOrAddFileToExisting(
&packages_service.PackageCreationInfo{
PackageInfo: packages_service.PackageInfo{
Owner: ctx.Package.Owner,
PackageType: packages_model.TypeDebian,
Name: pck.Name,
Version: pck.Version,
},
Creator: ctx.Doer,
Metadata: pck.Metadata,
},
&packages_service.PackageFileCreationInfo{
PackageFileInfo: packages_service.PackageFileInfo{
Filename: fmt.Sprintf("%s_%s_%s.deb", pck.Name, pck.Version, pck.Architecture),
CompositeKey: fmt.Sprintf("%s|%s", distribution, component),
},
Creator: ctx.Doer,
Data: buf,
IsLead: true,
Properties: map[string]string{
debian_module.PropertyDistribution: distribution,
debian_module.PropertyComponent: component,
debian_module.PropertyArchitecture: pck.Architecture,
debian_module.PropertyControl: pck.Control,
},
},
)
if err != nil {
switch err {
case packages_model.ErrDuplicatePackageVersion:
apiError(ctx, http.StatusBadRequest, err)
case packages_service.ErrQuotaTotalCount, packages_service.ErrQuotaTypeSize, packages_service.ErrQuotaTotalSize:
apiError(ctx, http.StatusForbidden, err)
default:
apiError(ctx, http.StatusInternalServerError, err)
}
return
}
if err := debian_service.BuildSpecificRepositoryFiles(ctx, ctx.Package.Owner.ID, distribution, component, pck.Architecture); err != nil {
apiError(ctx, http.StatusInternalServerError, err)
return
}
ctx.Status(http.StatusCreated)
}
func DownloadPackageFile(ctx *context.Context) {
name := ctx.Params("name")
version := ctx.Params("version")
s, pf, err := packages_service.GetFileStreamByPackageNameAndVersion(
ctx,
&packages_service.PackageInfo{
Owner: ctx.Package.Owner,
PackageType: packages_model.TypeDebian,
Name: name,
Version: version,
},
&packages_service.PackageFileInfo{
Filename: fmt.Sprintf("%s_%s_%s.deb", name, version, ctx.Params("architecture")),
CompositeKey: fmt.Sprintf("%s|%s", ctx.Params("distribution"), ctx.Params("component")),
},
)
if err != nil {
if errors.Is(err, util.ErrNotExist) {
apiError(ctx, http.StatusNotFound, err)
} else {
apiError(ctx, http.StatusInternalServerError, err)
}
return
}
defer s.Close()
ctx.ServeContent(s, &context.ServeHeaderOptions{
ContentType: "application/vnd.debian.binary-package",
Filename: pf.Name,
LastModified: pf.CreatedUnix.AsLocalTime(),
})
}
func DeletePackageFile(ctx *context.Context) {
distribution := ctx.Params("distribution")
component := ctx.Params("component")
name := ctx.Params("name")
version := ctx.Params("version")
architecture := ctx.Params("architecture")
owner := ctx.Package.Owner
var pd *packages_model.PackageDescriptor
err := db.WithTx(ctx, func(ctx stdctx.Context) error {
pv, err := packages_model.GetVersionByNameAndVersion(ctx, owner.ID, packages_model.TypeDebian, name, version)
if err != nil {
return err
}
pf, err := packages_model.GetFileForVersionByName(
ctx,
pv.ID,
fmt.Sprintf("%s_%s_%s.deb", name, version, architecture),
fmt.Sprintf("%s|%s", distribution, component),
)
if err != nil {
return err
}
if err := packages_service.DeletePackageFile(ctx, pf); err != nil {
return err
}
has, err := packages_model.HasVersionFileReferences(ctx, pv.ID)
if err != nil {
return err
}
if !has {
pd, err = packages_model.GetPackageDescriptor(ctx, pv)
if err != nil {
return err
}
if err := packages_service.DeletePackageVersionAndReferences(ctx, pv); err != nil {
return err
}
}
return nil
})
if err != nil {
if errors.Is(err, util.ErrNotExist) {
apiError(ctx, http.StatusNotFound, err)
} else {
apiError(ctx, http.StatusInternalServerError, err)
}
return
}
if pd != nil {
notification.NotifyPackageDelete(ctx, ctx.Doer, pd)
}
if err := debian_service.BuildSpecificRepositoryFiles(ctx, ctx.Package.Owner.ID, distribution, component, architecture); err != nil {
apiError(ctx, http.StatusInternalServerError, err)
return
}
ctx.Status(http.StatusNoContent)
}
+1 -1
View File
@@ -84,7 +84,7 @@ func UploadPackage(ctx *context.Context) {
defer upload.Close()
}
buf, err := packages_module.CreateHashedBufferFromReader(upload, 32*1024*1024)
buf, err := packages_module.CreateHashedBufferFromReader(upload)
if err != nil {
log.Error("Error creating hashed buffer: %v", err)
apiError(ctx, http.StatusInternalServerError, err)
+1 -1
View File
@@ -155,7 +155,7 @@ func UploadPackage(ctx *context.Context) {
defer upload.Close()
}
buf, err := packages_module.CreateHashedBufferFromReader(upload, 32*1024*1024)
buf, err := packages_module.CreateHashedBufferFromReader(upload)
if err != nil {
apiError(ctx, http.StatusInternalServerError, err)
return
+1 -1
View File
@@ -245,7 +245,7 @@ func UploadPackageFile(ctx *context.Context) {
packageName := params.GroupID + "-" + params.ArtifactID
buf, err := packages_module.CreateHashedBufferFromReader(ctx.Req.Body, 32*1024*1024)
buf, err := packages_module.CreateHashedBufferFromReader(ctx.Req.Body)
if err != nil {
apiError(ctx, http.StatusInternalServerError, err)
return
+1 -1
View File
@@ -189,7 +189,7 @@ func UploadPackage(ctx *context.Context) {
}
}
buf, err := packages_module.CreateHashedBufferFromReader(bytes.NewReader(npmPackage.Data), 32*1024*1024)
buf, err := packages_module.CreateHashedBufferFromReader(bytes.NewReader(npmPackage.Data))
if err != nil {
apiError(ctx, http.StatusInternalServerError, err)
return
+3 -3
View File
@@ -475,7 +475,7 @@ func UploadSymbolPackage(ctx *context.Context) {
Version: np.Version,
}
_, _, err = packages_service.AddFileToExistingPackage(
_, err = packages_service.AddFileToExistingPackage(
pi,
&packages_service.PackageFileCreationInfo{
PackageFileInfo: packages_service.PackageFileInfo{
@@ -501,7 +501,7 @@ func UploadSymbolPackage(ctx *context.Context) {
}
for _, pdb := range pdbs {
_, _, err := packages_service.AddFileToExistingPackage(
_, err := packages_service.AddFileToExistingPackage(
pi,
&packages_service.PackageFileCreationInfo{
PackageFileInfo: packages_service.PackageFileInfo{
@@ -545,7 +545,7 @@ func processUploadedFile(ctx *context.Context, expectedType nuget_module.Package
closables = append(closables, upload)
}
buf, err := packages_module.CreateHashedBufferFromReader(upload, 32*1024*1024)
buf, err := packages_module.CreateHashedBufferFromReader(upload)
if err != nil {
apiError(ctx, http.StatusInternalServerError, err)
return nil, nil, closables
+1 -1
View File
@@ -166,7 +166,7 @@ func UploadPackageFile(ctx *context.Context) {
}
defer file.Close()
buf, err := packages_module.CreateHashedBufferFromReader(file, 32*1024*1024)
buf, err := packages_module.CreateHashedBufferFromReader(file)
if err != nil {
apiError(ctx, http.StatusInternalServerError, err)
return
+1 -1
View File
@@ -117,7 +117,7 @@ func UploadPackageFile(ctx *context.Context) {
}
defer file.Close()
buf, err := packages_module.CreateHashedBufferFromReader(file, 32*1024*1024)
buf, err := packages_module.CreateHashedBufferFromReader(file)
if err != nil {
apiError(ctx, http.StatusInternalServerError, err)
return
+1 -1
View File
@@ -209,7 +209,7 @@ func UploadPackageFile(ctx *context.Context) {
defer upload.Close()
}
buf, err := packages_module.CreateHashedBufferFromReader(upload, 32*1024*1024)
buf, err := packages_module.CreateHashedBufferFromReader(upload)
if err != nil {
apiError(ctx, http.StatusInternalServerError, err)
return
+1 -1
View File
@@ -300,7 +300,7 @@ func UploadPackageFile(ctx *context.Context) {
}
defer file.Close()
buf, err := packages_module.CreateHashedBufferFromReader(file, 32*1024*1024)
buf, err := packages_module.CreateHashedBufferFromReader(file)
if err != nil {
apiError(ctx, http.StatusInternalServerError, err)
return
+1 -1
View File
@@ -158,7 +158,7 @@ func UploadPackageFile(ctx *context.Context) {
defer upload.Close()
}
buf, err := packages_module.CreateHashedBufferFromReader(upload, 32*1024*1024)
buf, err := packages_module.CreateHashedBufferFromReader(upload)
if err != nil {
apiError(ctx, http.StatusInternalServerError, err)
return
+2 -2
View File
@@ -95,7 +95,7 @@ func AdoptRepository(ctx *context.APIContext) {
}
// check not a repo
has, err := repo_model.IsRepositoryExist(ctx, ctxUser, repoName)
has, err := repo_model.IsRepositoryModelExist(ctx, ctxUser, repoName)
if err != nil {
ctx.InternalServerError(err)
return
@@ -157,7 +157,7 @@ func DeleteUnadoptedRepository(ctx *context.APIContext) {
}
// check not a repo
has, err := repo_model.IsRepositoryExist(ctx, ctxUser, repoName)
has, err := repo_model.IsRepositoryModelExist(ctx, ctxUser, repoName)
if err != nil {
ctx.InternalServerError(err)
return
+4
View File
@@ -719,6 +719,10 @@ func Routes(ctx gocontext.Context) *web.Route {
m.Post("/markup", bind(api.MarkupOption{}), misc.Markup)
m.Post("/markdown", bind(api.MarkdownOption{}), misc.Markdown)
m.Post("/markdown/raw", misc.MarkdownRaw)
m.Get("/gitignore/templates", misc.ListGitignoresTemplates)
m.Get("/gitignore/templates/{name}", misc.GetGitignoreTemplateInfo)
m.Get("/licenses", misc.ListLicenseTemplates)
m.Get("/licenses/{name}", misc.GetLicenseTemplateInfo)
m.Group("/settings", func() {
m.Get("/ui", settings.GetGeneralUISettings)
m.Get("/api", settings.GetGeneralAPISettings)
+56
View File
@@ -0,0 +1,56 @@
// Copyright 2023 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package misc
import (
"net/http"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/options"
repo_module "code.gitea.io/gitea/modules/repository"
"code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/util"
)
// Shows a list of all Gitignore templates
func ListGitignoresTemplates(ctx *context.APIContext) {
// swagger:operation GET /gitignore/templates miscellaneous listGitignoresTemplates
// ---
// summary: Returns a list of all gitignore templates
// produces:
// - application/json
// responses:
// "200":
// "$ref": "#/responses/GitignoreTemplateList"
ctx.JSON(http.StatusOK, repo_module.Gitignores)
}
// SHows information about a gitignore template
func GetGitignoreTemplateInfo(ctx *context.APIContext) {
// swagger:operation GET /gitignore/templates/{name} miscellaneous getGitignoreTemplateInfo
// ---
// summary: Returns information about a gitignore template
// produces:
// - application/json
// parameters:
// - name: name
// in: path
// description: name of the template
// type: string
// required: true
// responses:
// "200":
// "$ref": "#/responses/GitignoreTemplateInfo"
// "404":
// "$ref": "#/responses/notFound"
name := util.PathJoinRelX(ctx.Params("name"))
text, err := options.Gitignore(name)
if err != nil {
ctx.NotFound()
return
}
ctx.JSON(http.StatusOK, &structs.GitignoreTemplateInfo{Name: name, Source: string(text)})
}
+76
View File
@@ -0,0 +1,76 @@
// Copyright 2023 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package misc
import (
"fmt"
"net/http"
"net/url"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/options"
repo_module "code.gitea.io/gitea/modules/repository"
"code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/util"
)
// Returns a list of all License templates
func ListLicenseTemplates(ctx *context.APIContext) {
// swagger:operation GET /licenses miscellaneous listLicenseTemplates
// ---
// summary: Returns a list of all license templates
// produces:
// - application/json
// responses:
// "200":
// "$ref": "#/responses/LicenseTemplateList"
response := make([]api.LicensesTemplateListEntry, len(repo_module.Licenses))
for i, license := range repo_module.Licenses {
response[i] = api.LicensesTemplateListEntry{
Key: license,
Name: license,
URL: fmt.Sprintf("%sapi/v1/licenses/%s", setting.AppURL, url.PathEscape(license)),
}
}
ctx.JSON(http.StatusOK, response)
}
// Returns information about a gitignore template
func GetLicenseTemplateInfo(ctx *context.APIContext) {
// swagger:operation GET /licenses/{name} miscellaneous getLicenseTemplateInfo
// ---
// summary: Returns information about a license template
// produces:
// - application/json
// parameters:
// - name: name
// in: path
// description: name of the license
// type: string
// required: true
// responses:
// "200":
// "$ref": "#/responses/LicenseTemplateInfo"
// "404":
// "$ref": "#/responses/notFound"
name := util.PathJoinRelX(ctx.Params("name"))
text, err := options.License(name)
if err != nil {
ctx.NotFound()
return
}
response := api.LicenseTemplateInfo{
Key: name,
Name: name,
URL: fmt.Sprintf("%sapi/v1/licenses/%s", setting.AppURL, url.PathEscape(name)),
Body: string(text),
// This is for combatibilty with the GitHub API. This Text is for some reason added to each License response.
Implementation: "Create a text file (typically named LICENSE or LICENSE.txt) in the root of your source code and copy the text of the license into the file",
}
ctx.JSON(http.StatusOK, response)
}
+1 -1
View File
@@ -30,7 +30,7 @@ const (
)
func createContext(req *http.Request) (*context.Context, *httptest.ResponseRecorder) {
_, rnd := templates.HTMLRenderer(req.Context())
rnd := templates.HTMLRenderer()
resp := httptest.NewRecorder()
c := &context.Context{
Req: req,
+1 -1
View File
@@ -40,7 +40,7 @@ func ListPackages(ctx *context.APIContext) {
// in: query
// description: package type filter
// type: string
// enum: [cargo, chef, composer, conan, conda, container, generic, helm, maven, npm, nuget, pub, pypi, rubygems, swift, vagrant]
// enum: [cargo, chef, composer, conan, conda, container, debian, generic, helm, maven, npm, nuget, pub, pypi, rubygems, swift, vagrant]
// - name: q
// in: query
// description: name filter
+6 -1
View File
@@ -115,6 +115,10 @@ func GetAllCommits(ctx *context.APIContext) {
// in: query
// description: page size of results (ignored if used with 'path')
// type: integer
// - name: not
// in: query
// description: commits that match the given specifier will not be listed.
// type: string
// responses:
// "200":
// "$ref": "#/responses/CommitList"
@@ -181,7 +185,8 @@ func GetAllCommits(ctx *context.APIContext) {
}
// Query commits
commits, err = baseCommit.CommitsByRange(listOptions.Page, listOptions.PageSize)
not := ctx.FormString("not")
commits, err = baseCommit.CommitsByRange(listOptions.Page, listOptions.PageSize, not)
if err != nil {
ctx.Error(http.StatusInternalServerError, "CommitsByRange", err)
return
+1 -1
View File
@@ -141,7 +141,7 @@ func CreateFork(ctx *context.APIContext) {
Description: repo.Description,
})
if err != nil {
if repo_model.IsErrReachLimitOfRepo(err) || repo_model.IsErrRepoAlreadyExist(err) {
if repo_service.IsErrForkAlreadyExist(err) || repo_model.IsErrRepoAlreadyExist(err) || repo_model.IsErrReachLimitOfRepo(err) {
ctx.Error(http.StatusConflict, "ForkRepository", err)
} else {
ctx.Error(http.StatusInternalServerError, "ForkRepository", err)
+28
View File
@@ -14,6 +14,34 @@ type swaggerResponseServerVersion struct {
Body api.ServerVersion `json:"body"`
}
// GitignoreTemplateList
// swagger:response GitignoreTemplateList
type swaggerResponseGitignoreTemplateList struct {
// in:body
Body []string `json:"body"`
}
// GitignoreTemplateInfo
// swagger:response GitignoreTemplateInfo
type swaggerResponseGitignoreTemplateInfo struct {
// in:body
Body api.GitignoreTemplateInfo `json:"body"`
}
// LicenseTemplateList
// swagger:response LicenseTemplateList
type swaggerResponseLicensesTemplateList struct {
// in:body
Body []api.LicensesTemplateListEntry `json:"body"`
}
// LicenseTemplateInfo
// swagger:response LicenseTemplateInfo
type swaggerResponseLicenseTemplateInfo struct {
// in:body
Body api.LicenseTemplateInfo `json:"body"`
}
// StringSlice
// swagger:response StringSlice
type swaggerResponseStringSlice struct {
+26 -13
View File
@@ -15,24 +15,23 @@ import (
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/web/routing"
"gitea.com/go-chi/session"
"github.com/chi-middleware/proxy"
chi "github.com/go-chi/chi/v5"
)
// Middlewares returns common middlewares
func Middlewares() []func(http.Handler) http.Handler {
handlers := []func(http.Handler) http.Handler{
func(next http.Handler) http.Handler {
return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
// First of all escape the URL RawPath to ensure that all routing is done using a correctly escaped URL
req.URL.RawPath = req.URL.EscapedPath()
// ProtocolMiddlewares returns HTTP protocol related middlewares
func ProtocolMiddlewares() (handlers []any) {
handlers = append(handlers, func(next http.Handler) http.Handler {
return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
// First of all escape the URL RawPath to ensure that all routing is done using a correctly escaped URL
req.URL.RawPath = req.URL.EscapedPath()
ctx, _, finished := process.GetManager().AddTypedContext(req.Context(), fmt.Sprintf("%s: %s", req.Method, req.RequestURI), process.RequestProcessType, true)
defer finished()
next.ServeHTTP(context.NewResponse(resp), req.WithContext(cache.WithCacheContext(ctx)))
})
},
}
ctx, _, finished := process.GetManager().AddTypedContext(req.Context(), fmt.Sprintf("%s: %s", req.Method, req.RequestURI), process.RequestProcessType, true)
defer finished()
next.ServeHTTP(context.NewResponse(resp), req.WithContext(cache.WithCacheContext(ctx)))
})
})
if setting.ReverseProxyLimit > 0 {
opt := proxy.NewForwardedHeadersOptions().
@@ -112,3 +111,17 @@ func stripSlashesMiddleware(next http.Handler) http.Handler {
next.ServeHTTP(resp, req)
})
}
func Sessioner() func(next http.Handler) http.Handler {
return session.Sessioner(session.Options{
Provider: setting.SessionConfig.Provider,
ProviderConfig: setting.SessionConfig.ProviderConfig,
CookieName: setting.SessionConfig.CookieName,
CookiePath: setting.SessionConfig.CookiePath,
Gclifetime: setting.SessionConfig.Gclifetime,
Maxlifetime: setting.SessionConfig.Maxlifetime,
Secure: setting.SessionConfig.Secure,
SameSite: setting.SessionConfig.SameSite,
Domain: setting.SessionConfig.Domain,
})
}
+2 -7
View File
@@ -175,22 +175,17 @@ func GlobalInitInstalled(ctx context.Context) {
// NormalRoutes represents non install routes
func NormalRoutes(ctx context.Context) *web.Route {
ctx, _ = templates.HTMLRenderer(ctx)
_ = templates.HTMLRenderer()
r := web.NewRoute()
for _, middle := range common.Middlewares() {
r.Use(middle)
}
r.Use(common.ProtocolMiddlewares()...)
r.Mount("/", web_routers.Routes(ctx))
r.Mount("/api/v1", apiv1.Routes(ctx))
r.Mount("/api/internal", private.Routes())
if setting.Packages.Enabled {
// Add endpoints to match common package manager APIs
// This implements package support for most package managers
r.Mount("/api/packages", packages_router.CommonRoutes(ctx))
// This implements the OCI API (Note this is not preceded by /api but is instead /v2)
r.Mount("/v2", packages_router.ContainerRoutes(ctx))
}
+1 -1
View File
@@ -55,7 +55,7 @@ func getSupportedDbTypeNames() (dbTypeNames []map[string]string) {
// Init prepare for rendering installation page
func Init(ctx goctx.Context) func(next http.Handler) http.Handler {
_, rnd := templates.HTMLRenderer(ctx)
rnd := templates.HTMLRenderer()
dbTypeNames := getSupportedDbTypeNames()
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
+9 -23
View File
@@ -19,8 +19,6 @@ import (
"code.gitea.io/gitea/routers/common"
"code.gitea.io/gitea/routers/web/healthcheck"
"code.gitea.io/gitea/services/forms"
"gitea.com/go-chi/session"
)
type dataStore map[string]interface{}
@@ -30,7 +28,6 @@ func (d *dataStore) GetData() map[string]interface{} {
}
func installRecovery(ctx goctx.Context) func(next http.Handler) http.Handler {
_, rnd := templates.HTMLRenderer(ctx)
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
defer func() {
@@ -69,6 +66,7 @@ func installRecovery(ctx goctx.Context) func(next http.Handler) http.Handler {
if !setting.IsProd {
store["ErrorMsg"] = combinedErr
}
rnd := templates.HTMLRenderer()
err = rnd.HTML(w, http.StatusInternalServerError, "status/500", templates.BaseVars().Merge(store))
if err != nil {
log.Error("%v", err)
@@ -83,34 +81,22 @@ func installRecovery(ctx goctx.Context) func(next http.Handler) http.Handler {
// Routes registers the installation routes
func Routes(ctx goctx.Context) *web.Route {
base := web.NewRoute()
base.Use(common.ProtocolMiddlewares()...)
base.RouteMethods("/assets/*", "GET, HEAD", public.AssetsHandlerFunc("/assets/"))
r := web.NewRoute()
for _, middle := range common.Middlewares() {
r.Use(middle)
}
r.Use(web.MiddlewareWithPrefix("/assets/", nil, public.AssetsHandlerFunc("/assets/")))
r.Use(session.Sessioner(session.Options{
Provider: setting.SessionConfig.Provider,
ProviderConfig: setting.SessionConfig.ProviderConfig,
CookieName: setting.SessionConfig.CookieName,
CookiePath: setting.SessionConfig.CookiePath,
Gclifetime: setting.SessionConfig.Gclifetime,
Maxlifetime: setting.SessionConfig.Maxlifetime,
Secure: setting.SessionConfig.Secure,
SameSite: setting.SessionConfig.SameSite,
Domain: setting.SessionConfig.Domain,
}))
r.Use(common.Sessioner())
r.Use(installRecovery(ctx))
r.Use(Init(ctx))
r.Get("/", Install) // it must be on the root, because the "install.js" use the window.location to replace the "localhost" AppURL
r.Post("/", web.Bind(forms.InstallForm{}), SubmitInstall)
r.Get("/post-install", InstallDone)
r.Get("/api/healthz", healthcheck.Check)
r.NotFound(installNotFound)
return r
base.Mount("", r)
return base
}
func installNotFound(w http.ResponseWriter, req *http.Request) {
+8 -5
View File
@@ -11,11 +11,14 @@ import (
)
func TestRoutes(t *testing.T) {
// TODO: this test seems not really testing the handlers
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
routes := Routes(ctx)
assert.NotNil(t, routes)
assert.EqualValues(t, "/", routes.R.Routes()[0].Pattern)
assert.Nil(t, routes.R.Routes()[0].SubRoutes)
assert.Len(t, routes.R.Routes()[0].Handlers, 2)
base := Routes(ctx)
assert.NotNil(t, base)
r := base.R.Routes()[1]
routes := r.SubRoutes.Routes()[0]
assert.EqualValues(t, "/", routes.Pattern)
assert.Nil(t, routes.SubRoutes)
assert.Len(t, routes.Handlers, 2)
}
-5
View File
@@ -113,7 +113,6 @@ func updateSystemStatus() {
// Dashboard show admin panel dashboard
func Dashboard(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("admin.dashboard")
ctx.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminDashboard"] = true
ctx.Data["Stats"] = activities_model.GetStatistic()
ctx.Data["NeedUpdate"] = updatechecker.GetNeedUpdate()
@@ -129,7 +128,6 @@ func Dashboard(ctx *context.Context) {
func DashboardPost(ctx *context.Context) {
form := web.GetForm(ctx).(*forms.AdminDashboardForm)
ctx.Data["Title"] = ctx.Tr("admin.dashboard")
ctx.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminDashboard"] = true
ctx.Data["Stats"] = activities_model.GetStatistic()
updateSystemStatus()
@@ -155,7 +153,6 @@ func DashboardPost(ctx *context.Context) {
// Monitor show admin monitor page
func Monitor(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("admin.monitor")
ctx.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminMonitor"] = true
ctx.Data["Processes"], ctx.Data["ProcessCount"] = process.GetManager().Processes(false, true)
ctx.Data["Entries"] = cron.ListTasks()
@@ -167,7 +164,6 @@ func Monitor(ctx *context.Context) {
// GoroutineStacktrace show admin monitor goroutines page
func GoroutineStacktrace(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("admin.monitor")
ctx.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminMonitor"] = true
processStacks, processCount, goroutineCount, err := process.GetManager().ProcessStacktraces(false, false)
@@ -202,7 +198,6 @@ func Queue(ctx *context.Context) {
return
}
ctx.Data["Title"] = ctx.Tr("admin.monitor.queue", mq.Name)
ctx.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminMonitor"] = true
ctx.Data["Queue"] = mq
ctx.HTML(http.StatusOK, tplQueue)
-5
View File
@@ -31,7 +31,6 @@ func newOAuth2CommonHandlers() *user_setting.OAuth2CommonHandlers {
// Applications render org applications page (for org, at the moment, there are only OAuth2 applications)
func Applications(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("settings.applications")
ctx.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminApplications"] = true
apps, err := auth.GetOAuth2ApplicationsByUserID(ctx, 0)
@@ -47,7 +46,6 @@ func Applications(ctx *context.Context) {
// ApplicationsPost response for adding an oauth2 application
func ApplicationsPost(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("settings.applications")
ctx.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminApplications"] = true
oa := newOAuth2CommonHandlers()
@@ -56,7 +54,6 @@ func ApplicationsPost(ctx *context.Context) {
// EditApplication displays the given application
func EditApplication(ctx *context.Context) {
ctx.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminApplications"] = true
oa := newOAuth2CommonHandlers()
@@ -66,7 +63,6 @@ func EditApplication(ctx *context.Context) {
// EditApplicationPost response for editing oauth2 application
func EditApplicationPost(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("settings.applications")
ctx.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminApplications"] = true
oa := newOAuth2CommonHandlers()
@@ -76,7 +72,6 @@ func EditApplicationPost(ctx *context.Context) {
// ApplicationsRegenerateSecret handles the post request for regenerating the secret
func ApplicationsRegenerateSecret(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("settings")
ctx.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminApplications"] = true
oa := newOAuth2CommonHandlers()
-5
View File
@@ -45,7 +45,6 @@ var (
// Authentications show authentication config page
func Authentications(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("admin.authentication")
ctx.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminAuthentications"] = true
var err error
@@ -89,7 +88,6 @@ var (
// NewAuthSource render adding a new auth source page
func NewAuthSource(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("admin.auths.new")
ctx.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminAuthentications"] = true
ctx.Data["type"] = auth.LDAP.Int()
@@ -237,7 +235,6 @@ func parseSSPIConfig(ctx *context.Context, form forms.AuthenticationForm) (*sspi
func NewAuthSourcePost(ctx *context.Context) {
form := *web.GetForm(ctx).(*forms.AuthenticationForm)
ctx.Data["Title"] = ctx.Tr("admin.auths.new")
ctx.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminAuthentications"] = true
ctx.Data["CurrentTypeName"] = auth.Type(form.Type).String()
@@ -333,7 +330,6 @@ func NewAuthSourcePost(ctx *context.Context) {
// EditAuthSource render editing auth source page
func EditAuthSource(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("admin.auths.edit")
ctx.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminAuthentications"] = true
ctx.Data["SecurityProtocols"] = securityProtocols
@@ -369,7 +365,6 @@ func EditAuthSource(ctx *context.Context) {
func EditAuthSourcePost(ctx *context.Context) {
form := *web.GetForm(ctx).(*forms.AuthenticationForm)
ctx.Data["Title"] = ctx.Tr("admin.auths.edit")
ctx.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminAuthentications"] = true
ctx.Data["SMTPAuths"] = smtp.Authenticators
-1
View File
@@ -100,7 +100,6 @@ func shadowPassword(provider, cfgItem string) string {
// Config show admin config page
func Config(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("admin.config")
ctx.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminConfig"] = true
systemSettings, err := system_model.GetAllSettings(ctx)
-1
View File
@@ -24,7 +24,6 @@ const (
// Emails show all emails
func Emails(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("admin.emails")
ctx.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminEmails"] = true
opts := &user_model.SearchEmailOptions{
-1
View File
@@ -22,7 +22,6 @@ const (
// Notices show notices for admin
func Notices(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("admin.notices")
ctx.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminNotices"] = true
total := system_model.CountNotices()
-1
View File
@@ -21,7 +21,6 @@ const (
// Organizations show all the organizations
func Organizations(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("admin.organizations")
ctx.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminOrganizations"] = true
explore.RenderUserSearch(ctx, &user_model.SearchUserOptions{
-1
View File
@@ -64,7 +64,6 @@ func Packages(ctx *context.Context) {
}
ctx.Data["Title"] = ctx.Tr("packages.title")
ctx.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminPackages"] = true
ctx.Data["Query"] = query
ctx.Data["PackageType"] = packageType
+1 -3
View File
@@ -29,7 +29,6 @@ const (
// Repos show all the repositories
func Repos(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("admin.repositories")
ctx.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminRepositories"] = true
explore.RenderRepoSearch(ctx, &explore.RepoSearchOptions{
@@ -67,7 +66,6 @@ func DeleteRepo(ctx *context.Context) {
// UnadoptedRepos lists the unadopted repositories
func UnadoptedRepos(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("admin.repositories")
ctx.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminRepositories"] = true
opts := db.ListOptions{
@@ -135,7 +133,7 @@ func AdoptOrDeleteRepository(ctx *context.Context) {
repoName := dirSplit[1]
// check not a repo
has, err := repo_model.IsRepositoryExist(ctx, ctxUser, repoName)
has, err := repo_model.IsRepositoryModelExist(ctx, ctxUser, repoName)
if err != nil {
ctx.ServerError("IsRepositoryExist", err)
return
+2 -67
View File
@@ -4,75 +4,10 @@
package admin
import (
"net/url"
actions_model "code.gitea.io/gitea/models/actions"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/setting"
actions_shared "code.gitea.io/gitea/routers/web/shared/actions"
)
const (
tplRunners base.TplName = "admin/runners/base"
tplRunnerEdit base.TplName = "admin/runners/edit"
)
// Runners show all the runners
func Runners(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("actions.runners")
ctx.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminRunners"] = true
page := ctx.FormInt("page")
if page <= 1 {
page = 1
}
opts := actions_model.FindRunnerOptions{
ListOptions: db.ListOptions{
Page: page,
PageSize: 100,
},
Sort: ctx.Req.URL.Query().Get("sort"),
Filter: ctx.Req.URL.Query().Get("q"),
}
actions_shared.RunnersList(ctx, tplRunners, opts)
}
// EditRunner show editing runner page
func EditRunner(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("actions.runners.edit_runner")
ctx.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminRunners"] = true
page := ctx.FormInt("page")
if page <= 1 {
page = 1
}
actions_shared.RunnerDetails(ctx, tplRunnerEdit, page, ctx.ParamsInt64(":runnerid"), 0, 0)
}
// EditRunnerPost response for editing runner
func EditRunnerPost(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("actions.runners.edit")
ctx.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminRunners"] = true
actions_shared.RunnerDetailsEditPost(ctx, ctx.ParamsInt64(":runnerid"), 0, 0,
setting.AppSubURL+"/admin/runners/"+url.PathEscape(ctx.Params(":runnerid")))
}
// DeleteRunnerPost response for deleting a runner
func DeleteRunnerPost(ctx *context.Context) {
actions_shared.RunnerDeletePost(ctx, ctx.ParamsInt64(":runnerid"),
setting.AppSubURL+"/admin/runners/",
setting.AppSubURL+"/admin/runners/"+url.PathEscape(ctx.Params(":runnerid")),
)
}
func ResetRunnerRegistrationToken(ctx *context.Context) {
actions_shared.RunnerResetRegistrationToken(ctx, 0, 0, setting.AppSubURL+"/admin/runners/")
func RedirectToDefaultSetting(ctx *context.Context) {
ctx.Redirect(setting.AppSubURL + "/admin/actions/runners")
}
-5
View File
@@ -37,7 +37,6 @@ const (
// Users show all the users
func Users(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("admin.users")
ctx.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminUsers"] = true
extraParamStrings := map[string]string{}
@@ -80,7 +79,6 @@ func Users(ctx *context.Context) {
// NewUser render adding a new user page
func NewUser(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("admin.users.new_account")
ctx.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminUsers"] = true
ctx.Data["DefaultUserVisibilityMode"] = setting.Service.DefaultUserVisibilityMode
ctx.Data["AllowedUserVisibilityModes"] = setting.Service.AllowedUserVisibilityModesSlice.ToVisibleTypeSlice()
@@ -102,7 +100,6 @@ func NewUser(ctx *context.Context) {
func NewUserPost(ctx *context.Context) {
form := web.GetForm(ctx).(*forms.AdminCreateUserForm)
ctx.Data["Title"] = ctx.Tr("admin.users.new_account")
ctx.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminUsers"] = true
ctx.Data["DefaultUserVisibilityMode"] = setting.Service.DefaultUserVisibilityMode
ctx.Data["AllowedUserVisibilityModes"] = setting.Service.AllowedUserVisibilityModesSlice.ToVisibleTypeSlice()
@@ -253,7 +250,6 @@ func prepareUserInfo(ctx *context.Context) *user_model.User {
// EditUser show editing user page
func EditUser(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("admin.users.edit_account")
ctx.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminUsers"] = true
ctx.Data["DisableRegularOrgCreation"] = setting.Admin.DisableRegularOrgCreation
ctx.Data["DisableMigrations"] = setting.Repository.DisableMigrations
@@ -271,7 +267,6 @@ func EditUser(ctx *context.Context) {
func EditUserPost(ctx *context.Context) {
form := web.GetForm(ctx).(*forms.AdminEditUserForm)
ctx.Data["Title"] = ctx.Tr("admin.users.edit_account")
ctx.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminUsers"] = true
ctx.Data["DisableMigrations"] = setting.Repository.DisableMigrations
ctx.Data["AllowedUserVisibilityModes"] = setting.Service.AllowedUserVisibilityModesSlice.ToVisibleTypeSlice()
+4 -9
View File
@@ -59,12 +59,7 @@ func storageHandler(storageSetting setting.Storage, prefix string, objStore stor
return
}
http.Redirect(
w,
req,
u.String(),
http.StatusTemporaryRedirect,
)
http.Redirect(w, req, u.String(), http.StatusTemporaryRedirect)
})
}
@@ -122,10 +117,10 @@ func (d *dataStore) GetData() map[string]interface{} {
return *d
}
// Recovery returns a middleware that recovers from any panics and writes a 500 and a log if so.
// RecoveryWith500Page returns a middleware that recovers from any panics and writes a 500 and a log if so.
// This error will be created with the gitea 500 page.
func Recovery(ctx goctx.Context) func(next http.Handler) http.Handler {
_, rnd := templates.HTMLRenderer(ctx)
func RecoveryWith500Page(ctx goctx.Context) func(next http.Handler) http.Handler {
rnd := templates.HTMLRenderer()
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
defer func() {
+1 -1
View File
@@ -16,7 +16,7 @@ import (
// ShowBranchFeed shows tags and/or releases on the repo as RSS / Atom feed
func ShowBranchFeed(ctx *context.Context, repo *repo.Repository, formatType string) {
commits, err := ctx.Repo.Commit.CommitsByRange(0, 10)
commits, err := ctx.Repo.Commit.CommitsByRange(0, 10, "")
if err != nil {
ctx.ServerError("ShowBranchFeed", err)
return
+49
View File
@@ -0,0 +1,49 @@
// Copyright 2023 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package misc
import (
"net/http"
"os"
"path"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/httpcache"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting"
)
func SSHInfo(rw http.ResponseWriter, req *http.Request) {
if !git.SupportProcReceive {
rw.WriteHeader(http.StatusNotFound)
return
}
rw.Header().Set("content-type", "text/json;charset=UTF-8")
_, err := rw.Write([]byte(`{"type":"gitea","version":1}`))
if err != nil {
log.Error("fail to write result: err: %v", err)
rw.WriteHeader(http.StatusInternalServerError)
return
}
rw.WriteHeader(http.StatusOK)
}
func DummyOK(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(http.StatusOK)
}
func RobotsTxt(w http.ResponseWriter, req *http.Request) {
filePath := path.Join(setting.CustomPath, "robots.txt")
fi, err := os.Stat(filePath)
if err == nil && httpcache.HandleTimeCache(req, w, fi) {
return
}
http.ServeFile(w, req, filePath)
}
func StaticRedirect(target string) func(w http.ResponseWriter, req *http.Request) {
return func(w http.ResponseWriter, req *http.Request) {
http.Redirect(w, req, path.Join(setting.StaticURLPrefix, target), http.StatusMovedPermanently)
}
}
+7
View File
@@ -10,6 +10,7 @@ import (
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/organization"
repo_model "code.gitea.io/gitea/models/repo"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/markup"
@@ -143,6 +144,11 @@ func Home(ctx *context.Context) {
return
}
var isFollowing bool
if ctx.Doer != nil {
isFollowing = user_model.IsFollowing(ctx.Doer.ID, ctx.ContextUser.ID)
}
ctx.Data["Repos"] = repos
ctx.Data["Total"] = count
ctx.Data["MembersTotal"] = membersCount
@@ -150,6 +156,7 @@ func Home(ctx *context.Context) {
ctx.Data["Teams"] = ctx.Org.Teams
ctx.Data["DisableNewPullMirrors"] = setting.Mirror.DisableNewPull
ctx.Data["PageIsViewRepositories"] = true
ctx.Data["IsFollowing"] = isFollowing
pager := context.NewPagination(int(count), setting.UI.User.RepoPagingNum, page, 5)
pager.SetDefaultParams(ctx)
-78
View File
@@ -1,78 +0,0 @@
// Copyright 2022 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package org
import (
"net/url"
actions_model "code.gitea.io/gitea/models/actions"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/context"
actions_shared "code.gitea.io/gitea/routers/web/shared/actions"
)
// Runners render runners page
func Runners(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("org.runners")
ctx.Data["PageIsOrgSettings"] = true
ctx.Data["PageIsOrgSettingsRunners"] = true
page := ctx.FormInt("page")
if page <= 1 {
page = 1
}
opts := actions_model.FindRunnerOptions{
ListOptions: db.ListOptions{
Page: page,
PageSize: 100,
},
Sort: ctx.Req.URL.Query().Get("sort"),
Filter: ctx.Req.URL.Query().Get("q"),
OwnerID: ctx.Org.Organization.ID,
WithAvailable: true,
}
actions_shared.RunnersList(ctx, tplSettingsRunners, opts)
}
// ResetRunnerRegistrationToken reset runner registration token
func ResetRunnerRegistrationToken(ctx *context.Context) {
actions_shared.RunnerResetRegistrationToken(ctx,
ctx.Org.Organization.ID, 0,
ctx.Org.OrgLink+"/settings/runners")
}
// RunnersEdit render runner edit page
func RunnersEdit(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("org.runners.edit")
ctx.Data["PageIsOrgSettings"] = true
ctx.Data["PageIsOrgSettingsRunners"] = true
page := ctx.FormInt("page")
if page <= 1 {
page = 1
}
actions_shared.RunnerDetails(ctx, tplSettingsRunnersEdit, page,
ctx.ParamsInt64(":runnerid"), ctx.Org.Organization.ID, 0,
)
}
// RunnersEditPost response for editing runner
func RunnersEditPost(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("org.runners.edit")
ctx.Data["PageIsOrgSettings"] = true
ctx.Data["PageIsOrgSettingsRunners"] = true
actions_shared.RunnerDetailsEditPost(ctx, ctx.ParamsInt64(":runnerid"),
ctx.Org.Organization.ID, 0,
ctx.Org.OrgLink+"/settings/runners/"+url.PathEscape(ctx.Params(":runnerid")))
}
// RunnerDeletePost response for deleting runner
func RunnerDeletePost(ctx *context.Context) {
actions_shared.RunnerDeletePost(ctx,
ctx.ParamsInt64(":runnerid"),
ctx.Org.OrgLink+"/settings/runners",
ctx.Org.OrgLink+"/settings/runners/"+url.PathEscape(ctx.Params(":runnerid")))
}
-4
View File
@@ -37,10 +37,6 @@ const (
tplSettingsHooks base.TplName = "org/settings/hooks"
// tplSettingsLabels template path for render labels settings
tplSettingsLabels base.TplName = "org/settings/labels"
// tplSettingsRunners template path for render runners settings
tplSettingsRunners base.TplName = "org/settings/runners"
// tplSettingsRunnersEdit template path for render runners edit settings
tplSettingsRunnersEdit base.TplName = "org/settings/runners_edit"
)
// Settings render the main settings page
+12
View File
@@ -0,0 +1,12 @@
// Copyright 2022 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package setting
import (
"code.gitea.io/gitea/modules/context"
)
func RedirectToDefaultSetting(ctx *context.Context) {
ctx.Redirect(ctx.Org.OrgLink + "/settings/actions/runners")
}
-50
View File
@@ -1,50 +0,0 @@
// Copyright 2022 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package org
import (
"net/http"
"code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/context"
shared "code.gitea.io/gitea/routers/web/shared/secrets"
)
const (
tplSettingsSecrets base.TplName = "org/settings/secrets"
)
// Secrets render organization secrets page
func Secrets(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("secrets.secrets")
ctx.Data["PageIsOrgSettings"] = true
ctx.Data["PageIsOrgSettingsSecrets"] = true
shared.SetSecretsContext(ctx, ctx.ContextUser.ID, 0)
if ctx.Written() {
return
}
ctx.HTML(http.StatusOK, tplSettingsSecrets)
}
// SecretsPost add secrets
func SecretsPost(ctx *context.Context) {
shared.PerformSecretsPost(
ctx,
ctx.ContextUser.ID,
0,
ctx.Org.OrgLink+"/settings/secrets",
)
}
// SecretsDelete delete secrets
func SecretsDelete(ctx *context.Context) {
shared.PerformSecretsDelete(
ctx,
ctx.ContextUser.ID,
0,
ctx.Org.OrgLink+"/settings/secrets",
)
}
+9 -1
View File
@@ -86,9 +86,17 @@ func TeamsAction(ctx *context.Context) {
return
}
}
redirect := ctx.Org.OrgLink + "/teams/"
if isOrgMember, err := org_model.IsOrganizationMember(ctx, ctx.Org.Organization.ID, ctx.Doer.ID); err != nil {
ctx.ServerError("IsOrganizationMember", err)
return
} else if !isOrgMember {
redirect = setting.AppSubURL + "/"
}
ctx.JSON(http.StatusOK,
map[string]interface{}{
"redirect": ctx.Org.OrgLink + "/teams/",
"redirect": redirect,
})
return
case "remove":
+34 -7
View File
@@ -55,6 +55,7 @@ type ViewResponse struct {
Status string `json:"status"`
CanCancel bool `json:"canCancel"`
CanApprove bool `json:"canApprove"` // the run needs an approval and the doer has permission to approve
CanRerun bool `json:"canRerun"`
Done bool `json:"done"`
Jobs []*ViewJob `json:"jobs"`
Commit ViewCommit `json:"commit"`
@@ -136,6 +137,7 @@ func ViewPost(ctx *context_module.Context) {
resp.State.Run.Link = run.Link()
resp.State.Run.CanCancel = !run.Status.IsDone() && ctx.Repo.CanWrite(unit.TypeActions)
resp.State.Run.CanApprove = run.NeedApproval && ctx.Repo.CanWrite(unit.TypeActions)
resp.State.Run.CanRerun = run.Status.IsDone() && ctx.Repo.CanWrite(unit.TypeActions)
resp.State.Run.Done = run.Status.IsDone()
resp.State.Run.Jobs = make([]*ViewJob, 0, len(jobs)) // marshal to '[]' instead fo 'null' in json
resp.State.Run.Status = run.Status.String()
@@ -238,7 +240,7 @@ func ViewPost(ctx *context_module.Context) {
ctx.JSON(http.StatusOK, resp)
}
func Rerun(ctx *context_module.Context) {
func RerunOne(ctx *context_module.Context) {
runIndex := ctx.ParamsInt64("run")
jobIndex := ctx.ParamsInt64("job")
@@ -246,10 +248,37 @@ func Rerun(ctx *context_module.Context) {
if ctx.Written() {
return
}
if err := rerunJob(ctx, job); err != nil {
ctx.Error(http.StatusInternalServerError, err.Error())
return
}
ctx.JSON(http.StatusOK, struct{}{})
}
func RerunAll(ctx *context_module.Context) {
runIndex := ctx.ParamsInt64("run")
_, jobs := getRunJobs(ctx, runIndex, 0)
if ctx.Written() {
return
}
for _, j := range jobs {
if err := rerunJob(ctx, j); err != nil {
ctx.Error(http.StatusInternalServerError, err.Error())
return
}
}
ctx.JSON(http.StatusOK, struct{}{})
}
func rerunJob(ctx *context_module.Context, job *actions_model.ActionRunJob) error {
status := job.Status
if !status.IsDone() {
ctx.JSON(http.StatusOK, struct{}{})
return
return nil
}
job.TaskID = 0
@@ -261,13 +290,11 @@ func Rerun(ctx *context_module.Context) {
_, err := actions_model.UpdateRunJob(ctx, job, builder.Eq{"status": status}, "task_id", "status", "started", "stopped")
return err
}); err != nil {
ctx.Error(http.StatusInternalServerError, err.Error())
return
return err
}
actions_service.CreateCommitStatus(ctx, job)
ctx.JSON(http.StatusOK, struct{}{})
return nil
}
func Cancel(ctx *context_module.Context) {
+5
View File
@@ -110,6 +110,11 @@ func ServeAttachment(ctx *context.Context, uuid string) {
return
}
} else { // If we have the repository we check access
context.CheckRepoScopedToken(ctx, repository)
if ctx.Written() {
return
}
perm, err := access_model.GetUserRepoPermission(ctx, repository, ctx.Doer)
if err != nil {
ctx.Error(http.StatusInternalServerError, "GetUserRepoPermission", err.Error())
+1 -1
View File
@@ -70,7 +70,7 @@ func Commits(ctx *context.Context) {
}
// Both `git log branchName` and `git log commitId` work.
commits, err := ctx.Repo.Commit.CommitsByRange(page, pageSize)
commits, err := ctx.Repo.Commit.CommitsByRange(page, pageSize, "")
if err != nil {
ctx.ServerError("CommitsByRange", err)
return
+8 -3
View File
@@ -19,7 +19,7 @@ import (
"time"
actions_model "code.gitea.io/gitea/models/actions"
"code.gitea.io/gitea/models/auth"
auth_model "code.gitea.io/gitea/models/auth"
"code.gitea.io/gitea/models/perm"
access_model "code.gitea.io/gitea/models/perm/access"
repo_model "code.gitea.io/gitea/models/repo"
@@ -152,13 +152,18 @@ func httpBase(ctx *context.Context) (h *serviceHandler) {
return
}
context.CheckRepoScopedToken(ctx, repo)
if ctx.Written() {
return
}
if ctx.IsBasicAuth && ctx.Data["IsApiToken"] != true && ctx.Data["IsActionsToken"] != true {
_, err = auth.GetTwoFactorByUID(ctx.Doer.ID)
_, err = auth_model.GetTwoFactorByUID(ctx.Doer.ID)
if err == nil {
// TODO: This response should be changed to "invalid credentials" for security reasons once the expectation behind it (creating an app token to authenticate) is properly documented
ctx.PlainText(http.StatusUnauthorized, "Users with two-factor authentication enabled cannot perform HTTP/HTTPS operations via plain username and password. Please create and use a personal access token on the user settings page")
return
} else if !auth.IsErrTwoFactorNotEnrolled(err) {
} else if !auth_model.IsErrTwoFactorNotEnrolled(err) {
ctx.ServerError("IsErrTwoFactorNotEnrolled", err)
return
}
+27 -10
View File
@@ -241,7 +241,7 @@ func issues(ctx *context.Context, milestoneID, projectID int64, isPullOption uti
pager := context.NewPagination(total, setting.UI.IssuePagingNum, page, 5)
var mileIDs []int64
if milestoneID > 0 {
if milestoneID > 0 || milestoneID == db.NoConditionID { // -1 to get those issues which have no any milestone assigned
mileIDs = []int64{milestoneID}
}
@@ -438,14 +438,8 @@ func Issues(ctx *context.Context) {
return
}
var err error
// Get milestones
ctx.Data["Milestones"], _, err = issues_model.GetMilestones(issues_model.GetMilestonesOption{
RepoID: ctx.Repo.Repository.ID,
State: api.StateType(ctx.FormString("state")),
})
if err != nil {
ctx.ServerError("GetAllRepoMilestones", err)
renderMilestones(ctx)
if ctx.Written() {
return
}
@@ -454,6 +448,29 @@ func Issues(ctx *context.Context) {
ctx.HTML(http.StatusOK, tplIssues)
}
func renderMilestones(ctx *context.Context) {
// Get milestones
milestones, _, err := issues_model.GetMilestones(issues_model.GetMilestonesOption{
RepoID: ctx.Repo.Repository.ID,
State: api.StateAll,
})
if err != nil {
ctx.ServerError("GetAllRepoMilestones", err)
return
}
openMilestones, closedMilestones := issues_model.MilestoneList{}, issues_model.MilestoneList{}
for _, milestone := range milestones {
if milestone.IsClosed {
closedMilestones = append(closedMilestones, milestone)
} else {
openMilestones = append(openMilestones, milestone)
}
}
ctx.Data["OpenMilestones"] = openMilestones
ctx.Data["ClosedMilestones"] = closedMilestones
}
// RetrieveRepoMilestonesAndAssignees find all the milestones and assignees of a repository
func RetrieveRepoMilestonesAndAssignees(ctx *context.Context, repo *repo_model.Repository) {
var err error
@@ -2689,7 +2706,7 @@ func UpdateIssueStatus(ctx *context.Context) {
if err := issue_service.ChangeStatus(issue, ctx.Doer, "", isClosed); err != nil {
if issues_model.IsErrDependenciesLeft(err) {
ctx.JSON(http.StatusPreconditionFailed, map[string]interface{}{
"error": "cannot close this issue because it still has open dependencies",
"error": ctx.Tr("repo.issues.dependency.issue_batch_close_blocked", issue.Index),
})
return
}
+18
View File
@@ -18,7 +18,9 @@ import (
"code.gitea.io/gitea/models/unit"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/cache"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/log"
repo_module "code.gitea.io/gitea/modules/repository"
"code.gitea.io/gitea/modules/setting"
@@ -59,6 +61,22 @@ func MustBeAbleToUpload(ctx *context.Context) {
}
}
func CommitInfoCache(ctx *context.Context) {
var err error
ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(ctx.Repo.Repository.DefaultBranch)
if err != nil {
ctx.ServerError("GetBranchCommit", err)
return
}
ctx.Repo.CommitsCount, err = ctx.Repo.GetCommitsCount()
if err != nil {
ctx.ServerError("GetCommitsCount", err)
return
}
ctx.Data["CommitsCount"] = ctx.Repo.CommitsCount
ctx.Repo.GitRepo.LastCommitCache = git.NewLastCommitCache(ctx.Repo.CommitsCount, ctx.Repo.Repository.FullName(), ctx.Repo.GitRepo, cache.GetCache())
}
func checkContextUser(ctx *context.Context, uid int64) *user_model.User {
orgs, err := organization.GetOrgsCanCreateRepoByUserID(ctx.Doer.ID)
if err != nil {
-76
View File
@@ -1,76 +0,0 @@
// Copyright 2022 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package repo
import (
"net/url"
actions_model "code.gitea.io/gitea/models/actions"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/context"
actions_shared "code.gitea.io/gitea/routers/web/shared/actions"
)
const (
tplRunners = "repo/settings/runners"
tplRunnerEdit = "repo/settings/runner_edit"
)
// Runners render runners page
func Runners(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("actions.runners")
ctx.Data["PageIsSettingsRunners"] = true
page := ctx.FormInt("page")
if page <= 1 {
page = 1
}
opts := actions_model.FindRunnerOptions{
ListOptions: db.ListOptions{
Page: page,
PageSize: 100,
},
Sort: ctx.Req.URL.Query().Get("sort"),
Filter: ctx.Req.URL.Query().Get("q"),
RepoID: ctx.Repo.Repository.ID,
WithAvailable: true,
}
actions_shared.RunnersList(ctx, tplRunners, opts)
}
func RunnersEdit(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("actions.runners")
ctx.Data["PageIsSettingsRunners"] = true
page := ctx.FormInt("page")
if page <= 1 {
page = 1
}
actions_shared.RunnerDetails(ctx, tplRunnerEdit, page,
ctx.ParamsInt64(":runnerid"), 0, ctx.Repo.Repository.ID,
)
}
func RunnersEditPost(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("actions.runners")
ctx.Data["PageIsSettingsRunners"] = true
actions_shared.RunnerDetailsEditPost(ctx, ctx.ParamsInt64(":runnerid"),
0, ctx.Repo.Repository.ID,
ctx.Repo.RepoLink+"/settings/runners/"+url.PathEscape(ctx.Params(":runnerid")))
}
func ResetRunnerRegistrationToken(ctx *context.Context) {
actions_shared.RunnerResetRegistrationToken(ctx,
0, ctx.Repo.Repository.ID,
ctx.Repo.RepoLink+"/settings/runners")
}
// RunnerDeletePost response for deleting runner
func RunnerDeletePost(ctx *context.Context) {
actions_shared.RunnerDeletePost(ctx, ctx.ParamsInt64(":runnerid"),
ctx.Repo.RepoLink+"/settings/runners",
ctx.Repo.RepoLink+"/settings/runners/"+url.PathEscape(ctx.Params(":runnerid")))
}
+167
View File
@@ -0,0 +1,167 @@
// Copyright 2022 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package setting
import (
"errors"
"net/http"
"net/url"
actions_model "code.gitea.io/gitea/models/actions"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/setting"
actions_shared "code.gitea.io/gitea/routers/web/shared/actions"
)
const (
// TODO: Separate secrets from runners when layout is ready
tplRepoRunners base.TplName = "repo/settings/actions"
tplOrgRunners base.TplName = "org/settings/actions"
tplAdminRunners base.TplName = "admin/actions"
tplRepoRunnerEdit base.TplName = "repo/settings/runner_edit"
tplOrgRunnerEdit base.TplName = "org/settings/runners_edit"
tplAdminRunnerEdit base.TplName = "admin/runners/edit"
)
type runnersCtx struct {
OwnerID int64
RepoID int64
IsRepo bool
IsOrg bool
IsAdmin bool
RunnersTemplate base.TplName
RunnerEditTemplate base.TplName
RedirectLink string
}
func getRunnersCtx(ctx *context.Context) (*runnersCtx, error) {
if ctx.Data["PageIsRepoSettings"] == true {
return &runnersCtx{
RepoID: ctx.Repo.Repository.ID,
OwnerID: 0,
IsRepo: true,
RunnersTemplate: tplRepoRunners,
RunnerEditTemplate: tplRepoRunnerEdit,
RedirectLink: ctx.Repo.RepoLink + "/settings/actions/runners/",
}, nil
}
if ctx.Data["PageIsOrgSettings"] == true {
return &runnersCtx{
RepoID: 0,
OwnerID: ctx.Org.Organization.ID,
IsOrg: true,
RunnersTemplate: tplOrgRunners,
RunnerEditTemplate: tplOrgRunnerEdit,
RedirectLink: ctx.Org.OrgLink + "/settings/actions/runners/",
}, nil
}
if ctx.Data["PageIsAdmin"] == true {
return &runnersCtx{
RepoID: 0,
OwnerID: 0,
IsAdmin: true,
RunnersTemplate: tplAdminRunners,
RunnerEditTemplate: tplAdminRunnerEdit,
RedirectLink: setting.AppSubURL + "/admin/actions/runners/",
}, nil
}
return nil, errors.New("unable to set Runners context")
}
// Runners render settings/actions/runners page for repo level
func Runners(ctx *context.Context) {
ctx.Data["PageIsSharedSettingsRunners"] = true
ctx.Data["Title"] = ctx.Tr("actions.actions")
ctx.Data["PageType"] = "runners"
rCtx, err := getRunnersCtx(ctx)
if err != nil {
ctx.ServerError("getRunnersCtx", err)
return
}
page := ctx.FormInt("page")
if page <= 1 {
page = 1
}
opts := actions_model.FindRunnerOptions{
ListOptions: db.ListOptions{
Page: page,
PageSize: 100,
},
Sort: ctx.Req.URL.Query().Get("sort"),
Filter: ctx.Req.URL.Query().Get("q"),
}
if rCtx.IsRepo {
opts.RepoID = rCtx.RepoID
opts.WithAvailable = true
} else if rCtx.IsOrg {
opts.OwnerID = rCtx.OwnerID
opts.WithAvailable = true
}
actions_shared.RunnersList(ctx, opts)
ctx.HTML(http.StatusOK, rCtx.RunnersTemplate)
}
// RunnersEdit renders runner edit page for repository level
func RunnersEdit(ctx *context.Context) {
ctx.Data["PageIsSharedSettingsRunners"] = true
ctx.Data["Title"] = ctx.Tr("actions.runners.edit_runner")
rCtx, err := getRunnersCtx(ctx)
if err != nil {
ctx.ServerError("getRunnersCtx", err)
return
}
page := ctx.FormInt("page")
if page <= 1 {
page = 1
}
actions_shared.RunnerDetails(ctx, page,
ctx.ParamsInt64(":runnerid"), rCtx.OwnerID, rCtx.RepoID,
)
ctx.HTML(http.StatusOK, rCtx.RunnerEditTemplate)
}
func RunnersEditPost(ctx *context.Context) {
rCtx, err := getRunnersCtx(ctx)
if err != nil {
ctx.ServerError("getRunnersCtx", err)
return
}
actions_shared.RunnerDetailsEditPost(ctx, ctx.ParamsInt64(":runnerid"),
rCtx.OwnerID, rCtx.RepoID,
rCtx.RedirectLink+url.PathEscape(ctx.Params(":runnerid")))
}
func ResetRunnerRegistrationToken(ctx *context.Context) {
rCtx, err := getRunnersCtx(ctx)
if err != nil {
ctx.ServerError("getRunnersCtx", err)
return
}
actions_shared.RunnerResetRegistrationToken(ctx, rCtx.OwnerID, rCtx.RepoID, rCtx.RedirectLink)
}
// RunnerDeletePost response for deleting runner
func RunnerDeletePost(ctx *context.Context) {
rCtx, err := getRunnersCtx(ctx)
if err != nil {
ctx.ServerError("getRunnersCtx", err)
return
}
actions_shared.RunnerDeletePost(ctx, ctx.ParamsInt64(":runnerid"), rCtx.RedirectLink, rCtx.RedirectLink+url.PathEscape(ctx.Params(":runnerid")))
}
func RedirectToDefaultSetting(ctx *context.Context) {
ctx.Redirect(ctx.Repo.RepoLink + "/settings/actions/runners")
}
+115
View File
@@ -0,0 +1,115 @@
// Copyright 2022 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package setting
import (
"errors"
"net/http"
"code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/setting"
shared "code.gitea.io/gitea/routers/web/shared/secrets"
)
const (
// TODO: Separate secrets from runners when layout is ready
tplRepoSecrets base.TplName = "repo/settings/actions"
tplOrgSecrets base.TplName = "org/settings/actions"
tplUserSecrets base.TplName = "user/settings/actions"
)
type secretsCtx struct {
OwnerID int64
RepoID int64
IsRepo bool
IsOrg bool
IsUser bool
SecretsTemplate base.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 {
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
}
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,
)
}
+4 -13
View File
@@ -130,15 +130,6 @@ func SettingsProtectedBranch(c *context.Context) {
}
c.Data["branch_status_check_contexts"] = contexts
c.Data["is_context_required"] = func(context string) bool {
for _, c := range rule.StatusCheckContexts {
if c == context {
return true
}
}
return false
}
if c.Repo.Owner.IsOrganization() {
teams, err := organization.OrgFromUser(c.Repo.Owner).TeamsWithAccessToRepo(c.Repo.Repository.ID, perm.AccessModeRead)
if err != nil {
@@ -352,7 +343,7 @@ func RenameBranchPost(ctx *context.Context) {
if ctx.HasError() {
ctx.Flash.Error(ctx.GetErrMsg())
ctx.Redirect(fmt.Sprintf("%s/settings/branches", ctx.Repo.RepoLink))
ctx.Redirect(fmt.Sprintf("%s/branches", ctx.Repo.RepoLink))
return
}
@@ -364,16 +355,16 @@ func RenameBranchPost(ctx *context.Context) {
if msg == "target_exist" {
ctx.Flash.Error(ctx.Tr("repo.settings.rename_branch_failed_exist", form.To))
ctx.Redirect(fmt.Sprintf("%s/settings/branches", ctx.Repo.RepoLink))
ctx.Redirect(fmt.Sprintf("%s/branches", ctx.Repo.RepoLink))
return
}
if msg == "from_not_exist" {
ctx.Flash.Error(ctx.Tr("repo.settings.rename_branch_failed_not_exist", form.From))
ctx.Redirect(fmt.Sprintf("%s/settings/branches", ctx.Repo.RepoLink))
ctx.Redirect(fmt.Sprintf("%s/branches", ctx.Repo.RepoLink))
return
}
ctx.Flash.Success(ctx.Tr("repo.settings.rename_branch_success", form.From, form.To))
ctx.Redirect(fmt.Sprintf("%s/settings/branches", ctx.Repo.RepoLink))
ctx.Redirect(fmt.Sprintf("%s/branches", ctx.Repo.RepoLink))
}
-48
View File
@@ -1,48 +0,0 @@
// Copyright 2022 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package repo
import (
"net/http"
"code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/setting"
shared "code.gitea.io/gitea/routers/web/shared/secrets"
)
const (
tplSecrets base.TplName = "repo/settings/secrets"
)
func Secrets(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("secrets.secrets")
ctx.Data["PageIsSettingsSecrets"] = true
ctx.Data["DisableSSH"] = setting.SSH.Disabled
shared.SetSecretsContext(ctx, 0, ctx.Repo.Repository.ID)
if ctx.Written() {
return
}
ctx.HTML(http.StatusOK, tplSecrets)
}
func SecretsPost(ctx *context.Context) {
shared.PerformSecretsPost(
ctx,
0,
ctx.Repo.Repository.ID,
ctx.Repo.RepoLink+"/settings/secrets",
)
}
func DeleteSecret(ctx *context.Context) {
shared.PerformSecretsDelete(
ctx,
0,
ctx.Repo.Repository.ID,
ctx.Repo.RepoLink+"/settings/secrets",
)
}
+4 -4
View File
@@ -67,7 +67,7 @@ type ownerRepoCtx struct {
// getOwnerRepoCtx determines whether this is a repo, owner, or admin (both default and system) context.
func getOwnerRepoCtx(ctx *context.Context) (*ownerRepoCtx, error) {
if is, ok := ctx.Data["IsRepositoryWebhook"]; ok && is.(bool) {
if ctx.Data["PageIsRepoSettings"] == true {
return &ownerRepoCtx{
RepoID: ctx.Repo.Repository.ID,
Link: path.Join(ctx.Repo.RepoLink, "settings/hooks"),
@@ -76,7 +76,7 @@ func getOwnerRepoCtx(ctx *context.Context) (*ownerRepoCtx, error) {
}, nil
}
if is, ok := ctx.Data["IsOrganizationWebhook"]; ok && is.(bool) {
if ctx.Data["PageIsOrgSettings"] == true {
return &ownerRepoCtx{
OwnerID: ctx.ContextUser.ID,
Link: path.Join(ctx.Org.OrgLink, "settings/hooks"),
@@ -85,7 +85,7 @@ func getOwnerRepoCtx(ctx *context.Context) (*ownerRepoCtx, error) {
}, nil
}
if is, ok := ctx.Data["IsUserWebhook"]; ok && is.(bool) {
if ctx.Data["PageIsUserSettings"] == true {
return &ownerRepoCtx{
OwnerID: ctx.Doer.ID,
Link: path.Join(setting.AppSubURL, "/user/settings/hooks"),
@@ -94,7 +94,7 @@ func getOwnerRepoCtx(ctx *context.Context) (*ownerRepoCtx, error) {
}, nil
}
if ctx.Doer.IsAdmin {
if ctx.Data["PageIsAdmin"] == true {
return &ownerRepoCtx{
IsAdmin: true,
IsSystemWebhook: ctx.Params(":configType") == "system-hooks",
+5 -9
View File
@@ -10,7 +10,6 @@ import (
actions_model "code.gitea.io/gitea/models/actions"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/util"
@@ -18,8 +17,8 @@ import (
"code.gitea.io/gitea/services/forms"
)
// RunnersList render common runners list page
func RunnersList(ctx *context.Context, tplName base.TplName, opts actions_model.FindRunnerOptions) {
// RunnersList prepares data for runners list
func RunnersList(ctx *context.Context, opts actions_model.FindRunnerOptions) {
count, err := actions_model.CountRunners(ctx, opts)
if err != nil {
ctx.ServerError("CountRunners", err)
@@ -58,13 +57,12 @@ func RunnersList(ctx *context.Context, tplName base.TplName, opts actions_model.
ctx.Data["RunnerRepoID"] = opts.RepoID
pager := context.NewPagination(int(count), opts.PageSize, opts.Page, 5)
ctx.Data["Page"] = pager
ctx.HTML(http.StatusOK, tplName)
ctx.Data["Page"] = pager
}
// RunnerDetails render runner details page
func RunnerDetails(ctx *context.Context, tplName base.TplName, page int, runnerID, ownerID, repoID int64) {
// RunnerDetails prepares data for runners edit page
func RunnerDetails(ctx *context.Context, page int, runnerID, ownerID, repoID int64) {
runner, err := actions_model.GetRunnerByID(ctx, runnerID)
if err != nil {
ctx.ServerError("GetRunnerByID", err)
@@ -111,8 +109,6 @@ func RunnerDetails(ctx *context.Context, tplName base.TplName, page int, runnerI
ctx.Data["Tasks"] = tasks
pager := context.NewPagination(int(count), opts.PageSize, opts.Page, 5)
ctx.Data["Page"] = pager
ctx.HTML(http.StatusOK, tplName)
}
// RunnerDetailsEditPost response for edit runner details
+50
View File
@@ -30,6 +30,8 @@ import (
"code.gitea.io/gitea/modules/markup/markdown"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/util"
"code.gitea.io/gitea/routers/web/feed"
context_service "code.gitea.io/gitea/services/context"
issue_service "code.gitea.io/gitea/services/issue"
pull_service "code.gitea.io/gitea/services/pull"
@@ -815,3 +817,51 @@ func ShowGPGKeys(ctx *context.Context) {
writer.Close()
ctx.PlainTextBytes(http.StatusOK, buf.Bytes())
}
func UsernameSubRoute(ctx *context.Context) {
// WORKAROUND to support usernames with "." in it
// https://github.com/go-chi/chi/issues/781
username := ctx.Params("username")
reloadParam := func(suffix string) (success bool) {
ctx.SetParams("username", strings.TrimSuffix(username, suffix))
context_service.UserAssignmentWeb()(ctx)
return !ctx.Written()
}
switch {
case strings.HasSuffix(username, ".png"):
if reloadParam(".png") {
AvatarByUserName(ctx)
}
case strings.HasSuffix(username, ".keys"):
if reloadParam(".keys") {
ShowSSHKeys(ctx)
}
case strings.HasSuffix(username, ".gpg"):
if reloadParam(".gpg") {
ShowGPGKeys(ctx)
}
case strings.HasSuffix(username, ".rss"):
if !setting.Other.EnableFeed {
ctx.Error(http.StatusNotFound)
return
}
if reloadParam(".rss") {
context_service.UserAssignmentWeb()(ctx)
feed.ShowUserFeedRSS(ctx)
}
case strings.HasSuffix(username, ".atom"):
if !setting.Other.EnableFeed {
ctx.Error(http.StatusNotFound)
return
}
if reloadParam(".atom") {
feed.ShowUserFeedAtom(ctx)
}
default:
context_service.UserAssignmentWeb()(ctx)
if !ctx.Written() {
ctx.Data["EnableFeed"] = setting.Other.EnableFeed
Profile(ctx)
}
}
}
+28 -6
View File
@@ -14,8 +14,10 @@ import (
access_model "code.gitea.io/gitea/models/perm/access"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/container"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/log"
debian_module "code.gitea.io/gitea/modules/packages/debian"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/util"
"code.gitea.io/gitea/modules/web"
@@ -163,6 +165,32 @@ func ViewPackageVersion(ctx *context.Context) {
ctx.Data["IsPackagesPage"] = true
ctx.Data["PackageDescriptor"] = pd
switch pd.Package.Type {
case packages_model.TypeContainer:
ctx.Data["RegistryHost"] = setting.Packages.RegistryHost
case packages_model.TypeDebian:
distributions := make(container.Set[string])
components := make(container.Set[string])
architectures := make(container.Set[string])
for _, f := range pd.Files {
for _, pp := range f.Properties {
switch pp.Name {
case debian_module.PropertyDistribution:
distributions.Add(pp.Value)
case debian_module.PropertyComponent:
components.Add(pp.Value)
case debian_module.PropertyArchitecture:
architectures.Add(pp.Value)
}
}
}
ctx.Data["Distributions"] = distributions.Values()
ctx.Data["Components"] = components.Values()
ctx.Data["Architectures"] = architectures.Values()
}
var (
total int64
pvs []*packages_model.PackageVersion
@@ -170,8 +198,6 @@ func ViewPackageVersion(ctx *context.Context) {
)
switch pd.Package.Type {
case packages_model.TypeContainer:
ctx.Data["RegistryHost"] = setting.Packages.RegistryHost
pvs, total, err = container_model.SearchImageTags(ctx, &container_model.ImageTagsSearchOptions{
Paginator: db.NewAbsoluteListOptions(0, 5),
PackageID: pd.Package.ID,
@@ -183,10 +209,6 @@ func ViewPackageVersion(ctx *context.Context) {
PackageID: pd.Package.ID,
IsInternal: util.OptionalBoolFalse,
})
if err != nil {
ctx.ServerError("SearchVersions", err)
return
}
}
if err != nil {
ctx.ServerError("", err)
+21 -20
View File
@@ -167,30 +167,31 @@ func Profile(ctx *context.Context) {
language := ctx.FormTrim("language")
ctx.Data["Language"] = language
followers, numFollowers, err := user_model.GetUserFollowers(ctx, ctx.ContextUser, ctx.Doer, db.ListOptions{
PageSize: pagingNum,
Page: page,
})
if err != nil {
ctx.ServerError("GetUserFollowers", err)
return
}
ctx.Data["NumFollowers"] = numFollowers
following, numFollowing, err := user_model.GetUserFollowing(ctx, ctx.ContextUser, ctx.Doer, db.ListOptions{
PageSize: pagingNum,
Page: page,
})
if err != nil {
ctx.ServerError("GetUserFollowing", err)
return
}
ctx.Data["NumFollowing"] = numFollowing
switch tab {
case "followers":
items, count, err := user_model.GetUserFollowers(ctx, ctx.ContextUser, ctx.Doer, db.ListOptions{
PageSize: pagingNum,
Page: page,
})
if err != nil {
ctx.ServerError("GetUserFollowers", err)
return
}
ctx.Data["Cards"] = items
ctx.Data["Cards"] = followers
total = int(count)
case "following":
items, count, err := user_model.GetUserFollowing(ctx, ctx.ContextUser, ctx.Doer, db.ListOptions{
PageSize: pagingNum,
Page: page,
})
if err != nil {
ctx.ServerError("GetUserFollowing", err)
return
}
ctx.Data["Cards"] = items
ctx.Data["Cards"] = following
total = int(count)
case "activity":
date := ctx.FormString("date")
+1 -1
View File
@@ -31,7 +31,7 @@ func AdoptOrDeleteRepository(ctx *context.Context) {
root := user_model.UserPath(ctxUser.LowerName)
// check not a repo
has, err := repo_model.IsRepositoryExist(ctx, ctxUser, dir)
has, err := repo_model.IsRepositoryModelExist(ctx, ctxUser, dir)
if err != nil {
ctx.ServerError("IsRepositoryExist", err)
return
+2 -36
View File
@@ -4,44 +4,10 @@
package setting
import (
"net/http"
"code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/setting"
shared "code.gitea.io/gitea/routers/web/shared/secrets"
)
const (
tplSettingsSecrets base.TplName = "user/settings/secrets"
)
func Secrets(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("secrets.secrets")
ctx.Data["PageIsSettingsSecrets"] = true
shared.SetSecretsContext(ctx, ctx.Doer.ID, 0)
if ctx.Written() {
return
}
ctx.HTML(http.StatusOK, tplSettingsSecrets)
}
func SecretsPost(ctx *context.Context) {
shared.PerformSecretsPost(
ctx,
ctx.Doer.ID,
0,
setting.AppSubURL+"/user/settings/secrets",
)
}
func SecretsDelete(ctx *context.Context) {
shared.PerformSecretsDelete(
ctx,
ctx.Doer.ID,
0,
setting.AppSubURL+"/user/settings/secrets",
)
func RedirectToDefaultSetting(ctx *context.Context) {
ctx.Redirect(setting.AppSubURL + "/user/settings/actions/secrets")
}
+85 -223
View File
@@ -6,16 +6,10 @@ package web
import (
gocontext "context"
"net/http"
"os"
"path"
"strings"
"code.gitea.io/gitea/models/perm"
"code.gitea.io/gitea/models/unit"
"code.gitea.io/gitea/modules/cache"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/httpcache"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/metrics"
"code.gitea.io/gitea/modules/public"
@@ -26,6 +20,7 @@ import (
"code.gitea.io/gitea/modules/validation"
"code.gitea.io/gitea/modules/web"
"code.gitea.io/gitea/modules/web/routing"
"code.gitea.io/gitea/routers/common"
"code.gitea.io/gitea/routers/web/admin"
"code.gitea.io/gitea/routers/web/auth"
"code.gitea.io/gitea/routers/web/devtest"
@@ -35,8 +30,10 @@ import (
"code.gitea.io/gitea/routers/web/healthcheck"
"code.gitea.io/gitea/routers/web/misc"
"code.gitea.io/gitea/routers/web/org"
org_setting "code.gitea.io/gitea/routers/web/org/setting"
"code.gitea.io/gitea/routers/web/repo"
"code.gitea.io/gitea/routers/web/repo/actions"
repo_setting "code.gitea.io/gitea/routers/web/repo/setting"
"code.gitea.io/gitea/routers/web/user"
user_setting "code.gitea.io/gitea/routers/web/user/setting"
"code.gitea.io/gitea/routers/web/user/setting/security"
@@ -48,7 +45,6 @@ import (
_ "code.gitea.io/gitea/modules/session" // to registers all internal adapters
"gitea.com/go-chi/captcha"
"gitea.com/go-chi/session"
"github.com/NYTimes/gziphandler"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/cors"
@@ -99,49 +95,31 @@ func buildAuthGroup() *auth_service.Group {
return group
}
func ctxDataSet(args ...any) func(ctx *context.Context) {
return func(ctx *context.Context) {
for i := 0; i < len(args); i += 2 {
ctx.Data[args[i].(string)] = args[i+1]
}
}
}
// Routes returns all web routes
func Routes(ctx gocontext.Context) *web.Route {
routes := web.NewRoute()
routes.Use(web.MiddlewareWithPrefix("/assets/", CorsHandler(), public.AssetsHandlerFunc("/assets/")))
sessioner := session.Sessioner(session.Options{
Provider: setting.SessionConfig.Provider,
ProviderConfig: setting.SessionConfig.ProviderConfig,
CookieName: setting.SessionConfig.CookieName,
CookiePath: setting.SessionConfig.CookiePath,
Gclifetime: setting.SessionConfig.Gclifetime,
Maxlifetime: setting.SessionConfig.Maxlifetime,
Secure: setting.SessionConfig.Secure,
SameSite: setting.SessionConfig.SameSite,
Domain: setting.SessionConfig.Domain,
})
routes.Use(sessioner)
ctx, _ = templates.HTMLRenderer(ctx)
routes.Use(Recovery(ctx))
// We use r.Route here over r.Use because this prevents requests that are not for avatars having to go through this additional handler
routes.Head("/", misc.DummyOK) // for health check - doesn't need to be passed through gzip handler
routes.RouteMethods("/assets/*", "GET, HEAD", CorsHandler(), public.AssetsHandlerFunc("/assets/"))
routes.RouteMethods("/avatars/*", "GET, HEAD", storageHandler(setting.Avatar.Storage, "avatars", storage.Avatars))
routes.RouteMethods("/repo-avatars/*", "GET, HEAD", storageHandler(setting.RepoAvatar.Storage, "repo-avatars", storage.RepoAvatars))
routes.RouteMethods("/apple-touch-icon.png", "GET, HEAD", misc.StaticRedirect("/assets/img/apple-touch-icon.png"))
routes.RouteMethods("/favicon.ico", "GET, HEAD", misc.StaticRedirect("/assets/img/favicon.png"))
// for health check - doesn't need to be passed through gzip handler
routes.Head("/", func(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(http.StatusOK)
})
_ = templates.HTMLRenderer()
// this png is very likely to always be below the limit for gzip so it doesn't need to pass through gzip
routes.Get("/apple-touch-icon.png", func(w http.ResponseWriter, req *http.Request) {
http.Redirect(w, req, path.Join(setting.StaticURLPrefix, "/assets/img/apple-touch-icon.png"), http.StatusPermanentRedirect)
})
// redirect default favicon to the path of the custom favicon with a default as a fallback
routes.Get("/favicon.ico", func(w http.ResponseWriter, req *http.Request) {
http.Redirect(w, req, path.Join(setting.StaticURLPrefix, "/assets/img/favicon.png"), http.StatusMovedPermanently)
})
common := []interface{}{}
common := []any{
common.Sessioner(),
RecoveryWith500Page(ctx),
}
if setting.EnableGzip {
h, err := gziphandler.GzipHandlerWithOpts(gziphandler.MinSize(GzipMinSize))
@@ -157,42 +135,18 @@ func Routes(ctx gocontext.Context) *web.Route {
}
if setting.HasRobotsTxt {
routes.Get("/robots.txt", append(common, func(w http.ResponseWriter, req *http.Request) {
filePath := path.Join(setting.CustomPath, "robots.txt")
fi, err := os.Stat(filePath)
if err == nil && httpcache.HandleTimeCache(req, w, fi) {
return
}
http.ServeFile(w, req, filePath)
})...)
routes.Get("/robots.txt", append(common, misc.RobotsTxt)...)
}
// prometheus metrics endpoint - do not need to go through contexter
if setting.Metrics.Enabled {
c := metrics.NewCollector()
prometheus.MustRegister(c)
prometheus.MustRegister(metrics.NewCollector())
routes.Get("/metrics", append(common, Metrics)...)
}
routes.Get("/ssh_info", func(rw http.ResponseWriter, req *http.Request) {
if !git.SupportProcReceive {
rw.WriteHeader(http.StatusNotFound)
return
}
rw.Header().Set("content-type", "text/json;charset=UTF-8")
_, err := rw.Write([]byte(`{"type":"gitea","version":1}`))
if err != nil {
log.Error("fail to write result: err: %v", err)
rw.WriteHeader(http.StatusInternalServerError)
return
}
rw.WriteHeader(http.StatusOK)
})
routes.Get("/ssh_info", misc.SSHInfo)
routes.Get("/api/healthz", healthcheck.Check)
// Removed: toolbox.Toolboxer middleware will provide debug information which seems unnecessary
common = append(common, context.Contexter(ctx))
group := buildAuthGroup()
@@ -207,7 +161,7 @@ func Routes(ctx gocontext.Context) *web.Route {
common = append(common, middleware.GetHead)
if setting.API.EnableSwagger {
// Note: The route moved from apiroutes because it's in fact want to render a web page
// Note: The route is here but no in API routes because it renders a web page
routes.Get("/api/swagger", append(common, misc.Swagger)...) // Render V1 by default
}
@@ -217,17 +171,14 @@ func Routes(ctx gocontext.Context) *web.Route {
common = append(common, goGet)
others := web.NewRoute()
for _, middle := range common {
others.Use(middle)
}
RegisterRoutes(others)
others.Use(common...)
registerRoutes(others)
routes.Mount("", others)
return routes
}
// RegisterRoutes register routes
func RegisterRoutes(m *web.Route) {
// registerRoutes register routes
func registerRoutes(m *web.Route) {
reqSignIn := auth_service.VerifyAuthWithOptions(&auth_service.VerifyOptions{SignInRequired: true})
ignSignIn := auth_service.VerifyAuthWithOptions(&auth_service.VerifyOptions{SignInRequired: setting.Service.RequireSignInView})
ignExploreSignIn := auth_service.VerifyAuthWithOptions(&auth_service.VerifyOptions{SignInRequired: setting.Service.RequireSignInView || setting.Service.Explore.RequireSigninView})
@@ -342,6 +293,24 @@ func RegisterRoutes(m *web.Route) {
m.Post("/packagist/{id}", web.Bind(forms.NewPackagistHookForm{}), repo.PackagistHooksEditPost)
}
addSettingsSecretsRoutes := func() {
m.Group("/secrets", func() {
m.Get("", repo_setting.Secrets)
m.Post("", web.Bind(forms.AddSecretForm{}), repo_setting.SecretsPost)
m.Post("/delete", repo_setting.SecretsDelete)
})
}
addSettingsRunnersRoutes := func() {
m.Group("/runners", func() {
m.Get("", repo_setting.Runners)
m.Combo("/{runnerid}").Get(repo_setting.RunnersEdit).
Post(web.Bind(forms.EditRunnerForm{}), repo_setting.RunnersEditPost)
m.Post("/{runnerid}/delete", repo_setting.RunnerDeletePost)
m.Get("/reset_registration_token", repo_setting.ResetRunnerRegistrationToken)
})
}
// FIXME: not all routes need go through same middleware.
// Especially some AJAX requests, we can reduce middleware number to improve performance.
// Routers.
@@ -354,8 +323,8 @@ func RegisterRoutes(m *web.Route) {
m.Get("/nodeinfo", NodeInfoLinks)
m.Get("/webfinger", WebfingerQuery)
}, federationEnabled)
m.Get("/change-password", func(w http.ResponseWriter, req *http.Request) {
http.Redirect(w, req, "/user/settings/account", http.StatusTemporaryRedirect)
m.Get("/change-password", func(ctx *context.Context) {
ctx.Redirect(setting.AppSubURL + "/user/settings/account")
})
})
@@ -501,11 +470,12 @@ func RegisterRoutes(m *web.Route) {
})
m.Post("/chef/regenerate_keypair", user_setting.RegenerateChefKeyPair)
}, packagesEnabled)
m.Group("/secrets", func() {
m.Get("", user_setting.Secrets)
m.Post("", web.Bind(forms.AddSecretForm{}), user_setting.SecretsPost)
m.Post("/delete", user_setting.SecretsDelete)
})
m.Group("/actions", func() {
m.Get("", user_setting.RedirectToDefaultSetting)
addSettingsSecretsRoutes()
}, actions.MustEnableActions)
m.Get("/organization", user_setting.Organization)
m.Get("/repos", user_setting.Repos)
m.Post("/repos/unadopted", user_setting.AdoptOrDeleteRepository)
@@ -519,14 +489,8 @@ func RegisterRoutes(m *web.Route) {
m.Post("/replay/{uuid}", repo.ReplayWebhook)
})
addWebhookEditRoutes()
}, webhooksEnabled, func(ctx *context.Context) {
ctx.Data["IsUserWebhook"] = true
})
}, reqSignIn, func(ctx *context.Context) {
ctx.Data["PageIsUserSettings"] = true
ctx.Data["AllThemes"] = setting.UI.Themes
ctx.Data["EnablePackages"] = setting.Packages.Enabled
})
}, webhooksEnabled)
}, reqSignIn, ctxDataSet("PageIsUserSettings", true, "AllThemes", setting.UI.Themes, "EnablePackages", setting.Packages.Enabled))
m.Group("/user", func() {
// r.Get("/feeds", binding.Bind(auth.FeedsForm{}), user.Feeds)
@@ -651,66 +615,15 @@ func RegisterRoutes(m *web.Route) {
}
})
m.Group("/runners", func() {
m.Get("", admin.Runners)
m.Get("/reset_registration_token", admin.ResetRunnerRegistrationToken)
m.Combo("/{runnerid}").Get(admin.EditRunner).Post(web.Bind(forms.EditRunnerForm{}), admin.EditRunnerPost)
m.Post("/{runnerid}/delete", admin.DeleteRunnerPost)
}, actions.MustEnableActions)
}, func(ctx *context.Context) {
ctx.Data["EnableOAuth2"] = setting.OAuth2.Enable
ctx.Data["EnablePackages"] = setting.Packages.Enabled
}, adminReq)
m.Group("/actions", func() {
m.Get("", admin.RedirectToDefaultSetting)
addSettingsRunnersRoutes()
})
}, adminReq, ctxDataSet("EnableOAuth2", setting.OAuth2.Enable, "EnablePackages", setting.Packages.Enabled))
// ***** END: Admin *****
m.Group("", func() {
m.Get("/favicon.ico", func(ctx *context.Context) {
ctx.SetServeHeaders(&context.ServeHeaderOptions{
Filename: "favicon.png",
})
http.ServeFile(ctx.Resp, ctx.Req, path.Join(setting.StaticRootPath, "public/img/favicon.png"))
})
m.Get("/{username}", func(ctx *context.Context) {
// WORKAROUND to support usernames with "." in it
// https://github.com/go-chi/chi/issues/781
username := ctx.Params("username")
reloadParam := func(suffix string) (success bool) {
ctx.SetParams("username", strings.TrimSuffix(username, suffix))
context_service.UserAssignmentWeb()(ctx)
return !ctx.Written()
}
switch {
case strings.HasSuffix(username, ".png"):
if reloadParam(".png") {
user.AvatarByUserName(ctx)
}
case strings.HasSuffix(username, ".keys"):
if reloadParam(".keys") {
user.ShowSSHKeys(ctx)
}
case strings.HasSuffix(username, ".gpg"):
if reloadParam(".gpg") {
user.ShowGPGKeys(ctx)
}
case strings.HasSuffix(username, ".rss"):
feedEnabled(ctx)
if !ctx.Written() && reloadParam(".rss") {
context_service.UserAssignmentWeb()(ctx)
feed.ShowUserFeedRSS(ctx)
}
case strings.HasSuffix(username, ".atom"):
feedEnabled(ctx)
if !ctx.Written() && reloadParam(".atom") {
feed.ShowUserFeedAtom(ctx)
}
default:
context_service.UserAssignmentWeb()(ctx)
if !ctx.Written() {
ctx.Data["EnableFeed"] = setting.Other.EnableFeed
user.Profile(ctx)
}
}
})
m.Get("/{username}", user.UsernameSubRoute)
m.Get("/attachments/{uuid}", repo.GetAttachment)
}, ignSignIn)
@@ -830,9 +743,7 @@ func RegisterRoutes(m *web.Route) {
m.Post("/replay/{uuid}", repo.ReplayWebhook)
})
addWebhookEditRoutes()
}, webhooksEnabled, func(ctx *context.Context) {
ctx.Data["IsOrganizationWebhook"] = true
})
}, webhooksEnabled)
m.Group("/labels", func() {
m.Get("", org.RetrieveLabels, org.Labels)
@@ -842,20 +753,12 @@ func RegisterRoutes(m *web.Route) {
m.Post("/initialize", web.Bind(forms.InitializeLabelsForm{}), org.InitializeLabels)
})
m.Group("/runners", func() {
m.Get("", org.Runners)
m.Combo("/{runnerid}").Get(org.RunnersEdit).
Post(web.Bind(forms.EditRunnerForm{}), org.RunnersEditPost)
m.Post("/{runnerid}/delete", org.RunnerDeletePost)
m.Get("/reset_registration_token", org.ResetRunnerRegistrationToken)
m.Group("/actions", func() {
m.Get("", org_setting.RedirectToDefaultSetting)
addSettingsRunnersRoutes()
addSettingsSecretsRoutes()
}, actions.MustEnableActions)
m.Group("/secrets", func() {
m.Get("", org.Secrets)
m.Post("", web.Bind(forms.AddSecretForm{}), org.SecretsPost)
m.Post("/delete", org.SecretsDelete)
})
m.RouteMethods("/delete", "GET,POST", org.SettingsDelete)
m.Group("/packages", func() {
@@ -876,10 +779,7 @@ func RegisterRoutes(m *web.Route) {
m.Post("/rebuild", org.RebuildCargoIndex)
})
}, packagesEnabled)
}, func(ctx *context.Context) {
ctx.Data["EnableOAuth2"] = setting.OAuth2.Enable
ctx.Data["EnablePackages"] = setting.Packages.Enabled
})
}, ctxDataSet("EnableOAuth2", setting.OAuth2.Enable, "EnablePackages", setting.Packages.Enabled, "PageIsOrgSettings", true))
}, context.OrgAssignment(true, true))
}, reqSignIn)
// ***** END: Organization *****
@@ -1013,9 +913,7 @@ func RegisterRoutes(m *web.Route) {
m.Post("/replay/{uuid}", repo.ReplayWebhook)
})
addWebhookEditRoutes()
}, webhooksEnabled, func(ctx *context.Context) {
ctx.Data["IsRepositoryWebhook"] = true
})
}, webhooksEnabled)
m.Group("/keys", func() {
m.Combo("").Get(repo.DeployKeys).
@@ -1023,12 +921,6 @@ func RegisterRoutes(m *web.Route) {
m.Post("/delete", repo.DeleteDeployKey)
})
m.Group("/secrets", func() {
m.Get("", repo.Secrets)
m.Post("", web.Bind(forms.AddSecretForm{}), repo.SecretsPost)
m.Post("/delete", repo.DeleteSecret)
})
m.Group("/lfs", func() {
m.Get("/", repo.LFSFiles)
m.Get("/show/{oid}", repo.LFSFileGet)
@@ -1042,18 +934,12 @@ func RegisterRoutes(m *web.Route) {
m.Post("/{lid}/unlock", repo.LFSUnlock)
})
})
m.Group("/runners", func() {
m.Get("", repo.Runners)
m.Combo("/{runnerid}").Get(repo.RunnersEdit).
Post(web.Bind(forms.EditRunnerForm{}), repo.RunnersEditPost)
m.Post("/{runnerid}/delete", repo.RunnerDeletePost)
m.Get("/reset_registration_token", repo.ResetRunnerRegistrationToken)
m.Group("/actions", func() {
m.Get("", repo_setting.RedirectToDefaultSetting)
addSettingsRunnersRoutes()
addSettingsSecretsRoutes()
}, actions.MustEnableActions)
}, func(ctx *context.Context) {
ctx.Data["PageIsSettings"] = true
ctx.Data["LFSStartServer"] = setting.LFS.StartServer
})
}, ctxDataSet("PageIsRepoSettings", true, "LFSStartServer", setting.LFS.StartServer))
}, reqSignIn, context.RepoAssignment, context.UnitTypes(), reqRepoAdmin, context.RepoRef())
m.Post("/{username}/{reponame}/action/{action}", reqSignIn, context.RepoAssignment, context.UnitTypes(), repo.Action)
@@ -1204,12 +1090,11 @@ func RegisterRoutes(m *web.Route) {
m.Get("", repo.TagsList)
m.Get(".rss", feedEnabled, repo.TagsListFeedRSS)
m.Get(".atom", feedEnabled, repo.TagsListFeedAtom)
}, func(ctx *context.Context) {
ctx.Data["EnableFeed"] = setting.Other.EnableFeed
}, repo.MustBeNotEmpty, reqRepoCodeReader, context.RepoRefByType(context.RepoRefTag, true))
}, ctxDataSet("EnableFeed", setting.Other.EnableFeed),
repo.MustBeNotEmpty, reqRepoCodeReader, context.RepoRefByType(context.RepoRefTag, true))
m.Post("/tags/delete", repo.DeleteTag, reqSignIn,
repo.MustBeNotEmpty, context.RepoMustNotBeArchived(), reqRepoCodeWriter, context.RepoRef())
}, reqSignIn, context.RepoAssignment, context.UnitTypes())
}, ignSignIn, context.RepoAssignment, context.UnitTypes())
// Releases
m.Group("/{username}/{reponame}", func() {
@@ -1219,9 +1104,8 @@ func RegisterRoutes(m *web.Route) {
m.Get("/latest", repo.LatestRelease)
m.Get(".rss", feedEnabled, repo.ReleasesFeedRSS)
m.Get(".atom", feedEnabled, repo.ReleasesFeedAtom)
}, func(ctx *context.Context) {
ctx.Data["EnableFeed"] = setting.Other.EnableFeed
}, repo.MustBeNotEmpty, reqRepoReleaseReader, context.RepoRefByType(context.RepoRefTag, true))
}, ctxDataSet("EnableFeed", setting.Other.EnableFeed),
repo.MustBeNotEmpty, reqRepoReleaseReader, context.RepoRefByType(context.RepoRefTag, true))
m.Get("/releases/attachments/{uuid}", repo.GetAttachment, repo.MustBeNotEmpty, reqRepoReleaseReader)
m.Group("/releases", func() {
m.Get("/new", repo.NewRelease)
@@ -1233,21 +1117,7 @@ func RegisterRoutes(m *web.Route) {
m.Group("/releases", func() {
m.Get("/edit/*", repo.EditRelease)
m.Post("/edit/*", web.Bind(forms.EditReleaseForm{}), repo.EditReleasePost)
}, reqSignIn, repo.MustBeNotEmpty, context.RepoMustNotBeArchived(), reqRepoReleaseWriter, func(ctx *context.Context) {
var err error
ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(ctx.Repo.Repository.DefaultBranch)
if err != nil {
ctx.ServerError("GetBranchCommit", err)
return
}
ctx.Repo.CommitsCount, err = ctx.Repo.GetCommitsCount()
if err != nil {
ctx.ServerError("GetCommitsCount", err)
return
}
ctx.Data["CommitsCount"] = ctx.Repo.CommitsCount
ctx.Repo.GitRepo.LastCommitCache = git.NewLastCommitCache(ctx.Repo.CommitsCount, ctx.Repo.Repository.FullName(), ctx.Repo.GitRepo, cache.GetCache())
})
}, reqSignIn, repo.MustBeNotEmpty, context.RepoMustNotBeArchived(), reqRepoReleaseWriter, repo.CommitInfoCache)
}, ignSignIn, context.RepoAssignment, context.UnitTypes(), reqRepoReleaseReader)
// to maintain compatibility with old attachments
@@ -1316,28 +1186,21 @@ func RegisterRoutes(m *web.Route) {
m.Combo("").
Get(actions.View).
Post(web.Bind(actions.ViewRequest{}), actions.ViewPost)
m.Post("/rerun", reqRepoActionsWriter, actions.Rerun)
m.Post("/rerun", reqRepoActionsWriter, actions.RerunOne)
})
m.Post("/cancel", reqRepoActionsWriter, actions.Cancel)
m.Post("/approve", reqRepoActionsWriter, actions.Approve)
m.Post("/rerun", reqRepoActionsWriter, actions.RerunAll)
})
}, reqRepoActionsReader, actions.MustEnableActions)
m.Group("/wiki", func() {
m.Combo("/").
Get(repo.Wiki).
Post(context.RepoMustNotBeArchived(),
reqSignIn,
reqRepoWikiWriter,
web.Bind(forms.NewWikiForm{}),
repo.WikiPost)
Post(context.RepoMustNotBeArchived(), reqSignIn, reqRepoWikiWriter, web.Bind(forms.NewWikiForm{}), repo.WikiPost)
m.Combo("/*").
Get(repo.Wiki).
Post(context.RepoMustNotBeArchived(),
reqSignIn,
reqRepoWikiWriter,
web.Bind(forms.NewWikiForm{}),
repo.WikiPost)
Post(context.RepoMustNotBeArchived(), reqSignIn, reqRepoWikiWriter, web.Bind(forms.NewWikiForm{}), repo.WikiPost)
m.Get("/commit/{sha:[a-f0-9]{7,40}}", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.Diff)
m.Get("/commit/{sha:[a-f0-9]{7,40}}.{ext:patch|diff}", repo.RawDiff)
}, repo.MustEnableWiki, func(ctx *context.Context) {
@@ -1468,8 +1331,7 @@ func RegisterRoutes(m *web.Route) {
m.Group("", func() {
m.Get("/forks", repo.Forks)
}, context.RepoRef(), reqRepoCodeReader)
m.Get("/commit/{sha:([a-f0-9]{7,40})}.{ext:patch|diff}",
repo.MustBeNotEmpty, reqRepoCodeReader, repo.RawDiff)
m.Get("/commit/{sha:([a-f0-9]{7,40})}.{ext:patch|diff}", repo.MustBeNotEmpty, reqRepoCodeReader, repo.RawDiff)
}, ignSignIn, context.RepoAssignment, context.UnitTypes())
m.Post("/{username}/{reponame}/lastcommit/*", ignSignInAndCsrf, context.RepoAssignment, context.UnitTypes(), context.RepoRefByType(context.RepoRefCommit), reqRepoCodeReader, repo.LastCommit)