Browse Source

[refactor] replace int with httpStatusCodes (#15282)

* replace "200" (int) with "http.StatusOK" (const)

* ctx.Error & ctx.HTML

* ctx.JSON Part1

* ctx.JSON Part2

* ctx.JSON Part3
tags/v1.15.0-rc1
6543 3 years ago
parent
commit
16dea6cebd
No account linked to committer's email address
64 changed files with 504 additions and 441 deletions
  1. 4
    4
      modules/context/api.go
  2. 13
    11
      modules/context/auth.go
  3. 1
    1
      modules/context/context.go
  4. 24
    23
      modules/lfs/locks.go
  5. 7
    6
      routers/admin/admin.go
  6. 11
    10
      routers/admin/auths.go
  7. 3
    2
      routers/admin/emails.go
  8. 4
    2
      routers/admin/hooks.go
  9. 2
    1
      routers/admin/notice.go
  10. 4
    3
      routers/admin/repos.go
  11. 8
    7
      routers/admin/users.go
  12. 1
    1
      routers/api/v1/api.go
  13. 3
    1
      routers/dev/template.go
  14. 7
    6
      routers/home.go
  15. 3
    3
      routers/install.go
  16. 3
    2
      routers/org/home.go
  17. 9
    7
      routers/org/members.go
  18. 3
    2
      routers/org/org.go
  19. 4
    2
      routers/org/org_labels.go
  20. 7
    6
      routers/org/setting.go
  21. 14
    14
      routers/org/teams.go
  22. 1
    1
      routers/private/hook.go
  23. 3
    2
      routers/repo/activity.go
  24. 10
    10
      routers/repo/attachment.go
  25. 2
    1
      routers/repo/blame.go
  26. 3
    2
      routers/repo/branch.go
  27. 7
    6
      routers/repo/commit.go
  28. 6
    5
      routers/repo/compare.go
  29. 25
    24
      routers/repo/editor.go
  30. 33
    33
      routers/repo/issue.go
  31. 8
    6
      routers/repo/issue_label.go
  32. 1
    1
      routers/repo/issue_watch.go
  33. 7
    6
      routers/repo/lfs.go
  34. 3
    3
      routers/repo/migrate.go
  35. 8
    7
      routers/repo/milestone.go
  36. 27
    26
      routers/repo/projects.go
  37. 11
    11
      routers/repo/pull.go
  38. 7
    6
      routers/repo/pull_review.go
  39. 9
    8
      routers/repo/release.go
  40. 13
    12
      routers/repo/repo.go
  41. 2
    1
      routers/repo/search.go
  42. 22
    21
      routers/repo/setting.go
  43. 4
    3
      routers/repo/setting_protected_branch.go
  44. 6
    5
      routers/repo/topic.go
  45. 6
    5
      routers/repo/view.go
  46. 23
    22
      routers/repo/webhook.go
  47. 13
    12
      routers/repo/wiki.go
  48. 4
    4
      routers/routes/web.go
  49. 3
    1
      routers/swagger_json.go
  50. 34
    34
      routers/user/auth.go
  51. 6
    5
      routers/user/auth_openid.go
  52. 4
    3
      routers/user/home.go
  53. 6
    5
      routers/user/oauth.go
  54. 3
    2
      routers/user/profile.go
  55. 5
    4
      routers/user/setting/account.go
  56. 5
    3
      routers/user/setting/applications.go
  57. 5
    3
      routers/user/setting/keys.go
  58. 9
    8
      routers/user/setting/oauth2.go
  59. 5
    4
      routers/user/setting/profile.go
  60. 4
    2
      routers/user/setting/security.go
  61. 4
    2
      routers/user/setting/security_openid.go
  62. 3
    2
      routers/user/setting/security_twofa.go
  63. 5
    4
      routers/user/setting/security_u2f.go
  64. 4
    2
      routers/user/task.go

+ 4
- 4
modules/context/api.go View File

if models.IsErrTwoFactorNotEnrolled(err) { if models.IsErrTwoFactorNotEnrolled(err) {
return // No 2FA enrollment for this user return // No 2FA enrollment for this user
} }
ctx.Context.Error(500)
ctx.Context.Error(http.StatusInternalServerError)
return return
} }
ok, err := twofa.ValidateTOTP(otpHeader) ok, err := twofa.ValidateTOTP(otpHeader)
if err != nil { if err != nil {
ctx.Context.Error(500)
ctx.Context.Error(http.StatusInternalServerError)
return return
} }
if !ok { if !ok {
repoPath := models.RepoPath(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name) repoPath := models.RepoPath(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
gitRepo, err := git.OpenRepository(repoPath) gitRepo, err := git.OpenRepository(repoPath)
if err != nil { if err != nil {
ctx.Error(500, "RepoRef Invalid repo "+repoPath, err)
ctx.Error(http.StatusInternalServerError, "RepoRef Invalid repo "+repoPath, err)
return return
} }
ctx.Repo.GitRepo = gitRepo ctx.Repo.GitRepo = gitRepo
} }
} }


ctx.JSON(404, map[string]interface{}{
ctx.JSON(http.StatusNotFound, map[string]interface{}{
"message": message, "message": message,
"documentation_url": setting.API.SwaggerURL, "documentation_url": setting.API.SwaggerURL,
"errors": errors, "errors": errors,

+ 13
- 11
modules/context/auth.go View File

package context package context


import ( import (
"net/http"

"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
if ctx.IsSigned { if ctx.IsSigned {
if !ctx.User.IsActive && setting.Service.RegisterEmailConfirm { if !ctx.User.IsActive && setting.Service.RegisterEmailConfirm {
ctx.Data["Title"] = ctx.Tr("auth.active_your_account") ctx.Data["Title"] = ctx.Tr("auth.active_your_account")
ctx.HTML(200, "user/auth/activate")
ctx.HTML(http.StatusOK, "user/auth/activate")
return return
} }
if !ctx.User.IsActive || ctx.User.ProhibitLogin { if !ctx.User.IsActive || ctx.User.ProhibitLogin {
log.Info("Failed authentication attempt for %s from %s", ctx.User.Name, ctx.RemoteAddr()) log.Info("Failed authentication attempt for %s from %s", ctx.User.Name, ctx.RemoteAddr())
ctx.Data["Title"] = ctx.Tr("auth.prohibit_login") ctx.Data["Title"] = ctx.Tr("auth.prohibit_login")
ctx.HTML(200, "user/auth/prohibit_login")
ctx.HTML(http.StatusOK, "user/auth/prohibit_login")
return return
} }


return return
} else if !ctx.User.IsActive && setting.Service.RegisterEmailConfirm { } else if !ctx.User.IsActive && setting.Service.RegisterEmailConfirm {
ctx.Data["Title"] = ctx.Tr("auth.active_your_account") ctx.Data["Title"] = ctx.Tr("auth.active_your_account")
ctx.HTML(200, "user/auth/activate")
ctx.HTML(http.StatusOK, "user/auth/activate")
return return
} }
} }


if options.AdminRequired { if options.AdminRequired {
if !ctx.User.IsAdmin { if !ctx.User.IsAdmin {
ctx.Error(403)
ctx.Error(http.StatusForbidden)
return return
} }
ctx.Data["PageIsAdmin"] = true ctx.Data["PageIsAdmin"] = true
if ctx.IsSigned { if ctx.IsSigned {
if !ctx.User.IsActive && setting.Service.RegisterEmailConfirm { if !ctx.User.IsActive && setting.Service.RegisterEmailConfirm {
ctx.Data["Title"] = ctx.Tr("auth.active_your_account") ctx.Data["Title"] = ctx.Tr("auth.active_your_account")
ctx.JSON(403, map[string]string{
ctx.JSON(http.StatusForbidden, map[string]string{
"message": "This account is not activated.", "message": "This account is not activated.",
}) })
return return
if !ctx.User.IsActive || ctx.User.ProhibitLogin { if !ctx.User.IsActive || ctx.User.ProhibitLogin {
log.Info("Failed authentication attempt for %s from %s", ctx.User.Name, ctx.RemoteAddr()) log.Info("Failed authentication attempt for %s from %s", ctx.User.Name, ctx.RemoteAddr())
ctx.Data["Title"] = ctx.Tr("auth.prohibit_login") ctx.Data["Title"] = ctx.Tr("auth.prohibit_login")
ctx.JSON(403, map[string]string{
ctx.JSON(http.StatusForbidden, map[string]string{
"message": "This account is prohibited from signing in, please contact your site administrator.", "message": "This account is prohibited from signing in, please contact your site administrator.",
}) })
return return
} }


if ctx.User.MustChangePassword { if ctx.User.MustChangePassword {
ctx.JSON(403, map[string]string{
ctx.JSON(http.StatusForbidden, map[string]string{
"message": "You must change your password. Change it at: " + setting.AppURL + "/user/change_password", "message": "You must change your password. Change it at: " + setting.AppURL + "/user/change_password",
}) })
return return
if options.SignInRequired { if options.SignInRequired {
if !ctx.IsSigned { if !ctx.IsSigned {
// Restrict API calls with error message. // Restrict API calls with error message.
ctx.JSON(403, map[string]string{
ctx.JSON(http.StatusForbidden, map[string]string{
"message": "Only signed in user is allowed to call APIs.", "message": "Only signed in user is allowed to call APIs.",
}) })
return return
} else if !ctx.User.IsActive && setting.Service.RegisterEmailConfirm { } else if !ctx.User.IsActive && setting.Service.RegisterEmailConfirm {
ctx.Data["Title"] = ctx.Tr("auth.active_your_account") ctx.Data["Title"] = ctx.Tr("auth.active_your_account")
ctx.HTML(200, "user/auth/activate")
ctx.HTML(http.StatusOK, "user/auth/activate")
return return
} }
if ctx.IsSigned && ctx.IsBasicAuth { if ctx.IsSigned && ctx.IsBasicAuth {
return return
} }
if !ok { if !ok {
ctx.JSON(403, map[string]string{
ctx.JSON(http.StatusForbidden, map[string]string{
"message": "Only signed in user is allowed to call APIs.", "message": "Only signed in user is allowed to call APIs.",
}) })
return return


if options.AdminRequired { if options.AdminRequired {
if !ctx.User.IsAdmin { if !ctx.User.IsAdmin {
ctx.JSON(403, map[string]string{
ctx.JSON(http.StatusForbidden, map[string]string{
"message": "You have no permission to request for this.", "message": "You have no permission to request for this.",
}) })
return return

+ 1
- 1
modules/context/context.go View File

} }
ctx.Flash.ErrorMsg = msg ctx.Flash.ErrorMsg = msg
ctx.Data["Flash"] = ctx.Flash ctx.Data["Flash"] = ctx.Flash
ctx.HTML(200, tpl)
ctx.HTML(http.StatusOK, tpl)
} }


// NotFound displays a 404 (Not Found) page and prints the given error, if any. // NotFound displays a 404 (Not Found) page and prints the given error, if any.

+ 24
- 23
modules/lfs/locks.go View File

package lfs package lfs


import ( import (
"net/http"
"strconv" "strconv"
"strings" "strings"


func checkIsValidRequest(ctx *context.Context) bool { func checkIsValidRequest(ctx *context.Context) bool {
if !setting.LFS.StartServer { if !setting.LFS.StartServer {
log.Debug("Attempt to access LFS server but LFS server is disabled") log.Debug("Attempt to access LFS server but LFS server is disabled")
writeStatus(ctx, 404)
writeStatus(ctx, http.StatusNotFound)
return false return false
} }
if !MetaMatcher(ctx.Req) { if !MetaMatcher(ctx.Req) {
log.Info("Attempt access LOCKs without accepting the correct media type: %s", metaMediaType) log.Info("Attempt access LOCKs without accepting the correct media type: %s", metaMediaType)
writeStatus(ctx, 400)
writeStatus(ctx, http.StatusBadRequest)
return false return false
} }
if !ctx.IsSigned { if !ctx.IsSigned {
user, _, _, err := parseToken(ctx.Req.Header.Get("Authorization")) user, _, _, err := parseToken(ctx.Req.Header.Get("Authorization"))
if err != nil { if err != nil {
ctx.Resp.Header().Set("WWW-Authenticate", "Basic realm=gitea-lfs") ctx.Resp.Header().Set("WWW-Authenticate", "Basic realm=gitea-lfs")
writeStatus(ctx, 401)
writeStatus(ctx, http.StatusUnauthorized)
return false return false
} }
ctx.User = user ctx.User = user
func handleLockListOut(ctx *context.Context, repo *models.Repository, lock *models.LFSLock, err error) { func handleLockListOut(ctx *context.Context, repo *models.Repository, lock *models.LFSLock, err error) {
if err != nil { if err != nil {
if models.IsErrLFSLockNotExist(err) { if models.IsErrLFSLockNotExist(err) {
ctx.JSON(200, api.LFSLockList{
ctx.JSON(http.StatusOK, api.LFSLockList{
Locks: []*api.LFSLock{}, Locks: []*api.LFSLock{},
}) })
return return
} }
ctx.JSON(500, api.LFSLockError{
ctx.JSON(http.StatusInternalServerError, api.LFSLockError{
Message: "unable to list locks : Internal Server Error", Message: "unable to list locks : Internal Server Error",
}) })
return return
} }
if repo.ID != lock.RepoID { if repo.ID != lock.RepoID {
ctx.JSON(200, api.LFSLockList{
ctx.JSON(http.StatusOK, api.LFSLockList{
Locks: []*api.LFSLock{}, Locks: []*api.LFSLock{},
}) })
return return
} }
ctx.JSON(200, api.LFSLockList{
ctx.JSON(http.StatusOK, api.LFSLockList{
Locks: []*api.LFSLock{convert.ToLFSLock(lock)}, Locks: []*api.LFSLock{convert.ToLFSLock(lock)},
}) })
} }
authenticated := authenticate(ctx, repository, rv.Authorization, false) authenticated := authenticate(ctx, repository, rv.Authorization, false)
if !authenticated { if !authenticated {
ctx.Resp.Header().Set("WWW-Authenticate", "Basic realm=gitea-lfs") ctx.Resp.Header().Set("WWW-Authenticate", "Basic realm=gitea-lfs")
ctx.JSON(401, api.LFSLockError{
ctx.JSON(http.StatusUnauthorized, api.LFSLockError{
Message: "You must have pull access to list locks", Message: "You must have pull access to list locks",
}) })
return return
if id != "" { //Case where we request a specific id if id != "" { //Case where we request a specific id
v, err := strconv.ParseInt(id, 10, 64) v, err := strconv.ParseInt(id, 10, 64)
if err != nil { if err != nil {
ctx.JSON(400, api.LFSLockError{
ctx.JSON(http.StatusBadRequest, api.LFSLockError{
Message: "bad request : " + err.Error(), Message: "bad request : " + err.Error(),
}) })
return return
lockList, err := models.GetLFSLockByRepoID(repository.ID, cursor, limit) lockList, err := models.GetLFSLockByRepoID(repository.ID, cursor, limit)
if err != nil { if err != nil {
log.Error("Unable to list locks for repository ID[%d]: Error: %v", repository.ID, err) log.Error("Unable to list locks for repository ID[%d]: Error: %v", repository.ID, err)
ctx.JSON(500, api.LFSLockError{
ctx.JSON(http.StatusInternalServerError, api.LFSLockError{
Message: "unable to list locks : Internal Server Error", Message: "unable to list locks : Internal Server Error",
}) })
return return
if limit > 0 && len(lockList) == limit { if limit > 0 && len(lockList) == limit {
next = strconv.Itoa(cursor + 1) next = strconv.Itoa(cursor + 1)
} }
ctx.JSON(200, api.LFSLockList{
ctx.JSON(http.StatusOK, api.LFSLockList{
Locks: lockListAPI, Locks: lockListAPI,
Next: next, Next: next,
}) })
authenticated := authenticate(ctx, repository, authorization, true) authenticated := authenticate(ctx, repository, authorization, true)
if !authenticated { if !authenticated {
ctx.Resp.Header().Set("WWW-Authenticate", "Basic realm=gitea-lfs") ctx.Resp.Header().Set("WWW-Authenticate", "Basic realm=gitea-lfs")
ctx.JSON(401, api.LFSLockError{
ctx.JSON(http.StatusUnauthorized, api.LFSLockError{
Message: "You must have push access to create locks", Message: "You must have push access to create locks",
}) })
return return
}) })
if err != nil { if err != nil {
if models.IsErrLFSLockAlreadyExist(err) { if models.IsErrLFSLockAlreadyExist(err) {
ctx.JSON(409, api.LFSLockError{
ctx.JSON(http.StatusConflict, api.LFSLockError{
Lock: convert.ToLFSLock(lock), Lock: convert.ToLFSLock(lock),
Message: "already created lock", Message: "already created lock",
}) })
} }
if models.IsErrLFSUnauthorizedAction(err) { if models.IsErrLFSUnauthorizedAction(err) {
ctx.Resp.Header().Set("WWW-Authenticate", "Basic realm=gitea-lfs") ctx.Resp.Header().Set("WWW-Authenticate", "Basic realm=gitea-lfs")
ctx.JSON(401, api.LFSLockError{
ctx.JSON(http.StatusUnauthorized, api.LFSLockError{
Message: "You must have push access to create locks : " + err.Error(), Message: "You must have push access to create locks : " + err.Error(),
}) })
return return
} }
log.Error("Unable to CreateLFSLock in repository %-v at %s for user %-v: Error: %v", repository, req.Path, ctx.User, err) log.Error("Unable to CreateLFSLock in repository %-v at %s for user %-v: Error: %v", repository, req.Path, ctx.User, err)
ctx.JSON(500, api.LFSLockError{
ctx.JSON(http.StatusInternalServerError, api.LFSLockError{
Message: "internal server error : Internal Server Error", Message: "internal server error : Internal Server Error",
}) })
return return
} }
ctx.JSON(201, api.LFSLockResponse{Lock: convert.ToLFSLock(lock)})
ctx.JSON(http.StatusCreated, api.LFSLockResponse{Lock: convert.ToLFSLock(lock)})
} }


// VerifyLockHandler list locks for verification // VerifyLockHandler list locks for verification
authenticated := authenticate(ctx, repository, authorization, true) authenticated := authenticate(ctx, repository, authorization, true)
if !authenticated { if !authenticated {
ctx.Resp.Header().Set("WWW-Authenticate", "Basic realm=gitea-lfs") ctx.Resp.Header().Set("WWW-Authenticate", "Basic realm=gitea-lfs")
ctx.JSON(401, api.LFSLockError{
ctx.JSON(http.StatusUnauthorized, api.LFSLockError{
Message: "You must have push access to verify locks", Message: "You must have push access to verify locks",
}) })
return return
lockList, err := models.GetLFSLockByRepoID(repository.ID, cursor, limit) lockList, err := models.GetLFSLockByRepoID(repository.ID, cursor, limit)
if err != nil { if err != nil {
log.Error("Unable to list locks for repository ID[%d]: Error: %v", repository.ID, err) log.Error("Unable to list locks for repository ID[%d]: Error: %v", repository.ID, err)
ctx.JSON(500, api.LFSLockError{
ctx.JSON(http.StatusInternalServerError, api.LFSLockError{
Message: "unable to list locks : Internal Server Error", Message: "unable to list locks : Internal Server Error",
}) })
return return
lockTheirsListAPI = append(lockTheirsListAPI, convert.ToLFSLock(l)) lockTheirsListAPI = append(lockTheirsListAPI, convert.ToLFSLock(l))
} }
} }
ctx.JSON(200, api.LFSLockListVerify{
ctx.JSON(http.StatusOK, api.LFSLockListVerify{
Ours: lockOursListAPI, Ours: lockOursListAPI,
Theirs: lockTheirsListAPI, Theirs: lockTheirsListAPI,
Next: next, Next: next,
authenticated := authenticate(ctx, repository, authorization, true) authenticated := authenticate(ctx, repository, authorization, true)
if !authenticated { if !authenticated {
ctx.Resp.Header().Set("WWW-Authenticate", "Basic realm=gitea-lfs") ctx.Resp.Header().Set("WWW-Authenticate", "Basic realm=gitea-lfs")
ctx.JSON(401, api.LFSLockError{
ctx.JSON(http.StatusUnauthorized, api.LFSLockError{
Message: "You must have push access to delete locks", Message: "You must have push access to delete locks",
}) })
return return
if err != nil { if err != nil {
if models.IsErrLFSUnauthorizedAction(err) { if models.IsErrLFSUnauthorizedAction(err) {
ctx.Resp.Header().Set("WWW-Authenticate", "Basic realm=gitea-lfs") ctx.Resp.Header().Set("WWW-Authenticate", "Basic realm=gitea-lfs")
ctx.JSON(401, api.LFSLockError{
ctx.JSON(http.StatusUnauthorized, api.LFSLockError{
Message: "You must have push access to delete locks : " + err.Error(), Message: "You must have push access to delete locks : " + err.Error(),
}) })
return return
} }
log.Error("Unable to DeleteLFSLockByID[%d] by user %-v with force %t: Error: %v", ctx.ParamsInt64("lid"), ctx.User, req.Force, err) log.Error("Unable to DeleteLFSLockByID[%d] by user %-v with force %t: Error: %v", ctx.ParamsInt64("lid"), ctx.User, req.Force, err)
ctx.JSON(500, api.LFSLockError{
ctx.JSON(http.StatusInternalServerError, api.LFSLockError{
Message: "unable to delete lock : Internal Server Error", Message: "unable to delete lock : Internal Server Error",
}) })
return return
} }
ctx.JSON(200, api.LFSLockResponse{Lock: convert.ToLFSLock(lock)})
ctx.JSON(http.StatusOK, api.LFSLockResponse{Lock: convert.ToLFSLock(lock)})
} }

+ 7
- 6
routers/admin/admin.go View File



import ( import (
"fmt" "fmt"
"net/http"
"net/url" "net/url"
"os" "os"
"runtime" "runtime"
updateSystemStatus() updateSystemStatus()
ctx.Data["SysStatus"] = sysStatus ctx.Data["SysStatus"] = sysStatus
ctx.Data["SSH"] = setting.SSH ctx.Data["SSH"] = setting.SSH
ctx.HTML(200, tplDashboard)
ctx.HTML(http.StatusOK, tplDashboard)
} }


// DashboardPost run an admin operation // DashboardPost run an admin operation
ctx.Data["EnableXORMLog"] = setting.EnableXORMLog ctx.Data["EnableXORMLog"] = setting.EnableXORMLog
ctx.Data["LogSQL"] = setting.Database.LogSQL ctx.Data["LogSQL"] = setting.Database.LogSQL


ctx.HTML(200, tplConfig)
ctx.HTML(http.StatusOK, tplConfig)
} }


// Monitor show admin monitor page // Monitor show admin monitor page
ctx.Data["Processes"] = process.GetManager().Processes() ctx.Data["Processes"] = process.GetManager().Processes()
ctx.Data["Entries"] = cron.ListTasks() ctx.Data["Entries"] = cron.ListTasks()
ctx.Data["Queues"] = queue.GetManager().ManagedQueues() ctx.Data["Queues"] = queue.GetManager().ManagedQueues()
ctx.HTML(200, tplMonitor)
ctx.HTML(http.StatusOK, tplMonitor)
} }


// MonitorCancel cancels a process // MonitorCancel cancels a process
func MonitorCancel(ctx *context.Context) { func MonitorCancel(ctx *context.Context) {
pid := ctx.ParamsInt64("pid") pid := ctx.ParamsInt64("pid")
process.GetManager().Cancel(pid) process.GetManager().Cancel(pid)
ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"redirect": setting.AppSubURL + "/admin/monitor", "redirect": setting.AppSubURL + "/admin/monitor",
}) })
} }
ctx.Data["PageIsAdmin"] = true ctx.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminMonitor"] = true ctx.Data["PageIsAdminMonitor"] = true
ctx.Data["Queue"] = mq ctx.Data["Queue"] = mq
ctx.HTML(200, tplQueue)
ctx.HTML(http.StatusOK, tplQueue)
} }


// WorkerCancel cancels a worker group // WorkerCancel cancels a worker group
pid := ctx.ParamsInt64("pid") pid := ctx.ParamsInt64("pid")
mq.CancelWorkers(pid) mq.CancelWorkers(pid)
ctx.Flash.Info(ctx.Tr("admin.monitor.queue.pool.cancelling")) ctx.Flash.Info(ctx.Tr("admin.monitor.queue.pool.cancelling"))
ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"redirect": setting.AppSubURL + "/admin/monitor/queue/" + strconv.FormatInt(qid, 10), "redirect": setting.AppSubURL + "/admin/monitor/queue/" + strconv.FormatInt(qid, 10),
}) })
} }

+ 11
- 10
routers/admin/auths.go View File

import ( import (
"errors" "errors"
"fmt" "fmt"
"net/http"
"regexp" "regexp"


"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
} }


ctx.Data["Total"] = models.CountLoginSources() ctx.Data["Total"] = models.CountLoginSources()
ctx.HTML(200, tplAuths)
ctx.HTML(http.StatusOK, tplAuths)
} }


type dropdownItem struct { type dropdownItem struct {
break break
} }


ctx.HTML(200, tplAuthNew)
ctx.HTML(http.StatusOK, tplAuthNew)
} }


func parseLDAPConfig(form auth.AuthenticationForm) *models.LDAPConfig { func parseLDAPConfig(form auth.AuthenticationForm) *models.LDAPConfig {
return return
} }
default: default:
ctx.Error(400)
ctx.Error(http.StatusBadRequest)
return return
} }
ctx.Data["HasTLS"] = hasTLS ctx.Data["HasTLS"] = hasTLS


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, tplAuthNew)
ctx.HTML(http.StatusOK, tplAuthNew)
return return
} }


if source.IsOAuth2() { if source.IsOAuth2() {
ctx.Data["CurrentOAuth2Provider"] = models.OAuth2Providers[source.OAuth2().Provider] ctx.Data["CurrentOAuth2Provider"] = models.OAuth2Providers[source.OAuth2().Provider]
} }
ctx.HTML(200, tplAuthEdit)
ctx.HTML(http.StatusOK, tplAuthEdit)
} }


// EditAuthSourcePost response for editing auth source // EditAuthSourcePost response for editing auth source
ctx.Data["HasTLS"] = source.HasTLS() ctx.Data["HasTLS"] = source.HasTLS()


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, tplAuthEdit)
ctx.HTML(http.StatusOK, tplAuthEdit)
return return
} }


return return
} }
default: default:
ctx.Error(400)
ctx.Error(http.StatusBadRequest)
return return
} }


if err := models.UpdateSource(source); err != nil { if err := models.UpdateSource(source); err != nil {
if models.IsErrOpenIDConnectInitialize(err) { if models.IsErrOpenIDConnectInitialize(err) {
ctx.Flash.Error(err.Error(), true) ctx.Flash.Error(err.Error(), true)
ctx.HTML(200, tplAuthEdit)
ctx.HTML(http.StatusOK, tplAuthEdit)
} else { } else {
ctx.ServerError("UpdateSource", err) ctx.ServerError("UpdateSource", err)
} }
} else { } else {
ctx.Flash.Error(fmt.Sprintf("DeleteSource: %v", err)) ctx.Flash.Error(fmt.Sprintf("DeleteSource: %v", err))
} }
ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"redirect": setting.AppSubURL + "/admin/auths/" + ctx.Params(":authid"), "redirect": setting.AppSubURL + "/admin/auths/" + ctx.Params(":authid"),
}) })
return return
log.Trace("Authentication deleted by admin(%s): %d", ctx.User.Name, source.ID) log.Trace("Authentication deleted by admin(%s): %d", ctx.User.Name, source.ID)


ctx.Flash.Success(ctx.Tr("admin.auths.deletion_success")) ctx.Flash.Success(ctx.Tr("admin.auths.deletion_success"))
ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"redirect": setting.AppSubURL + "/admin/auths", "redirect": setting.AppSubURL + "/admin/auths",
}) })
} }

+ 3
- 2
routers/admin/emails.go View File



import ( import (
"bytes" "bytes"
"net/http"
"net/url" "net/url"


"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
pager.SetDefaultParams(ctx) pager.SetDefaultParams(ctx)
ctx.Data["Page"] = pager ctx.Data["Page"] = pager


ctx.HTML(200, tplEmails)
ctx.HTML(http.StatusOK, tplEmails)
} }


var ( var (
activate, oka := truefalse[ctx.Query("activate")] activate, oka := truefalse[ctx.Query("activate")]


if uid == 0 || len(email) == 0 || !okp || !oka { if uid == 0 || len(email) == 0 || !okp || !oka {
ctx.Error(400)
ctx.Error(http.StatusBadRequest)
return return
} }



+ 4
- 2
routers/admin/hooks.go View File

package admin package admin


import ( import (
"net/http"

"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/context"
ctx.Data["DefaultWebhooks"] = def ctx.Data["DefaultWebhooks"] = def
ctx.Data["SystemWebhooks"] = sys ctx.Data["SystemWebhooks"] = sys


ctx.HTML(200, tplAdminHooks)
ctx.HTML(http.StatusOK, tplAdminHooks)
} }


// DeleteDefaultOrSystemWebhook handler to delete an admin-defined system or default webhook // DeleteDefaultOrSystemWebhook handler to delete an admin-defined system or default webhook
ctx.Flash.Success(ctx.Tr("repo.settings.webhook_deletion_success")) ctx.Flash.Success(ctx.Tr("repo.settings.webhook_deletion_success"))
} }


ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"redirect": setting.AppSubURL + "/admin/hooks", "redirect": setting.AppSubURL + "/admin/hooks",
}) })
} }

+ 2
- 1
routers/admin/notice.go View File

package admin package admin


import ( import (
"net/http"
"strconv" "strconv"


"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"


ctx.Data["Page"] = context.NewPagination(int(total), setting.UI.Admin.NoticePagingNum, page, 5) ctx.Data["Page"] = context.NewPagination(int(total), setting.UI.Admin.NoticePagingNum, page, 5)


ctx.HTML(200, tplNotices)
ctx.HTML(http.StatusOK, tplNotices)
} }


// DeleteNotices delete the specific notices // DeleteNotices delete the specific notices

+ 4
- 3
routers/admin/repos.go View File

package admin package admin


import ( import (
"net/http"
"net/url" "net/url"
"strconv" "strconv"
"strings" "strings"
log.Trace("Repository deleted: %s", repo.FullName()) log.Trace("Repository deleted: %s", repo.FullName())


ctx.Flash.Success(ctx.Tr("repo.settings.deletion_success")) ctx.Flash.Success(ctx.Tr("repo.settings.deletion_success"))
ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"redirect": setting.AppSubURL + "/admin/repos?page=" + ctx.Query("page") + "&sort=" + ctx.Query("sort"), "redirect": setting.AppSubURL + "/admin/repos?page=" + ctx.Query("page") + "&sort=" + ctx.Query("sort"),
}) })
} }
pager.SetDefaultParams(ctx) pager.SetDefaultParams(ctx)
pager.AddParam(ctx, "search", "search") pager.AddParam(ctx, "search", "search")
ctx.Data["Page"] = pager ctx.Data["Page"] = pager
ctx.HTML(200, tplUnadoptedRepos)
ctx.HTML(http.StatusOK, tplUnadoptedRepos)
return return
} }


pager.SetDefaultParams(ctx) pager.SetDefaultParams(ctx)
pager.AddParam(ctx, "search", "search") pager.AddParam(ctx, "search", "search")
ctx.Data["Page"] = pager ctx.Data["Page"] = pager
ctx.HTML(200, tplUnadoptedRepos)
ctx.HTML(http.StatusOK, tplUnadoptedRepos)
} }


// AdoptOrDeleteRepository adopts or deletes a repository // AdoptOrDeleteRepository adopts or deletes a repository

+ 8
- 7
routers/admin/users.go View File



import ( import (
"fmt" "fmt"
"net/http"
"strconv" "strconv"
"strings" "strings"


ctx.Data["Sources"] = sources ctx.Data["Sources"] = sources


ctx.Data["CanSendEmail"] = setting.MailService != nil ctx.Data["CanSendEmail"] = setting.MailService != nil
ctx.HTML(200, tplUserNew)
ctx.HTML(http.StatusOK, tplUserNew)
} }


// NewUserPost response for adding a new user // NewUserPost response for adding a new user
ctx.Data["CanSendEmail"] = setting.MailService != nil ctx.Data["CanSendEmail"] = setting.MailService != nil


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, tplUserNew)
ctx.HTML(http.StatusOK, tplUserNew)
return return
} }


return return
} }


ctx.HTML(200, tplUserEdit)
ctx.HTML(http.StatusOK, tplUserEdit)
} }


// EditUserPost response for editting user // EditUserPost response for editting user
} }


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, tplUserEdit)
ctx.HTML(http.StatusOK, tplUserEdit)
return return
} }


switch { switch {
case models.IsErrUserOwnRepos(err): case models.IsErrUserOwnRepos(err):
ctx.Flash.Error(ctx.Tr("admin.users.still_own_repo")) ctx.Flash.Error(ctx.Tr("admin.users.still_own_repo"))
ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"redirect": setting.AppSubURL + "/admin/users/" + ctx.Params(":userid"), "redirect": setting.AppSubURL + "/admin/users/" + ctx.Params(":userid"),
}) })
case models.IsErrUserHasOrgs(err): case models.IsErrUserHasOrgs(err):
ctx.Flash.Error(ctx.Tr("admin.users.still_has_org")) ctx.Flash.Error(ctx.Tr("admin.users.still_has_org"))
ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"redirect": setting.AppSubURL + "/admin/users/" + ctx.Params(":userid"), "redirect": setting.AppSubURL + "/admin/users/" + ctx.Params(":userid"),
}) })
default: default:
log.Trace("Account deleted by admin (%s): %s", ctx.User.Name, u.Name) log.Trace("Account deleted by admin (%s): %s", ctx.User.Name, u.Name)


ctx.Flash.Success(ctx.Tr("admin.users.deletion_success")) ctx.Flash.Success(ctx.Tr("admin.users.deletion_success"))
ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"redirect": setting.AppSubURL + "/admin/users", "redirect": setting.AppSubURL + "/admin/users",
}) })
} }

+ 1
- 1
routers/api/v1/api.go View File

var theObj = reflect.New(tp).Interface() // create a new form obj for every request but not use obj directly var theObj = reflect.New(tp).Interface() // create a new form obj for every request but not use obj directly
errs := binding.Bind(ctx.Req, theObj) errs := binding.Bind(ctx.Req, theObj)
if len(errs) > 0 { if len(errs) > 0 {
ctx.Error(422, "validationError", errs[0].Error())
ctx.Error(http.StatusUnprocessableEntity, "validationError", errs[0].Error())
return return
} }
web.SetForm(ctx, theObj) web.SetForm(ctx, theObj)

+ 3
- 1
routers/dev/template.go View File

package dev package dev


import ( import (
"net/http"

"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/context"
ctx.Data["ResetPwdCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ResetPwdCodeLives, ctx.Locale.Language()) ctx.Data["ResetPwdCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ResetPwdCodeLives, ctx.Locale.Language())
ctx.Data["CurDbValue"] = "" ctx.Data["CurDbValue"] = ""


ctx.HTML(200, base.TplName(ctx.Params("*")))
ctx.HTML(http.StatusOK, base.TplName(ctx.Params("*")))
} }

+ 7
- 6
routers/home.go View File



import ( import (
"bytes" "bytes"
"net/http"
"strings" "strings"


"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
if ctx.IsSigned { if ctx.IsSigned {
if !ctx.User.IsActive && setting.Service.RegisterEmailConfirm { if !ctx.User.IsActive && setting.Service.RegisterEmailConfirm {
ctx.Data["Title"] = ctx.Tr("auth.active_your_account") ctx.Data["Title"] = ctx.Tr("auth.active_your_account")
ctx.HTML(200, user.TplActivate)
ctx.HTML(http.StatusOK, user.TplActivate)
} else if !ctx.User.IsActive || ctx.User.ProhibitLogin { } else if !ctx.User.IsActive || ctx.User.ProhibitLogin {
log.Info("Failed authentication attempt for %s from %s", ctx.User.Name, ctx.RemoteAddr()) log.Info("Failed authentication attempt for %s from %s", ctx.User.Name, ctx.RemoteAddr())
ctx.Data["Title"] = ctx.Tr("auth.prohibit_login") ctx.Data["Title"] = ctx.Tr("auth.prohibit_login")
ctx.HTML(200, "user/auth/prohibit_login")
ctx.HTML(http.StatusOK, "user/auth/prohibit_login")
} else if ctx.User.MustChangePassword { } else if ctx.User.MustChangePassword {
ctx.Data["Title"] = ctx.Tr("auth.must_change_password") ctx.Data["Title"] = ctx.Tr("auth.must_change_password")
ctx.Data["ChangePasscodeLink"] = setting.AppSubURL + "/user/change_password" ctx.Data["ChangePasscodeLink"] = setting.AppSubURL + "/user/change_password"


ctx.Data["PageIsHome"] = true ctx.Data["PageIsHome"] = true
ctx.Data["IsRepoIndexerEnabled"] = setting.Indexer.RepoIndexerEnabled ctx.Data["IsRepoIndexerEnabled"] = setting.Indexer.RepoIndexerEnabled
ctx.HTML(200, tplHome)
ctx.HTML(http.StatusOK, tplHome)
} }


// RepoSearchOptions when calling search repositories // RepoSearchOptions when calling search repositories
pager.AddParam(ctx, "topic", "TopicOnly") pager.AddParam(ctx, "topic", "TopicOnly")
ctx.Data["Page"] = pager ctx.Data["Page"] = pager


ctx.HTML(200, opts.TplName)
ctx.HTML(http.StatusOK, opts.TplName)
} }


// ExploreRepos render explore repositories page // ExploreRepos render explore repositories page
pager.SetDefaultParams(ctx) pager.SetDefaultParams(ctx)
ctx.Data["Page"] = pager ctx.Data["Page"] = pager


ctx.HTML(200, tplName)
ctx.HTML(http.StatusOK, tplName)
} }


// ExploreUsers render explore users page // ExploreUsers render explore users page
pager.AddParam(ctx, "l", "Language") pager.AddParam(ctx, "l", "Language")
ctx.Data["Page"] = pager ctx.Data["Page"] = pager


ctx.HTML(200, tplExploreCode)
ctx.HTML(http.StatusOK, tplExploreCode)
} }


// NotFound render 404 page // NotFound render 404 page

+ 3
- 3
routers/install.go View File

form.PasswordAlgorithm = setting.PasswordHashAlgo form.PasswordAlgorithm = setting.PasswordHashAlgo


middleware.AssignForm(form, ctx.Data) middleware.AssignForm(form, ctx.Data)
ctx.HTML(200, tplInstall)
ctx.HTML(http.StatusOK, tplInstall)
} }


// InstallPost response for submit install items // InstallPost response for submit install items
ctx.Data["Err_Admin"] = true ctx.Data["Err_Admin"] = true
} }


ctx.HTML(200, tplInstall)
ctx.HTML(http.StatusOK, tplInstall)
return return
} }


ctx.Flash.Success(ctx.Tr("install.install_success")) ctx.Flash.Success(ctx.Tr("install.install_success"))


ctx.Header().Add("Refresh", "1; url="+setting.AppURL+"user/login") ctx.Header().Add("Refresh", "1; url="+setting.AppURL+"user/login")
ctx.HTML(200, tplPostInstall)
ctx.HTML(http.StatusOK, tplPostInstall)


// Now get the http.Server from this request and shut it down // Now get the http.Server from this request and shut it down
// NB: This is not our hammerable graceful shutdown this is http.Server.Shutdown // NB: This is not our hammerable graceful shutdown this is http.Server.Shutdown

+ 3
- 2
routers/org/home.go View File

package org package org


import ( import (
"net/http"
"strings" "strings"


"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
if ctx.User != nil { if ctx.User != nil {
isMember, err := org.IsOrgMember(ctx.User.ID) isMember, err := org.IsOrgMember(ctx.User.ID)
if err != nil { if err != nil {
ctx.Error(500, "IsOrgMember")
ctx.Error(http.StatusInternalServerError, "IsOrgMember")
return return
} }
opts.PublicOnly = !isMember && !ctx.User.IsAdmin opts.PublicOnly = !isMember && !ctx.User.IsAdmin
pager.SetDefaultParams(ctx) pager.SetDefaultParams(ctx)
ctx.Data["Page"] = pager ctx.Data["Page"] = pager


ctx.HTML(200, tplOrgHome)
ctx.HTML(http.StatusOK, tplOrgHome)
} }

+ 9
- 7
routers/org/members.go View File

package org package org


import ( import (
"net/http"

"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/context"
if ctx.User != nil { if ctx.User != nil {
isMember, err := ctx.Org.Organization.IsOrgMember(ctx.User.ID) isMember, err := ctx.Org.Organization.IsOrgMember(ctx.User.ID)
if err != nil { if err != nil {
ctx.Error(500, "IsOrgMember")
ctx.Error(http.StatusInternalServerError, "IsOrgMember")
return return
} }
opts.PublicOnly = !isMember && !ctx.User.IsAdmin opts.PublicOnly = !isMember && !ctx.User.IsAdmin


total, err := models.CountOrgMembers(opts) total, err := models.CountOrgMembers(opts)
if err != nil { if err != nil {
ctx.Error(500, "CountOrgMembers")
ctx.Error(http.StatusInternalServerError, "CountOrgMembers")
return return
} }


ctx.Data["MembersIsUserOrgOwner"] = members.IsUserOrgOwner(org.ID) ctx.Data["MembersIsUserOrgOwner"] = members.IsUserOrgOwner(org.ID)
ctx.Data["MembersTwoFaStatus"] = members.GetTwoFaStatus() ctx.Data["MembersTwoFaStatus"] = members.GetTwoFaStatus()


ctx.HTML(200, tplMembers)
ctx.HTML(http.StatusOK, tplMembers)
} }


// MembersAction response for operation to a member of organization // MembersAction response for operation to a member of organization
switch ctx.Params(":action") { switch ctx.Params(":action") {
case "private": case "private":
if ctx.User.ID != uid && !ctx.Org.IsOwner { if ctx.User.ID != uid && !ctx.Org.IsOwner {
ctx.Error(404)
ctx.Error(http.StatusNotFound)
return return
} }
err = models.ChangeOrgUserStatus(org.ID, uid, false) err = models.ChangeOrgUserStatus(org.ID, uid, false)
case "public": case "public":
if ctx.User.ID != uid && !ctx.Org.IsOwner { if ctx.User.ID != uid && !ctx.Org.IsOwner {
ctx.Error(404)
ctx.Error(http.StatusNotFound)
return return
} }
err = models.ChangeOrgUserStatus(org.ID, uid, true) err = models.ChangeOrgUserStatus(org.ID, uid, true)
case "remove": case "remove":
if !ctx.Org.IsOwner { if !ctx.Org.IsOwner {
ctx.Error(404)
ctx.Error(http.StatusNotFound)
return return
} }
err = org.RemoveMember(uid) err = org.RemoveMember(uid)


if err != nil { if err != nil {
log.Error("Action(%s): %v", ctx.Params(":action"), err) log.Error("Action(%s): %v", ctx.Params(":action"), err)
ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"ok": false, "ok": false,
"err": err.Error(), "err": err.Error(),
}) })

+ 3
- 2
routers/org/org.go View File



import ( import (
"errors" "errors"
"net/http"


"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/base"
ctx.ServerError("Not allowed", errors.New(ctx.Tr("org.form.create_org_not_allowed"))) ctx.ServerError("Not allowed", errors.New(ctx.Tr("org.form.create_org_not_allowed")))
return return
} }
ctx.HTML(200, tplCreateOrg)
ctx.HTML(http.StatusOK, tplCreateOrg)
} }


// CreatePost response for create organization // CreatePost response for create organization
} }


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, tplCreateOrg)
ctx.HTML(http.StatusOK, tplCreateOrg)
return return
} }



+ 4
- 2
routers/org/org_labels.go View File

package org package org


import ( import (
"net/http"

"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/context"
auth "code.gitea.io/gitea/modules/forms" auth "code.gitea.io/gitea/modules/forms"
if err != nil { if err != nil {
switch { switch {
case models.IsErrOrgLabelNotExist(err): case models.IsErrOrgLabelNotExist(err):
ctx.Error(404)
ctx.Error(http.StatusNotFound)
default: default:
ctx.ServerError("UpdateLabel", err) ctx.ServerError("UpdateLabel", err)
} }
ctx.Flash.Success(ctx.Tr("repo.issues.label_deletion_success")) ctx.Flash.Success(ctx.Tr("repo.issues.label_deletion_success"))
} }


ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"redirect": ctx.Org.OrgLink + "/settings/labels", "redirect": ctx.Org.OrgLink + "/settings/labels",
}) })
} }

+ 7
- 6
routers/org/setting.go View File

package org package org


import ( import (
"net/http"
"strings" "strings"


"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
ctx.Data["PageIsSettingsOptions"] = true ctx.Data["PageIsSettingsOptions"] = true
ctx.Data["CurrentVisibility"] = ctx.Org.Organization.Visibility ctx.Data["CurrentVisibility"] = ctx.Org.Organization.Visibility
ctx.Data["RepoAdminChangeTeamAccess"] = ctx.Org.Organization.RepoAdminChangeTeamAccess ctx.Data["RepoAdminChangeTeamAccess"] = ctx.Org.Organization.RepoAdminChangeTeamAccess
ctx.HTML(200, tplSettingsOptions)
ctx.HTML(http.StatusOK, tplSettingsOptions)
} }


// SettingsPost response for settings change submited // SettingsPost response for settings change submited
ctx.Data["CurrentVisibility"] = ctx.Org.Organization.Visibility ctx.Data["CurrentVisibility"] = ctx.Org.Organization.Visibility


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, tplSettingsOptions)
ctx.HTML(http.StatusOK, tplSettingsOptions)
return return
} }


return return
} }


ctx.HTML(200, tplSettingsDelete)
ctx.HTML(http.StatusOK, tplSettingsDelete)
} }


// Webhooks render webhook list page // Webhooks render webhook list page
} }


ctx.Data["Webhooks"] = ws ctx.Data["Webhooks"] = ws
ctx.HTML(200, tplSettingsHooks)
ctx.HTML(http.StatusOK, tplSettingsHooks)
} }


// DeleteWebhook response for delete webhook // DeleteWebhook response for delete webhook
ctx.Flash.Success(ctx.Tr("repo.settings.webhook_deletion_success")) ctx.Flash.Success(ctx.Tr("repo.settings.webhook_deletion_success"))
} }


ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"redirect": ctx.Org.OrgLink + "/settings/hooks", "redirect": ctx.Org.OrgLink + "/settings/hooks",
}) })
} }
ctx.Data["PageIsOrgSettingsLabels"] = true ctx.Data["PageIsOrgSettingsLabels"] = true
ctx.Data["RequireTribute"] = true ctx.Data["RequireTribute"] = true
ctx.Data["LabelTemplates"] = models.LabelTemplates ctx.Data["LabelTemplates"] = models.LabelTemplates
ctx.HTML(200, tplSettingsLabels)
ctx.HTML(http.StatusOK, tplSettingsLabels)
} }

+ 14
- 14
routers/org/teams.go View File

} }
ctx.Data["Teams"] = org.Teams ctx.Data["Teams"] = org.Teams


ctx.HTML(200, tplTeams)
ctx.HTML(http.StatusOK, tplTeams)
} }


// TeamsAction response for join, leave, remove, add operations to team // TeamsAction response for join, leave, remove, add operations to team
switch ctx.Params(":action") { switch ctx.Params(":action") {
case "join": case "join":
if !ctx.Org.IsOwner { if !ctx.Org.IsOwner {
ctx.Error(404)
ctx.Error(http.StatusNotFound)
return return
} }
err = ctx.Org.Team.AddMember(ctx.User.ID) err = ctx.Org.Team.AddMember(ctx.User.ID)
err = ctx.Org.Team.RemoveMember(ctx.User.ID) err = ctx.Org.Team.RemoveMember(ctx.User.ID)
case "remove": case "remove":
if !ctx.Org.IsOwner { if !ctx.Org.IsOwner {
ctx.Error(404)
ctx.Error(http.StatusNotFound)
return return
} }
err = ctx.Org.Team.RemoveMember(uid) err = ctx.Org.Team.RemoveMember(uid)
page = "team" page = "team"
case "add": case "add":
if !ctx.Org.IsOwner { if !ctx.Org.IsOwner {
ctx.Error(404)
ctx.Error(http.StatusNotFound)
return return
} }
uname := utils.RemoveUsernameParameterSuffix(strings.ToLower(ctx.Query("uname"))) uname := utils.RemoveUsernameParameterSuffix(strings.ToLower(ctx.Query("uname")))
ctx.Flash.Error(ctx.Tr("form.last_org_owner")) ctx.Flash.Error(ctx.Tr("form.last_org_owner"))
} else { } else {
log.Error("Action(%s): %v", ctx.Params(":action"), err) log.Error("Action(%s): %v", ctx.Params(":action"), err)
ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"ok": false, "ok": false,
"err": err.Error(), "err": err.Error(),
}) })
// TeamsRepoAction operate team's repository // TeamsRepoAction operate team's repository
func TeamsRepoAction(ctx *context.Context) { func TeamsRepoAction(ctx *context.Context) {
if !ctx.Org.IsOwner { if !ctx.Org.IsOwner {
ctx.Error(404)
ctx.Error(http.StatusNotFound)
return return
} }


} }


if action == "addall" || action == "removeall" { if action == "addall" || action == "removeall" {
ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"redirect": ctx.Org.OrgLink + "/teams/" + ctx.Org.Team.LowerName + "/repositories", "redirect": ctx.Org.OrgLink + "/teams/" + ctx.Org.Team.LowerName + "/repositories",
}) })
return return
ctx.Data["PageIsOrgTeamsNew"] = true ctx.Data["PageIsOrgTeamsNew"] = true
ctx.Data["Team"] = &models.Team{} ctx.Data["Team"] = &models.Team{}
ctx.Data["Units"] = models.Units ctx.Data["Units"] = models.Units
ctx.HTML(200, tplTeamNew)
ctx.HTML(http.StatusOK, tplTeamNew)
} }


// NewTeamPost response for create new team // NewTeamPost response for create new team
ctx.Data["Team"] = t ctx.Data["Team"] = t


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, tplTeamNew)
ctx.HTML(http.StatusOK, tplTeamNew)
return return
} }


ctx.ServerError("GetMembers", err) ctx.ServerError("GetMembers", err)
return return
} }
ctx.HTML(200, tplTeamMembers)
ctx.HTML(http.StatusOK, tplTeamMembers)
} }


// TeamRepositories show the repositories of team // TeamRepositories show the repositories of team
ctx.ServerError("GetRepositories", err) ctx.ServerError("GetRepositories", err)
return return
} }
ctx.HTML(200, tplTeamRepositories)
ctx.HTML(http.StatusOK, tplTeamRepositories)
} }


// EditTeam render team edit page // EditTeam render team edit page
ctx.Data["team_name"] = ctx.Org.Team.Name ctx.Data["team_name"] = ctx.Org.Team.Name
ctx.Data["desc"] = ctx.Org.Team.Description ctx.Data["desc"] = ctx.Org.Team.Description
ctx.Data["Units"] = models.Units ctx.Data["Units"] = models.Units
ctx.HTML(200, tplTeamNew)
ctx.HTML(http.StatusOK, tplTeamNew)
} }


// EditTeamPost response for modify team information // EditTeamPost response for modify team information
t.CanCreateOrgRepo = form.CanCreateOrgRepo t.CanCreateOrgRepo = form.CanCreateOrgRepo


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, tplTeamNew)
ctx.HTML(http.StatusOK, tplTeamNew)
return return
} }


ctx.Flash.Success(ctx.Tr("org.teams.delete_team_success")) ctx.Flash.Success(ctx.Tr("org.teams.delete_team_success"))
} }


ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"redirect": ctx.Org.OrgLink + "/teams", "redirect": ctx.Org.OrgLink + "/teams",
}) })
} }

+ 1
- 1
routers/private/hook.go View File

protectBranch, err := models.GetProtectedBranchBy(repo.ID, branchName) protectBranch, err := models.GetProtectedBranchBy(repo.ID, branchName)
if err != nil { if err != nil {
log.Error("Unable to get protected branch: %s in %-v Error: %v", branchName, repo, err) log.Error("Unable to get protected branch: %s in %-v Error: %v", branchName, repo, err)
ctx.JSON(500, map[string]interface{}{
ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
"err": err.Error(), "err": err.Error(),
}) })
return return

+ 3
- 2
routers/repo/activity.go View File

package repo package repo


import ( import (
"net/http"
"time" "time"


"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
return return
} }


ctx.HTML(200, tplActivity)
ctx.HTML(http.StatusOK, tplActivity)
} }


// ActivityAuthors renders JSON with top commit authors for given time period over all branches // ActivityAuthors renders JSON with top commit authors for given time period over all branches
return return
} }


ctx.JSON(200, authors)
ctx.JSON(http.StatusOK, authors)
} }

+ 10
- 10
routers/repo/attachment.go View File

// UploadAttachment response for uploading attachments // UploadAttachment response for uploading attachments
func uploadAttachment(ctx *context.Context, allowedTypes string) { func uploadAttachment(ctx *context.Context, allowedTypes string) {
if !setting.Attachment.Enabled { if !setting.Attachment.Enabled {
ctx.Error(404, "attachment is not enabled")
ctx.Error(http.StatusNotFound, "attachment is not enabled")
return return
} }


file, header, err := ctx.Req.FormFile("file") file, header, err := ctx.Req.FormFile("file")
if err != nil { if err != nil {
ctx.Error(500, fmt.Sprintf("FormFile: %v", err))
ctx.Error(http.StatusInternalServerError, fmt.Sprintf("FormFile: %v", err))
return return
} }
defer file.Close() defer file.Close()


err = upload.Verify(buf, header.Filename, allowedTypes) err = upload.Verify(buf, header.Filename, allowedTypes)
if err != nil { if err != nil {
ctx.Error(400, err.Error())
ctx.Error(http.StatusBadRequest, err.Error())
return return
} }


Name: header.Filename, Name: header.Filename,
}, buf, file) }, buf, file)
if err != nil { if err != nil {
ctx.Error(500, fmt.Sprintf("NewAttachment: %v", err))
ctx.Error(http.StatusInternalServerError, fmt.Sprintf("NewAttachment: %v", err))
return return
} }


log.Trace("New attachment uploaded: %s", attach.UUID) log.Trace("New attachment uploaded: %s", attach.UUID)
ctx.JSON(200, map[string]string{
ctx.JSON(http.StatusOK, map[string]string{
"uuid": attach.UUID, "uuid": attach.UUID,
}) })
} }
file := ctx.Query("file") file := ctx.Query("file")
attach, err := models.GetAttachmentByUUID(file) attach, err := models.GetAttachmentByUUID(file)
if err != nil { if err != nil {
ctx.Error(400, err.Error())
ctx.Error(http.StatusBadRequest, err.Error())
return return
} }
if !ctx.IsSigned || (ctx.User.ID != attach.UploaderID) { if !ctx.IsSigned || (ctx.User.ID != attach.UploaderID) {
ctx.Error(403)
ctx.Error(http.StatusForbidden)
return return
} }
err = models.DeleteAttachment(attach, true) err = models.DeleteAttachment(attach, true)
if err != nil { if err != nil {
ctx.Error(500, fmt.Sprintf("DeleteAttachment: %v", err))
ctx.Error(http.StatusInternalServerError, fmt.Sprintf("DeleteAttachment: %v", err))
return return
} }
ctx.JSON(200, map[string]string{
ctx.JSON(http.StatusOK, map[string]string{
"uuid": attach.UUID, "uuid": attach.UUID,
}) })
} }
attach, err := models.GetAttachmentByUUID(ctx.Params(":uuid")) attach, err := models.GetAttachmentByUUID(ctx.Params(":uuid"))
if err != nil { if err != nil {
if models.IsErrAttachmentNotExist(err) { if models.IsErrAttachmentNotExist(err) {
ctx.Error(404)
ctx.Error(http.StatusNotFound)
} else { } else {
ctx.ServerError("GetAttachmentByUUID", err) ctx.ServerError("GetAttachmentByUUID", err)
} }

+ 2
- 1
routers/repo/blame.go View File

"fmt" "fmt"
"html" "html"
gotemplate "html/template" gotemplate "html/template"
"net/http"
"strings" "strings"


"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"


renderBlame(ctx, blameParts, commitNames) renderBlame(ctx, blameParts, commitNames)


ctx.HTML(200, tplBlame)
ctx.HTML(http.StatusOK, tplBlame)
} }


func renderBlame(ctx *context.Context, blameParts []git.BlamePart, commitNames map[string]models.UserCommit) { func renderBlame(ctx *context.Context, blameParts []git.BlamePart, commitNames map[string]models.UserCommit) {

+ 3
- 2
routers/repo/branch.go View File



import ( import (
"fmt" "fmt"
"net/http"
"strings" "strings"


"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
pager.SetDefaultParams(ctx) pager.SetDefaultParams(ctx)
ctx.Data["Page"] = pager ctx.Data["Page"] = pager


ctx.HTML(200, tplBranch)
ctx.HTML(http.StatusOK, tplBranch)
} }


// DeleteBranchPost responses for delete merged branch // DeleteBranchPost responses for delete merged branch
} }


func redirect(ctx *context.Context) { func redirect(ctx *context.Context) {
ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"redirect": ctx.Repo.RepoLink + "/branches", "redirect": ctx.Repo.RepoLink + "/branches",
}) })
} }

+ 7
- 6
routers/repo/commit.go View File



import ( import (
"errors" "errors"
"net/http"
"path" "path"
"strings" "strings"


pager.SetDefaultParams(ctx) pager.SetDefaultParams(ctx)
ctx.Data["Page"] = pager ctx.Data["Page"] = pager


ctx.HTML(200, tplCommits)
ctx.HTML(http.StatusOK, tplCommits)
} }


// Graph render commit graph - show commits from all branches. // Graph render commit graph - show commits from all branches.
} }
ctx.Data["Page"] = paginator ctx.Data["Page"] = paginator
if ctx.QueryBool("div-only") { if ctx.QueryBool("div-only") {
ctx.HTML(200, tplGraphDiv)
ctx.HTML(http.StatusOK, tplGraphDiv)
return return
} }


ctx.HTML(200, tplGraph)
ctx.HTML(http.StatusOK, tplGraph)
} }


// SearchCommits render commits filtered by keyword // SearchCommits render commits filtered by keyword
ctx.Data["Reponame"] = ctx.Repo.Repository.Name ctx.Data["Reponame"] = ctx.Repo.Repository.Name
ctx.Data["CommitCount"] = commits.Len() ctx.Data["CommitCount"] = commits.Len()
ctx.Data["Branch"] = ctx.Repo.BranchName ctx.Data["Branch"] = ctx.Repo.BranchName
ctx.HTML(200, tplCommits)
ctx.HTML(http.StatusOK, tplCommits)
} }


// FileHistory show a file's reversions // FileHistory show a file's reversions
pager.SetDefaultParams(ctx) pager.SetDefaultParams(ctx)
ctx.Data["Page"] = pager ctx.Data["Page"] = pager


ctx.HTML(200, tplCommits)
ctx.HTML(http.StatusOK, tplCommits)
} }


// Diff show different from current commit to previous commit // Diff show different from current commit to previous commit
ctx.ServerError("commit.GetTagName", err) ctx.ServerError("commit.GetTagName", err)
return return
} }
ctx.HTML(200, tplCommitPage)
ctx.HTML(http.StatusOK, tplCommitPage)
} }


// RawDiff dumps diff results of repository in given commit ID to io.Writer // RawDiff dumps diff results of repository in given commit ID to io.Writer

+ 6
- 5
routers/repo/compare.go View File

"fmt" "fmt"
"html" "html"
"io/ioutil" "io/ioutil"
"net/http"
"path" "path"
"path/filepath" "path/filepath"
"strings" "strings"
} else { } else {
ctx.Data["HasPullRequest"] = true ctx.Data["HasPullRequest"] = true
ctx.Data["PullRequest"] = pr ctx.Data["PullRequest"] = pr
ctx.HTML(200, tplCompareDiff)
ctx.HTML(http.StatusOK, tplCompareDiff)
return return
} }




ctx.Data["HasIssuesOrPullsWritePermission"] = ctx.Repo.CanWrite(models.UnitTypePullRequests) ctx.Data["HasIssuesOrPullsWritePermission"] = ctx.Repo.CanWrite(models.UnitTypePullRequests)


ctx.HTML(200, tplCompare)
ctx.HTML(http.StatusOK, tplCompare)
} }


// ExcerptBlob render blob excerpt contents // ExcerptBlob render blob excerpt contents
chunkSize := gitdiff.BlobExcerptChunkSize chunkSize := gitdiff.BlobExcerptChunkSize
commit, err := gitRepo.GetCommit(commitID) commit, err := gitRepo.GetCommit(commitID)
if err != nil { if err != nil {
ctx.Error(500, "GetCommit")
ctx.Error(http.StatusInternalServerError, "GetCommit")
return return
} }
section := &gitdiff.DiffSection{ section := &gitdiff.DiffSection{
idxRight = lastRight idxRight = lastRight
} }
if err != nil { if err != nil {
ctx.Error(500, "getExcerptLines")
ctx.Error(http.StatusInternalServerError, "getExcerptLines")
return return
} }
if idxRight > lastRight { if idxRight > lastRight {
ctx.Data["fileName"] = filePath ctx.Data["fileName"] = filePath
ctx.Data["AfterCommitID"] = commitID ctx.Data["AfterCommitID"] = commitID
ctx.Data["Anchor"] = anchor ctx.Data["Anchor"] = anchor
ctx.HTML(200, tplBlobExcerpt)
ctx.HTML(http.StatusOK, tplBlobExcerpt)
} }


func getExcerptLines(commit *git.Commit, filePath string, idxLeft int, idxRight int, chunkSize int) ([]*gitdiff.DiffLine, error) { func getExcerptLines(commit *git.Commit, filePath string, idxLeft int, idxRight int, chunkSize int) ([]*gitdiff.DiffLine, error) {

+ 25
- 24
routers/repo/editor.go View File

import ( import (
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"net/http"
"path" "path"
"strings" "strings"


ctx.Data["PreviewableFileModes"] = strings.Join(setting.Repository.Editor.PreviewableFileModes, ",") ctx.Data["PreviewableFileModes"] = strings.Join(setting.Repository.Editor.PreviewableFileModes, ",")
ctx.Data["Editorconfig"] = GetEditorConfig(ctx, treePath) ctx.Data["Editorconfig"] = GetEditorConfig(ctx, treePath)


ctx.HTML(200, tplEditFile)
ctx.HTML(http.StatusOK, tplEditFile)
} }


// GetEditorConfig returns a editorconfig JSON string for given treePath or "null" // GetEditorConfig returns a editorconfig JSON string for given treePath or "null"
ctx.Data["Editorconfig"] = GetEditorConfig(ctx, form.TreePath) ctx.Data["Editorconfig"] = GetEditorConfig(ctx, form.TreePath)


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, tplEditFile)
ctx.HTML(http.StatusOK, tplEditFile)
return return
} }


case git.EntryModeBlob: case git.EntryModeBlob:
ctx.RenderWithErr(ctx.Tr("repo.editor.directory_is_a_file", fileErr.Path), tplEditFile, &form) ctx.RenderWithErr(ctx.Tr("repo.editor.directory_is_a_file", fileErr.Path), tplEditFile, &form)
default: default:
ctx.Error(500, err.Error())
ctx.Error(http.StatusInternalServerError, err.Error())
} }
} else { } else {
ctx.Error(500, err.Error())
ctx.Error(http.StatusInternalServerError, err.Error())
} }
} else if models.IsErrRepoFileAlreadyExists(err) { } else if models.IsErrRepoFileAlreadyExists(err) {
ctx.Data["Err_TreePath"] = true ctx.Data["Err_TreePath"] = true
if branchErr, ok := err.(git.ErrBranchNotExist); ok { if branchErr, ok := err.(git.ErrBranchNotExist); ok {
ctx.RenderWithErr(ctx.Tr("repo.editor.branch_does_not_exist", branchErr.Name), tplEditFile, &form) ctx.RenderWithErr(ctx.Tr("repo.editor.branch_does_not_exist", branchErr.Name), tplEditFile, &form)
} else { } else {
ctx.Error(500, err.Error())
ctx.Error(http.StatusInternalServerError, err.Error())
} }
} else if models.IsErrBranchAlreadyExists(err) { } else if models.IsErrBranchAlreadyExists(err) {
// For when a user specifies a new branch that already exists // For when a user specifies a new branch that already exists
if branchErr, ok := err.(models.ErrBranchAlreadyExists); ok { if branchErr, ok := err.(models.ErrBranchAlreadyExists); ok {
ctx.RenderWithErr(ctx.Tr("repo.editor.branch_already_exists", branchErr.BranchName), tplEditFile, &form) ctx.RenderWithErr(ctx.Tr("repo.editor.branch_already_exists", branchErr.BranchName), tplEditFile, &form)
} else { } else {
ctx.Error(500, err.Error())
ctx.Error(http.StatusInternalServerError, err.Error())
} }
} else if models.IsErrCommitIDDoesNotMatch(err) { } else if models.IsErrCommitIDDoesNotMatch(err) {
ctx.RenderWithErr(ctx.Tr("repo.editor.file_changed_while_editing", ctx.Repo.RepoLink+"/compare/"+form.LastCommit+"..."+ctx.Repo.CommitID), tplEditFile, &form) ctx.RenderWithErr(ctx.Tr("repo.editor.file_changed_while_editing", ctx.Repo.RepoLink+"/compare/"+form.LastCommit+"..."+ctx.Repo.CommitID), tplEditFile, &form)
form := web.GetForm(ctx).(*auth.EditPreviewDiffForm) form := web.GetForm(ctx).(*auth.EditPreviewDiffForm)
treePath := cleanUploadFileName(ctx.Repo.TreePath) treePath := cleanUploadFileName(ctx.Repo.TreePath)
if len(treePath) == 0 { if len(treePath) == 0 {
ctx.Error(500, "file name to diff is invalid")
ctx.Error(http.StatusInternalServerError, "file name to diff is invalid")
return return
} }


entry, err := ctx.Repo.Commit.GetTreeEntryByPath(treePath) entry, err := ctx.Repo.Commit.GetTreeEntryByPath(treePath)
if err != nil { if err != nil {
ctx.Error(500, "GetTreeEntryByPath: "+err.Error())
ctx.Error(http.StatusInternalServerError, "GetTreeEntryByPath: "+err.Error())
return return
} else if entry.IsDir() { } else if entry.IsDir() {
ctx.Error(422)
ctx.Error(http.StatusUnprocessableEntity)
return return
} }


diff, err := repofiles.GetDiffPreview(ctx.Repo.Repository, ctx.Repo.BranchName, treePath, form.Content) diff, err := repofiles.GetDiffPreview(ctx.Repo.Repository, ctx.Repo.BranchName, treePath, form.Content)
if err != nil { if err != nil {
ctx.Error(500, "GetDiffPreview: "+err.Error())
ctx.Error(http.StatusInternalServerError, "GetDiffPreview: "+err.Error())
return return
} }


} }
ctx.Data["File"] = diff.Files[0] ctx.Data["File"] = diff.Files[0]


ctx.HTML(200, tplEditDiffPreview)
ctx.HTML(http.StatusOK, tplEditDiffPreview)
} }


// DeleteFile render delete file page // DeleteFile render delete file page
} }
ctx.Data["new_branch_name"] = GetUniquePatchBranchName(ctx) ctx.Data["new_branch_name"] = GetUniquePatchBranchName(ctx)


ctx.HTML(200, tplDeleteFile)
ctx.HTML(http.StatusOK, tplDeleteFile)
} }


// DeleteFilePost response for deleting file // DeleteFilePost response for deleting file
ctx.Data["last_commit"] = ctx.Repo.CommitID ctx.Data["last_commit"] = ctx.Repo.CommitID


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, tplDeleteFile)
ctx.HTML(http.StatusOK, tplDeleteFile)
return return
} }


if branchErr, ok := err.(git.ErrBranchNotExist); ok { if branchErr, ok := err.(git.ErrBranchNotExist); ok {
ctx.RenderWithErr(ctx.Tr("repo.editor.branch_does_not_exist", branchErr.Name), tplDeleteFile, &form) ctx.RenderWithErr(ctx.Tr("repo.editor.branch_does_not_exist", branchErr.Name), tplDeleteFile, &form)
} else { } else {
ctx.Error(500, err.Error())
ctx.Error(http.StatusInternalServerError, err.Error())
} }
} else if models.IsErrBranchAlreadyExists(err) { } else if models.IsErrBranchAlreadyExists(err) {
// For when a user specifies a new branch that already exists // For when a user specifies a new branch that already exists
if branchErr, ok := err.(models.ErrBranchAlreadyExists); ok { if branchErr, ok := err.(models.ErrBranchAlreadyExists); ok {
ctx.RenderWithErr(ctx.Tr("repo.editor.branch_already_exists", branchErr.BranchName), tplDeleteFile, &form) ctx.RenderWithErr(ctx.Tr("repo.editor.branch_already_exists", branchErr.BranchName), tplDeleteFile, &form)
} else { } else {
ctx.Error(500, err.Error())
ctx.Error(http.StatusInternalServerError, err.Error())
} }
} else if models.IsErrCommitIDDoesNotMatch(err) || git.IsErrPushOutOfDate(err) { } else if models.IsErrCommitIDDoesNotMatch(err) || git.IsErrPushOutOfDate(err) {
ctx.RenderWithErr(ctx.Tr("repo.editor.file_changed_while_deleting", ctx.Repo.RepoLink+"/compare/"+form.LastCommit+"..."+ctx.Repo.CommitID), tplDeleteFile, &form) ctx.RenderWithErr(ctx.Tr("repo.editor.file_changed_while_deleting", ctx.Repo.RepoLink+"/compare/"+form.LastCommit+"..."+ctx.Repo.CommitID), tplDeleteFile, &form)
} }
ctx.Data["new_branch_name"] = GetUniquePatchBranchName(ctx) ctx.Data["new_branch_name"] = GetUniquePatchBranchName(ctx)


ctx.HTML(200, tplUploadFile)
ctx.HTML(http.StatusOK, tplUploadFile)
} }


// UploadFilePost response for uploading file // UploadFilePost response for uploading file
ctx.Data["new_branch_name"] = branchName ctx.Data["new_branch_name"] = branchName


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, tplUploadFile)
ctx.HTML(http.StatusOK, tplUploadFile)
return return
} }


case git.EntryModeBlob: case git.EntryModeBlob:
ctx.RenderWithErr(ctx.Tr("repo.editor.directory_is_a_file", fileErr.Path), tplUploadFile, &form) ctx.RenderWithErr(ctx.Tr("repo.editor.directory_is_a_file", fileErr.Path), tplUploadFile, &form)
default: default:
ctx.Error(500, err.Error())
ctx.Error(http.StatusInternalServerError, err.Error())
} }
} else if models.IsErrRepoFileAlreadyExists(err) { } else if models.IsErrRepoFileAlreadyExists(err) {
ctx.Data["Err_TreePath"] = true ctx.Data["Err_TreePath"] = true
func UploadFileToServer(ctx *context.Context) { func UploadFileToServer(ctx *context.Context) {
file, header, err := ctx.Req.FormFile("file") file, header, err := ctx.Req.FormFile("file")
if err != nil { if err != nil {
ctx.Error(500, fmt.Sprintf("FormFile: %v", err))
ctx.Error(http.StatusInternalServerError, fmt.Sprintf("FormFile: %v", err))
return return
} }
defer file.Close() defer file.Close()


err = upload.Verify(buf, header.Filename, setting.Repository.Upload.AllowedTypes) err = upload.Verify(buf, header.Filename, setting.Repository.Upload.AllowedTypes)
if err != nil { if err != nil {
ctx.Error(400, err.Error())
ctx.Error(http.StatusBadRequest, err.Error())
return return
} }


name := cleanUploadFileName(header.Filename) name := cleanUploadFileName(header.Filename)
if len(name) == 0 { if len(name) == 0 {
ctx.Error(500, "Upload file name is invalid")
ctx.Error(http.StatusInternalServerError, "Upload file name is invalid")
return return
} }


upload, err := models.NewUpload(name, buf, file) upload, err := models.NewUpload(name, buf, file)
if err != nil { if err != nil {
ctx.Error(500, fmt.Sprintf("NewUpload: %v", err))
ctx.Error(http.StatusInternalServerError, fmt.Sprintf("NewUpload: %v", err))
return return
} }


log.Trace("New file uploaded: %s", upload.UUID) log.Trace("New file uploaded: %s", upload.UUID)
ctx.JSON(200, map[string]string{
ctx.JSON(http.StatusOK, map[string]string{
"uuid": upload.UUID, "uuid": upload.UUID,
}) })
} }
} }


if err := models.DeleteUploadByUUID(form.File); err != nil { if err := models.DeleteUploadByUUID(form.File); err != nil {
ctx.Error(500, fmt.Sprintf("DeleteUploadByUUID: %v", err))
ctx.Error(http.StatusInternalServerError, fmt.Sprintf("DeleteUploadByUUID: %v", err))
return return
} }



+ 33
- 33
routers/repo/issue.go View File



ctx.Data["CanWriteIssuesOrPulls"] = ctx.Repo.CanWriteIssuesOrPulls(isPullList) ctx.Data["CanWriteIssuesOrPulls"] = ctx.Repo.CanWriteIssuesOrPulls(isPullList)


ctx.HTML(200, tplIssues)
ctx.HTML(http.StatusOK, tplIssues)
} }


// RetrieveRepoMilestonesAndAssignees find all the milestones and assignees of a repository // RetrieveRepoMilestonesAndAssignees find all the milestones and assignees of a repository


ctx.Data["HasIssuesOrPullsWritePermission"] = ctx.Repo.CanWrite(models.UnitTypeIssues) ctx.Data["HasIssuesOrPullsWritePermission"] = ctx.Repo.CanWrite(models.UnitTypeIssues)


ctx.HTML(200, tplIssueNew)
ctx.HTML(http.StatusOK, tplIssueNew)
} }


// NewIssueChooseTemplate render creating issue from template page // NewIssueChooseTemplate render creating issue from template page
ctx.Data["NewIssueChooseTemplate"] = len(issueTemplates) > 0 ctx.Data["NewIssueChooseTemplate"] = len(issueTemplates) > 0
ctx.Data["IssueTemplates"] = issueTemplates ctx.Data["IssueTemplates"] = issueTemplates


ctx.HTML(200, tplIssueChoose)
ctx.HTML(http.StatusOK, tplIssueChoose)
} }


// ValidateRepoMetas check and returns repository's meta informations // ValidateRepoMetas check and returns repository's meta informations
} }


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, tplIssueNew)
ctx.HTML(http.StatusOK, tplIssueNew)
return return
} }




if err := issue_service.NewIssue(repo, issue, labelIDs, attachments, assigneeIDs); err != nil { if err := issue_service.NewIssue(repo, issue, labelIDs, attachments, assigneeIDs); err != nil {
if models.IsErrUserDoesNotHaveAccessToRepo(err) { if models.IsErrUserDoesNotHaveAccessToRepo(err) {
ctx.Error(400, "UserDoesNotHaveAccessToRepo", err.Error())
ctx.Error(http.StatusBadRequest, "UserDoesNotHaveAccessToRepo", err.Error())
return return
} }
ctx.ServerError("NewIssue", err) ctx.ServerError("NewIssue", err)
ctx.Data["IsRepoAdmin"] = ctx.IsSigned && (ctx.Repo.IsAdmin() || ctx.User.IsAdmin) ctx.Data["IsRepoAdmin"] = ctx.IsSigned && (ctx.Repo.IsAdmin() || ctx.User.IsAdmin)
ctx.Data["LockReasons"] = setting.Repository.Issue.LockReasons ctx.Data["LockReasons"] = setting.Repository.Issue.LockReasons
ctx.Data["RefEndName"] = git.RefEndName(issue.Ref) ctx.Data["RefEndName"] = git.RefEndName(issue.Ref)
ctx.HTML(200, tplIssueView)
ctx.HTML(http.StatusOK, tplIssueView)
} }


// GetActionIssue will return the issue which is used in the context. // GetActionIssue will return the issue which is used in the context.
} }


if !ctx.IsSigned || (!issue.IsPoster(ctx.User.ID) && !ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull)) { if !ctx.IsSigned || (!issue.IsPoster(ctx.User.ID) && !ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull)) {
ctx.Error(403)
ctx.Error(http.StatusForbidden)
return return
} }


title := ctx.QueryTrim("title") title := ctx.QueryTrim("title")
if len(title) == 0 { if len(title) == 0 {
ctx.Error(204)
ctx.Error(http.StatusNoContent)
return return
} }


return return
} }


ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"title": issue.Title, "title": issue.Title,
}) })
} }
} }


if !ctx.IsSigned || (!issue.IsPoster(ctx.User.ID) && !ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull)) || issue.IsPull { if !ctx.IsSigned || (!issue.IsPoster(ctx.User.ID) && !ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull)) || issue.IsPull {
ctx.Error(403)
ctx.Error(http.StatusForbidden)
return return
} }


return return
} }


ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"ref": ref, "ref": ref,
}) })
} }
} }


if !ctx.IsSigned || (ctx.User.ID != issue.PosterID && !ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull)) { if !ctx.IsSigned || (ctx.User.ID != issue.PosterID && !ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull)) {
ctx.Error(403)
ctx.Error(http.StatusForbidden)
return return
} }


ctx.ServerError("UpdateAttachments", err) ctx.ServerError("UpdateAttachments", err)
} }


ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"content": string(markdown.Render([]byte(issue.Content), ctx.Query("context"), ctx.Repo.Repository.ComposeMetas())), "content": string(markdown.Render([]byte(issue.Content), ctx.Query("context"), ctx.Repo.Repository.ComposeMetas())),
"attachments": attachmentsHTML(ctx, issue.Attachments, issue.Content), "attachments": attachmentsHTML(ctx, issue.Attachments, issue.Content),
}) })
} }
} }


ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"ok": true, "ok": true,
}) })
} }
} }
} }
} }
ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"ok": true, "ok": true,
}) })
} }
} }
} }


ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"ok": true, "ok": true,
}) })
} }
} }
} }
} }
ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"ok": true, "ok": true,
}) })
} }
} }
} }


ctx.Error(403)
ctx.Error(http.StatusForbidden)
return return
} }


} }


if !ctx.IsSigned || (ctx.User.ID != comment.PosterID && !ctx.Repo.CanWriteIssuesOrPulls(comment.Issue.IsPull)) { if !ctx.IsSigned || (ctx.User.ID != comment.PosterID && !ctx.Repo.CanWriteIssuesOrPulls(comment.Issue.IsPull)) {
ctx.Error(403)
ctx.Error(http.StatusForbidden)
return return
} else if comment.Type != models.CommentTypeComment && comment.Type != models.CommentTypeCode { } else if comment.Type != models.CommentTypeComment && comment.Type != models.CommentTypeCode {
ctx.Error(204)
ctx.Error(http.StatusNoContent)
return return
} }


oldContent := comment.Content oldContent := comment.Content
comment.Content = ctx.Query("content") comment.Content = ctx.Query("content")
if len(comment.Content) == 0 { if len(comment.Content) == 0 {
ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"content": "", "content": "",
}) })
return return
ctx.ServerError("UpdateAttachments", err) ctx.ServerError("UpdateAttachments", err)
} }


ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"content": string(markdown.Render([]byte(comment.Content), ctx.Query("context"), ctx.Repo.Repository.ComposeMetas())), "content": string(markdown.Render([]byte(comment.Content), ctx.Query("context"), ctx.Repo.Repository.ComposeMetas())),
"attachments": attachmentsHTML(ctx, comment.Attachments, comment.Content), "attachments": attachmentsHTML(ctx, comment.Attachments, comment.Content),
}) })
} }


if !ctx.IsSigned || (ctx.User.ID != comment.PosterID && !ctx.Repo.CanWriteIssuesOrPulls(comment.Issue.IsPull)) { if !ctx.IsSigned || (ctx.User.ID != comment.PosterID && !ctx.Repo.CanWriteIssuesOrPulls(comment.Issue.IsPull)) {
ctx.Error(403)
ctx.Error(http.StatusForbidden)
return return
} else if comment.Type != models.CommentTypeComment && comment.Type != models.CommentTypeCode { } else if comment.Type != models.CommentTypeComment && comment.Type != models.CommentTypeCode {
ctx.Error(204)
ctx.Error(http.StatusNoContent)
return return
} }


} }
} }


ctx.Error(403)
ctx.Error(http.StatusForbidden)
return return
} }


} }


if len(issue.Reactions) == 0 { if len(issue.Reactions) == 0 {
ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"empty": true, "empty": true,
"html": "", "html": "",
}) })
ctx.ServerError("ChangeIssueReaction.HTMLString", err) ctx.ServerError("ChangeIssueReaction.HTMLString", err)
return return
} }
ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"html": html, "html": html,
}) })
} }
} }
} }


ctx.Error(403)
ctx.Error(http.StatusForbidden)
return return
} else if comment.Type != models.CommentTypeComment && comment.Type != models.CommentTypeCode { } else if comment.Type != models.CommentTypeComment && comment.Type != models.CommentTypeCode {
ctx.Error(204)
ctx.Error(http.StatusNoContent)
return return
} }


} }


if len(comment.Reactions) == 0 { if len(comment.Reactions) == 0 {
ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"empty": true, "empty": true,
"html": "", "html": "",
}) })
ctx.ServerError("ChangeCommentReaction.HTMLString", err) ctx.ServerError("ChangeCommentReaction.HTMLString", err)
return return
} }
ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"html": html, "html": html,
}) })
} }
for i := 0; i < len(issue.Attachments); i++ { for i := 0; i < len(issue.Attachments); i++ {
attachments[i] = convert.ToReleaseAttachment(issue.Attachments[i]) attachments[i] = convert.ToReleaseAttachment(issue.Attachments[i])
} }
ctx.JSON(200, attachments)
ctx.JSON(http.StatusOK, attachments)
} }


// GetCommentAttachments returns attachments for the comment // GetCommentAttachments returns attachments for the comment
attachments = append(attachments, convert.ToReleaseAttachment(comment.Attachments[i])) attachments = append(attachments, convert.ToReleaseAttachment(comment.Attachments[i]))
} }
} }
ctx.JSON(200, attachments)
ctx.JSON(http.StatusOK, attachments)
} }


func updateAttachments(item interface{}, files []string) error { func updateAttachments(item interface{}, files []string) error {

+ 8
- 6
routers/repo/issue_label.go View File

package repo package repo


import ( import (
"net/http"

"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/context"
ctx.Data["PageIsLabels"] = true ctx.Data["PageIsLabels"] = true
ctx.Data["RequireTribute"] = true ctx.Data["RequireTribute"] = true
ctx.Data["LabelTemplates"] = models.LabelTemplates ctx.Data["LabelTemplates"] = models.LabelTemplates
ctx.HTML(200, tplLabels)
ctx.HTML(http.StatusOK, tplLabels)
} }


// InitializeLabels init labels for a repository // InitializeLabels init labels for a repository
if err != nil { if err != nil {
switch { switch {
case models.IsErrRepoLabelNotExist(err): case models.IsErrRepoLabelNotExist(err):
ctx.Error(404)
ctx.Error(http.StatusNotFound)
default: default:
ctx.ServerError("UpdateLabel", err) ctx.ServerError("UpdateLabel", err)
} }
ctx.Flash.Success(ctx.Tr("repo.issues.label_deletion_success")) ctx.Flash.Success(ctx.Tr("repo.issues.label_deletion_success"))
} }


ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"redirect": ctx.Repo.RepoLink + "/labels", "redirect": ctx.Repo.RepoLink + "/labels",
}) })
} }
label, err := models.GetLabelByID(ctx.QueryInt64("id")) label, err := models.GetLabelByID(ctx.QueryInt64("id"))
if err != nil { if err != nil {
if models.IsErrRepoLabelNotExist(err) { if models.IsErrRepoLabelNotExist(err) {
ctx.Error(404, "GetLabelByID")
ctx.Error(http.StatusNotFound, "GetLabelByID")
} else { } else {
ctx.ServerError("GetLabelByID", err) ctx.ServerError("GetLabelByID", err)
} }
} }
default: default:
log.Warn("Unrecognized action: %s", action) log.Warn("Unrecognized action: %s", action)
ctx.Error(500)
ctx.Error(http.StatusInternalServerError)
return return
} }


ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"ok": true, "ok": true,
}) })
} }

+ 1
- 1
routers/repo/issue_watch.go View File

log.Trace("Permission Denied: Not logged in") log.Trace("Permission Denied: Not logged in")
} }
} }
ctx.Error(403)
ctx.Error(http.StatusForbidden)
return return
} }



+ 7
- 6
routers/repo/lfs.go View File

gotemplate "html/template" gotemplate "html/template"
"io" "io"
"io/ioutil" "io/ioutil"
"net/http"
"path" "path"
"strconv" "strconv"
"strings" "strings"
} }
ctx.Data["LFSFiles"] = lfsMetaObjects ctx.Data["LFSFiles"] = lfsMetaObjects
ctx.Data["Page"] = pager ctx.Data["Page"] = pager
ctx.HTML(200, tplSettingsLFS)
ctx.HTML(http.StatusOK, tplSettingsLFS)
} }


// LFSLocks shows a repository's LFS locks // LFSLocks shows a repository's LFS locks


if len(lfsLocks) == 0 { if len(lfsLocks) == 0 {
ctx.Data["Page"] = pager ctx.Data["Page"] = pager
ctx.HTML(200, tplSettingsLFSLocks)
ctx.HTML(http.StatusOK, tplSettingsLFSLocks)
return return
} }


ctx.Data["Linkable"] = linkable ctx.Data["Linkable"] = linkable


ctx.Data["Page"] = pager ctx.Data["Page"] = pager
ctx.HTML(200, tplSettingsLFSLocks)
ctx.HTML(http.StatusOK, tplSettingsLFSLocks)
} }


// LFSLockFile locks a file // LFSLockFile locks a file
case base.IsImageFile(buf): case base.IsImageFile(buf):
ctx.Data["IsImageFile"] = true ctx.Data["IsImageFile"] = true
} }
ctx.HTML(200, tplSettingsLFSFile)
ctx.HTML(http.StatusOK, tplSettingsLFSFile)
} }


// LFSDelete disassociates the provided oid from the repository and if the lfs file is no longer associated with any repositories - deletes it // LFSDelete disassociates the provided oid from the repository and if the lfs file is no longer associated with any repositories - deletes it
} }


ctx.Data["Results"] = results ctx.Data["Results"] = results
ctx.HTML(200, tplSettingsLFSFileFind)
ctx.HTML(http.StatusOK, tplSettingsLFSFileFind)
} }


// LFSPointerFiles will search the repository for pointer files and report which are missing LFS files in the content store // LFSPointerFiles will search the repository for pointer files and report which are missing LFS files in the content store
} }
default: default:
} }
ctx.HTML(200, tplSettingsLFSPointers)
ctx.HTML(http.StatusOK, tplSettingsLFSPointers)
} }


type pointerResult struct { type pointerResult struct {

+ 3
- 3
routers/repo/migrate.go View File

ctx.Data["Org"] = ctx.Query("org") ctx.Data["Org"] = ctx.Query("org")
ctx.Data["Mirror"] = ctx.Query("mirror") ctx.Data["Mirror"] = ctx.Query("mirror")


ctx.HTML(200, tplMigrate)
ctx.HTML(http.StatusOK, tplMigrate)
return return
} }


} }
ctx.Data["ContextUser"] = ctxUser ctx.Data["ContextUser"] = ctxUser


ctx.HTML(200, base.TplName("repo/migrate/"+serviceType.Name()))
ctx.HTML(http.StatusOK, base.TplName("repo/migrate/"+serviceType.Name()))
} }


func handleMigrateError(ctx *context.Context, owner *models.User, err error, name string, tpl base.TplName, form *auth.MigrateRepoForm) { func handleMigrateError(ctx *context.Context, owner *models.User, err error, name string, tpl base.TplName, form *auth.MigrateRepoForm) {
tpl := base.TplName("repo/migrate/" + serviceType.Name()) tpl := base.TplName("repo/migrate/" + serviceType.Name())


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, tpl)
ctx.HTML(http.StatusOK, tpl)
return return
} }



+ 8
- 7
routers/repo/milestone.go View File

package repo package repo


import ( import (
"net/http"
"time" "time"


"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
pager.AddParam(ctx, "state", "State") pager.AddParam(ctx, "state", "State")
ctx.Data["Page"] = pager ctx.Data["Page"] = pager


ctx.HTML(200, tplMilestone)
ctx.HTML(http.StatusOK, tplMilestone)
} }


// NewMilestone render creating milestone page // NewMilestone render creating milestone page
ctx.Data["Title"] = ctx.Tr("repo.milestones.new") ctx.Data["Title"] = ctx.Tr("repo.milestones.new")
ctx.Data["PageIsIssueList"] = true ctx.Data["PageIsIssueList"] = true
ctx.Data["PageIsMilestones"] = true ctx.Data["PageIsMilestones"] = true
ctx.HTML(200, tplMilestoneNew)
ctx.HTML(http.StatusOK, tplMilestoneNew)
} }


// NewMilestonePost response for creating milestone // NewMilestonePost response for creating milestone
ctx.Data["PageIsMilestones"] = true ctx.Data["PageIsMilestones"] = true


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, tplMilestoneNew)
ctx.HTML(http.StatusOK, tplMilestoneNew)
return return
} }


if len(m.DeadlineString) > 0 { if len(m.DeadlineString) > 0 {
ctx.Data["deadline"] = m.DeadlineString ctx.Data["deadline"] = m.DeadlineString
} }
ctx.HTML(200, tplMilestoneNew)
ctx.HTML(http.StatusOK, tplMilestoneNew)
} }


// EditMilestonePost response for edting milestone // EditMilestonePost response for edting milestone
ctx.Data["PageIsEditMilestone"] = true ctx.Data["PageIsEditMilestone"] = true


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, tplMilestoneNew)
ctx.HTML(http.StatusOK, tplMilestoneNew)
return return
} }


ctx.Flash.Success(ctx.Tr("repo.milestones.deletion_success")) ctx.Flash.Success(ctx.Tr("repo.milestones.deletion_success"))
} }


ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"redirect": ctx.Repo.RepoLink + "/milestones", "redirect": ctx.Repo.RepoLink + "/milestones",
}) })
} }
ctx.Data["CanWriteIssues"] = ctx.Repo.CanWriteIssuesOrPulls(false) ctx.Data["CanWriteIssues"] = ctx.Repo.CanWriteIssuesOrPulls(false)
ctx.Data["CanWritePulls"] = ctx.Repo.CanWriteIssuesOrPulls(true) ctx.Data["CanWritePulls"] = ctx.Repo.CanWriteIssuesOrPulls(true)


ctx.HTML(200, tplMilestoneIssues)
ctx.HTML(http.StatusOK, tplMilestoneIssues)
} }

+ 27
- 26
routers/repo/projects.go View File



import ( import (
"fmt" "fmt"
"net/http"
"strings" "strings"


"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
ctx.Data["IsProjectsPage"] = true ctx.Data["IsProjectsPage"] = true
ctx.Data["SortType"] = sortType ctx.Data["SortType"] = sortType


ctx.HTML(200, tplProjects)
ctx.HTML(http.StatusOK, tplProjects)
} }


// NewProject render creating a project page // NewProject render creating a project page
ctx.Data["Title"] = ctx.Tr("repo.projects.new") ctx.Data["Title"] = ctx.Tr("repo.projects.new")
ctx.Data["ProjectTypes"] = models.GetProjectsConfig() ctx.Data["ProjectTypes"] = models.GetProjectsConfig()
ctx.Data["CanWriteProjects"] = ctx.Repo.Permission.CanWrite(models.UnitTypeProjects) ctx.Data["CanWriteProjects"] = ctx.Repo.Permission.CanWrite(models.UnitTypeProjects)
ctx.HTML(200, tplProjectsNew)
ctx.HTML(http.StatusOK, tplProjectsNew)
} }


// NewProjectPost creates a new project // NewProjectPost creates a new project
if ctx.HasError() { if ctx.HasError() {
ctx.Data["CanWriteProjects"] = ctx.Repo.Permission.CanWrite(models.UnitTypeProjects) ctx.Data["CanWriteProjects"] = ctx.Repo.Permission.CanWrite(models.UnitTypeProjects)
ctx.Data["ProjectTypes"] = models.GetProjectsConfig() ctx.Data["ProjectTypes"] = models.GetProjectsConfig()
ctx.HTML(200, tplProjectsNew)
ctx.HTML(http.StatusOK, tplProjectsNew)
return return
} }


ctx.Flash.Success(ctx.Tr("repo.projects.deletion_success")) ctx.Flash.Success(ctx.Tr("repo.projects.deletion_success"))
} }


ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"redirect": ctx.Repo.RepoLink + "/projects", "redirect": ctx.Repo.RepoLink + "/projects",
}) })
} }
ctx.Data["title"] = p.Title ctx.Data["title"] = p.Title
ctx.Data["content"] = p.Description ctx.Data["content"] = p.Description


ctx.HTML(200, tplProjectsNew)
ctx.HTML(http.StatusOK, tplProjectsNew)
} }


// EditProjectPost response for editing a project // EditProjectPost response for editing a project
ctx.Data["CanWriteProjects"] = ctx.Repo.Permission.CanWrite(models.UnitTypeProjects) ctx.Data["CanWriteProjects"] = ctx.Repo.Permission.CanWrite(models.UnitTypeProjects)


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, tplProjectsNew)
ctx.HTML(http.StatusOK, tplProjectsNew)
return return
} }


ctx.Data["PageIsProjects"] = true ctx.Data["PageIsProjects"] = true
ctx.Data["RequiresDraggable"] = true ctx.Data["RequiresDraggable"] = true


ctx.HTML(200, tplProjectsView)
ctx.HTML(http.StatusOK, tplProjectsView)
} }


// UpdateIssueProject change an issue's project // UpdateIssueProject change an issue's project
} }
} }


ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"ok": true, "ok": true,
}) })
} }
// DeleteProjectBoard allows for the deletion of a project board // DeleteProjectBoard allows for the deletion of a project board
func DeleteProjectBoard(ctx *context.Context) { func DeleteProjectBoard(ctx *context.Context) {
if ctx.User == nil { if ctx.User == nil {
ctx.JSON(403, map[string]string{
ctx.JSON(http.StatusForbidden, map[string]string{
"message": "Only signed in users are allowed to perform this action.", "message": "Only signed in users are allowed to perform this action.",
}) })
return return
} }


if !ctx.Repo.IsOwner() && !ctx.Repo.IsAdmin() && !ctx.Repo.CanAccess(models.AccessModeWrite, models.UnitTypeProjects) { if !ctx.Repo.IsOwner() && !ctx.Repo.IsAdmin() && !ctx.Repo.CanAccess(models.AccessModeWrite, models.UnitTypeProjects) {
ctx.JSON(403, map[string]string{
ctx.JSON(http.StatusForbidden, map[string]string{
"message": "Only authorized users are allowed to perform this action.", "message": "Only authorized users are allowed to perform this action.",
}) })
return return
return return
} }
if pb.ProjectID != ctx.ParamsInt64(":id") { if pb.ProjectID != ctx.ParamsInt64(":id") {
ctx.JSON(422, map[string]string{
ctx.JSON(http.StatusUnprocessableEntity, map[string]string{
"message": fmt.Sprintf("ProjectBoard[%d] is not in Project[%d] as expected", pb.ID, project.ID), "message": fmt.Sprintf("ProjectBoard[%d] is not in Project[%d] as expected", pb.ID, project.ID),
}) })
return return
} }


if project.RepoID != ctx.Repo.Repository.ID { if project.RepoID != ctx.Repo.Repository.ID {
ctx.JSON(422, map[string]string{
ctx.JSON(http.StatusUnprocessableEntity, map[string]string{
"message": fmt.Sprintf("ProjectBoard[%d] is not in Repository[%d] as expected", pb.ID, ctx.Repo.Repository.ID), "message": fmt.Sprintf("ProjectBoard[%d] is not in Repository[%d] as expected", pb.ID, ctx.Repo.Repository.ID),
}) })
return return
return return
} }


ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"ok": true, "ok": true,
}) })
} }
func AddBoardToProjectPost(ctx *context.Context) { func AddBoardToProjectPost(ctx *context.Context) {
form := web.GetForm(ctx).(*auth.EditProjectBoardForm) form := web.GetForm(ctx).(*auth.EditProjectBoardForm)
if !ctx.Repo.IsOwner() && !ctx.Repo.IsAdmin() && !ctx.Repo.CanAccess(models.AccessModeWrite, models.UnitTypeProjects) { if !ctx.Repo.IsOwner() && !ctx.Repo.IsAdmin() && !ctx.Repo.CanAccess(models.AccessModeWrite, models.UnitTypeProjects) {
ctx.JSON(403, map[string]string{
ctx.JSON(http.StatusForbidden, map[string]string{
"message": "Only authorized users are allowed to perform this action.", "message": "Only authorized users are allowed to perform this action.",
}) })
return return
return return
} }


ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"ok": true, "ok": true,
}) })
} }


func checkProjectBoardChangePermissions(ctx *context.Context) (*models.Project, *models.ProjectBoard) { func checkProjectBoardChangePermissions(ctx *context.Context) (*models.Project, *models.ProjectBoard) {
if ctx.User == nil { if ctx.User == nil {
ctx.JSON(403, map[string]string{
ctx.JSON(http.StatusForbidden, map[string]string{
"message": "Only signed in users are allowed to perform this action.", "message": "Only signed in users are allowed to perform this action.",
}) })
return nil, nil return nil, nil
} }


if !ctx.Repo.IsOwner() && !ctx.Repo.IsAdmin() && !ctx.Repo.CanAccess(models.AccessModeWrite, models.UnitTypeProjects) { if !ctx.Repo.IsOwner() && !ctx.Repo.IsAdmin() && !ctx.Repo.CanAccess(models.AccessModeWrite, models.UnitTypeProjects) {
ctx.JSON(403, map[string]string{
ctx.JSON(http.StatusForbidden, map[string]string{
"message": "Only authorized users are allowed to perform this action.", "message": "Only authorized users are allowed to perform this action.",
}) })
return nil, nil return nil, nil
return nil, nil return nil, nil
} }
if board.ProjectID != ctx.ParamsInt64(":id") { if board.ProjectID != ctx.ParamsInt64(":id") {
ctx.JSON(422, map[string]string{
ctx.JSON(http.StatusUnprocessableEntity, map[string]string{
"message": fmt.Sprintf("ProjectBoard[%d] is not in Project[%d] as expected", board.ID, project.ID), "message": fmt.Sprintf("ProjectBoard[%d] is not in Project[%d] as expected", board.ID, project.ID),
}) })
return nil, nil return nil, nil
} }


if project.RepoID != ctx.Repo.Repository.ID { if project.RepoID != ctx.Repo.Repository.ID {
ctx.JSON(422, map[string]string{
ctx.JSON(http.StatusUnprocessableEntity, map[string]string{
"message": fmt.Sprintf("ProjectBoard[%d] is not in Repository[%d] as expected", board.ID, ctx.Repo.Repository.ID), "message": fmt.Sprintf("ProjectBoard[%d] is not in Repository[%d] as expected", board.ID, ctx.Repo.Repository.ID),
}) })
return nil, nil return nil, nil
return return
} }


ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"ok": true, "ok": true,
}) })
} }
return return
} }


ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"ok": true, "ok": true,
}) })
} }
func MoveIssueAcrossBoards(ctx *context.Context) { func MoveIssueAcrossBoards(ctx *context.Context) {


if ctx.User == nil { if ctx.User == nil {
ctx.JSON(403, map[string]string{
ctx.JSON(http.StatusForbidden, map[string]string{
"message": "Only signed in users are allowed to perform this action.", "message": "Only signed in users are allowed to perform this action.",
}) })
return return
} }


if !ctx.Repo.IsOwner() && !ctx.Repo.IsAdmin() && !ctx.Repo.CanAccess(models.AccessModeWrite, models.UnitTypeProjects) { if !ctx.Repo.IsOwner() && !ctx.Repo.IsAdmin() && !ctx.Repo.CanAccess(models.AccessModeWrite, models.UnitTypeProjects) {
ctx.JSON(403, map[string]string{
ctx.JSON(http.StatusForbidden, map[string]string{
"message": "Only authorized users are allowed to perform this action.", "message": "Only authorized users are allowed to perform this action.",
}) })
return return
return return
} }


ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"ok": true, "ok": true,
}) })
} }
ctx.Data["ProjectTypes"] = models.GetProjectsConfig() ctx.Data["ProjectTypes"] = models.GetProjectsConfig()
ctx.Data["CanWriteProjects"] = ctx.Repo.Permission.CanWrite(models.UnitTypeProjects) ctx.Data["CanWriteProjects"] = ctx.Repo.Permission.CanWrite(models.UnitTypeProjects)


ctx.HTML(200, tplGenericProjectsNew)
ctx.HTML(http.StatusOK, tplGenericProjectsNew)
} }


// CreateProjectPost creates an individual and/or organization project // CreateProjectPost creates an individual and/or organization project


if ctx.HasError() { if ctx.HasError() {
ctx.Data["CanWriteProjects"] = ctx.Repo.Permission.CanWrite(models.UnitTypeProjects) ctx.Data["CanWriteProjects"] = ctx.Repo.Permission.CanWrite(models.UnitTypeProjects)
ctx.HTML(200, tplGenericProjectsNew)
ctx.HTML(http.StatusOK, tplGenericProjectsNew)
return return
} }



+ 11
- 11
routers/repo/pull.go View File

return return
} }


ctx.HTML(200, tplFork)
ctx.HTML(http.StatusOK, tplFork)
} }


// ForkPost response for forking a repository // ForkPost response for forking a repository
ctx.Data["ContextUser"] = ctxUser ctx.Data["ContextUser"] = ctxUser


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, tplFork)
ctx.HTML(http.StatusOK, tplFork)
return return
} }


ctx.ServerError("IsOwnedBy", err) ctx.ServerError("IsOwnedBy", err)
return return
} else if !isOwner { } else if !isOwner {
ctx.Error(403)
ctx.Error(http.StatusForbidden)
return return
} }
} }
ctx.Data["CommitCount"] = commits.Len() ctx.Data["CommitCount"] = commits.Len()


getBranchData(ctx, issue) getBranchData(ctx, issue)
ctx.HTML(200, tplPullCommits)
ctx.HTML(http.StatusOK, tplPullCommits)
} }


// ViewPullFiles render pull request changed files list page // ViewPullFiles render pull request changed files list page
getBranchData(ctx, issue) getBranchData(ctx, issue)
ctx.Data["IsIssuePoster"] = ctx.IsSigned && issue.IsPoster(ctx.User.ID) ctx.Data["IsIssuePoster"] = ctx.IsSigned && issue.IsPoster(ctx.User.ID)
ctx.Data["HasIssuesOrPullsWritePermission"] = ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull) ctx.Data["HasIssuesOrPullsWritePermission"] = ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull)
ctx.HTML(200, tplPullFiles)
ctx.HTML(http.StatusOK, tplPullFiles)
} }


// UpdatePullRequest merge PR's baseBranch into headBranch // UpdatePullRequest merge PR's baseBranch into headBranch
return return
} }


ctx.HTML(200, tplCompareDiff)
ctx.HTML(http.StatusOK, tplCompareDiff)
return return
} }




if err := pull_service.NewPullRequest(repo, pullIssue, labelIDs, attachments, pullRequest, assigneeIDs); err != nil { if err := pull_service.NewPullRequest(repo, pullIssue, labelIDs, attachments, pullRequest, assigneeIDs); err != nil {
if models.IsErrUserDoesNotHaveAccessToRepo(err) { if models.IsErrUserDoesNotHaveAccessToRepo(err) {
ctx.Error(400, "UserDoesNotHaveAccessToRepo", err.Error())
ctx.Error(http.StatusBadRequest, "UserDoesNotHaveAccessToRepo", err.Error())
return return
} else if git.IsErrPushRejected(err) { } else if git.IsErrPushRejected(err) {
pushrejErr := err.(*git.ErrPushRejected) pushrejErr := err.(*git.ErrPushRejected)
branch := ctx.Query("branch") branch := ctx.Query("branch")
secret := ctx.Query("secret") secret := ctx.Query("secret")
if len(branch) == 0 || len(secret) == 0 || pusherID <= 0 { if len(branch) == 0 || len(secret) == 0 || pusherID <= 0 {
ctx.Error(404)
ctx.Error(http.StatusNotFound)
log.Trace("TriggerTask: branch or secret is empty, or pusher ID is not valid") log.Trace("TriggerTask: branch or secret is empty, or pusher ID is not valid")
return return
} }
got := []byte(base.EncodeMD5(owner.Salt)) got := []byte(base.EncodeMD5(owner.Salt))
want := []byte(secret) want := []byte(secret)
if subtle.ConstantTimeCompare(got, want) != 1 { if subtle.ConstantTimeCompare(got, want) != 1 {
ctx.Error(404)
ctx.Error(http.StatusNotFound)
log.Trace("TriggerTask [%s/%s]: invalid secret", owner.Name, repo.Name) log.Trace("TriggerTask [%s/%s]: invalid secret", owner.Name, repo.Name)
return return
} }
pusher, err := models.GetUserByID(pusherID) pusher, err := models.GetUserByID(pusherID)
if err != nil { if err != nil {
if models.IsErrUserNotExist(err) { if models.IsErrUserNotExist(err) {
ctx.Error(404)
ctx.Error(http.StatusNotFound)
} else { } else {
ctx.ServerError("GetUserByID", err) ctx.ServerError("GetUserByID", err)
} }
defer gitBaseRepo.Close() defer gitBaseRepo.Close()


defer func() { defer func() {
ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"redirect": pr.BaseRepo.Link() + "/pulls/" + fmt.Sprint(issue.Index), "redirect": pr.BaseRepo.Link() + "/pulls/" + fmt.Sprint(issue.Index),
}) })
}() }()

+ 7
- 6
routers/repo/pull_review.go View File



import ( import (
"fmt" "fmt"
"net/http"


"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/base"
return return
} }
ctx.Data["AfterCommitID"] = pullHeadCommitID ctx.Data["AfterCommitID"] = pullHeadCommitID
ctx.HTML(200, tplNewComment)
ctx.HTML(http.StatusOK, tplNewComment)
} }


// CreateCodeComment will create a code comment including an pending review if required // CreateCodeComment will create a code comment including an pending review if required
return return
} }
if !permResult { if !permResult {
ctx.Error(403)
ctx.Error(http.StatusForbidden)
return return
} }


if !comment.Issue.IsPull { if !comment.Issue.IsPull {
ctx.Error(400)
ctx.Error(http.StatusBadRequest)
return return
} }


return return
} }
} else { } else {
ctx.Error(400)
ctx.Error(http.StatusBadRequest)
return return
} }


renderConversation(ctx, comment) renderConversation(ctx, comment)
return return
} }
ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"ok": true, "ok": true,
}) })
} }
return return
} }
ctx.Data["AfterCommitID"] = pullHeadCommitID ctx.Data["AfterCommitID"] = pullHeadCommitID
ctx.HTML(200, tplConversation)
ctx.HTML(http.StatusOK, tplConversation)
} }


// SubmitReview creates a review out of the existing pending review or creates a new one if no pending review exist // SubmitReview creates a review out of the existing pending review or creates a new one if no pending review exist

+ 9
- 8
routers/repo/release.go View File



import ( import (
"fmt" "fmt"
"net/http"
"strings" "strings"


"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
pager.SetDefaultParams(ctx) pager.SetDefaultParams(ctx)
ctx.Data["Page"] = pager ctx.Data["Page"] = pager


ctx.HTML(200, tplReleases)
ctx.HTML(http.StatusOK, tplReleases)
} }


// SingleRelease renders a single release's page // SingleRelease renders a single release's page
release.Note = markdown.RenderString(release.Note, ctx.Repo.RepoLink, ctx.Repo.Repository.ComposeMetas()) release.Note = markdown.RenderString(release.Note, ctx.Repo.RepoLink, ctx.Repo.Repository.ComposeMetas())


ctx.Data["Releases"] = []*models.Release{release} ctx.Data["Releases"] = []*models.Release{release}
ctx.HTML(200, tplReleases)
ctx.HTML(http.StatusOK, tplReleases)
} }


// LatestRelease redirects to the latest release // LatestRelease redirects to the latest release
} }
ctx.Data["IsAttachmentEnabled"] = setting.Attachment.Enabled ctx.Data["IsAttachmentEnabled"] = setting.Attachment.Enabled
upload.AddUploadContext(ctx, "release") upload.AddUploadContext(ctx, "release")
ctx.HTML(200, tplReleaseNew)
ctx.HTML(http.StatusOK, tplReleaseNew)
} }


// NewReleasePost response for creating a release // NewReleasePost response for creating a release
ctx.Data["RequireTribute"] = true ctx.Data["RequireTribute"] = true


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, tplReleaseNew)
ctx.HTML(http.StatusOK, tplReleaseNew)
return return
} }


} }
ctx.Data["attachments"] = rel.Attachments ctx.Data["attachments"] = rel.Attachments


ctx.HTML(200, tplReleaseNew)
ctx.HTML(http.StatusOK, tplReleaseNew)
} }


// EditReleasePost response for edit release // EditReleasePost response for edit release
ctx.Data["prerelease"] = rel.IsPrerelease ctx.Data["prerelease"] = rel.IsPrerelease


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, tplReleaseNew)
ctx.HTML(http.StatusOK, tplReleaseNew)
return return
} }


} }


if isDelTag { if isDelTag {
ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"redirect": ctx.Repo.RepoLink + "/tags", "redirect": ctx.Repo.RepoLink + "/tags",
}) })
return return
} }


ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"redirect": ctx.Repo.RepoLink + "/releases", "redirect": ctx.Repo.RepoLink + "/releases",
}) })
} }

+ 13
- 12
routers/repo/repo.go View File

import ( import (
"errors" "errors"
"fmt" "fmt"
"net/http"
"strings" "strings"
"time" "time"




// Check ownership of organization. // Check ownership of organization.
if !org.IsOrganization() { if !org.IsOrganization() {
ctx.Error(403)
ctx.Error(http.StatusForbidden)
return nil return nil
} }
if !ctx.User.IsAdmin { if !ctx.User.IsAdmin {
ctx.ServerError("CanCreateOrgRepo", err) ctx.ServerError("CanCreateOrgRepo", err)
return nil return nil
} else if !canCreate { } else if !canCreate {
ctx.Error(403)
ctx.Error(http.StatusForbidden)
return nil return nil
} }
} else { } else {
ctx.Data["CanCreateRepo"] = ctx.User.CanCreateRepo() ctx.Data["CanCreateRepo"] = ctx.User.CanCreateRepo()
ctx.Data["MaxCreationLimit"] = ctx.User.MaxCreationLimit() ctx.Data["MaxCreationLimit"] = ctx.User.MaxCreationLimit()


ctx.HTML(200, tplCreate)
ctx.HTML(http.StatusOK, tplCreate)
} }


func handleCreateError(ctx *context.Context, owner *models.User, err error, name string, tpl base.TplName, form interface{}) { func handleCreateError(ctx *context.Context, owner *models.User, err error, name string, tpl base.TplName, form interface{}) {
ctx.Data["ContextUser"] = ctxUser ctx.Data["ContextUser"] = ctxUser


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, tplCreate)
ctx.HTML(http.StatusOK, tplCreate)
return return
} }


err = acceptOrRejectRepoTransfer(ctx, false) err = acceptOrRejectRepoTransfer(ctx, false)
case "desc": // FIXME: this is not used case "desc": // FIXME: this is not used
if !ctx.Repo.IsOwner() { if !ctx.Repo.IsOwner() {
ctx.Error(404)
ctx.Error(http.StatusNotFound)
return return
} }


releases, err := models.GetReleasesByRepoIDAndNames(models.DefaultDBContext(), curRepo.ID, tagNames) releases, err := models.GetReleasesByRepoIDAndNames(models.DefaultDBContext(), curRepo.ID, tagNames)
if err != nil { if err != nil {
if models.IsErrAttachmentNotExist(err) { if models.IsErrAttachmentNotExist(err) {
ctx.Error(404)
ctx.Error(http.StatusNotFound)
return return
} }
ctx.ServerError("RedirectDownload", err) ctx.ServerError("RedirectDownload", err)
release := releases[0] release := releases[0]
att, err := models.GetAttachmentByReleaseIDFileName(release.ID, fileName) att, err := models.GetAttachmentByReleaseIDFileName(release.ID, fileName)
if err != nil { if err != nil {
ctx.Error(404)
ctx.Error(http.StatusNotFound)
return return
} }
if att != nil { if att != nil {
return return
} }
} }
ctx.Error(404)
ctx.Error(http.StatusNotFound)
} }


// Download an archive of a repository // Download an archive of a repository
aReq := archiver_service.DeriveRequestFrom(ctx, uri) aReq := archiver_service.DeriveRequestFrom(ctx, uri)


if aReq == nil { if aReq == nil {
ctx.Error(404)
ctx.Error(http.StatusNotFound)
return return
} }


if complete { if complete {
ctx.ServeFile(aReq.GetArchivePath(), downloadName) ctx.ServeFile(aReq.GetArchivePath(), downloadName)
} else { } else {
ctx.Error(404)
ctx.Error(http.StatusNotFound)
} }
} }


aReq := archiver_service.DeriveRequestFrom(ctx, uri) aReq := archiver_service.DeriveRequestFrom(ctx, uri)


if aReq == nil { if aReq == nil {
ctx.Error(404)
ctx.Error(http.StatusNotFound)
return return
} }


complete, _ = aReq.TimedWaitForCompletion(ctx, 2*time.Second) complete, _ = aReq.TimedWaitForCompletion(ctx, 2*time.Second)
} }


ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"complete": complete, "complete": complete,
}) })
} }

+ 2
- 1
routers/repo/search.go View File

package repo package repo


import ( import (
"net/http"
"path" "path"
"strings" "strings"


pager.AddParam(ctx, "l", "Language") pager.AddParam(ctx, "l", "Language")
ctx.Data["Page"] = pager ctx.Data["Page"] = pager


ctx.HTML(200, tplSearch)
ctx.HTML(http.StatusOK, tplSearch)
} }

+ 22
- 21
routers/repo/setting.go View File

"errors" "errors"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"net/http"
"strings" "strings"
"time" "time"


ctx.Data["SigningKeyAvailable"] = len(signing) > 0 ctx.Data["SigningKeyAvailable"] = len(signing) > 0
ctx.Data["SigningSettings"] = setting.Repository.Signing ctx.Data["SigningSettings"] = setting.Repository.Signing


ctx.HTML(200, tplSettingsOptions)
ctx.HTML(http.StatusOK, tplSettingsOptions)
} }


// SettingsPost response for changes of a repository // SettingsPost response for changes of a repository
switch ctx.Query("action") { switch ctx.Query("action") {
case "update": case "update":
if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, tplSettingsOptions)
ctx.HTML(http.StatusOK, tplSettingsOptions)
return return
} }




case "admin": case "admin":
if !ctx.User.IsAdmin { if !ctx.User.IsAdmin {
ctx.Error(403)
ctx.Error(http.StatusForbidden)
return return
} }




case "convert": case "convert":
if !ctx.Repo.IsOwner() { if !ctx.Repo.IsOwner() {
ctx.Error(404)
ctx.Error(http.StatusNotFound)
return return
} }
if repo.Name != form.RepoName { if repo.Name != form.RepoName {
} }


if !repo.IsMirror { if !repo.IsMirror {
ctx.Error(404)
ctx.Error(http.StatusNotFound)
return return
} }
repo.IsMirror = false repo.IsMirror = false


case "convert_fork": case "convert_fork":
if !ctx.Repo.IsOwner() { if !ctx.Repo.IsOwner() {
ctx.Error(404)
ctx.Error(http.StatusNotFound)
return return
} }
if err := repo.GetOwner(); err != nil { if err := repo.GetOwner(); err != nil {
} }


if !repo.IsFork { if !repo.IsFork {
ctx.Error(404)
ctx.Error(http.StatusNotFound)
return return
} }




case "transfer": case "transfer":
if !ctx.Repo.IsOwner() { if !ctx.Repo.IsOwner() {
ctx.Error(404)
ctx.Error(http.StatusNotFound)
return return
} }
if repo.Name != form.RepoName { if repo.Name != form.RepoName {


case "cancel_transfer": case "cancel_transfer":
if !ctx.Repo.IsOwner() { if !ctx.Repo.IsOwner() {
ctx.Error(404)
ctx.Error(http.StatusNotFound)
return return
} }




case "delete": case "delete":
if !ctx.Repo.IsOwner() { if !ctx.Repo.IsOwner() {
ctx.Error(404)
ctx.Error(http.StatusNotFound)
return return
} }
if repo.Name != form.RepoName { if repo.Name != form.RepoName {


case "delete-wiki": case "delete-wiki":
if !ctx.Repo.IsOwner() { if !ctx.Repo.IsOwner() {
ctx.Error(404)
ctx.Error(http.StatusNotFound)
return return
} }
if repo.Name != form.RepoName { if repo.Name != form.RepoName {


case "archive": case "archive":
if !ctx.Repo.IsOwner() { if !ctx.Repo.IsOwner() {
ctx.Error(403)
ctx.Error(http.StatusForbidden)
return return
} }


ctx.Redirect(ctx.Repo.RepoLink + "/settings") ctx.Redirect(ctx.Repo.RepoLink + "/settings")
case "unarchive": case "unarchive":
if !ctx.Repo.IsOwner() { if !ctx.Repo.IsOwner() {
ctx.Error(403)
ctx.Error(http.StatusForbidden)
return return
} }


ctx.Data["Org"] = ctx.Repo.Repository.Owner ctx.Data["Org"] = ctx.Repo.Repository.Owner
ctx.Data["Units"] = models.Units ctx.Data["Units"] = models.Units


ctx.HTML(200, tplCollaboration)
ctx.HTML(http.StatusOK, tplCollaboration)
} }


// CollaborationPost response for actions for a collaboration of a repository // CollaborationPost response for actions for a collaboration of a repository
ctx.Flash.Success(ctx.Tr("repo.settings.remove_collaborator_success")) ctx.Flash.Success(ctx.Tr("repo.settings.remove_collaborator_success"))
} }


ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"redirect": ctx.Repo.RepoLink + "/settings/collaboration", "redirect": ctx.Repo.RepoLink + "/settings/collaboration",
}) })
} }
} }


ctx.Flash.Success(ctx.Tr("repo.settings.remove_team_success")) ctx.Flash.Success(ctx.Tr("repo.settings.remove_team_success"))
ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"redirect": ctx.Repo.RepoLink + "/settings/collaboration", "redirect": ctx.Repo.RepoLink + "/settings/collaboration",
}) })
} }
} }
ctx.Data["Hooks"] = hooks ctx.Data["Hooks"] = hooks


ctx.HTML(200, tplGithooks)
ctx.HTML(http.StatusOK, tplGithooks)
} }


// GitHooksEdit render for editing a hook of repository page // GitHooksEdit render for editing a hook of repository page
return return
} }
ctx.Data["Hook"] = hook ctx.Data["Hook"] = hook
ctx.HTML(200, tplGithookEdit)
ctx.HTML(http.StatusOK, tplGithookEdit)
} }


// GitHooksEditPost response for editing a git hook of a repository // GitHooksEditPost response for editing a git hook of a repository
} }
ctx.Data["Deploykeys"] = keys ctx.Data["Deploykeys"] = keys


ctx.HTML(200, tplDeployKeys)
ctx.HTML(http.StatusOK, tplDeployKeys)
} }


// DeployKeysPost response for adding a deploy key of a repository // DeployKeysPost response for adding a deploy key of a repository
ctx.Data["Deploykeys"] = keys ctx.Data["Deploykeys"] = keys


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, tplDeployKeys)
ctx.HTML(http.StatusOK, tplDeployKeys)
return return
} }


ctx.Flash.Success(ctx.Tr("repo.settings.deploy_key_deletion_success")) ctx.Flash.Success(ctx.Tr("repo.settings.deploy_key_deletion_success"))
} }


ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"redirect": ctx.Repo.RepoLink + "/settings/keys", "redirect": ctx.Repo.RepoLink + "/settings/keys",
}) })
} }

+ 4
- 3
routers/repo/setting_protected_branch.go View File



import ( import (
"fmt" "fmt"
"net/http"
"strings" "strings"
"time" "time"




ctx.Data["LeftBranches"] = leftBranches ctx.Data["LeftBranches"] = leftBranches


ctx.HTML(200, tplBranches)
ctx.HTML(http.StatusOK, tplBranches)
} }


// ProtectedBranchPost response for protect for a branch of a repository // ProtectedBranchPost response for protect for a branch of a repository
switch ctx.Query("action") { switch ctx.Query("action") {
case "default_branch": case "default_branch":
if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, tplBranches)
ctx.HTML(http.StatusOK, tplBranches)
return return
} }


} }


c.Data["Branch"] = protectBranch c.Data["Branch"] = protectBranch
c.HTML(200, tplProtectedBranch)
c.HTML(http.StatusOK, tplProtectedBranch)
} }


// SettingsProtectedBranchPost updates the protected branch settings // SettingsProtectedBranchPost updates the protected branch settings

+ 6
- 5
routers/repo/topic.go View File

package repo package repo


import ( import (
"net/http"
"strings" "strings"


"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
// TopicsPost response for creating repository // TopicsPost response for creating repository
func TopicsPost(ctx *context.Context) { func TopicsPost(ctx *context.Context) {
if ctx.User == nil { if ctx.User == nil {
ctx.JSON(403, map[string]interface{}{
ctx.JSON(http.StatusForbidden, map[string]interface{}{
"message": "Only owners could change the topics.", "message": "Only owners could change the topics.",
}) })
return return
validTopics, invalidTopics := models.SanitizeAndValidateTopics(topics) validTopics, invalidTopics := models.SanitizeAndValidateTopics(topics)


if len(validTopics) > 25 { if len(validTopics) > 25 {
ctx.JSON(422, map[string]interface{}{
ctx.JSON(http.StatusUnprocessableEntity, map[string]interface{}{
"invalidTopics": nil, "invalidTopics": nil,
"message": ctx.Tr("repo.topic.count_prompt"), "message": ctx.Tr("repo.topic.count_prompt"),
}) })
} }


if len(invalidTopics) > 0 { if len(invalidTopics) > 0 {
ctx.JSON(422, map[string]interface{}{
ctx.JSON(http.StatusUnprocessableEntity, map[string]interface{}{
"invalidTopics": invalidTopics, "invalidTopics": invalidTopics,
"message": ctx.Tr("repo.topic.format_prompt"), "message": ctx.Tr("repo.topic.format_prompt"),
}) })
err := models.SaveTopics(ctx.Repo.Repository.ID, validTopics...) err := models.SaveTopics(ctx.Repo.Repository.ID, validTopics...)
if err != nil { if err != nil {
log.Error("SaveTopics failed: %v", err) log.Error("SaveTopics failed: %v", err)
ctx.JSON(500, map[string]interface{}{
ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
"message": "Save topics failed.", "message": "Save topics failed.",
}) })
return return
} }


ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"status": "ok", "status": "ok",
}) })
} }

+ 6
- 5
routers/repo/view.go View File

gotemplate "html/template" gotemplate "html/template"
"io" "io"
"io/ioutil" "io/ioutil"
"net/http"
"net/url" "net/url"
"path" "path"
"strconv" "strconv"
ctx.Data["Repo"] = ctx.Repo ctx.Data["Repo"] = ctx.Repo
ctx.Data["MigrateTask"] = task ctx.Data["MigrateTask"] = task
ctx.Data["CloneAddr"] = safeURL(cfg.CloneAddr) ctx.Data["CloneAddr"] = safeURL(cfg.CloneAddr)
ctx.HTML(200, tplMigrating)
ctx.HTML(http.StatusOK, tplMigrating)
return return
} }


ctx.Data["PageIsViewCode"] = true ctx.Data["PageIsViewCode"] = true


if ctx.Repo.Repository.IsEmpty { if ctx.Repo.Repository.IsEmpty {
ctx.HTML(200, tplRepoEMPTY)
ctx.HTML(http.StatusOK, tplRepoEMPTY)
return return
} }


ctx.Data["TreeLink"] = treeLink ctx.Data["TreeLink"] = treeLink
ctx.Data["TreeNames"] = treeNames ctx.Data["TreeNames"] = treeNames
ctx.Data["BranchLink"] = branchLink ctx.Data["BranchLink"] = branchLink
ctx.HTML(200, tplRepoHome)
ctx.HTML(http.StatusOK, tplRepoHome)
} }


// RenderUserCards render a page show users according the input templaet // RenderUserCards render a page show users according the input templaet
} }
ctx.Data["Cards"] = items ctx.Data["Cards"] = items


ctx.HTML(200, tpl)
ctx.HTML(http.StatusOK, tpl)
} }


// Watchers render repository's watch users // Watchers render repository's watch users
} }
ctx.Data["Forks"] = forks ctx.Data["Forks"] = forks


ctx.HTML(200, tplForks)
ctx.HTML(http.StatusOK, tplForks)
} }

+ 23
- 22
routers/repo/webhook.go View File

import ( import (
"errors" "errors"
"fmt" "fmt"
"net/http"
"path" "path"
"strings" "strings"


} }
ctx.Data["Webhooks"] = ws ctx.Data["Webhooks"] = ws


ctx.HTML(200, tplHooks)
ctx.HTML(http.StatusOK, tplHooks)
} }


type orgRepoCtx struct { type orgRepoCtx struct {
} }
ctx.Data["BaseLink"] = orCtx.LinkNew ctx.Data["BaseLink"] = orCtx.LinkNew


ctx.HTML(200, orCtx.NewTemplate)
ctx.HTML(http.StatusOK, orCtx.NewTemplate)
} }


// ParseHookEvent convert web form content to models.HookEvent // ParseHookEvent convert web form content to models.HookEvent
ctx.Data["BaseLink"] = orCtx.LinkNew ctx.Data["BaseLink"] = orCtx.LinkNew


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, orCtx.NewTemplate)
ctx.HTML(http.StatusOK, orCtx.NewTemplate)
return return
} }


ctx.Data["BaseLink"] = orCtx.LinkNew ctx.Data["BaseLink"] = orCtx.LinkNew


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, orCtx.NewTemplate)
ctx.HTML(http.StatusOK, orCtx.NewTemplate)
return return
} }


} }


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, orCtx.NewTemplate)
ctx.HTML(http.StatusOK, orCtx.NewTemplate)
return return
} }


} }


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, orCtx.NewTemplate)
ctx.HTML(http.StatusOK, orCtx.NewTemplate)
return return
} }


} }


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, orCtx.NewTemplate)
ctx.HTML(http.StatusOK, orCtx.NewTemplate)
return return
} }


} }


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, orCtx.NewTemplate)
ctx.HTML(http.StatusOK, orCtx.NewTemplate)
return return
} }


} }


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, orCtx.NewTemplate)
ctx.HTML(http.StatusOK, orCtx.NewTemplate)
return return
} }


} }


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, orCtx.NewTemplate)
ctx.HTML(http.StatusOK, orCtx.NewTemplate)
return return
} }


} }


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, orCtx.NewTemplate)
ctx.HTML(http.StatusOK, orCtx.NewTemplate)
return return
} }


} }
ctx.Data["Webhook"] = w ctx.Data["Webhook"] = w


ctx.HTML(200, orCtx.NewTemplate)
ctx.HTML(http.StatusOK, orCtx.NewTemplate)
} }


// WebHooksEditPost response for editing web hook // WebHooksEditPost response for editing web hook
ctx.Data["Webhook"] = w ctx.Data["Webhook"] = w


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, orCtx.NewTemplate)
ctx.HTML(http.StatusOK, orCtx.NewTemplate)
return return
} }


ctx.Data["Webhook"] = w ctx.Data["Webhook"] = w


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, orCtx.NewTemplate)
ctx.HTML(http.StatusOK, orCtx.NewTemplate)
return return
} }


ctx.Data["Webhook"] = w ctx.Data["Webhook"] = w


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, orCtx.NewTemplate)
ctx.HTML(http.StatusOK, orCtx.NewTemplate)
return return
} }


ctx.Data["Webhook"] = w ctx.Data["Webhook"] = w


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, orCtx.NewTemplate)
ctx.HTML(http.StatusOK, orCtx.NewTemplate)
return return
} }


ctx.Data["Webhook"] = w ctx.Data["Webhook"] = w


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, orCtx.NewTemplate)
ctx.HTML(http.StatusOK, orCtx.NewTemplate)
return return
} }


ctx.Data["Webhook"] = w ctx.Data["Webhook"] = w


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, orCtx.NewTemplate)
ctx.HTML(http.StatusOK, orCtx.NewTemplate)
return return
} }
json := jsoniter.ConfigCompatibleWithStandardLibrary json := jsoniter.ConfigCompatibleWithStandardLibrary
ctx.Data["Webhook"] = w ctx.Data["Webhook"] = w


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, orCtx.NewTemplate)
ctx.HTML(http.StatusOK, orCtx.NewTemplate)
return return
} }
json := jsoniter.ConfigCompatibleWithStandardLibrary json := jsoniter.ConfigCompatibleWithStandardLibrary
ctx.Data["Webhook"] = w ctx.Data["Webhook"] = w


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, orCtx.NewTemplate)
ctx.HTML(http.StatusOK, orCtx.NewTemplate)
return return
} }


ctx.Data["Webhook"] = w ctx.Data["Webhook"] = w


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, orCtx.NewTemplate)
ctx.HTML(http.StatusOK, orCtx.NewTemplate)
return return
} }


ctx.Flash.Success(ctx.Tr("repo.settings.webhook_deletion_success")) ctx.Flash.Success(ctx.Tr("repo.settings.webhook_deletion_success"))
} }


ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"redirect": ctx.Repo.RepoLink + "/settings/hooks", "redirect": ctx.Repo.RepoLink + "/settings/hooks",
}) })
} }

+ 13
- 12
routers/repo/wiki.go View File

import ( import (
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"net/http"
"net/url" "net/url"
"path/filepath" "path/filepath"
"strings" "strings"


if !ctx.Repo.Repository.HasWiki() { if !ctx.Repo.Repository.HasWiki() {
ctx.Data["Title"] = ctx.Tr("repo.wiki") ctx.Data["Title"] = ctx.Tr("repo.wiki")
ctx.HTML(200, tplWikiStart)
ctx.HTML(http.StatusOK, tplWikiStart)
return return
} }


}() }()
if entry == nil { if entry == nil {
ctx.Data["Title"] = ctx.Tr("repo.wiki") ctx.Data["Title"] = ctx.Tr("repo.wiki")
ctx.HTML(200, tplWikiStart)
ctx.HTML(http.StatusOK, tplWikiStart)
return return
} }


} }
ctx.Data["Author"] = lastCommit.Author ctx.Data["Author"] = lastCommit.Author


ctx.HTML(200, tplWikiView)
ctx.HTML(http.StatusOK, tplWikiView)
} }


// WikiRevision renders file revision list of wiki page // WikiRevision renders file revision list of wiki page


if !ctx.Repo.Repository.HasWiki() { if !ctx.Repo.Repository.HasWiki() {
ctx.Data["Title"] = ctx.Tr("repo.wiki") ctx.Data["Title"] = ctx.Tr("repo.wiki")
ctx.HTML(200, tplWikiStart)
ctx.HTML(http.StatusOK, tplWikiStart)
return return
} }


}() }()
if entry == nil { if entry == nil {
ctx.Data["Title"] = ctx.Tr("repo.wiki") ctx.Data["Title"] = ctx.Tr("repo.wiki")
ctx.HTML(200, tplWikiStart)
ctx.HTML(http.StatusOK, tplWikiStart)
return return
} }


} }
ctx.Data["Author"] = lastCommit.Author ctx.Data["Author"] = lastCommit.Author


ctx.HTML(200, tplWikiRevision)
ctx.HTML(http.StatusOK, tplWikiRevision)
} }


// WikiPages render wiki pages list page // WikiPages render wiki pages list page
wikiRepo.Close() wikiRepo.Close()
} }
}() }()
ctx.HTML(200, tplWikiPages)
ctx.HTML(http.StatusOK, tplWikiPages)
} }


// WikiRaw outputs raw blob requested by user (image for example) // WikiRaw outputs raw blob requested by user (image for example)
ctx.Data["title"] = "Home" ctx.Data["title"] = "Home"
} }


ctx.HTML(200, tplWikiNew)
ctx.HTML(http.StatusOK, tplWikiNew)
} }


// NewWikiPost response for wiki create request // NewWikiPost response for wiki create request
ctx.Data["RequireSimpleMDE"] = true ctx.Data["RequireSimpleMDE"] = true


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, tplWikiNew)
ctx.HTML(http.StatusOK, tplWikiNew)
return return
} }


return return
} }


ctx.HTML(200, tplWikiNew)
ctx.HTML(http.StatusOK, tplWikiNew)
} }


// EditWikiPost response for wiki modify request // EditWikiPost response for wiki modify request
ctx.Data["RequireSimpleMDE"] = true ctx.Data["RequireSimpleMDE"] = true


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, tplWikiNew)
ctx.HTML(http.StatusOK, tplWikiNew)
return return
} }


return return
} }


ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"redirect": ctx.Repo.RepoLink + "/wiki/", "redirect": ctx.Repo.RepoLink + "/wiki/",
}) })
} }

+ 4
- 4
routers/routes/web.go View File



openIDSignInEnabled := func(ctx *context.Context) { openIDSignInEnabled := func(ctx *context.Context) {
if !setting.Service.EnableOpenIDSignIn { if !setting.Service.EnableOpenIDSignIn {
ctx.Error(403)
ctx.Error(http.StatusForbidden)
return return
} }
} }


openIDSignUpEnabled := func(ctx *context.Context) { openIDSignUpEnabled := func(ctx *context.Context) {
if !setting.Service.EnableOpenIDSignUp { if !setting.Service.EnableOpenIDSignUp {
ctx.Error(403)
ctx.Error(http.StatusForbidden)
return return
} }
} }


reqMilestonesDashboardPageEnabled := func(ctx *context.Context) { reqMilestonesDashboardPageEnabled := func(ctx *context.Context) {
if !setting.Service.ShowMilestonesDashboardPage { if !setting.Service.ShowMilestonesDashboardPage {
ctx.Error(403)
ctx.Error(http.StatusForbidden)
return return
} }
} }
// webhooksEnabled requires webhooks to be enabled by admin. // webhooksEnabled requires webhooks to be enabled by admin.
webhooksEnabled := func(ctx *context.Context) { webhooksEnabled := func(ctx *context.Context) {
if setting.DisableWebhooks { if setting.DisableWebhooks {
ctx.Error(403)
ctx.Error(http.StatusForbidden)
return return
} }
} }

+ 3
- 1
routers/swagger_json.go View File

package routers package routers


import ( import (
"net/http"

"code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/log"
ctx.Resp.Header().Set("Content-Type", "application/json") ctx.Resp.Header().Set("Content-Type", "application/json")
if err := t.Execute(ctx.Resp, ctx.Data); err != nil { if err := t.Execute(ctx.Resp, ctx.Data); err != nil {
log.Error("%v", err) log.Error("%v", err)
ctx.Error(500)
ctx.Error(http.StatusInternalServerError)
} }
} }

+ 34
- 34
routers/user/auth.go View File

ctx.Data["PageIsLogin"] = true ctx.Data["PageIsLogin"] = true
ctx.Data["EnableSSPI"] = models.IsSSPIEnabled() ctx.Data["EnableSSPI"] = models.IsSSPIEnabled()


ctx.HTML(200, tplSignIn)
ctx.HTML(http.StatusOK, tplSignIn)
} }


// SignInPost response for sign in request // SignInPost response for sign in request
ctx.Data["EnableSSPI"] = models.IsSSPIEnabled() ctx.Data["EnableSSPI"] = models.IsSSPIEnabled()


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, tplSignIn)
ctx.HTML(http.StatusOK, tplSignIn)
return return
} }


} else if models.IsErrUserProhibitLogin(err) { } else if models.IsErrUserProhibitLogin(err) {
log.Info("Failed authentication attempt for %s from %s: %v", form.UserName, ctx.RemoteAddr(), err) log.Info("Failed authentication attempt for %s from %s: %v", form.UserName, ctx.RemoteAddr(), err)
ctx.Data["Title"] = ctx.Tr("auth.prohibit_login") ctx.Data["Title"] = ctx.Tr("auth.prohibit_login")
ctx.HTML(200, "user/auth/prohibit_login")
ctx.HTML(http.StatusOK, "user/auth/prohibit_login")
} else if models.IsErrUserInactive(err) { } else if models.IsErrUserInactive(err) {
if setting.Service.RegisterEmailConfirm { if setting.Service.RegisterEmailConfirm {
ctx.Data["Title"] = ctx.Tr("auth.active_your_account") ctx.Data["Title"] = ctx.Tr("auth.active_your_account")
ctx.HTML(200, TplActivate)
ctx.HTML(http.StatusOK, TplActivate)
} else { } else {
log.Info("Failed authentication attempt for %s from %s: %v", form.UserName, ctx.RemoteAddr(), err) log.Info("Failed authentication attempt for %s from %s: %v", form.UserName, ctx.RemoteAddr(), err)
ctx.Data["Title"] = ctx.Tr("auth.prohibit_login") ctx.Data["Title"] = ctx.Tr("auth.prohibit_login")
ctx.HTML(200, "user/auth/prohibit_login")
ctx.HTML(http.StatusOK, "user/auth/prohibit_login")
} }
} else { } else {
ctx.ServerError("UserSignIn", err) ctx.ServerError("UserSignIn", err)
return return
} }


ctx.HTML(200, tplTwofa)
ctx.HTML(http.StatusOK, tplTwofa)
} }


// TwoFactorPost validates a user's two-factor authentication token. // TwoFactorPost validates a user's two-factor authentication token.
return return
} }


ctx.HTML(200, tplTwofaScratch)
ctx.HTML(http.StatusOK, tplTwofaScratch)
} }


// TwoFactorScratchPost validates and invalidates a user's two-factor scratch token. // TwoFactorScratchPost validates and invalidates a user's two-factor scratch token.
return return
} }


ctx.HTML(200, tplU2F)
ctx.HTML(http.StatusOK, tplU2F)
} }


// U2FChallenge submits a sign challenge to the browser // U2FChallenge submits a sign challenge to the browser
ctx.ServerError("UserSignIn: unable to store session", err) ctx.ServerError("UserSignIn: unable to store session", err)
} }


ctx.JSON(200, challenge.SignRequest(regs.ToRegistrations()))
ctx.JSON(http.StatusOK, challenge.SignRequest(regs.ToRegistrations()))
} }


// U2FSign authenticates the user by signResp // U2FSign authenticates the user by signResp
return return
} }
} }
ctx.Error(401)
ctx.Error(http.StatusUnauthorized)
} }


// This handles the final part of the sign-in process of the user. // This handles the final part of the sign-in process of the user.
} }
} }


ctx.HTML(200, tplLinkAccount)
ctx.HTML(http.StatusOK, tplLinkAccount)
} }


// LinkAccountPostSignIn handle the coupling of external account with another account using signIn // LinkAccountPostSignIn handle the coupling of external account with another account using signIn
} }


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, tplLinkAccount)
ctx.HTML(http.StatusOK, tplLinkAccount)
return return
} }


} }


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, tplLinkAccount)
ctx.HTML(http.StatusOK, tplLinkAccount)
return return
} }


if setting.Service.DisableRegistration { if setting.Service.DisableRegistration {
ctx.Error(403)
ctx.Error(http.StatusForbidden)
return return
} }


ctx.Data["IsSendRegisterMail"] = true ctx.Data["IsSendRegisterMail"] = true
ctx.Data["Email"] = u.Email ctx.Data["Email"] = u.Email
ctx.Data["ActiveCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale.Language()) ctx.Data["ActiveCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale.Language())
ctx.HTML(200, TplActivate)
ctx.HTML(http.StatusOK, TplActivate)


if err := ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil { if err := ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
log.Error("Set cache(MailResendLimit) fail: %v", err) log.Error("Set cache(MailResendLimit) fail: %v", err)
//Show Disabled Registration message if DisableRegistration or AllowOnlyExternalRegistration options are true //Show Disabled Registration message if DisableRegistration or AllowOnlyExternalRegistration options are true
ctx.Data["DisableRegistration"] = setting.Service.DisableRegistration || setting.Service.AllowOnlyExternalRegistration ctx.Data["DisableRegistration"] = setting.Service.DisableRegistration || setting.Service.AllowOnlyExternalRegistration


ctx.HTML(200, tplSignUp)
ctx.HTML(http.StatusOK, tplSignUp)
} }


// SignUpPost response for sign up information submission // SignUpPost response for sign up information submission


//Permission denied if DisableRegistration or AllowOnlyExternalRegistration options are true //Permission denied if DisableRegistration or AllowOnlyExternalRegistration options are true
if setting.Service.DisableRegistration || setting.Service.AllowOnlyExternalRegistration { if setting.Service.DisableRegistration || setting.Service.AllowOnlyExternalRegistration {
ctx.Error(403)
ctx.Error(http.StatusForbidden)
return return
} }


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, tplSignUp)
ctx.HTML(http.StatusOK, tplSignUp)
return return
} }


ctx.Data["IsSendRegisterMail"] = true ctx.Data["IsSendRegisterMail"] = true
ctx.Data["Email"] = u.Email ctx.Data["Email"] = u.Email
ctx.Data["ActiveCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale.Language()) ctx.Data["ActiveCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale.Language())
ctx.HTML(200, TplActivate)
ctx.HTML(http.StatusOK, TplActivate)


if err := ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil { if err := ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
log.Error("Set cache(MailResendLimit) fail: %v", err) log.Error("Set cache(MailResendLimit) fail: %v", err)
if len(code) == 0 { if len(code) == 0 {
ctx.Data["IsActivatePage"] = true ctx.Data["IsActivatePage"] = true
if ctx.User.IsActive { if ctx.User.IsActive {
ctx.Error(404)
ctx.Error(http.StatusNotFound)
return return
} }
// Resend confirmation email. // Resend confirmation email.
} else { } else {
ctx.Data["ServiceNotEnabled"] = true ctx.Data["ServiceNotEnabled"] = true
} }
ctx.HTML(200, TplActivate)
ctx.HTML(http.StatusOK, TplActivate)
return return
} }


// if code is wrong // if code is wrong
if user == nil { if user == nil {
ctx.Data["IsActivateFailed"] = true ctx.Data["IsActivateFailed"] = true
ctx.HTML(200, TplActivate)
ctx.HTML(http.StatusOK, TplActivate)
return return
} }


if len(password) == 0 { if len(password) == 0 {
ctx.Data["Code"] = code ctx.Data["Code"] = code
ctx.Data["NeedsPassword"] = true ctx.Data["NeedsPassword"] = true
ctx.HTML(200, TplActivate)
ctx.HTML(http.StatusOK, TplActivate)
return return
} }
if !user.ValidatePassword(password) { if !user.ValidatePassword(password) {
ctx.Data["IsActivateFailed"] = true ctx.Data["IsActivateFailed"] = true
ctx.HTML(200, TplActivate)
ctx.HTML(http.StatusOK, TplActivate)
return return
} }
} }
} }
if err := models.UpdateUserCols(user, "is_active", "rands"); err != nil { if err := models.UpdateUserCols(user, "is_active", "rands"); err != nil {
if models.IsErrUserNotExist(err) { if models.IsErrUserNotExist(err) {
ctx.Error(404)
ctx.Error(http.StatusNotFound)
} else { } else {
ctx.ServerError("UpdateUser", err) ctx.ServerError("UpdateUser", err)
} }


if setting.MailService == nil { if setting.MailService == nil {
ctx.Data["IsResetDisable"] = true ctx.Data["IsResetDisable"] = true
ctx.HTML(200, tplForgotPassword)
ctx.HTML(http.StatusOK, tplForgotPassword)
return return
} }


ctx.Data["Email"] = email ctx.Data["Email"] = email


ctx.Data["IsResetRequest"] = true ctx.Data["IsResetRequest"] = true
ctx.HTML(200, tplForgotPassword)
ctx.HTML(http.StatusOK, tplForgotPassword)
} }


// ForgotPasswdPost response for forget password request // ForgotPasswdPost response for forget password request
if models.IsErrUserNotExist(err) { if models.IsErrUserNotExist(err) {
ctx.Data["ResetPwdCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ResetPwdCodeLives, ctx.Locale.Language()) ctx.Data["ResetPwdCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ResetPwdCodeLives, ctx.Locale.Language())
ctx.Data["IsResetSent"] = true ctx.Data["IsResetSent"] = true
ctx.HTML(200, tplForgotPassword)
ctx.HTML(http.StatusOK, tplForgotPassword)
return return
} }




if ctx.Cache.IsExist("MailResendLimit_" + u.LowerName) { if ctx.Cache.IsExist("MailResendLimit_" + u.LowerName) {
ctx.Data["ResendLimited"] = true ctx.Data["ResendLimited"] = true
ctx.HTML(200, tplForgotPassword)
ctx.HTML(http.StatusOK, tplForgotPassword)
return return
} }




ctx.Data["ResetPwdCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ResetPwdCodeLives, ctx.Locale.Language()) ctx.Data["ResetPwdCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ResetPwdCodeLives, ctx.Locale.Language())
ctx.Data["IsResetSent"] = true ctx.Data["IsResetSent"] = true
ctx.HTML(200, tplForgotPassword)
ctx.HTML(http.StatusOK, tplForgotPassword)
} }


func commonResetPassword(ctx *context.Context) (*models.User, *models.TwoFactor) { func commonResetPassword(ctx *context.Context) (*models.User, *models.TwoFactor) {
return return
} }


ctx.HTML(200, tplResetPassword)
ctx.HTML(http.StatusOK, tplResetPassword)
} }


// ResetPasswdPost response from account recovery request // ResetPasswdPost response from account recovery request


if u == nil { if u == nil {
// Flash error has been set // Flash error has been set
ctx.HTML(200, tplResetPassword)
ctx.HTML(http.StatusOK, tplResetPassword)
return return
} }


ctx.Data["Title"] = ctx.Tr("auth.must_change_password") ctx.Data["Title"] = ctx.Tr("auth.must_change_password")
ctx.Data["ChangePasscodeLink"] = setting.AppSubURL + "/user/settings/change_password" ctx.Data["ChangePasscodeLink"] = setting.AppSubURL + "/user/settings/change_password"
ctx.Data["MustChangePassword"] = true ctx.Data["MustChangePassword"] = true
ctx.HTML(200, tplMustChangePassword)
ctx.HTML(http.StatusOK, tplMustChangePassword)
} }


// MustChangePasswordPost response for updating a user's password after his/her // MustChangePasswordPost response for updating a user's password after his/her
ctx.Data["Title"] = ctx.Tr("auth.must_change_password") ctx.Data["Title"] = ctx.Tr("auth.must_change_password")
ctx.Data["ChangePasscodeLink"] = setting.AppSubURL + "/user/settings/change_password" ctx.Data["ChangePasscodeLink"] = setting.AppSubURL + "/user/settings/change_password"
if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, tplMustChangePassword)
ctx.HTML(http.StatusOK, tplMustChangePassword)
return return
} }
u := ctx.User u := ctx.User

+ 6
- 5
routers/user/auth_openid.go View File



import ( import (
"fmt" "fmt"
"net/http"
"net/url" "net/url"


"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"


ctx.Data["PageIsSignIn"] = true ctx.Data["PageIsSignIn"] = true
ctx.Data["PageIsLoginOpenID"] = true ctx.Data["PageIsLoginOpenID"] = true
ctx.HTML(200, tplSignInOpenID)
ctx.HTML(http.StatusOK, tplSignInOpenID)
} }


// Check if the given OpenID URI is allowed by blacklist/whitelist // Check if the given OpenID URI is allowed by blacklist/whitelist
ctx.Data["PageIsLoginOpenID"] = true ctx.Data["PageIsLoginOpenID"] = true


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, tplSignInOpenID)
ctx.HTML(http.StatusOK, tplSignInOpenID)
return return
} }


if userName != "" { if userName != "" {
ctx.Data["user_name"] = userName ctx.Data["user_name"] = userName
} }
ctx.HTML(200, tplConnectOID)
ctx.HTML(http.StatusOK, tplConnectOID)
} }


// ConnectOpenIDPost handles submission of a form to connect an OpenID URI to an existing account // ConnectOpenIDPost handles submission of a form to connect an OpenID URI to an existing account
if email != "" { if email != "" {
ctx.Data["email"] = email ctx.Data["email"] = email
} }
ctx.HTML(200, tplSignUpOID)
ctx.HTML(http.StatusOK, tplSignUpOID)
} }


// RegisterOpenIDPost handles submission of a form to create a new user authenticated via an OpenID URI // RegisterOpenIDPost handles submission of a form to create a new user authenticated via an OpenID URI
ctx.Data["IsSendRegisterMail"] = true ctx.Data["IsSendRegisterMail"] = true
ctx.Data["Email"] = u.Email ctx.Data["Email"] = u.Email
ctx.Data["ActiveCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale.Language()) ctx.Data["ActiveCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale.Language())
ctx.HTML(200, TplActivate)
ctx.HTML(http.StatusOK, TplActivate)


if err := ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil { if err := ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
log.Error("Set cache(MailResendLimit) fail: %v", err) log.Error("Set cache(MailResendLimit) fail: %v", err)

+ 4
- 3
routers/user/home.go View File

import ( import (
"bytes" "bytes"
"fmt" "fmt"
"net/http"
"regexp" "regexp"
"sort" "sort"
"strconv" "strconv"
if ctx.Written() { if ctx.Written() {
return return
} }
ctx.HTML(200, tplDashboard)
ctx.HTML(http.StatusOK, tplDashboard)
} }


// Milestones render the user milestones page // Milestones render the user milestones page
pager.AddParam(ctx, "state", "State") pager.AddParam(ctx, "state", "State")
ctx.Data["Page"] = pager ctx.Data["Page"] = pager


ctx.HTML(200, tplMilestones)
ctx.HTML(http.StatusOK, tplMilestones)
} }


// Pulls renders the user's pull request overview page // Pulls renders the user's pull request overview page
pager.AddParam(ctx, "assignee", "AssigneeID") pager.AddParam(ctx, "assignee", "AssigneeID")
ctx.Data["Page"] = pager ctx.Data["Page"] = pager


ctx.HTML(200, tplIssues)
ctx.HTML(http.StatusOK, tplIssues)
} }


func getRepoIDs(reposQuery string) []int64 { func getRepoIDs(reposQuery string) []int64 {

+ 6
- 5
routers/user/oauth.go View File

"encoding/base64" "encoding/base64"
"fmt" "fmt"
"html" "html"
"net/http"
"net/url" "net/url"
"strings" "strings"


// we'll tolerate errors here as they *should* get saved elsewhere // we'll tolerate errors here as they *should* get saved elsewhere
log.Error("Unable to save changes to the session: %v", err) log.Error("Unable to save changes to the session: %v", err)
} }
ctx.HTML(200, tplGrantAccess)
ctx.HTML(http.StatusOK, tplGrantAccess)
} }


// GrantApplicationOAuth manages the post request submitted when a user grants access to an application // GrantApplicationOAuth manages the post request submitted when a user grants access to an application
form := web.GetForm(ctx).(*auth.GrantApplicationForm) form := web.GetForm(ctx).(*auth.GrantApplicationForm)
if ctx.Session.Get("client_id") != form.ClientID || ctx.Session.Get("state") != form.State || if ctx.Session.Get("client_id") != form.ClientID || ctx.Session.Get("state") != form.State ||
ctx.Session.Get("redirect_uri") != form.RedirectURI { ctx.Session.Get("redirect_uri") != form.RedirectURI {
ctx.Error(400)
ctx.Error(http.StatusBadRequest)
return return
} }
app, err := models.GetOAuth2ApplicationByClientID(form.ClientID) app, err := models.GetOAuth2ApplicationByClientID(form.ClientID)
handleAccessTokenError(ctx, *tokenErr) handleAccessTokenError(ctx, *tokenErr)
return return
} }
ctx.JSON(200, accessToken)
ctx.JSON(http.StatusOK, accessToken)
} }


func handleAuthorizationCode(ctx *context.Context, form auth.AccessTokenForm) { func handleAuthorizationCode(ctx *context.Context, form auth.AccessTokenForm) {
return return
} }
// send successful response // send successful response
ctx.JSON(200, resp)
ctx.JSON(http.StatusOK, resp)
} }


func handleAccessTokenError(ctx *context.Context, acErr AccessTokenError) { func handleAccessTokenError(ctx *context.Context, acErr AccessTokenError) {
ctx.JSON(400, acErr)
ctx.JSON(http.StatusBadRequest, acErr)
} }


func handleServerError(ctx *context.Context, state string, redirectURI string) { func handleServerError(ctx *context.Context, state string, redirectURI string) {

+ 3
- 2
routers/user/profile.go View File



import ( import (
"fmt" "fmt"
"net/http"
"path" "path"
"strings" "strings"


ctx.ServeFile(path.Join(setting.StaticRootPath, "public/img/favicon.png")) ctx.ServeFile(path.Join(setting.StaticRootPath, "public/img/favicon.png"))
return return
} else if strings.HasSuffix(uname, ".png") { } else if strings.HasSuffix(uname, ".png") {
ctx.Error(404)
ctx.Error(http.StatusNotFound)
return return
} }




ctx.Data["ShowUserEmail"] = len(ctxUser.Email) > 0 && ctx.IsSigned && (!ctxUser.KeepEmailPrivate || ctxUser.ID == ctx.User.ID) ctx.Data["ShowUserEmail"] = len(ctxUser.Email) > 0 && ctx.IsSigned && (!ctxUser.KeepEmailPrivate || ctxUser.ID == ctx.User.ID)


ctx.HTML(200, tplProfile)
ctx.HTML(http.StatusOK, tplProfile)
} }


// Action response for follow/unfollow user request // Action response for follow/unfollow user request

+ 5
- 4
routers/user/setting/account.go View File



import ( import (
"errors" "errors"
"net/http"
"time" "time"


"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"


loadAccountData(ctx) loadAccountData(ctx)


ctx.HTML(200, tplSettingsAccount)
ctx.HTML(http.StatusOK, tplSettingsAccount)
} }


// AccountPost response for change user's password // AccountPost response for change user's password
if ctx.HasError() { if ctx.HasError() {
loadAccountData(ctx) loadAccountData(ctx)


ctx.HTML(200, tplSettingsAccount)
ctx.HTML(http.StatusOK, tplSettingsAccount)
return return
} }


if ctx.HasError() { if ctx.HasError() {
loadAccountData(ctx) loadAccountData(ctx)


ctx.HTML(200, tplSettingsAccount)
ctx.HTML(http.StatusOK, tplSettingsAccount)
return return
} }


log.Trace("Email address deleted: %s", ctx.User.Name) log.Trace("Email address deleted: %s", ctx.User.Name)


ctx.Flash.Success(ctx.Tr("settings.email_deletion_success")) ctx.Flash.Success(ctx.Tr("settings.email_deletion_success"))
ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"redirect": setting.AppSubURL + "/user/settings/account", "redirect": setting.AppSubURL + "/user/settings/account",
}) })
} }

+ 5
- 3
routers/user/setting/applications.go View File

package setting package setting


import ( import (
"net/http"

"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/context"


loadApplicationsData(ctx) loadApplicationsData(ctx)


ctx.HTML(200, tplSettingsApplications)
ctx.HTML(http.StatusOK, tplSettingsApplications)
} }


// ApplicationsPost response for add user's access token // ApplicationsPost response for add user's access token
if ctx.HasError() { if ctx.HasError() {
loadApplicationsData(ctx) loadApplicationsData(ctx)


ctx.HTML(200, tplSettingsApplications)
ctx.HTML(http.StatusOK, tplSettingsApplications)
return return
} }


ctx.Flash.Success(ctx.Tr("settings.delete_token_success")) ctx.Flash.Success(ctx.Tr("settings.delete_token_success"))
} }


ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"redirect": setting.AppSubURL + "/user/settings/applications", "redirect": setting.AppSubURL + "/user/settings/applications",
}) })
} }

+ 5
- 3
routers/user/setting/keys.go View File

package setting package setting


import ( import (
"net/http"

"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/context"


loadKeysData(ctx) loadKeysData(ctx)


ctx.HTML(200, tplSettingsKeys)
ctx.HTML(http.StatusOK, tplSettingsKeys)
} }


// KeysPost response for change user's SSH/GPG keys // KeysPost response for change user's SSH/GPG keys
if ctx.HasError() { if ctx.HasError() {
loadKeysData(ctx) loadKeysData(ctx)


ctx.HTML(200, tplSettingsKeys)
ctx.HTML(http.StatusOK, tplSettingsKeys)
return return
} }
switch form.Type { switch form.Type {
ctx.Flash.Warning("Function not implemented") ctx.Flash.Warning("Function not implemented")
ctx.Redirect(setting.AppSubURL + "/user/settings/keys") ctx.Redirect(setting.AppSubURL + "/user/settings/keys")
} }
ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"redirect": setting.AppSubURL + "/user/settings/keys", "redirect": setting.AppSubURL + "/user/settings/keys",
}) })
} }

+ 9
- 8
routers/user/setting/oauth2.go View File



import ( import (
"fmt" "fmt"
"net/http"


"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/base"
if ctx.HasError() { if ctx.HasError() {
loadApplicationsData(ctx) loadApplicationsData(ctx)


ctx.HTML(200, tplSettingsApplications)
ctx.HTML(http.StatusOK, tplSettingsApplications)
return return
} }
// TODO validate redirect URI // TODO validate redirect URI
ctx.ServerError("GenerateClientSecret", err) ctx.ServerError("GenerateClientSecret", err)
return return
} }
ctx.HTML(200, tplSettingsOAuthApplications)
ctx.HTML(http.StatusOK, tplSettingsOAuthApplications)
} }


// OAuthApplicationsEdit response for editing oauth2 application // OAuthApplicationsEdit response for editing oauth2 application
if ctx.HasError() { if ctx.HasError() {
loadApplicationsData(ctx) loadApplicationsData(ctx)


ctx.HTML(200, tplSettingsApplications)
ctx.HTML(http.StatusOK, tplSettingsApplications)
return return
} }
// TODO validate redirect URI // TODO validate redirect URI
return return
} }
ctx.Flash.Success(ctx.Tr("settings.update_oauth2_application_success")) ctx.Flash.Success(ctx.Tr("settings.update_oauth2_application_success"))
ctx.HTML(200, tplSettingsOAuthApplications)
ctx.HTML(http.StatusOK, tplSettingsOAuthApplications)
} }


// OAuthApplicationsRegenerateSecret handles the post request for regenerating the secret // OAuthApplicationsRegenerateSecret handles the post request for regenerating the secret
return return
} }
ctx.Flash.Success(ctx.Tr("settings.update_oauth2_application_success")) ctx.Flash.Success(ctx.Tr("settings.update_oauth2_application_success"))
ctx.HTML(200, tplSettingsOAuthApplications)
ctx.HTML(http.StatusOK, tplSettingsOAuthApplications)
} }


// OAuth2ApplicationShow displays the given application // OAuth2ApplicationShow displays the given application
return return
} }
ctx.Data["App"] = app ctx.Data["App"] = app
ctx.HTML(200, tplSettingsOAuthApplications)
ctx.HTML(http.StatusOK, tplSettingsOAuthApplications)
} }


// DeleteOAuth2Application deletes the given oauth2 application // DeleteOAuth2Application deletes the given oauth2 application
log.Trace("OAuth2 Application deleted: %s", ctx.User.Name) log.Trace("OAuth2 Application deleted: %s", ctx.User.Name)


ctx.Flash.Success(ctx.Tr("settings.remove_oauth2_application_success")) ctx.Flash.Success(ctx.Tr("settings.remove_oauth2_application_success"))
ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"redirect": setting.AppSubURL + "/user/settings/applications", "redirect": setting.AppSubURL + "/user/settings/applications",
}) })
} }
} }


ctx.Flash.Success(ctx.Tr("settings.revoke_oauth2_grant_success")) ctx.Flash.Success(ctx.Tr("settings.revoke_oauth2_grant_success"))
ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"redirect": setting.AppSubURL + "/user/settings/applications", "redirect": setting.AppSubURL + "/user/settings/applications",
}) })
} }

+ 5
- 4
routers/user/setting/profile.go View File

"errors" "errors"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"net/http"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
ctx.Data["Title"] = ctx.Tr("settings") ctx.Data["Title"] = ctx.Tr("settings")
ctx.Data["PageIsSettingsProfile"] = true ctx.Data["PageIsSettingsProfile"] = true


ctx.HTML(200, tplSettingsProfile)
ctx.HTML(http.StatusOK, tplSettingsProfile)
} }


// HandleUsernameChange handle username changes from user settings and admin interface // HandleUsernameChange handle username changes from user settings and admin interface
ctx.Data["PageIsSettingsProfile"] = true ctx.Data["PageIsSettingsProfile"] = true


if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, tplSettingsProfile)
ctx.HTML(http.StatusOK, tplSettingsProfile)
return return
} }


return return
} }
ctx.Data["Orgs"] = orgs ctx.Data["Orgs"] = orgs
ctx.HTML(200, tplSettingsOrganization)
ctx.HTML(http.StatusOK, tplSettingsOrganization)
} }


// Repos display a list of all repositories of the user // Repos display a list of all repositories of the user
pager := context.NewPagination(int(count), opts.PageSize, opts.Page, 5) pager := context.NewPagination(int(count), opts.PageSize, opts.Page, 5)
pager.SetDefaultParams(ctx) pager.SetDefaultParams(ctx)
ctx.Data["Page"] = pager ctx.Data["Page"] = pager
ctx.HTML(200, tplSettingsRepositories)
ctx.HTML(http.StatusOK, tplSettingsRepositories)
} }

+ 4
- 2
routers/user/setting/security.go View File

package setting package setting


import ( import (
"net/http"

"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/context"


loadSecurityData(ctx) loadSecurityData(ctx)


ctx.HTML(200, tplSettingsSecurity)
ctx.HTML(http.StatusOK, tplSettingsSecurity)
} }


// DeleteAccountLink delete a single account link // DeleteAccountLink delete a single account link
} }
} }


ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"redirect": setting.AppSubURL + "/user/settings/security", "redirect": setting.AppSubURL + "/user/settings/security",
}) })
} }

+ 4
- 2
routers/user/setting/security_openid.go View File

package setting package setting


import ( import (
"net/http"

"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/auth/openid" "code.gitea.io/gitea/modules/auth/openid"
"code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/context"
if ctx.HasError() { if ctx.HasError() {
loadSecurityData(ctx) loadSecurityData(ctx)


ctx.HTML(200, tplSettingsSecurity)
ctx.HTML(http.StatusOK, tplSettingsSecurity)
return return
} }


log.Trace("OpenID address deleted: %s", ctx.User.Name) log.Trace("OpenID address deleted: %s", ctx.User.Name)


ctx.Flash.Success(ctx.Tr("settings.openid_deletion_success")) ctx.Flash.Success(ctx.Tr("settings.openid_deletion_success"))
ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"redirect": setting.AppSubURL + "/user/settings/security", "redirect": setting.AppSubURL + "/user/settings/security",
}) })
} }

+ 3
- 2
routers/user/setting/security_twofa.go View File

"encoding/base64" "encoding/base64"
"html/template" "html/template"
"image/png" "image/png"
"net/http"
"strings" "strings"


"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
return return
} }


ctx.HTML(200, tplSettingsTwofaEnroll)
ctx.HTML(http.StatusOK, tplSettingsTwofaEnroll)
} }


// EnrollTwoFactorPost handles enrolling the user into 2FA. // EnrollTwoFactorPost handles enrolling the user into 2FA.
if !twofaGenerateSecretAndQr(ctx) { if !twofaGenerateSecretAndQr(ctx) {
return return
} }
ctx.HTML(200, tplSettingsTwofaEnroll)
ctx.HTML(http.StatusOK, tplSettingsTwofaEnroll)
return return
} }



+ 5
- 4
routers/user/setting/security_u2f.go View File



import ( import (
"errors" "errors"
"net/http"


"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/context"
func U2FRegister(ctx *context.Context) { func U2FRegister(ctx *context.Context) {
form := web.GetForm(ctx).(*auth.U2FRegistrationForm) form := web.GetForm(ctx).(*auth.U2FRegistrationForm)
if form.Name == "" { if form.Name == "" {
ctx.Error(409)
ctx.Error(http.StatusConflict)
return return
} }
challenge, err := u2f.NewChallenge(setting.U2F.AppID, setting.U2F.TrustedFacets) challenge, err := u2f.NewChallenge(setting.U2F.AppID, setting.U2F.TrustedFacets)
} }
for _, reg := range regs { for _, reg := range regs {
if reg.Name == form.Name { if reg.Name == form.Name {
ctx.Error(409, "Name already taken")
ctx.Error(http.StatusConflict, "Name already taken")
return return
} }
} }
// we'll tolerate errors here as they *should* get saved elsewhere // we'll tolerate errors here as they *should* get saved elsewhere
log.Error("Unable to save changes to the session: %v", err) log.Error("Unable to save changes to the session: %v", err)
} }
ctx.JSON(200, u2f.NewWebRegisterRequest(challenge, regs.ToRegistrations()))
ctx.JSON(http.StatusOK, u2f.NewWebRegisterRequest(challenge, regs.ToRegistrations()))
} }


// U2FRegisterPost receives the response of the security key // U2FRegisterPost receives the response of the security key
ctx.ServerError("DeleteRegistration", err) ctx.ServerError("DeleteRegistration", err)
return return
} }
ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"redirect": setting.AppSubURL + "/user/settings/security", "redirect": setting.AppSubURL + "/user/settings/security",
}) })
} }

+ 4
- 2
routers/user/task.go View File

package user package user


import ( import (
"net/http"

"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/context"
) )
func TaskStatus(ctx *context.Context) { func TaskStatus(ctx *context.Context) {
task, opts, err := models.GetMigratingTaskByID(ctx.ParamsInt64("task"), ctx.User.ID) task, opts, err := models.GetMigratingTaskByID(ctx.ParamsInt64("task"), ctx.User.ID)
if err != nil { if err != nil {
ctx.JSON(500, map[string]interface{}{
ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
"err": err, "err": err,
}) })
return return
} }


ctx.JSON(200, map[string]interface{}{
ctx.JSON(http.StatusOK, map[string]interface{}{
"status": task.Status, "status": task.Status,
"err": task.Errors, "err": task.Errors,
"repo-id": task.RepoID, "repo-id": task.RepoID,

Loading…
Cancel
Save