diff options
author | kolaente <konrad@kola-entertainments.de> | 2019-06-12 21:41:28 +0200 |
---|---|---|
committer | techknowlogick <techknowlogick@gitea.io> | 2019-06-12 15:41:28 -0400 |
commit | f9ec2f89f2265bc1371a6c62359de9816534fa6b (patch) | |
tree | f48b138a457e5ac6cf843bbb38400926704370f7 /routers | |
parent | 5832f8d90df2d72cb38698c3e9050f2b29717dc7 (diff) | |
download | gitea-f9ec2f89f2265bc1371a6c62359de9816534fa6b.tar.gz gitea-f9ec2f89f2265bc1371a6c62359de9816534fa6b.zip |
Add golangci (#6418)
Diffstat (limited to 'routers')
29 files changed, 306 insertions, 159 deletions
diff --git a/routers/admin/admin.go b/routers/admin/admin.go index 5107e18b7d..b4eac2c677 100644 --- a/routers/admin/admin.go +++ b/routers/admin/admin.go @@ -261,10 +261,6 @@ func Config(ctx *context.Context) { } ctx.Data["EnvVars"] = envVars - - type logger struct { - Mode, Config string - } ctx.Data["Loggers"] = setting.LogDescriptions ctx.Data["RedirectMacaronLog"] = setting.RedirectMacaronLog ctx.Data["EnableAccessLog"] = setting.EnableAccessLog diff --git a/routers/api/v1/misc/markdown.go b/routers/api/v1/misc/markdown.go index 06e344a15b..b00b00c499 100644 --- a/routers/api/v1/misc/markdown.go +++ b/routers/api/v1/misc/markdown.go @@ -5,6 +5,7 @@ package misc import ( + "net/http" "strings" api "code.gitea.io/gitea/modules/structs" @@ -42,7 +43,7 @@ func Markdown(ctx *context.APIContext, form api.MarkdownOption) { } if len(form.Text) == 0 { - ctx.Write([]byte("")) + _, _ = ctx.Write([]byte("")) return } @@ -63,12 +64,24 @@ func Markdown(ctx *context.APIContext, form api.MarkdownOption) { meta = ctx.Repo.Repository.ComposeMetas() } if form.Wiki { - ctx.Write([]byte(markdown.RenderWiki(md, urlPrefix, meta))) + _, err := ctx.Write([]byte(markdown.RenderWiki(md, urlPrefix, meta))) + if err != nil { + ctx.Error(http.StatusInternalServerError, "", err) + return + } } else { - ctx.Write(markdown.Render(md, urlPrefix, meta)) + _, err := ctx.Write(markdown.Render(md, urlPrefix, meta)) + if err != nil { + ctx.Error(http.StatusInternalServerError, "", err) + return + } } default: - ctx.Write(markdown.RenderRaw([]byte(form.Text), "", false)) + _, err := ctx.Write(markdown.RenderRaw([]byte(form.Text), "", false)) + if err != nil { + ctx.Error(http.StatusInternalServerError, "", err) + return + } } } @@ -98,5 +111,9 @@ func MarkdownRaw(ctx *context.APIContext) { ctx.Error(422, "", err) return } - ctx.Write(markdown.RenderRaw(body, "", false)) + _, err = ctx.Write(markdown.RenderRaw(body, "", false)) + if err != nil { + ctx.Error(http.StatusInternalServerError, "", err) + return + } } diff --git a/routers/api/v1/repo/pull.go b/routers/api/v1/repo/pull.go index 0e1db144b1..b14b0b02b8 100644 --- a/routers/api/v1/repo/pull.go +++ b/routers/api/v1/repo/pull.go @@ -353,7 +353,11 @@ func EditPullRequest(ctx *context.APIContext, form api.EditPullRequestOption) { return } - pr.LoadIssue() + err = pr.LoadIssue() + if err != nil { + ctx.Error(http.StatusInternalServerError, "LoadIssue", err) + return + } issue := pr.Issue issue.Repo = ctx.Repo.Repository @@ -547,7 +551,11 @@ func MergePullRequest(ctx *context.APIContext, form auth.MergePullRequestForm) { return } - pr.LoadIssue() + err = pr.LoadIssue() + if err != nil { + ctx.Error(http.StatusInternalServerError, "LoadIssue", err) + return + } pr.Issue.Repo = ctx.Repo.Repository if ctx.IsSigned { diff --git a/routers/api/v1/repo/repo.go b/routers/api/v1/repo/repo.go index f8df3e9fa1..26cfff51ce 100644 --- a/routers/api/v1/repo/repo.go +++ b/routers/api/v1/repo/repo.go @@ -631,15 +631,6 @@ func updateBasicProperties(ctx *context.APIContext, opts api.EditRepoOption) err return nil } -func unitTypeInTypes(unitType models.UnitType, unitTypes []models.UnitType) bool { - for _, tp := range unitTypes { - if unitType == tp { - return true - } - } - return false -} - // updateRepoUnits updates repo units: Issue settings, Wiki settings, PR settings func updateRepoUnits(ctx *context.APIContext, opts api.EditRepoOption) error { owner := ctx.Repo.Owner diff --git a/routers/api/v1/user/gpg_key.go b/routers/api/v1/user/gpg_key.go index c2c55e9b92..7bf43c5822 100644 --- a/routers/api/v1/user/gpg_key.go +++ b/routers/api/v1/user/gpg_key.go @@ -9,14 +9,9 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/context" - "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/routers/api/v1/convert" ) -func composePublicGPGKeysAPILink() string { - return setting.AppURL + "api/v1/user/gpg_keys/" -} - func listGPGKeys(ctx *context.APIContext, uid int64) { keys, err := models.ListGPGKeys(uid) if err != nil { diff --git a/routers/init.go b/routers/init.go index b3078b478a..e6b23cf8b8 100644 --- a/routers/init.go +++ b/routers/init.go @@ -41,7 +41,7 @@ func checkRunMode() { func NewServices() { setting.NewServices() mailer.NewContext() - cache.NewContext() + _ = cache.NewContext() } // In case of problems connecting to DB, retry connection. Eg, PGSQL in Docker Container on Synology diff --git a/routers/org/teams.go b/routers/org/teams.go index 27db14e4b5..f662bd92e2 100644 --- a/routers/org/teams.go +++ b/routers/org/teams.go @@ -5,6 +5,7 @@ package org import ( + "net/http" "path" "strings" @@ -287,7 +288,11 @@ func EditTeamPost(ctx *context.Context, form auth.CreateTeamForm) { Type: tp, }) } - models.UpdateTeamUnits(t, units) + err := models.UpdateTeamUnits(t, units) + if err != nil { + ctx.Error(http.StatusInternalServerError, "LoadIssue", err.Error()) + return + } } if ctx.HasError() { diff --git a/routers/private/hook.go b/routers/private/hook.go index a5985f161e..3da5e38edb 100644 --- a/routers/private/hook.go +++ b/routers/private/hook.go @@ -214,5 +214,4 @@ func HookPostReceive(ctx *macaron.Context) { ctx.JSON(http.StatusOK, map[string]interface{}{ "message": false, }) - return } diff --git a/routers/private/serv.go b/routers/private/serv.go index 68e4361e56..90579a3dcc 100644 --- a/routers/private/serv.go +++ b/routers/private/serv.go @@ -62,7 +62,6 @@ func ServNoCommand(ctx *macaron.Context) { results.Owner = user } ctx.JSON(http.StatusOK, &results) - return } // ServCommand returns information about the provided keyid @@ -282,5 +281,4 @@ func ServCommand(ctx *macaron.Context) { ctx.JSON(http.StatusOK, results) // We will update the keys in a different call. - return } diff --git a/routers/repo/blame.go b/routers/repo/blame.go index 964fdc8746..2b2f45f0bb 100644 --- a/routers/repo/blame.go +++ b/routers/repo/blame.go @@ -192,7 +192,7 @@ func RefBlame(ctx *context.Context) { func renderBlame(ctx *context.Context, blameParts []models.BlamePart, commitNames map[string]models.UserCommit) { repoLink := ctx.Repo.RepoLink - var lines = make([]string, 0, 0) + var lines = make([]string, 0) var commitInfo bytes.Buffer var lineNumbers bytes.Buffer diff --git a/routers/repo/commit.go b/routers/repo/commit.go index dde6d8f321..4dbedea2a0 100644 --- a/routers/repo/commit.go +++ b/routers/repo/commit.go @@ -261,6 +261,9 @@ func Diff(ctx *context.Context) { } ctx.Data["RawPath"] = setting.AppSubURL + "/" + path.Join(userName, repoName, "raw", "commit", commitID) ctx.Data["BranchName"], err = commit.GetBranchName() + if err != nil { + ctx.ServerError("commit.GetBranchName", err) + } ctx.HTML(200, tplCommitPage) } diff --git a/routers/repo/download.go b/routers/repo/download.go index 41c4a18102..2da8b109ca 100644 --- a/routers/repo/download.go +++ b/routers/repo/download.go @@ -15,6 +15,7 @@ import ( "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/lfs" + "code.gitea.io/gitea/modules/log" ) // ServeData download file from io.Reader @@ -39,8 +40,11 @@ func ServeData(ctx *context.Context, name string, reader io.Reader) error { ctx.Resp.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, name)) } - ctx.Resp.Write(buf) - _, err := io.Copy(ctx.Resp, reader) + _, err := ctx.Resp.Write(buf) + if err != nil { + return err + } + _, err = io.Copy(ctx.Resp, reader) return err } @@ -50,7 +54,11 @@ func ServeBlob(ctx *context.Context, blob *git.Blob) error { if err != nil { return err } - defer dataRc.Close() + defer func() { + if err = dataRc.Close(); err != nil { + log.Error("ServeBlob: Close: %v", err) + } + }() return ServeData(ctx, ctx.Repo.TreePath, dataRc) } @@ -61,7 +69,11 @@ func ServeBlobOrLFS(ctx *context.Context, blob *git.Blob) error { if err != nil { return err } - defer dataRc.Close() + defer func() { + if err = dataRc.Close(); err != nil { + log.Error("ServeBlobOrLFS: Close: %v", err) + } + }() if meta, _ := lfs.ReadPointerFile(dataRc); meta != nil { meta, _ = ctx.Repo.Repository.GetLFSMetaObjectByOid(meta.Oid) diff --git a/routers/repo/editor.go b/routers/repo/editor.go index 46f12d66d2..062ecfebf7 100644 --- a/routers/repo/editor.go +++ b/routers/repo/editor.go @@ -118,9 +118,7 @@ func editFile(ctx *context.Context, isNewFile bool) { d, _ := ioutil.ReadAll(dataRc) buf = append(buf, d...) if content, err := templates.ToUTF8WithErr(buf); err != nil { - if err != nil { - log.Error("ToUTF8WithErr: %v", err) - } + log.Error("ToUTF8WithErr: %v", err) ctx.Data["FileContent"] = string(buf) } else { ctx.Data["FileContent"] = content @@ -235,16 +233,12 @@ func editFilePost(ctx *context.Context, form auth.EditRepoFileForm, isNewFile bo switch fileErr.Type { case git.EntryModeSymlink: ctx.RenderWithErr(ctx.Tr("repo.editor.file_is_a_symlink", fileErr.Path), tplEditFile, &form) - break case git.EntryModeTree: ctx.RenderWithErr(ctx.Tr("repo.editor.filename_is_a_directory", fileErr.Path), tplEditFile, &form) - break case git.EntryModeBlob: ctx.RenderWithErr(ctx.Tr("repo.editor.directory_is_a_file", fileErr.Path), tplEditFile, &form) - break default: ctx.Error(500, err.Error()) - break } } else { ctx.Error(500, err.Error()) @@ -403,16 +397,12 @@ func DeleteFilePost(ctx *context.Context, form auth.DeleteRepoFileForm) { switch fileErr.Type { case git.EntryModeSymlink: ctx.RenderWithErr(ctx.Tr("repo.editor.file_is_a_symlink", fileErr.Path), tplEditFile, &form) - break case git.EntryModeTree: ctx.RenderWithErr(ctx.Tr("repo.editor.filename_is_a_directory", fileErr.Path), tplEditFile, &form) - break case git.EntryModeBlob: ctx.RenderWithErr(ctx.Tr("repo.editor.directory_is_a_file", fileErr.Path), tplEditFile, &form) - break default: ctx.ServerError("DeleteRepoFile", err) - break } } else { ctx.ServerError("DeleteRepoFile", err) diff --git a/routers/repo/http.go b/routers/repo/http.go index 214e2f3411..3072209448 100644 --- a/routers/repo/http.go +++ b/routers/repo/http.go @@ -206,10 +206,8 @@ func HTTP(ctx *context.Context) { if err = models.UpdateAccessToken(token); err != nil { ctx.ServerError("UpdateAccessToken", err) } - } else { - if !models.IsErrAccessTokenNotExist(err) && !models.IsErrAccessTokenEmpty(err) { - log.Error("GetAccessTokenBySha: %v", err) - } + } else if !models.IsErrAccessTokenNotExist(err) && !models.IsErrAccessTokenEmpty(err) { + log.Error("GetAccessTokenBySha: %v", err) } if authUser == nil { @@ -332,17 +330,17 @@ type route struct { } var routes = []route{ - {regexp.MustCompile("(.*?)/git-upload-pack$"), "POST", serviceUploadPack}, - {regexp.MustCompile("(.*?)/git-receive-pack$"), "POST", serviceReceivePack}, - {regexp.MustCompile("(.*?)/info/refs$"), "GET", getInfoRefs}, - {regexp.MustCompile("(.*?)/HEAD$"), "GET", getTextFile}, - {regexp.MustCompile("(.*?)/objects/info/alternates$"), "GET", getTextFile}, - {regexp.MustCompile("(.*?)/objects/info/http-alternates$"), "GET", getTextFile}, - {regexp.MustCompile("(.*?)/objects/info/packs$"), "GET", getInfoPacks}, - {regexp.MustCompile("(.*?)/objects/info/[^/]*$"), "GET", getTextFile}, - {regexp.MustCompile("(.*?)/objects/[0-9a-f]{2}/[0-9a-f]{38}$"), "GET", getLooseObject}, - {regexp.MustCompile("(.*?)/objects/pack/pack-[0-9a-f]{40}\\.pack$"), "GET", getPackFile}, - {regexp.MustCompile("(.*?)/objects/pack/pack-[0-9a-f]{40}\\.idx$"), "GET", getIdxFile}, + {regexp.MustCompile(`(.*?)/git-upload-pack$`), "POST", serviceUploadPack}, + {regexp.MustCompile(`(.*?)/git-receive-pack$`), "POST", serviceReceivePack}, + {regexp.MustCompile(`(.*?)/info/refs$`), "GET", getInfoRefs}, + {regexp.MustCompile(`(.*?)/HEAD$`), "GET", getTextFile}, + {regexp.MustCompile(`(.*?)/objects/info/alternates$`), "GET", getTextFile}, + {regexp.MustCompile(`(.*?)/objects/info/http-alternates$`), "GET", getTextFile}, + {regexp.MustCompile(`(.*?)/objects/info/packs$`), "GET", getInfoPacks}, + {regexp.MustCompile(`(.*?)/objects/info/[^/]*$`), "GET", getTextFile}, + {regexp.MustCompile(`(.*?)/objects/[0-9a-f]{2}/[0-9a-f]{38}$`), "GET", getLooseObject}, + {regexp.MustCompile(`(.*?)/objects/pack/pack-[0-9a-f]{40}\.pack$`), "GET", getPackFile}, + {regexp.MustCompile(`(.*?)/objects/pack/pack-[0-9a-f]{40}\.idx$`), "GET", getIdxFile}, } // FIXME: use process module @@ -393,7 +391,12 @@ func hasAccess(service string, h serviceHandler, checkContentType bool) bool { } func serviceRPC(h serviceHandler, service string) { - defer h.r.Body.Close() + defer func() { + if err := h.r.Body.Close(); err != nil { + log.Error("serviceRPC: Close: %v", err) + } + + }() if !hasAccess(service, h, true) { h.w.WriteHeader(http.StatusUnauthorized) @@ -469,9 +472,9 @@ func getInfoRefs(h serviceHandler) { h.w.Header().Set("Content-Type", fmt.Sprintf("application/x-git-%s-advertisement", service)) h.w.WriteHeader(http.StatusOK) - h.w.Write(packetWrite("# service=git-" + service + "\n")) - h.w.Write([]byte("0000")) - h.w.Write(refs) + _, _ = h.w.Write(packetWrite("# service=git-" + service + "\n")) + _, _ = h.w.Write([]byte("0000")) + _, _ = h.w.Write(refs) } else { updateServerInfo(h.dir) h.sendFile("text/plain; charset=utf-8") @@ -524,16 +527,25 @@ func HTTPBackend(ctx *context.Context, cfg *serviceConfig) http.HandlerFunc { if m := route.reg.FindStringSubmatch(r.URL.Path); m != nil { if setting.Repository.DisableHTTPGit { w.WriteHeader(http.StatusForbidden) - w.Write([]byte("Interacting with repositories by HTTP protocol is not allowed")) + _, err := w.Write([]byte("Interacting with repositories by HTTP protocol is not allowed")) + if err != nil { + log.Error(err.Error()) + } return } if route.method != r.Method { if r.Proto == "HTTP/1.1" { w.WriteHeader(http.StatusMethodNotAllowed) - w.Write([]byte("Method Not Allowed")) + _, err := w.Write([]byte("Method Not Allowed")) + if err != nil { + log.Error(err.Error()) + } } else { w.WriteHeader(http.StatusBadRequest) - w.Write([]byte("Bad Request")) + _, err := w.Write([]byte("Bad Request")) + if err != nil { + log.Error(err.Error()) + } } return } @@ -552,6 +564,5 @@ func HTTPBackend(ctx *context.Context, cfg *serviceConfig) http.HandlerFunc { } ctx.NotFound("HTTPBackend", nil) - return } } diff --git a/routers/repo/issue.go b/routers/repo/issue.go index cd384da0d6..3904d29532 100644 --- a/routers/repo/issue.go +++ b/routers/repo/issue.go @@ -945,7 +945,15 @@ func ViewIssue(ctx *context.Context) { // Get Dependencies ctx.Data["BlockedByDependencies"], err = issue.BlockedByDependencies() + if err != nil { + ctx.ServerError("BlockedByDependencies", err) + return + } ctx.Data["BlockingDependencies"], err = issue.BlockingDependencies() + if err != nil { + ctx.ServerError("BlockingDependencies", err) + return + } ctx.Data["Participants"] = participants ctx.Data["NumParticipants"] = len(participants) @@ -1226,7 +1234,8 @@ func NewComment(ctx *context.Context, form auth.CreateCommentForm) { if form.Status == "reopen" && issue.IsPull { pull := issue.PullRequest - pr, err := models.GetUnmergedPullRequest(pull.HeadRepoID, pull.BaseRepoID, pull.HeadBranch, pull.BaseBranch) + var err error + pr, err = models.GetUnmergedPullRequest(pull.HeadRepoID, pull.BaseRepoID, pull.HeadBranch, pull.BaseBranch) if err != nil { if !models.IsErrPullRequestNotExist(err) { ctx.ServerError("GetUnmergedPullRequest", err) diff --git a/routers/repo/issue_label.go b/routers/repo/issue_label.go index 556a24c33e..cae6535c79 100644 --- a/routers/repo/issue_label.go +++ b/routers/repo/issue_label.go @@ -129,7 +129,6 @@ func DeleteLabel(ctx *context.Context) { ctx.JSON(200, map[string]interface{}{ "redirect": ctx.Repo.RepoLink + "/labels", }) - return } // UpdateIssueLabel change issue's labels diff --git a/routers/repo/milestone.go b/routers/repo/milestone.go index 644f7e043b..3ad638e60a 100644 --- a/routers/repo/milestone.go +++ b/routers/repo/milestone.go @@ -19,7 +19,6 @@ import ( const ( tplMilestone base.TplName = "repo/issue/milestones" tplMilestoneNew base.TplName = "repo/issue/milestone_new" - tplMilestoneEdit base.TplName = "repo/issue/milestone_edit" tplMilestoneIssues base.TplName = "repo/issue/milestone_issues" ) @@ -57,7 +56,7 @@ func Milestones(ctx *context.Context) { return } if ctx.Repo.Repository.IsTimetrackerEnabled() { - if miles.LoadTotalTrackedTimes(); err != nil { + if err := miles.LoadTotalTrackedTimes(); err != nil { ctx.ServerError("LoadTotalTrackedTimes", err) return } diff --git a/routers/repo/pull.go b/routers/repo/pull.go index 71c684356d..5be8aa57c1 100644 --- a/routers/repo/pull.go +++ b/routers/repo/pull.go @@ -793,10 +793,10 @@ func CleanUpPullRequest(ctx *context.Context) { // Forked repository has already been deleted ctx.NotFound("CleanUpPullRequest", nil) return - } else if pr.GetBaseRepo(); err != nil { + } else if err = pr.GetBaseRepo(); err != nil { ctx.ServerError("GetBaseRepo", err) return - } else if pr.HeadRepo.GetOwner(); err != nil { + } else if err = pr.HeadRepo.GetOwner(); err != nil { ctx.ServerError("HeadRepo.GetOwner", err) return } diff --git a/routers/repo/setting.go b/routers/repo/setting.go index 767cdacde0..757295069e 100644 --- a/routers/repo/setting.go +++ b/routers/repo/setting.go @@ -419,7 +419,10 @@ func SettingsPost(ctx *context.Context, form auth.RepoSettingForm) { return } - repo.DeleteWiki() + err := repo.DeleteWiki() + if err != nil { + log.Error("Delete Wiki: %v", err.Error()) + } log.Trace("Repository wiki deleted: %s/%s", ctx.Repo.Owner.Name, repo.Name) ctx.Flash.Success(ctx.Tr("repo.settings.wiki_deletion_success")) diff --git a/routers/repo/view.go b/routers/repo/view.go index 3483a53a0d..edaf24017c 100644 --- a/routers/repo/view.go +++ b/routers/repo/view.go @@ -294,9 +294,7 @@ func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink st // Building code view blocks with line number on server side. var fileContent string if content, err := templates.ToUTF8WithErr(buf); err != nil { - if err != nil { - log.Error("ToUTF8WithErr: %v", err) - } + log.Error("ToUTF8WithErr: %v", err) fileContent = string(buf) } else { fileContent = content diff --git a/routers/repo/webhook.go b/routers/repo/webhook.go index 8daf721b50..20a3a45c18 100644 --- a/routers/repo/webhook.go +++ b/routers/repo/webhook.go @@ -197,12 +197,20 @@ func WebHooksNewPost(ctx *context.Context, form auth.NewWebhookForm) { } // GogsHooksNewPost response for creating webhook -func GogsHooksNewPost(ctx *context.Context, form auth.NewGogshookForm) { +func GogsHooksNewPost(ctx *context.Context, form auth.NewWebhookForm) { + newGenericWebhookPost(ctx, form, models.GOGS) +} + +func newGenericWebhookPost(ctx *context.Context, form auth.NewWebhookForm, kind models.HookTaskType) { ctx.Data["Title"] = ctx.Tr("repo.settings.add_webhook") ctx.Data["PageIsSettingsHooks"] = true ctx.Data["PageIsSettingsHooksNew"] = true ctx.Data["Webhook"] = models.Webhook{HookEvent: &models.HookEvent{}} - ctx.Data["HookType"] = "gogs" + + ctx.Data["HookType"] = "gitea" + if kind == models.GOGS { + ctx.Data["HookType"] = "gogs" + } orCtx, err := getOrgRepoCtx(ctx) if err != nil { @@ -228,7 +236,7 @@ func GogsHooksNewPost(ctx *context.Context, form auth.NewGogshookForm) { Secret: form.Secret, HookEvent: ParseHookEvent(form.WebhookForm), IsActive: form.Active, - HookTaskType: models.GOGS, + HookTaskType: kind, OrgID: orCtx.OrgID, } if err := w.UpdateEvent(); err != nil { diff --git a/routers/routes/routes.go b/routers/routes/routes.go index f7ccfc43d2..744088a9d7 100644 --- a/routers/routes/routes.go +++ b/routers/routes/routes.go @@ -47,19 +47,6 @@ import ( macaron "gopkg.in/macaron.v1" ) -/*func giteaLogger(l *log.LoggerAsWriter) macaron.Handler { - return func(ctx *macaron.Context) { - start := time.Now() - - l.Log(fmt.Sprintf("[Macaron] Started %s %s for %s", ctx.Req.Method, ctx.Req.RequestURI, ctx.RemoteAddr())) - - ctx.Next() - - rw := ctx.Resp.(macaron.ResponseWriter) - l.Log(fmt.Sprintf("[Macaron] Completed %s %s %v %s in %v", ctx.Req.Method, ctx.Req.RequestURI, rw.Status(), http.StatusText(rw.Status()), time.Since(start))) - } -}*/ - type routerLoggerOptions struct { Ctx *macaron.Context Identity *string @@ -83,14 +70,20 @@ func setupAccessLogger(m *macaron.Macaron) { rw := ctx.Resp.(macaron.ResponseWriter) buf := bytes.NewBuffer([]byte{}) - logTemplate.Execute(buf, routerLoggerOptions{ + err := logTemplate.Execute(buf, routerLoggerOptions{ Ctx: ctx, Identity: &identity, Start: &start, ResponseWriter: &rw, }) + if err != nil { + log.Error("Could not set up macaron access logger: %v", err.Error()) + } - logger.SendLog(log.INFO, "", "", 0, buf.String(), "") + err = logger.SendLog(log.INFO, "", "", 0, buf.String(), "") + if err != nil { + log.Error("Could not set up macaron access logger: %v", err.Error()) + } }) } @@ -99,13 +92,13 @@ func RouterHandler(level log.Level) func(ctx *macaron.Context) { return func(ctx *macaron.Context) { start := time.Now() - log.GetLogger("router").Log(0, level, "Started %s %s for %s", log.ColoredMethod(ctx.Req.Method), ctx.Req.RequestURI, ctx.RemoteAddr()) + _ = log.GetLogger("router").Log(0, level, "Started %s %s for %s", log.ColoredMethod(ctx.Req.Method), ctx.Req.RequestURI, ctx.RemoteAddr()) rw := ctx.Resp.(macaron.ResponseWriter) ctx.Next() status := rw.Status() - log.GetLogger("router").Log(0, level, "Completed %s %s %v %s in %v", log.ColoredMethod(ctx.Req.Method), ctx.Req.RequestURI, log.ColoredStatus(status), log.ColoredStatus(status, http.StatusText(rw.Status())), log.ColoredTime(time.Since(start))) + _ = log.GetLogger("router").Log(0, level, "Completed %s %s %v %s in %v", log.ColoredMethod(ctx.Req.Method), ctx.Req.RequestURI, log.ColoredStatus(status), log.ColoredStatus(status, http.StatusText(rw.Status())), log.ColoredTime(time.Since(start))) } } @@ -443,14 +436,14 @@ func RegisterRoutes(m *macaron.Macaron) { m.Post("/delete", admin.DeleteDefaultWebhook) m.Get("/:type/new", repo.WebhooksNew) m.Post("/gitea/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost) - m.Post("/gogs/new", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksNewPost) + m.Post("/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.GogsHooksNewPost) m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost) m.Post("/discord/new", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksNewPost) m.Post("/dingtalk/new", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksNewPost) m.Post("/msteams/new", bindIgnErr(auth.NewMSTeamsHookForm{}), repo.MSTeamsHooksNewPost) m.Get("/:id", repo.WebHooksEdit) m.Post("/gitea/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost) - m.Post("/gogs/:id", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksEditPost) + m.Post("/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.GogsHooksEditPost) m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost) m.Post("/discord/:id", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksEditPost) m.Post("/dingtalk/:id", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksEditPost) @@ -582,7 +575,7 @@ func RegisterRoutes(m *macaron.Macaron) { m.Post("/delete", org.DeleteWebhook) m.Get("/:type/new", repo.WebhooksNew) m.Post("/gitea/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost) - m.Post("/gogs/new", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksNewPost) + m.Post("/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.GogsHooksNewPost) m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost) m.Post("/discord/new", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksNewPost) m.Post("/dingtalk/new", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksNewPost) @@ -640,7 +633,7 @@ func RegisterRoutes(m *macaron.Macaron) { m.Post("/delete", repo.DeleteWebhook) m.Get("/:type/new", repo.WebhooksNew) m.Post("/gitea/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost) - m.Post("/gogs/new", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksNewPost) + m.Post("/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.GogsHooksNewPost) m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost) m.Post("/discord/new", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksNewPost) m.Post("/dingtalk/new", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksNewPost) diff --git a/routers/user/auth.go b/routers/user/auth.go index b8f697b3ca..0731e34675 100644 --- a/routers/user/auth.go +++ b/routers/user/auth.go @@ -77,8 +77,14 @@ func AutoSignIn(ctx *context.Context) (bool, error) { } isSucceed = true - ctx.Session.Set("uid", u.ID) - ctx.Session.Set("uname", u.Name) + err = ctx.Session.Set("uid", u.ID) + if err != nil { + return false, err + } + err = ctx.Session.Set("uname", u.Name) + if err != nil { + return false, err + } ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL, "", setting.SessionConfig.Secure, true) return true, nil } @@ -191,8 +197,16 @@ func SignInPost(ctx *context.Context, form auth.SignInForm) { } // User needs to use 2FA, save data and redirect to 2FA page. - ctx.Session.Set("twofaUid", u.ID) - ctx.Session.Set("twofaRemember", form.Remember) + err = ctx.Session.Set("twofaUid", u.ID) + if err != nil { + ctx.ServerError("UserSignIn", err) + return + } + err = ctx.Session.Set("twofaRemember", form.Remember) + if err != nil { + ctx.ServerError("UserSignIn", err) + return + } regs, err := models.GetU2FRegistrationsByUID(u.ID) if err == nil && len(regs) > 0 { @@ -383,6 +397,10 @@ func U2FChallenge(ctx *context.Context) { return } challenge, err := u2f.NewChallenge(setting.U2F.AppID, setting.U2F.TrustedFacets) + if err != nil { + ctx.ServerError("u2f.NewChallenge", err) + return + } if err = ctx.Session.Set("u2fChallenge", challenge); err != nil { ctx.ServerError("UserSignIn", err) return @@ -462,16 +480,22 @@ func handleSignInFull(ctx *context.Context, u *models.User, remember bool, obeyR setting.CookieRememberName, u.Name, days, setting.AppSubURL, "", setting.SessionConfig.Secure, true) } - ctx.Session.Delete("openid_verified_uri") - ctx.Session.Delete("openid_signin_remember") - ctx.Session.Delete("openid_determined_email") - ctx.Session.Delete("openid_determined_username") - ctx.Session.Delete("twofaUid") - ctx.Session.Delete("twofaRemember") - ctx.Session.Delete("u2fChallenge") - ctx.Session.Delete("linkAccount") - ctx.Session.Set("uid", u.ID) - ctx.Session.Set("uname", u.Name) + _ = ctx.Session.Delete("openid_verified_uri") + _ = ctx.Session.Delete("openid_signin_remember") + _ = ctx.Session.Delete("openid_determined_email") + _ = ctx.Session.Delete("openid_determined_username") + _ = ctx.Session.Delete("twofaUid") + _ = ctx.Session.Delete("twofaRemember") + _ = ctx.Session.Delete("u2fChallenge") + _ = ctx.Session.Delete("linkAccount") + err := ctx.Session.Set("uid", u.ID) + if err != nil { + log.Error(fmt.Sprintf("Error setting session: %v", err)) + } + err = ctx.Session.Set("uname", u.Name) + if err != nil { + log.Error(fmt.Sprintf("Error setting session: %v", err)) + } // Language setting of the user overwrites the one previously set // If the user does not have a locale set, we save the current one. @@ -563,7 +587,10 @@ func handleOAuth2SignIn(u *models.User, gothUser goth.User, ctx *context.Context if u == nil { // no existing user is found, request attach or new account - ctx.Session.Set("linkAccountGothUser", gothUser) + err = ctx.Session.Set("linkAccountGothUser", gothUser) + if err != nil { + log.Error(fmt.Sprintf("Error setting session: %v", err)) + } ctx.Redirect(setting.AppSubURL + "/user/link_account") return } @@ -573,8 +600,14 @@ func handleOAuth2SignIn(u *models.User, gothUser goth.User, ctx *context.Context _, err = models.GetTwoFactorByUID(u.ID) if err != nil { if models.IsErrTwoFactorNotEnrolled(err) { - ctx.Session.Set("uid", u.ID) - ctx.Session.Set("uname", u.Name) + err = ctx.Session.Set("uid", u.ID) + if err != nil { + log.Error(fmt.Sprintf("Error setting session: %v", err)) + } + err = ctx.Session.Set("uname", u.Name) + if err != nil { + log.Error(fmt.Sprintf("Error setting session: %v", err)) + } // Clear whatever CSRF has right now, force to generate a new one ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL, "", setting.SessionConfig.Secure, true) @@ -600,8 +633,14 @@ func handleOAuth2SignIn(u *models.User, gothUser goth.User, ctx *context.Context } // User needs to use 2FA, save data and redirect to 2FA page. - ctx.Session.Set("twofaUid", u.ID) - ctx.Session.Set("twofaRemember", false) + err = ctx.Session.Set("twofaUid", u.ID) + if err != nil { + log.Error(fmt.Sprintf("Error setting session: %v", err)) + } + err = ctx.Session.Set("twofaRemember", false) + if err != nil { + log.Error(fmt.Sprintf("Error setting session: %v", err)) + } // If U2F is enrolled -> Redirect to U2F instead regs, err := models.GetU2FRegistrationsByUID(u.ID) @@ -760,9 +799,18 @@ func LinkAccountPostSignIn(ctx *context.Context, signInForm auth.SignInForm) { } // User needs to use 2FA, save data and redirect to 2FA page. - ctx.Session.Set("twofaUid", u.ID) - ctx.Session.Set("twofaRemember", signInForm.Remember) - ctx.Session.Set("linkAccount", true) + err = ctx.Session.Set("twofaUid", u.ID) + if err != nil { + log.Error(fmt.Sprintf("Error setting session: %v", err)) + } + err = ctx.Session.Set("twofaRemember", signInForm.Remember) + if err != nil { + log.Error(fmt.Sprintf("Error setting session: %v", err)) + } + err = ctx.Session.Set("linkAccount", true) + if err != nil { + log.Error(fmt.Sprintf("Error setting session: %v", err)) + } // If U2F is enrolled -> Redirect to U2F instead regs, err := models.GetU2FRegistrationsByUID(u.ID) @@ -897,11 +945,11 @@ func LinkAccountPostRegister(ctx *context.Context, cpt *captcha.Captcha, form au } func handleSignOut(ctx *context.Context) { - ctx.Session.Delete("uid") - ctx.Session.Delete("uname") - ctx.Session.Delete("socialId") - ctx.Session.Delete("socialName") - ctx.Session.Delete("socialEmail") + _ = ctx.Session.Delete("uid") + _ = ctx.Session.Delete("uname") + _ = ctx.Session.Delete("socialId") + _ = ctx.Session.Delete("socialName") + _ = ctx.Session.Delete("socialEmail") ctx.SetCookie(setting.CookieUserName, "", -1, setting.AppSubURL, "", setting.SessionConfig.Secure, true) ctx.SetCookie(setting.CookieRememberName, "", -1, setting.AppSubURL, "", setting.SessionConfig.Secure, true) ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL, "", setting.SessionConfig.Secure, true) @@ -1086,8 +1134,14 @@ func Activate(ctx *context.Context) { log.Trace("User activated: %s", user.Name) - ctx.Session.Set("uid", user.ID) - ctx.Session.Set("uname", user.Name) + err = ctx.Session.Set("uid", user.ID) + if err != nil { + log.Error(fmt.Sprintf("Error setting session: %v", err)) + } + err = ctx.Session.Set("uname", user.Name) + if err != nil { + log.Error(fmt.Sprintf("Error setting session: %v", err)) + } ctx.Flash.Success(ctx.Tr("auth.account_activated")) ctx.Redirect(setting.AppSubURL + "/") return @@ -1113,7 +1167,6 @@ func ActivateEmail(ctx *context.Context) { } ctx.Redirect(setting.AppSubURL + "/user/settings/email") - return } // ForgotPasswd render the forget pasword page diff --git a/routers/user/auth_openid.go b/routers/user/auth_openid.go index 1351ca040b..f98c07acd7 100644 --- a/routers/user/auth_openid.go +++ b/routers/user/auth_openid.go @@ -126,7 +126,10 @@ func SignInOpenIDPost(ctx *context.Context, form auth.SignInOpenIDForm) { url += "&openid.sreg.optional=nickname%2Cemail" log.Trace("Form-passed openid-remember: %t", form.Remember) - ctx.Session.Set("openid_signin_remember", form.Remember) + err = ctx.Session.Set("openid_signin_remember", form.Remember) + if err != nil { + log.Error("SignInOpenIDPost: Could not set session: %v", err.Error()) + } ctx.Redirect(url) } @@ -152,7 +155,7 @@ func signInOpenIDVerify(ctx *context.Context) { /* Now we should seek for the user and log him in, or prompt * to register if not found */ - u, _ := models.GetUserByOpenID(id) + u, err := models.GetUserByOpenID(id) if err != nil { if !models.IsErrUserNotExist(err) { ctx.RenderWithErr(err.Error(), tplSignInOpenID, &auth.SignInOpenIDForm{ @@ -160,6 +163,7 @@ func signInOpenIDVerify(ctx *context.Context) { }) return } + log.Error("signInOpenIDVerify: %v", err) } if u != nil { log.Trace("User exists, logging in") @@ -191,7 +195,7 @@ func signInOpenIDVerify(ctx *context.Context) { log.Trace("User has email=" + email + " and nickname=" + nickname) if email != "" { - u, _ = models.GetUserByEmail(email) + u, err = models.GetUserByEmail(email) if err != nil { if !models.IsErrUserNotExist(err) { ctx.RenderWithErr(err.Error(), tplSignInOpenID, &auth.SignInOpenIDForm{ @@ -199,6 +203,7 @@ func signInOpenIDVerify(ctx *context.Context) { }) return } + log.Error("signInOpenIDVerify: %v", err) } if u != nil { log.Trace("Local user " + u.LowerName + " has OpenID provided email " + email) @@ -220,15 +225,24 @@ func signInOpenIDVerify(ctx *context.Context) { } } - ctx.Session.Set("openid_verified_uri", id) + err = ctx.Session.Set("openid_verified_uri", id) + if err != nil { + log.Error("signInOpenIDVerify: Could not set session: %v", err.Error()) + } - ctx.Session.Set("openid_determined_email", email) + err = ctx.Session.Set("openid_determined_email", email) + if err != nil { + log.Error("signInOpenIDVerify: Could not set session: %v", err.Error()) + } if u != nil { nickname = u.LowerName } - ctx.Session.Set("openid_determined_username", nickname) + err = ctx.Session.Set("openid_determined_username", nickname) + if err != nil { + log.Error("signInOpenIDVerify: Could not set session: %v", err.Error()) + } if u != nil || !setting.Service.EnableOpenIDSignUp { ctx.Redirect(setting.AppSubURL + "/user/openid/connect") @@ -350,7 +364,11 @@ func RegisterOpenIDPost(ctx *context.Context, cpt *captcha.Captcha, form auth.Si } if setting.Service.EnableCaptcha && setting.Service.CaptchaType == setting.ReCaptcha { - ctx.Req.ParseForm() + err := ctx.Req.ParseForm() + if err != nil { + ctx.ServerError("", err) + return + } valid, _ := recaptcha.Verify(form.GRecaptchaResponse) if !valid { ctx.Data["Err_Captcha"] = true diff --git a/routers/user/oauth.go b/routers/user/oauth.go index b85ea8125e..aaad26201b 100644 --- a/routers/user/oauth.go +++ b/routers/user/oauth.go @@ -7,12 +7,10 @@ package user import ( "encoding/base64" "fmt" + "github.com/go-macaron/binding" "net/url" "strings" - "github.com/dgrijalva/jwt-go" - "github.com/go-macaron/binding" - "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/auth" "code.gitea.io/gitea/modules/base" @@ -20,6 +18,8 @@ import ( "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/util" + + "github.com/dgrijalva/jwt-go" ) const ( @@ -164,6 +164,14 @@ func newAccessTokenResponse(grant *models.OAuth2Grant) (*AccessTokenResponse, *A func AuthorizeOAuth(ctx *context.Context, form auth.AuthorizationForm) { errs := binding.Errors{} errs = form.Validate(ctx.Context, errs) + if len(errs) > 0 { + errstring := "" + for _, e := range errs { + errstring += e.Error() + "\n" + } + ctx.ServerError("AuthorizeOAuth: Validate: ", fmt.Errorf("errors occured during validation: %s", errstring)) + return + } app, err := models.GetOAuth2ApplicationByClientID(form.ClientID) if err != nil { @@ -221,7 +229,6 @@ func AuthorizeOAuth(ctx *context.Context, form auth.AuthorizationForm) { }, form.RedirectURI) return } - break case "": break default: @@ -262,9 +269,24 @@ func AuthorizeOAuth(ctx *context.Context, form auth.AuthorizationForm) { ctx.Data["ApplicationUserLink"] = "<a href=\"" + setting.AppURL + app.User.LowerName + "\">@" + app.User.Name + "</a>" ctx.Data["ApplicationRedirectDomainHTML"] = "<strong>" + form.RedirectURI + "</strong>" // TODO document SESSION <=> FORM - ctx.Session.Set("client_id", app.ClientID) - ctx.Session.Set("redirect_uri", form.RedirectURI) - ctx.Session.Set("state", form.State) + err = ctx.Session.Set("client_id", app.ClientID) + if err != nil { + handleServerError(ctx, form.State, form.RedirectURI) + log.Error(err.Error()) + return + } + err = ctx.Session.Set("redirect_uri", form.RedirectURI) + if err != nil { + handleServerError(ctx, form.State, form.RedirectURI) + log.Error(err.Error()) + return + } + err = ctx.Session.Set("state", form.State) + if err != nil { + handleServerError(ctx, form.State, form.RedirectURI) + log.Error(err.Error()) + return + } ctx.HTML(200, tplGrantAccess) } diff --git a/routers/user/profile.go b/routers/user/profile.go index bda29522d9..7df92d44f5 100644 --- a/routers/user/profile.go +++ b/routers/user/profile.go @@ -20,7 +20,6 @@ import ( const ( tplFollowers base.TplName = "user/meta/followers" - tplStars base.TplName = "user/meta/stars" ) // GetUserByName get user by name diff --git a/routers/user/setting/profile.go b/routers/user/setting/profile.go index ac5c4c97fb..163bc869b4 100644 --- a/routers/user/setting/profile.go +++ b/routers/user/setting/profile.go @@ -141,13 +141,11 @@ func UpdateAvatarSetting(ctx *context.Context, form auth.AvatarForm, ctxUser *mo if err = ctxUser.UploadAvatar(data); err != nil { return fmt.Errorf("UploadAvatar: %v", err) } - } else { + } else if ctxUser.UseCustomAvatar && !com.IsFile(ctxUser.CustomAvatarPath()) { // No avatar is uploaded but setting has been changed to enable, // generate a random one when needed. - if ctxUser.UseCustomAvatar && !com.IsFile(ctxUser.CustomAvatarPath()) { - if err := ctxUser.GenerateRandomAvatar(); err != nil { - log.Error("GenerateRandomAvatar[%d]: %v", ctxUser.ID, err) - } + if err := ctxUser.GenerateRandomAvatar(); err != nil { + log.Error("GenerateRandomAvatar[%d]: %v", ctxUser.ID, err) } } diff --git a/routers/user/setting/security_twofa.go b/routers/user/setting/security_twofa.go index fca1151a04..6e3516dbba 100644 --- a/routers/user/setting/security_twofa.go +++ b/routers/user/setting/security_twofa.go @@ -73,6 +73,10 @@ func twofaGenerateSecretAndQr(ctx *context.Context) bool { uri := ctx.Session.Get("twofaUri") if uri != nil { otpKey, err = otp.NewKeyFromURL(uri.(string)) + if err != nil { + ctx.ServerError("SettingsTwoFactor: NewKeyFromURL: ", err) + return false + } } // Filter unsafe character ':' in issuer issuer := strings.Replace(setting.AppName+" ("+setting.Domain+")", ":", "", -1) @@ -103,8 +107,16 @@ func twofaGenerateSecretAndQr(ctx *context.Context) bool { } ctx.Data["QrUri"] = template.URL("data:image/png;base64," + base64.StdEncoding.EncodeToString(imgBytes.Bytes())) - ctx.Session.Set("twofaSecret", otpKey.Secret()) - ctx.Session.Set("twofaUri", otpKey.String()) + err = ctx.Session.Set("twofaSecret", otpKey.Secret()) + if err != nil { + ctx.ServerError("SettingsTwoFactor", err) + return false + } + err = ctx.Session.Set("twofaUri", otpKey.String()) + if err != nil { + ctx.ServerError("SettingsTwoFactor", err) + return false + } return true } @@ -184,8 +196,16 @@ func EnrollTwoFactorPost(ctx *context.Context, form auth.TwoFactorAuthForm) { return } - ctx.Session.Delete("twofaSecret") - ctx.Session.Delete("twofaUri") + err = ctx.Session.Delete("twofaSecret") + if err != nil { + ctx.ServerError("SettingsTwoFactor", err) + return + } + err = ctx.Session.Delete("twofaUri") + if err != nil { + ctx.ServerError("SettingsTwoFactor", err) + return + } ctx.Flash.Success(ctx.Tr("settings.twofa_enrolled", token)) ctx.Redirect(setting.AppSubURL + "/user/settings/security") } diff --git a/routers/user/setting/security_u2f.go b/routers/user/setting/security_u2f.go index c1d6eab967..b733467b84 100644 --- a/routers/user/setting/security_u2f.go +++ b/routers/user/setting/security_u2f.go @@ -42,7 +42,11 @@ func U2FRegister(ctx *context.Context, form auth.U2FRegistrationForm) { return } } - ctx.Session.Set("u2fName", form.Name) + err = ctx.Session.Set("u2fName", form.Name) + if err != nil { + ctx.ServerError("", err) + return + } ctx.JSON(200, u2f.NewWebRegisterRequest(challenge, regs.ToRegistrations())) } @@ -95,5 +99,4 @@ func U2FDelete(ctx *context.Context, form auth.U2FDeleteForm) { ctx.JSON(200, map[string]interface{}{ "redirect": setting.AppSubURL + "/user/settings/security", }) - return } |