[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
This commit is contained in:
6543 2021-04-05 17:30:52 +02:00 committed by GitHub
parent e9fba18a26
commit 16dea6cebd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
64 changed files with 504 additions and 441 deletions

View File

@ -203,12 +203,12 @@ func (ctx *APIContext) CheckForOTP() {
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 {
@ -288,7 +288,7 @@ func ReferencesGitRepo(allowEmpty bool) func(http.Handler) http.Handler {
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
@ -324,7 +324,7 @@ func (ctx *APIContext) NotFound(objs ...interface{}) {
} }
} }
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,

View File

@ -6,6 +6,8 @@
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"
@ -27,13 +29,13 @@ func Toggle(options *ToggleOptions) func(ctx *Context) {
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
} }
@ -76,7 +78,7 @@ func Toggle(options *ToggleOptions) func(ctx *Context) {
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
} }
} }
@ -93,7 +95,7 @@ func Toggle(options *ToggleOptions) func(ctx *Context) {
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
@ -108,7 +110,7 @@ func ToggleAPI(options *ToggleOptions) func(ctx *APIContext) {
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
@ -116,14 +118,14 @@ func ToggleAPI(options *ToggleOptions) func(ctx *APIContext) {
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
@ -139,13 +141,13 @@ func ToggleAPI(options *ToggleOptions) func(ctx *APIContext) {
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 {
@ -164,7 +166,7 @@ func ToggleAPI(options *ToggleOptions) func(ctx *APIContext) {
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
@ -174,7 +176,7 @@ func ToggleAPI(options *ToggleOptions) func(ctx *APIContext) {
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

View File

@ -213,7 +213,7 @@ func (ctx *Context) RenderWithErr(msg string, tpl base.TplName, form interface{}
} }
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.

View File

@ -5,6 +5,7 @@
package lfs package lfs
import ( import (
"net/http"
"strconv" "strconv"
"strings" "strings"
@ -21,19 +22,19 @@ import (
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
@ -44,23 +45,23 @@ func checkIsValidRequest(ctx *context.Context) bool {
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)},
}) })
} }
@ -86,7 +87,7 @@ func GetListLockHandler(ctx *context.Context) {
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
@ -106,7 +107,7 @@ func GetListLockHandler(ctx *context.Context) {
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
@ -133,7 +134,7 @@ func GetListLockHandler(ctx *context.Context) {
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
@ -146,7 +147,7 @@ func GetListLockHandler(ctx *context.Context) {
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,
}) })
@ -175,7 +176,7 @@ func PostLockHandler(ctx *context.Context) {
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
@ -199,7 +200,7 @@ func PostLockHandler(ctx *context.Context) {
}) })
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",
}) })
@ -207,18 +208,18 @@ func PostLockHandler(ctx *context.Context) {
} }
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
@ -244,7 +245,7 @@ func VerifyLockHandler(ctx *context.Context) {
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
@ -263,7 +264,7 @@ func VerifyLockHandler(ctx *context.Context) {
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
@ -281,7 +282,7 @@ func VerifyLockHandler(ctx *context.Context) {
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,
@ -311,7 +312,7 @@ func UnLockHandler(ctx *context.Context) {
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
@ -332,16 +333,16 @@ func UnLockHandler(ctx *context.Context) {
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)})
} }

View File

@ -7,6 +7,7 @@ package admin
import ( import (
"fmt" "fmt"
"net/http"
"net/url" "net/url"
"os" "os"
"runtime" "runtime"
@ -128,7 +129,7 @@ func Dashboard(ctx *context.Context) {
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
@ -315,7 +316,7 @@ func Config(ctx *context.Context) {
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
@ -326,14 +327,14 @@ func Monitor(ctx *context.Context) {
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",
}) })
} }
@ -350,7 +351,7 @@ func Queue(ctx *context.Context) {
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
@ -364,7 +365,7 @@ func WorkerCancel(ctx *context.Context) {
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),
}) })
} }

View File

@ -7,6 +7,7 @@ package admin
import ( import (
"errors" "errors"
"fmt" "fmt"
"net/http"
"regexp" "regexp"
"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
@ -49,7 +50,7 @@ func Authentications(ctx *context.Context) {
} }
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 {
@ -109,7 +110,7 @@ func NewAuthSource(ctx *context.Context) {
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 {
@ -256,13 +257,13 @@ func NewAuthSourcePost(ctx *context.Context) {
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
} }
@ -310,7 +311,7 @@ func EditAuthSource(ctx *context.Context) {
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
@ -333,7 +334,7 @@ func EditAuthSourcePost(ctx *context.Context) {
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
} }
@ -356,7 +357,7 @@ func EditAuthSourcePost(ctx *context.Context) {
return return
} }
default: default:
ctx.Error(400) ctx.Error(http.StatusBadRequest)
return return
} }
@ -367,7 +368,7 @@ func EditAuthSourcePost(ctx *context.Context) {
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)
} }
@ -393,7 +394,7 @@ func DeleteAuthSource(ctx *context.Context) {
} 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
@ -401,7 +402,7 @@ func DeleteAuthSource(ctx *context.Context) {
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",
}) })
} }

View File

@ -6,6 +6,7 @@ package admin
import ( import (
"bytes" "bytes"
"net/http"
"net/url" "net/url"
"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
@ -96,7 +97,7 @@ func Emails(ctx *context.Context) {
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 (
@ -118,7 +119,7 @@ func ActivateEmail(ctx *context.Context) {
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
} }

View File

@ -5,6 +5,8 @@
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"
@ -53,7 +55,7 @@ func DefaultOrSystemWebhooks(ctx *context.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
@ -64,7 +66,7 @@ func DeleteDefaultOrSystemWebhook(ctx *context.Context) {
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",
}) })
} }

View File

@ -6,6 +6,7 @@
package admin package admin
import ( import (
"net/http"
"strconv" "strconv"
"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
@ -42,7 +43,7 @@ func Notices(ctx *context.Context) {
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

View File

@ -5,6 +5,7 @@
package admin package admin
import ( import (
"net/http"
"net/url" "net/url"
"strconv" "strconv"
"strings" "strings"
@ -53,7 +54,7 @@ func DeleteRepo(ctx *context.Context) {
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"),
}) })
} }
@ -85,7 +86,7 @@ func UnadoptedRepos(ctx *context.Context) {
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
} }
@ -99,7 +100,7 @@ func UnadoptedRepos(ctx *context.Context) {
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

View File

@ -7,6 +7,7 @@ package admin
import ( import (
"fmt" "fmt"
"net/http"
"strconv" "strconv"
"strings" "strings"
@ -60,7 +61,7 @@ func NewUser(ctx *context.Context) {
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
@ -80,7 +81,7 @@ func NewUserPost(ctx *context.Context) {
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
} }
@ -212,7 +213,7 @@ func EditUser(ctx *context.Context) {
return return
} }
ctx.HTML(200, tplUserEdit) ctx.HTML(http.StatusOK, tplUserEdit)
} }
// EditUserPost response for editting user // EditUserPost response for editting user
@ -229,7 +230,7 @@ func EditUserPost(ctx *context.Context) {
} }
if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, tplUserEdit) ctx.HTML(http.StatusOK, tplUserEdit)
return return
} }
@ -348,12 +349,12 @@ func DeleteUser(ctx *context.Context) {
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:
@ -364,7 +365,7 @@ func DeleteUser(ctx *context.Context) {
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",
}) })
} }

View File

@ -538,7 +538,7 @@ func bind(obj interface{}) http.HandlerFunc {
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)

View File

@ -5,6 +5,8 @@
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"
@ -23,5 +25,5 @@ func TemplatePreview(ctx *context.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("*")))
} }

View File

@ -7,6 +7,7 @@ package routers
import ( import (
"bytes" "bytes"
"net/http"
"strings" "strings"
"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
@ -39,11 +40,11 @@ func Home(ctx *context.Context) {
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"
@ -68,7 +69,7 @@ func Home(ctx *context.Context) {
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
@ -166,7 +167,7 @@ func RenderRepoSearch(ctx *context.Context, opts *RepoSearchOptions) {
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
@ -243,7 +244,7 @@ func RenderUserSearch(ctx *context.Context, opts *models.SearchUserOptions, tplN
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
@ -402,7 +403,7 @@ func ExploreCode(ctx *context.Context) {
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

View File

@ -146,7 +146,7 @@ func Install(ctx *context.Context) {
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
@ -165,7 +165,7 @@ func InstallPost(ctx *context.Context) {
ctx.Data["Err_Admin"] = true ctx.Data["Err_Admin"] = true
} }
ctx.HTML(200, tplInstall) ctx.HTML(http.StatusOK, tplInstall)
return return
} }
@ -450,7 +450,7 @@ func InstallPost(ctx *context.Context) {
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

View File

@ -5,6 +5,7 @@
package org package org
import ( import (
"net/http"
"strings" "strings"
"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
@ -106,7 +107,7 @@ func Home(ctx *context.Context) {
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
@ -137,5 +138,5 @@ func Home(ctx *context.Context) {
pager.SetDefaultParams(ctx) pager.SetDefaultParams(ctx)
ctx.Data["Page"] = pager ctx.Data["Page"] = pager
ctx.HTML(200, tplOrgHome) ctx.HTML(http.StatusOK, tplOrgHome)
} }

View File

@ -6,6 +6,8 @@
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"
@ -37,7 +39,7 @@ func Members(ctx *context.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
@ -45,7 +47,7 @@ func Members(ctx *context.Context) {
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
} }
@ -63,7 +65,7 @@ func Members(ctx *context.Context) {
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
@ -79,19 +81,19 @@ func MembersAction(ctx *context.Context) {
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)
@ -111,7 +113,7 @@ func MembersAction(ctx *context.Context) {
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(),
}) })

View File

@ -7,6 +7,7 @@ package org
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"
@ -30,7 +31,7 @@ func Create(ctx *context.Context) {
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
@ -44,7 +45,7 @@ func CreatePost(ctx *context.Context) {
} }
if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, tplCreateOrg) ctx.HTML(http.StatusOK, tplCreateOrg)
return return
} }

View File

@ -5,6 +5,8 @@
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"
@ -58,7 +60,7 @@ func UpdateLabel(ctx *context.Context) {
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)
} }
@ -83,7 +85,7 @@ func DeleteLabel(ctx *context.Context) {
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",
}) })
} }

View File

@ -6,6 +6,7 @@
package org package org
import ( import (
"net/http"
"strings" "strings"
"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
@ -35,7 +36,7 @@ func Settings(ctx *context.Context) {
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
@ -46,7 +47,7 @@ func SettingsPost(ctx *context.Context) {
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
} }
@ -165,7 +166,7 @@ func SettingsDelete(ctx *context.Context) {
return return
} }
ctx.HTML(200, tplSettingsDelete) ctx.HTML(http.StatusOK, tplSettingsDelete)
} }
// Webhooks render webhook list page // Webhooks render webhook list page
@ -183,7 +184,7 @@ func Webhooks(ctx *context.Context) {
} }
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
@ -194,7 +195,7 @@ func DeleteWebhook(ctx *context.Context) {
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",
}) })
} }
@ -205,5 +206,5 @@ func Labels(ctx *context.Context) {
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)
} }

View File

@ -44,7 +44,7 @@ func Teams(ctx *context.Context) {
} }
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
@ -60,7 +60,7 @@ func TeamsAction(ctx *context.Context) {
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)
@ -68,14 +68,14 @@ func TeamsAction(ctx *context.Context) {
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")))
@ -111,7 +111,7 @@ func TeamsAction(ctx *context.Context) {
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(),
}) })
@ -132,7 +132,7 @@ func TeamsAction(ctx *context.Context) {
// 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
} }
@ -168,7 +168,7 @@ func TeamsRepoAction(ctx *context.Context) {
} }
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
@ -183,7 +183,7 @@ func NewTeam(ctx *context.Context) {
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
@ -218,7 +218,7 @@ func NewTeamPost(ctx *context.Context) {
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
} }
@ -250,7 +250,7 @@ func TeamMembers(ctx *context.Context) {
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
@ -262,7 +262,7 @@ func TeamRepositories(ctx *context.Context) {
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
@ -272,7 +272,7 @@ func EditTeam(ctx *context.Context) {
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
@ -321,7 +321,7 @@ func EditTeamPost(ctx *context.Context) {
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
} }
@ -351,7 +351,7 @@ func DeleteTeam(ctx *context.Context) {
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",
}) })
} }

View File

@ -173,7 +173,7 @@ func HookPreReceive(ctx *gitea_context.PrivateContext) {
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

View File

@ -5,6 +5,7 @@
package repo package repo
import ( import (
"net/http"
"time" "time"
"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
@ -64,7 +65,7 @@ func Activity(ctx *context.Context) {
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
@ -98,5 +99,5 @@ func ActivityAuthors(ctx *context.Context) {
return return
} }
ctx.JSON(200, authors) ctx.JSON(http.StatusOK, authors)
} }

View File

@ -29,13 +29,13 @@ func UploadReleaseAttachment(ctx *context.Context) {
// 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()
@ -48,7 +48,7 @@ func uploadAttachment(ctx *context.Context, allowedTypes string) {
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
} }
@ -57,12 +57,12 @@ func uploadAttachment(ctx *context.Context, allowedTypes string) {
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,
}) })
} }
@ -72,19 +72,19 @@ func DeleteAttachment(ctx *context.Context) {
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,
}) })
} }
@ -94,7 +94,7 @@ func GetAttachment(ctx *context.Context) {
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)
} }

View File

@ -10,6 +10,7 @@ import (
"fmt" "fmt"
"html" "html"
gotemplate "html/template" gotemplate "html/template"
"net/http"
"strings" "strings"
"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
@ -184,7 +185,7 @@ func RefBlame(ctx *context.Context) {
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) {

View File

@ -7,6 +7,7 @@ package repo
import ( import (
"fmt" "fmt"
"net/http"
"strings" "strings"
"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
@ -75,7 +76,7 @@ func Branches(ctx *context.Context) {
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
@ -163,7 +164,7 @@ func RestoreBranchPost(ctx *context.Context) {
} }
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",
}) })
} }

View File

@ -7,6 +7,7 @@ package repo
import ( import (
"errors" "errors"
"net/http"
"path" "path"
"strings" "strings"
@ -85,7 +86,7 @@ func Commits(ctx *context.Context) {
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.
@ -167,11 +168,11 @@ func Graph(ctx *context.Context) {
} }
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
@ -205,7 +206,7 @@ func SearchCommits(ctx *context.Context) {
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
@ -253,7 +254,7 @@ func FileHistory(ctx *context.Context) {
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
@ -372,7 +373,7 @@ func Diff(ctx *context.Context) {
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

View File

@ -11,6 +11,7 @@ import (
"fmt" "fmt"
"html" "html"
"io/ioutil" "io/ioutil"
"net/http"
"path" "path"
"path/filepath" "path/filepath"
"strings" "strings"
@ -632,7 +633,7 @@ func CompareDiff(ctx *context.Context) {
} 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
} }
@ -660,7 +661,7 @@ func CompareDiff(ctx *context.Context) {
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
@ -679,7 +680,7 @@ func ExcerptBlob(ctx *context.Context) {
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{
@ -704,7 +705,7 @@ func ExcerptBlob(ctx *context.Context) {
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 {
@ -735,7 +736,7 @@ func ExcerptBlob(ctx *context.Context) {
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) {

View File

@ -7,6 +7,7 @@ package repo
import ( import (
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"net/http"
"path" "path"
"strings" "strings"
@ -149,7 +150,7 @@ func editFile(ctx *context.Context, isNewFile bool) {
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"
@ -205,7 +206,7 @@ func editFilePost(ctx *context.Context, form auth.EditRepoFileForm, isNewFile bo
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
} }
@ -263,10 +264,10 @@ func editFilePost(ctx *context.Context, form auth.EditRepoFileForm, isNewFile bo
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
@ -276,7 +277,7 @@ func editFilePost(ctx *context.Context, form auth.EditRepoFileForm, isNewFile bo
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
@ -284,7 +285,7 @@ func editFilePost(ctx *context.Context, form auth.EditRepoFileForm, isNewFile bo
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)
@ -344,22 +345,22 @@ func DiffPreviewPost(ctx *context.Context) {
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
} }
@ -369,7 +370,7 @@ func DiffPreviewPost(ctx *context.Context) {
} }
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
@ -396,7 +397,7 @@ func DeleteFile(ctx *context.Context) {
} }
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
@ -418,7 +419,7 @@ func DeleteFilePost(ctx *context.Context) {
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
} }
@ -473,14 +474,14 @@ func DeleteFilePost(ctx *context.Context) {
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)
@ -560,7 +561,7 @@ func UploadFile(ctx *context.Context) {
} }
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
@ -597,7 +598,7 @@ func UploadFilePost(ctx *context.Context) {
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
} }
@ -672,7 +673,7 @@ func UploadFilePost(ctx *context.Context) {
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
@ -734,7 +735,7 @@ func cleanUploadFileName(name string) string {
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()
@ -747,24 +748,24 @@ func UploadFileToServer(ctx *context.Context) {
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,
}) })
} }
@ -778,7 +779,7 @@ func RemoveUploadFileFromServer(ctx *context.Context) {
} }
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
} }

View File

@ -393,7 +393,7 @@ func Issues(ctx *context.Context) {
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
@ -819,7 +819,7 @@ func NewIssue(ctx *context.Context) {
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
@ -832,7 +832,7 @@ func NewIssueChooseTemplate(ctx *context.Context) {
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
@ -960,7 +960,7 @@ func NewIssuePost(ctx *context.Context) {
} }
if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, tplIssueNew) ctx.HTML(http.StatusOK, tplIssueNew)
return return
} }
@ -981,7 +981,7 @@ func NewIssuePost(ctx *context.Context) {
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)
@ -1578,7 +1578,7 @@ func ViewIssue(ctx *context.Context) {
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.
@ -1650,13 +1650,13 @@ func UpdateIssueTitle(ctx *context.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
} }
@ -1665,7 +1665,7 @@ func UpdateIssueTitle(ctx *context.Context) {
return return
} }
ctx.JSON(200, map[string]interface{}{ ctx.JSON(http.StatusOK, map[string]interface{}{
"title": issue.Title, "title": issue.Title,
}) })
} }
@ -1678,7 +1678,7 @@ func UpdateIssueRef(ctx *context.Context) {
} }
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
} }
@ -1689,7 +1689,7 @@ func UpdateIssueRef(ctx *context.Context) {
return return
} }
ctx.JSON(200, map[string]interface{}{ ctx.JSON(http.StatusOK, map[string]interface{}{
"ref": ref, "ref": ref,
}) })
} }
@ -1702,7 +1702,7 @@ func UpdateIssueContent(ctx *context.Context) {
} }
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
} }
@ -1717,7 +1717,7 @@ func UpdateIssueContent(ctx *context.Context) {
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),
}) })
@ -1743,7 +1743,7 @@ func UpdateIssueMilestone(ctx *context.Context) {
} }
} }
ctx.JSON(200, map[string]interface{}{ ctx.JSON(http.StatusOK, map[string]interface{}{
"ok": true, "ok": true,
}) })
} }
@ -1789,7 +1789,7 @@ func UpdateIssueAssignee(ctx *context.Context) {
} }
} }
} }
ctx.JSON(200, map[string]interface{}{ ctx.JSON(http.StatusOK, map[string]interface{}{
"ok": true, "ok": true,
}) })
} }
@ -1914,7 +1914,7 @@ func UpdatePullReviewRequest(ctx *context.Context) {
} }
} }
ctx.JSON(200, map[string]interface{}{ ctx.JSON(http.StatusOK, map[string]interface{}{
"ok": true, "ok": true,
}) })
} }
@ -1954,7 +1954,7 @@ func UpdateIssueStatus(ctx *context.Context) {
} }
} }
} }
ctx.JSON(200, map[string]interface{}{ ctx.JSON(http.StatusOK, map[string]interface{}{
"ok": true, "ok": true,
}) })
} }
@ -1986,7 +1986,7 @@ func NewComment(ctx *context.Context) {
} }
} }
ctx.Error(403) ctx.Error(http.StatusForbidden)
return return
} }
@ -2109,17 +2109,17 @@ func UpdateCommentContent(ctx *context.Context) {
} }
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
@ -2134,7 +2134,7 @@ func UpdateCommentContent(ctx *context.Context) {
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),
}) })
@ -2154,10 +2154,10 @@ func DeleteComment(ctx *context.Context) {
} }
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
} }
@ -2196,7 +2196,7 @@ func ChangeIssueReaction(ctx *context.Context) {
} }
} }
ctx.Error(403) ctx.Error(http.StatusForbidden)
return return
} }
@ -2244,7 +2244,7 @@ func ChangeIssueReaction(ctx *context.Context) {
} }
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": "",
}) })
@ -2260,7 +2260,7 @@ func ChangeIssueReaction(ctx *context.Context) {
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,
}) })
} }
@ -2298,10 +2298,10 @@ func ChangeCommentReaction(ctx *context.Context) {
} }
} }
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
} }
@ -2344,7 +2344,7 @@ func ChangeCommentReaction(ctx *context.Context) {
} }
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": "",
}) })
@ -2360,7 +2360,7 @@ func ChangeCommentReaction(ctx *context.Context) {
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,
}) })
} }
@ -2406,7 +2406,7 @@ func GetIssueAttachments(ctx *context.Context) {
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
@ -2426,7 +2426,7 @@ func GetCommentAttachments(ctx *context.Context) {
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 {

View File

@ -5,6 +5,8 @@
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"
@ -26,7 +28,7 @@ func Labels(ctx *context.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
@ -127,7 +129,7 @@ func UpdateLabel(ctx *context.Context) {
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)
} }
@ -152,7 +154,7 @@ func DeleteLabel(ctx *context.Context) {
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",
}) })
} }
@ -176,7 +178,7 @@ func UpdateIssueLabel(ctx *context.Context) {
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)
} }
@ -211,11 +213,11 @@ func UpdateIssueLabel(ctx *context.Context) {
} }
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,
}) })
} }

View File

@ -38,7 +38,7 @@ func IssueWatch(ctx *context.Context) {
log.Trace("Permission Denied: Not logged in") log.Trace("Permission Denied: Not logged in")
} }
} }
ctx.Error(403) ctx.Error(http.StatusForbidden)
return return
} }

View File

@ -11,6 +11,7 @@ import (
gotemplate "html/template" gotemplate "html/template"
"io" "io"
"io/ioutil" "io/ioutil"
"net/http"
"path" "path"
"strconv" "strconv"
"strings" "strings"
@ -63,7 +64,7 @@ func LFSFiles(ctx *context.Context) {
} }
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
@ -97,7 +98,7 @@ func LFSLocks(ctx *context.Context) {
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
} }
@ -186,7 +187,7 @@ func LFSLocks(ctx *context.Context) {
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
@ -339,7 +340,7 @@ func LFSFileGet(ctx *context.Context) {
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
@ -404,7 +405,7 @@ func LFSFileFind(ctx *context.Context) {
} }
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
@ -478,7 +479,7 @@ func LFSPointerFiles(ctx *context.Context) {
} }
default: default:
} }
ctx.HTML(200, tplSettingsLFSPointers) ctx.HTML(http.StatusOK, tplSettingsLFSPointers)
} }
type pointerResult struct { type pointerResult struct {

View File

@ -41,7 +41,7 @@ func Migrate(ctx *context.Context) {
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
} }
@ -60,7 +60,7 @@ func Migrate(ctx *context.Context) {
} }
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) {
@ -135,7 +135,7 @@ func MigratePost(ctx *context.Context) {
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
} }

View File

@ -5,6 +5,7 @@
package repo package repo
import ( import (
"net/http"
"time" "time"
"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
@ -95,7 +96,7 @@ func Milestones(ctx *context.Context) {
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
@ -103,7 +104,7 @@ func NewMilestone(ctx *context.Context) {
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
@ -114,7 +115,7 @@ func NewMilestonePost(ctx *context.Context) {
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
} }
@ -163,7 +164,7 @@ func EditMilestone(ctx *context.Context) {
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
@ -174,7 +175,7 @@ func EditMilestonePost(ctx *context.Context) {
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
} }
@ -242,7 +243,7 @@ func DeleteMilestone(ctx *context.Context) {
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",
}) })
} }
@ -272,5 +273,5 @@ func MilestoneIssuesAndPulls(ctx *context.Context) {
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)
} }

View File

@ -6,6 +6,7 @@ package repo
import ( import (
"fmt" "fmt"
"net/http"
"strings" "strings"
"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
@ -101,7 +102,7 @@ func Projects(ctx *context.Context) {
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
@ -109,7 +110,7 @@ func NewProject(ctx *context.Context) {
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
@ -120,7 +121,7 @@ func NewProjectPost(ctx *context.Context) {
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
} }
@ -186,7 +187,7 @@ func DeleteProject(ctx *context.Context) {
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",
}) })
} }
@ -215,7 +216,7 @@ func EditProject(ctx *context.Context) {
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
@ -227,7 +228,7 @@ func EditProjectPost(ctx *context.Context) {
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
} }
@ -318,7 +319,7 @@ func ViewProject(ctx *context.Context) {
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
@ -341,7 +342,7 @@ func UpdateIssueProject(ctx *context.Context) {
} }
} }
ctx.JSON(200, map[string]interface{}{ ctx.JSON(http.StatusOK, map[string]interface{}{
"ok": true, "ok": true,
}) })
} }
@ -349,14 +350,14 @@ func UpdateIssueProject(ctx *context.Context) {
// 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
@ -378,14 +379,14 @@ func DeleteProjectBoard(ctx *context.Context) {
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
@ -396,7 +397,7 @@ func DeleteProjectBoard(ctx *context.Context) {
return return
} }
ctx.JSON(200, map[string]interface{}{ ctx.JSON(http.StatusOK, map[string]interface{}{
"ok": true, "ok": true,
}) })
} }
@ -405,7 +406,7 @@ func DeleteProjectBoard(ctx *context.Context) {
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
@ -430,21 +431,21 @@ func AddBoardToProjectPost(ctx *context.Context) {
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
@ -466,14 +467,14 @@ func checkProjectBoardChangePermissions(ctx *context.Context) (*models.Project,
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
@ -502,7 +503,7 @@ func EditProjectBoard(ctx *context.Context) {
return return
} }
ctx.JSON(200, map[string]interface{}{ ctx.JSON(http.StatusOK, map[string]interface{}{
"ok": true, "ok": true,
}) })
} }
@ -520,7 +521,7 @@ func SetDefaultProjectBoard(ctx *context.Context) {
return return
} }
ctx.JSON(200, map[string]interface{}{ ctx.JSON(http.StatusOK, map[string]interface{}{
"ok": true, "ok": true,
}) })
} }
@ -529,14 +530,14 @@ func SetDefaultProjectBoard(ctx *context.Context) {
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
@ -598,7 +599,7 @@ func MoveIssueAcrossBoards(ctx *context.Context) {
return return
} }
ctx.JSON(200, map[string]interface{}{ ctx.JSON(http.StatusOK, map[string]interface{}{
"ok": true, "ok": true,
}) })
} }
@ -609,7 +610,7 @@ func CreateProject(ctx *context.Context) {
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
@ -624,7 +625,7 @@ func CreateProjectPost(ctx *context.Context, form auth.UserCreateProjectForm) {
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
} }

View File

@ -167,7 +167,7 @@ func Fork(ctx *context.Context) {
return return
} }
ctx.HTML(200, tplFork) ctx.HTML(http.StatusOK, tplFork)
} }
// ForkPost response for forking a repository // ForkPost response for forking a repository
@ -188,7 +188,7 @@ func ForkPost(ctx *context.Context) {
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
} }
@ -221,7 +221,7 @@ func ForkPost(ctx *context.Context) {
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
} }
} }
@ -570,7 +570,7 @@ func ViewPullCommits(ctx *context.Context) {
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
@ -692,7 +692,7 @@ func ViewPullFiles(ctx *context.Context) {
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
@ -1015,7 +1015,7 @@ func CompareAndPullRequestPost(ctx *context.Context) {
return return
} }
ctx.HTML(200, tplCompareDiff) ctx.HTML(http.StatusOK, tplCompareDiff)
return return
} }
@ -1054,7 +1054,7 @@ func CompareAndPullRequestPost(ctx *context.Context) {
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)
@ -1090,7 +1090,7 @@ func TriggerTask(ctx *context.Context) {
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
} }
@ -1101,7 +1101,7 @@ func TriggerTask(ctx *context.Context) {
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
} }
@ -1109,7 +1109,7 @@ func TriggerTask(ctx *context.Context) {
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)
} }
@ -1179,7 +1179,7 @@ func CleanUpPullRequest(ctx *context.Context) {
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),
}) })
}() }()

View File

@ -6,6 +6,7 @@ package repo
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"
@ -41,7 +42,7 @@ func RenderNewCodeCommentForm(ctx *context.Context) {
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
@ -120,12 +121,12 @@ func UpdateResolveConversation(ctx *context.Context) {
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
} }
@ -136,7 +137,7 @@ func UpdateResolveConversation(ctx *context.Context) {
return return
} }
} else { } else {
ctx.Error(400) ctx.Error(http.StatusBadRequest)
return return
} }
@ -144,7 +145,7 @@ func UpdateResolveConversation(ctx *context.Context) {
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,
}) })
} }
@ -169,7 +170,7 @@ func renderConversation(ctx *context.Context, comment *models.Comment) {
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

View File

@ -7,6 +7,7 @@ package repo
import ( import (
"fmt" "fmt"
"net/http"
"strings" "strings"
"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
@ -141,7 +142,7 @@ func releasesOrTags(ctx *context.Context, isTagList bool) {
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
@ -184,7 +185,7 @@ func SingleRelease(ctx *context.Context) {
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
@ -237,7 +238,7 @@ func NewRelease(ctx *context.Context) {
} }
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
@ -249,7 +250,7 @@ func NewReleasePost(ctx *context.Context) {
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
} }
@ -378,7 +379,7 @@ func EditRelease(ctx *context.Context) {
} }
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
@ -411,7 +412,7 @@ func EditReleasePost(ctx *context.Context) {
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
} }
@ -464,13 +465,13 @@ func deleteReleaseOrTag(ctx *context.Context, isDelTag bool) {
} }
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",
}) })
} }

View File

@ -8,6 +8,7 @@ package repo
import ( import (
"errors" "errors"
"fmt" "fmt"
"net/http"
"strings" "strings"
"time" "time"
@ -85,7 +86,7 @@ func checkContextUser(ctx *context.Context, uid int64) *models.User {
// 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 {
@ -94,7 +95,7 @@ func checkContextUser(ctx *context.Context, uid int64) *models.User {
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 {
@ -149,7 +150,7 @@ func Create(ctx *context.Context) {
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{}) {
@ -199,7 +200,7 @@ func CreatePost(ctx *context.Context) {
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
} }
@ -281,7 +282,7 @@ func Action(ctx *context.Context) {
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
} }
@ -339,7 +340,7 @@ func RedirectDownload(ctx *context.Context) {
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)
@ -349,7 +350,7 @@ func RedirectDownload(ctx *context.Context) {
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 {
@ -357,7 +358,7 @@ func RedirectDownload(ctx *context.Context) {
return return
} }
} }
ctx.Error(404) ctx.Error(http.StatusNotFound)
} }
// Download an archive of a repository // Download an archive of a repository
@ -366,7 +367,7 @@ func Download(ctx *context.Context) {
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
} }
@ -380,7 +381,7 @@ func Download(ctx *context.Context) {
if complete { if complete {
ctx.ServeFile(aReq.GetArchivePath(), downloadName) ctx.ServeFile(aReq.GetArchivePath(), downloadName)
} else { } else {
ctx.Error(404) ctx.Error(http.StatusNotFound)
} }
} }
@ -392,7 +393,7 @@ func InitiateDownload(ctx *context.Context) {
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
} }
@ -402,7 +403,7 @@ func InitiateDownload(ctx *context.Context) {
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,
}) })
} }

View File

@ -5,6 +5,7 @@
package repo package repo
import ( import (
"net/http"
"path" "path"
"strings" "strings"
@ -51,5 +52,5 @@ func Search(ctx *context.Context) {
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)
} }

View File

@ -9,6 +9,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"net/http"
"strings" "strings"
"time" "time"
@ -51,7 +52,7 @@ func Settings(ctx *context.Context) {
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
@ -65,7 +66,7 @@ func SettingsPost(ctx *context.Context) {
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
} }
@ -366,7 +367,7 @@ func SettingsPost(ctx *context.Context) {
case "admin": case "admin":
if !ctx.User.IsAdmin { if !ctx.User.IsAdmin {
ctx.Error(403) ctx.Error(http.StatusForbidden)
return return
} }
@ -386,7 +387,7 @@ func SettingsPost(ctx *context.Context) {
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 {
@ -395,7 +396,7 @@ func SettingsPost(ctx *context.Context) {
} }
if !repo.IsMirror { if !repo.IsMirror {
ctx.Error(404) ctx.Error(http.StatusNotFound)
return return
} }
repo.IsMirror = false repo.IsMirror = false
@ -413,7 +414,7 @@ func SettingsPost(ctx *context.Context) {
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 {
@ -426,7 +427,7 @@ func SettingsPost(ctx *context.Context) {
} }
if !repo.IsFork { if !repo.IsFork {
ctx.Error(404) ctx.Error(http.StatusNotFound)
return return
} }
@ -450,7 +451,7 @@ func SettingsPost(ctx *context.Context) {
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 {
@ -500,7 +501,7 @@ func SettingsPost(ctx *context.Context) {
case "cancel_transfer": case "cancel_transfer":
if !ctx.Repo.IsOwner() { if !ctx.Repo.IsOwner() {
ctx.Error(404) ctx.Error(http.StatusNotFound)
return return
} }
@ -532,7 +533,7 @@ func SettingsPost(ctx *context.Context) {
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 {
@ -551,7 +552,7 @@ func SettingsPost(ctx *context.Context) {
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 {
@ -570,7 +571,7 @@ func SettingsPost(ctx *context.Context) {
case "archive": case "archive":
if !ctx.Repo.IsOwner() { if !ctx.Repo.IsOwner() {
ctx.Error(403) ctx.Error(http.StatusForbidden)
return return
} }
@ -593,7 +594,7 @@ func SettingsPost(ctx *context.Context) {
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
} }
@ -638,7 +639,7 @@ func Collaboration(ctx *context.Context) {
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
@ -709,7 +710,7 @@ func DeleteCollaboration(ctx *context.Context) {
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",
}) })
} }
@ -780,7 +781,7 @@ func DeleteTeam(ctx *context.Context) {
} }
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",
}) })
} }
@ -822,7 +823,7 @@ func GitHooks(ctx *context.Context) {
} }
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
@ -841,7 +842,7 @@ func GitHooksEdit(ctx *context.Context) {
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
@ -877,7 +878,7 @@ func DeployKeys(ctx *context.Context) {
} }
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
@ -894,7 +895,7 @@ func DeployKeysPost(ctx *context.Context) {
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
} }
@ -948,7 +949,7 @@ func DeleteDeployKey(ctx *context.Context) {
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",
}) })
} }

View File

@ -6,6 +6,7 @@ package repo
import ( import (
"fmt" "fmt"
"net/http"
"strings" "strings"
"time" "time"
@ -49,7 +50,7 @@ func ProtectedBranch(ctx *context.Context) {
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
@ -62,7 +63,7 @@ func ProtectedBranchPost(ctx *context.Context) {
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
} }
@ -165,7 +166,7 @@ func SettingsProtectedBranch(c *context.Context) {
} }
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

View File

@ -5,6 +5,7 @@
package repo package repo
import ( import (
"net/http"
"strings" "strings"
"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
@ -15,7 +16,7 @@ import (
// 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
@ -30,7 +31,7 @@ func TopicsPost(ctx *context.Context) {
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"),
}) })
@ -38,7 +39,7 @@ func TopicsPost(ctx *context.Context) {
} }
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"),
}) })
@ -48,13 +49,13 @@ func TopicsPost(ctx *context.Context) {
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",
}) })
} }

View File

@ -12,6 +12,7 @@ import (
gotemplate "html/template" gotemplate "html/template"
"io" "io"
"io/ioutil" "io/ioutil"
"net/http"
"net/url" "net/url"
"path" "path"
"strconv" "strconv"
@ -582,7 +583,7 @@ func Home(ctx *context.Context) {
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
} }
@ -641,7 +642,7 @@ func renderCode(ctx *context.Context) {
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
} }
@ -704,7 +705,7 @@ func renderCode(ctx *context.Context) {
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
@ -726,7 +727,7 @@ func RenderUserCards(ctx *context.Context, total int, getter func(opts models.Li
} }
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
@ -765,5 +766,5 @@ func Forks(ctx *context.Context) {
} }
ctx.Data["Forks"] = forks ctx.Data["Forks"] = forks
ctx.HTML(200, tplForks) ctx.HTML(http.StatusOK, tplForks)
} }

View File

@ -8,6 +8,7 @@ package repo
import ( import (
"errors" "errors"
"fmt" "fmt"
"net/http"
"path" "path"
"strings" "strings"
@ -47,7 +48,7 @@ func Webhooks(ctx *context.Context) {
} }
ctx.Data["Webhooks"] = ws ctx.Data["Webhooks"] = ws
ctx.HTML(200, tplHooks) ctx.HTML(http.StatusOK, tplHooks)
} }
type orgRepoCtx struct { type orgRepoCtx struct {
@ -148,7 +149,7 @@ func WebhooksNew(ctx *context.Context) {
} }
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
@ -198,7 +199,7 @@ func GiteaHooksNewPost(ctx *context.Context) {
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
} }
@ -253,7 +254,7 @@ func newGogsWebhookPost(ctx *context.Context, form auth.NewGogshookForm, kind mo
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
} }
@ -301,7 +302,7 @@ func DiscordHooksNewPost(ctx *context.Context) {
} }
if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, orCtx.NewTemplate) ctx.HTML(http.StatusOK, orCtx.NewTemplate)
return return
} }
@ -354,7 +355,7 @@ func DingtalkHooksNewPost(ctx *context.Context) {
} }
if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, orCtx.NewTemplate) ctx.HTML(http.StatusOK, orCtx.NewTemplate)
return return
} }
@ -397,7 +398,7 @@ func TelegramHooksNewPost(ctx *context.Context) {
} }
if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, orCtx.NewTemplate) ctx.HTML(http.StatusOK, orCtx.NewTemplate)
return return
} }
@ -450,7 +451,7 @@ func MatrixHooksNewPost(ctx *context.Context) {
} }
if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, orCtx.NewTemplate) ctx.HTML(http.StatusOK, orCtx.NewTemplate)
return return
} }
@ -506,7 +507,7 @@ func MSTeamsHooksNewPost(ctx *context.Context) {
} }
if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, orCtx.NewTemplate) ctx.HTML(http.StatusOK, orCtx.NewTemplate)
return return
} }
@ -549,7 +550,7 @@ func SlackHooksNewPost(ctx *context.Context) {
} }
if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, orCtx.NewTemplate) ctx.HTML(http.StatusOK, orCtx.NewTemplate)
return return
} }
@ -610,7 +611,7 @@ func FeishuHooksNewPost(ctx *context.Context) {
} }
if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, orCtx.NewTemplate) ctx.HTML(http.StatusOK, orCtx.NewTemplate)
return return
} }
@ -695,7 +696,7 @@ func WebHooksEdit(ctx *context.Context) {
} }
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
@ -712,7 +713,7 @@ func WebHooksEditPost(ctx *context.Context) {
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
} }
@ -753,7 +754,7 @@ func GogsHooksEditPost(ctx *context.Context) {
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
} }
@ -793,7 +794,7 @@ func SlackHooksEditPost(ctx *context.Context) {
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
} }
@ -845,7 +846,7 @@ func DiscordHooksEditPost(ctx *context.Context) {
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
} }
@ -889,7 +890,7 @@ func DingtalkHooksEditPost(ctx *context.Context) {
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
} }
@ -922,7 +923,7 @@ func TelegramHooksEditPost(ctx *context.Context) {
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
@ -964,7 +965,7 @@ func MatrixHooksEditPost(ctx *context.Context) {
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
@ -1009,7 +1010,7 @@ func MSTeamsHooksEditPost(ctx *context.Context) {
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
} }
@ -1042,7 +1043,7 @@ func FeishuHooksEditPost(ctx *context.Context) {
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
} }
@ -1124,7 +1125,7 @@ func DeleteWebhook(ctx *context.Context) {
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",
}) })
} }

View File

@ -8,6 +8,7 @@ package repo
import ( import (
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"net/http"
"net/url" "net/url"
"path/filepath" "path/filepath"
"strings" "strings"
@ -349,7 +350,7 @@ func Wiki(ctx *context.Context) {
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
} }
@ -367,7 +368,7 @@ func Wiki(ctx *context.Context) {
}() }()
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
} }
@ -384,7 +385,7 @@ func Wiki(ctx *context.Context) {
} }
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
@ -394,7 +395,7 @@ func WikiRevision(ctx *context.Context) {
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
} }
@ -412,7 +413,7 @@ func WikiRevision(ctx *context.Context) {
}() }()
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
} }
@ -425,7 +426,7 @@ func WikiRevision(ctx *context.Context) {
} }
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
@ -495,7 +496,7 @@ func WikiPages(ctx *context.Context) {
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)
@ -553,7 +554,7 @@ func NewWiki(ctx *context.Context) {
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
@ -564,7 +565,7 @@ func NewWikiPost(ctx *context.Context) {
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
} }
@ -611,7 +612,7 @@ func EditWiki(ctx *context.Context) {
return return
} }
ctx.HTML(200, tplWikiNew) ctx.HTML(http.StatusOK, tplWikiNew)
} }
// EditWikiPost response for wiki modify request // EditWikiPost response for wiki modify request
@ -622,7 +623,7 @@ func EditWikiPost(ctx *context.Context) {
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
} }
@ -653,7 +654,7 @@ func DeleteWikiPagePost(ctx *context.Context) {
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/",
}) })
} }

View File

@ -313,21 +313,21 @@ func RegisterRoutes(m *web.Route) {
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
} }
} }
@ -335,7 +335,7 @@ func RegisterRoutes(m *web.Route) {
// 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
} }
} }

View File

@ -5,6 +5,8 @@
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"
@ -19,6 +21,6 @@ func SwaggerV1Json(ctx *context.Context) {
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)
} }
} }

View File

@ -146,7 +146,7 @@ func SignIn(ctx *context.Context) {
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
@ -167,7 +167,7 @@ func SignInPost(ctx *context.Context) {
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
} }
@ -183,15 +183,15 @@ func SignInPost(ctx *context.Context) {
} 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)
@ -248,7 +248,7 @@ func TwoFactor(ctx *context.Context) {
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.
@ -327,7 +327,7 @@ func TwoFactorScratch(ctx *context.Context) {
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.
@ -393,7 +393,7 @@ func U2F(ctx *context.Context) {
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
@ -427,7 +427,7 @@ func U2FChallenge(ctx *context.Context) {
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
@ -487,7 +487,7 @@ func U2FSign(ctx *context.Context) {
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.
@ -791,7 +791,7 @@ func LinkAccount(ctx *context.Context) {
} }
} }
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
@ -821,7 +821,7 @@ func LinkAccountPostSignIn(ctx *context.Context) {
} }
if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, tplLinkAccount) ctx.HTML(http.StatusOK, tplLinkAccount)
return return
} }
@ -908,12 +908,12 @@ func LinkAccountPostRegister(ctx *context.Context) {
} }
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
} }
@ -1033,7 +1033,7 @@ func LinkAccountPostRegister(ctx *context.Context) {
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)
@ -1084,7 +1084,7 @@ func SignUp(ctx *context.Context) {
//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
@ -1104,12 +1104,12 @@ func SignUpPost(ctx *context.Context) {
//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
} }
@ -1218,7 +1218,7 @@ func SignUpPost(ctx *context.Context) {
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)
@ -1238,7 +1238,7 @@ func Activate(ctx *context.Context) {
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.
@ -1256,7 +1256,7 @@ func Activate(ctx *context.Context) {
} else { } else {
ctx.Data["ServiceNotEnabled"] = true ctx.Data["ServiceNotEnabled"] = true
} }
ctx.HTML(200, TplActivate) ctx.HTML(http.StatusOK, TplActivate)
return return
} }
@ -1264,7 +1264,7 @@ func Activate(ctx *context.Context) {
// 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
} }
@ -1273,12 +1273,12 @@ func Activate(ctx *context.Context) {
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
} }
} }
@ -1291,7 +1291,7 @@ func Activate(ctx *context.Context) {
} }
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)
} }
@ -1348,7 +1348,7 @@ func ForgotPasswd(ctx *context.Context) {
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
} }
@ -1356,7 +1356,7 @@ func ForgotPasswd(ctx *context.Context) {
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
@ -1377,7 +1377,7 @@ func ForgotPasswdPost(ctx *context.Context) {
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
} }
@ -1393,7 +1393,7 @@ func ForgotPasswdPost(ctx *context.Context) {
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
} }
@ -1405,7 +1405,7 @@ func ForgotPasswdPost(ctx *context.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["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) {
@ -1461,7 +1461,7 @@ func ResetPasswd(ctx *context.Context) {
return return
} }
ctx.HTML(200, tplResetPassword) ctx.HTML(http.StatusOK, tplResetPassword)
} }
// ResetPasswdPost response from account recovery request // ResetPasswdPost response from account recovery request
@ -1473,7 +1473,7 @@ func ResetPasswdPost(ctx *context.Context) {
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
} }
@ -1578,7 +1578,7 @@ func MustChangePassword(ctx *context.Context) {
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
@ -1588,7 +1588,7 @@ func MustChangePasswordPost(ctx *context.Context) {
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

View File

@ -6,6 +6,7 @@ package user
import ( import (
"fmt" "fmt"
"net/http"
"net/url" "net/url"
"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
@ -61,7 +62,7 @@ func SignInOpenID(ctx *context.Context) {
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
@ -97,7 +98,7 @@ func SignInOpenIDPost(ctx *context.Context) {
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
} }
@ -273,7 +274,7 @@ func ConnectOpenID(ctx *context.Context) {
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
@ -344,7 +345,7 @@ func RegisterOpenID(ctx *context.Context) {
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
@ -472,7 +473,7 @@ func RegisterOpenIDPost(ctx *context.Context) {
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)

View File

@ -8,6 +8,7 @@ package user
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"net/http"
"regexp" "regexp"
"sort" "sort"
"strconv" "strconv"
@ -160,7 +161,7 @@ func Dashboard(ctx *context.Context) {
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
@ -320,7 +321,7 @@ func Milestones(ctx *context.Context) {
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
@ -705,7 +706,7 @@ func buildIssueOverview(ctx *context.Context, unitType models.UnitType) {
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 {

View File

@ -8,6 +8,7 @@ import (
"encoding/base64" "encoding/base64"
"fmt" "fmt"
"html" "html"
"net/http"
"net/url" "net/url"
"strings" "strings"
@ -339,7 +340,7 @@ func AuthorizeOAuth(ctx *context.Context) {
// 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
@ -347,7 +348,7 @@ func GrantApplicationOAuth(ctx *context.Context) {
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)
@ -463,7 +464,7 @@ func handleRefreshToken(ctx *context.Context, form auth.AccessTokenForm) {
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) {
@ -526,11 +527,11 @@ 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) {

View File

@ -7,6 +7,7 @@ package user
import ( import (
"fmt" "fmt"
"net/http"
"path" "path"
"strings" "strings"
@ -49,7 +50,7 @@ func Profile(ctx *context.Context) {
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
} }
@ -268,7 +269,7 @@ func Profile(ctx *context.Context) {
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

View File

@ -7,6 +7,7 @@ package setting
import ( import (
"errors" "errors"
"net/http"
"time" "time"
"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
@ -33,7 +34,7 @@ func Account(ctx *context.Context) {
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
@ -45,7 +46,7 @@ func AccountPost(ctx *context.Context) {
if ctx.HasError() { if ctx.HasError() {
loadAccountData(ctx) loadAccountData(ctx)
ctx.HTML(200, tplSettingsAccount) ctx.HTML(http.StatusOK, tplSettingsAccount)
return return
} }
@ -167,7 +168,7 @@ func EmailPost(ctx *context.Context) {
if ctx.HasError() { if ctx.HasError() {
loadAccountData(ctx) loadAccountData(ctx)
ctx.HTML(200, tplSettingsAccount) ctx.HTML(http.StatusOK, tplSettingsAccount)
return return
} }
@ -216,7 +217,7 @@ func DeleteEmail(ctx *context.Context) {
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",
}) })
} }

View File

@ -6,6 +6,8 @@
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"
@ -25,7 +27,7 @@ func Applications(ctx *context.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
@ -37,7 +39,7 @@ func ApplicationsPost(ctx *context.Context) {
if ctx.HasError() { if ctx.HasError() {
loadApplicationsData(ctx) loadApplicationsData(ctx)
ctx.HTML(200, tplSettingsApplications) ctx.HTML(http.StatusOK, tplSettingsApplications)
return return
} }
@ -76,7 +78,7 @@ func DeleteApplication(ctx *context.Context) {
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",
}) })
} }

View File

@ -6,6 +6,8 @@
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"
@ -28,7 +30,7 @@ func Keys(ctx *context.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
@ -43,7 +45,7 @@ func KeysPost(ctx *context.Context) {
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 {
@ -188,7 +190,7 @@ func DeleteKey(ctx *context.Context) {
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",
}) })
} }

View File

@ -6,6 +6,7 @@ package setting
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"
@ -29,7 +30,7 @@ func OAuthApplicationsPost(ctx *context.Context) {
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
@ -49,7 +50,7 @@ func OAuthApplicationsPost(ctx *context.Context) {
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
@ -61,7 +62,7 @@ func OAuthApplicationsEdit(ctx *context.Context) {
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
@ -76,7 +77,7 @@ func OAuthApplicationsEdit(ctx *context.Context) {
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
@ -104,7 +105,7 @@ func OAuthApplicationsRegenerateSecret(ctx *context.Context) {
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
@ -123,7 +124,7 @@ func OAuth2ApplicationShow(ctx *context.Context) {
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
@ -135,7 +136,7 @@ func DeleteOAuth2Application(ctx *context.Context) {
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",
}) })
} }
@ -152,7 +153,7 @@ func RevokeOAuth2Grant(ctx *context.Context) {
} }
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",
}) })
} }

View File

@ -9,6 +9,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"net/http"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
@ -37,7 +38,7 @@ func Profile(ctx *context.Context) {
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
@ -79,7 +80,7 @@ func ProfilePost(ctx *context.Context) {
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
} }
@ -204,7 +205,7 @@ func Organization(ctx *context.Context) {
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
@ -305,5 +306,5 @@ func Repos(ctx *context.Context) {
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)
} }

View File

@ -6,6 +6,8 @@
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"
@ -30,7 +32,7 @@ func Security(ctx *context.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
@ -46,7 +48,7 @@ func DeleteAccountLink(ctx *context.Context) {
} }
} }
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",
}) })
} }

View File

@ -5,6 +5,8 @@
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"
@ -23,7 +25,7 @@ func OpenIDPost(ctx *context.Context) {
if ctx.HasError() { if ctx.HasError() {
loadSecurityData(ctx) loadSecurityData(ctx)
ctx.HTML(200, tplSettingsSecurity) ctx.HTML(http.StatusOK, tplSettingsSecurity)
return return
} }
@ -111,7 +113,7 @@ func DeleteOpenID(ctx *context.Context) {
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",
}) })
} }

View File

@ -10,6 +10,7 @@ import (
"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"
@ -162,7 +163,7 @@ func EnrollTwoFactor(ctx *context.Context) {
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.
@ -187,7 +188,7 @@ func EnrollTwoFactorPost(ctx *context.Context) {
if !twofaGenerateSecretAndQr(ctx) { if !twofaGenerateSecretAndQr(ctx) {
return return
} }
ctx.HTML(200, tplSettingsTwofaEnroll) ctx.HTML(http.StatusOK, tplSettingsTwofaEnroll)
return return
} }

View File

@ -6,6 +6,7 @@ package setting
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"
@ -21,7 +22,7 @@ import (
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)
@ -40,7 +41,7 @@ func U2FRegister(ctx *context.Context) {
} }
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
} }
} }
@ -53,7 +54,7 @@ func U2FRegister(ctx *context.Context) {
// 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
@ -104,7 +105,7 @@ func U2FDelete(ctx *context.Context) {
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",
}) })
} }

View File

@ -5,6 +5,8 @@
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"
) )
@ -13,13 +15,13 @@ import (
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,