|
| 1 | +// Copyright 2023 The Gitea Authors. All rights reserved. |
| 2 | +// SPDX-License-Identifier: MIT |
| 3 | + |
| 4 | +package context |
| 5 | + |
| 6 | +import ( |
| 7 | + "errors" |
| 8 | + "fmt" |
| 9 | + "net" |
| 10 | + "net/http" |
| 11 | + "net/url" |
| 12 | + "path" |
| 13 | + "strconv" |
| 14 | + "strings" |
| 15 | + "time" |
| 16 | + |
| 17 | + user_model "code.gitea.io/gitea/models/user" |
| 18 | + "code.gitea.io/gitea/modules/base" |
| 19 | + "code.gitea.io/gitea/modules/json" |
| 20 | + "code.gitea.io/gitea/modules/log" |
| 21 | + "code.gitea.io/gitea/modules/setting" |
| 22 | + "code.gitea.io/gitea/modules/templates" |
| 23 | + "code.gitea.io/gitea/modules/web/middleware" |
| 24 | +) |
| 25 | + |
| 26 | +// SetTotalCountHeader set "X-Total-Count" header |
| 27 | +func (ctx *Context) SetTotalCountHeader(total int64) { |
| 28 | + ctx.RespHeader().Set("X-Total-Count", fmt.Sprint(total)) |
| 29 | + ctx.AppendAccessControlExposeHeaders("X-Total-Count") |
| 30 | +} |
| 31 | + |
| 32 | +// AppendAccessControlExposeHeaders append headers by name to "Access-Control-Expose-Headers" header |
| 33 | +func (ctx *Context) AppendAccessControlExposeHeaders(names ...string) { |
| 34 | + val := ctx.RespHeader().Get("Access-Control-Expose-Headers") |
| 35 | + if len(val) != 0 { |
| 36 | + ctx.RespHeader().Set("Access-Control-Expose-Headers", fmt.Sprintf("%s, %s", val, strings.Join(names, ", "))) |
| 37 | + } else { |
| 38 | + ctx.RespHeader().Set("Access-Control-Expose-Headers", strings.Join(names, ", ")) |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +// Written returns true if there are something sent to web browser |
| 43 | +func (ctx *Context) Written() bool { |
| 44 | + return ctx.Resp.Status() > 0 |
| 45 | +} |
| 46 | + |
| 47 | +// Status writes status code |
| 48 | +func (ctx *Context) Status(status int) { |
| 49 | + ctx.Resp.WriteHeader(status) |
| 50 | +} |
| 51 | + |
| 52 | +// Write writes data to web browser |
| 53 | +func (ctx *Context) Write(bs []byte) (int, error) { |
| 54 | + return ctx.Resp.Write(bs) |
| 55 | +} |
| 56 | + |
| 57 | +// RedirectToUser redirect to a differently-named user |
| 58 | +func RedirectToUser(ctx *Context, userName string, redirectUserID int64) { |
| 59 | + user, err := user_model.GetUserByID(ctx, redirectUserID) |
| 60 | + if err != nil { |
| 61 | + ctx.ServerError("GetUserByID", err) |
| 62 | + return |
| 63 | + } |
| 64 | + |
| 65 | + redirectPath := strings.Replace( |
| 66 | + ctx.Req.URL.EscapedPath(), |
| 67 | + url.PathEscape(userName), |
| 68 | + url.PathEscape(user.Name), |
| 69 | + 1, |
| 70 | + ) |
| 71 | + if ctx.Req.URL.RawQuery != "" { |
| 72 | + redirectPath += "?" + ctx.Req.URL.RawQuery |
| 73 | + } |
| 74 | + ctx.Redirect(path.Join(setting.AppSubURL, redirectPath), http.StatusTemporaryRedirect) |
| 75 | +} |
| 76 | + |
| 77 | +// RedirectToFirst redirects to first not empty URL |
| 78 | +func (ctx *Context) RedirectToFirst(location ...string) { |
| 79 | + for _, loc := range location { |
| 80 | + if len(loc) == 0 { |
| 81 | + continue |
| 82 | + } |
| 83 | + |
| 84 | + // Unfortunately browsers consider a redirect Location with preceding "//" and "/\" as meaning redirect to "http(s)://REST_OF_PATH" |
| 85 | + // Therefore we should ignore these redirect locations to prevent open redirects |
| 86 | + if len(loc) > 1 && loc[0] == '/' && (loc[1] == '/' || loc[1] == '\\') { |
| 87 | + continue |
| 88 | + } |
| 89 | + |
| 90 | + u, err := url.Parse(loc) |
| 91 | + if err != nil || ((u.Scheme != "" || u.Host != "") && !strings.HasPrefix(strings.ToLower(loc), strings.ToLower(setting.AppURL))) { |
| 92 | + continue |
| 93 | + } |
| 94 | + |
| 95 | + ctx.Redirect(loc) |
| 96 | + return |
| 97 | + } |
| 98 | + |
| 99 | + ctx.Redirect(setting.AppSubURL + "/") |
| 100 | +} |
| 101 | + |
| 102 | +const tplStatus500 base.TplName = "status/500" |
| 103 | + |
| 104 | +// HTML calls Context.HTML and renders the template to HTTP response |
| 105 | +func (ctx *Context) HTML(status int, name base.TplName) { |
| 106 | + log.Debug("Template: %s", name) |
| 107 | + |
| 108 | + tmplStartTime := time.Now() |
| 109 | + if !setting.IsProd { |
| 110 | + ctx.Data["TemplateName"] = name |
| 111 | + } |
| 112 | + ctx.Data["TemplateLoadTimes"] = func() string { |
| 113 | + return strconv.FormatInt(time.Since(tmplStartTime).Nanoseconds()/1e6, 10) + "ms" |
| 114 | + } |
| 115 | + |
| 116 | + err := ctx.Render.HTML(ctx.Resp, status, string(name), ctx.Data) |
| 117 | + if err == nil { |
| 118 | + return |
| 119 | + } |
| 120 | + |
| 121 | + // if rendering fails, show error page |
| 122 | + if name != tplStatus500 { |
| 123 | + err = fmt.Errorf("failed to render template: %s, error: %s", name, templates.HandleTemplateRenderingError(err)) |
| 124 | + ctx.ServerError("Render failed", err) // show the 500 error page |
| 125 | + } else { |
| 126 | + ctx.PlainText(http.StatusInternalServerError, "Unable to render status/500 page, the template system is broken, or Gitea can't find your template files.") |
| 127 | + return |
| 128 | + } |
| 129 | +} |
| 130 | + |
| 131 | +// RenderToString renders the template content to a string |
| 132 | +func (ctx *Context) RenderToString(name base.TplName, data map[string]interface{}) (string, error) { |
| 133 | + var buf strings.Builder |
| 134 | + err := ctx.Render.HTML(&buf, http.StatusOK, string(name), data) |
| 135 | + return buf.String(), err |
| 136 | +} |
| 137 | + |
| 138 | +// RenderWithErr used for page has form validation but need to prompt error to users. |
| 139 | +func (ctx *Context) RenderWithErr(msg string, tpl base.TplName, form interface{}) { |
| 140 | + if form != nil { |
| 141 | + middleware.AssignForm(form, ctx.Data) |
| 142 | + } |
| 143 | + ctx.Flash.ErrorMsg = msg |
| 144 | + ctx.Data["Flash"] = ctx.Flash |
| 145 | + ctx.HTML(http.StatusOK, tpl) |
| 146 | +} |
| 147 | + |
| 148 | +// NotFound displays a 404 (Not Found) page and prints the given error, if any. |
| 149 | +func (ctx *Context) NotFound(logMsg string, logErr error) { |
| 150 | + ctx.notFoundInternal(logMsg, logErr) |
| 151 | +} |
| 152 | + |
| 153 | +func (ctx *Context) notFoundInternal(logMsg string, logErr error) { |
| 154 | + if logErr != nil { |
| 155 | + log.Log(2, log.DEBUG, "%s: %v", logMsg, logErr) |
| 156 | + if !setting.IsProd { |
| 157 | + ctx.Data["ErrorMsg"] = logErr |
| 158 | + } |
| 159 | + } |
| 160 | + |
| 161 | + // response simple message if Accept isn't text/html |
| 162 | + showHTML := false |
| 163 | + for _, part := range ctx.Req.Header["Accept"] { |
| 164 | + if strings.Contains(part, "text/html") { |
| 165 | + showHTML = true |
| 166 | + break |
| 167 | + } |
| 168 | + } |
| 169 | + |
| 170 | + if !showHTML { |
| 171 | + ctx.plainTextInternal(3, http.StatusNotFound, []byte("Not found.\n")) |
| 172 | + return |
| 173 | + } |
| 174 | + |
| 175 | + ctx.Data["IsRepo"] = ctx.Repo.Repository != nil |
| 176 | + ctx.Data["Title"] = "Page Not Found" |
| 177 | + ctx.HTML(http.StatusNotFound, base.TplName("status/404")) |
| 178 | +} |
| 179 | + |
| 180 | +// ServerError displays a 500 (Internal Server Error) page and prints the given error, if any. |
| 181 | +func (ctx *Context) ServerError(logMsg string, logErr error) { |
| 182 | + ctx.serverErrorInternal(logMsg, logErr) |
| 183 | +} |
| 184 | + |
| 185 | +func (ctx *Context) serverErrorInternal(logMsg string, logErr error) { |
| 186 | + if logErr != nil { |
| 187 | + log.ErrorWithSkip(2, "%s: %v", logMsg, logErr) |
| 188 | + if _, ok := logErr.(*net.OpError); ok || errors.Is(logErr, &net.OpError{}) { |
| 189 | + // This is an error within the underlying connection |
| 190 | + // and further rendering will not work so just return |
| 191 | + return |
| 192 | + } |
| 193 | + |
| 194 | + // it's safe to show internal error to admin users, and it helps |
| 195 | + if !setting.IsProd || (ctx.Doer != nil && ctx.Doer.IsAdmin) { |
| 196 | + ctx.Data["ErrorMsg"] = fmt.Sprintf("%s, %s", logMsg, logErr) |
| 197 | + } |
| 198 | + } |
| 199 | + |
| 200 | + ctx.Data["Title"] = "Internal Server Error" |
| 201 | + ctx.HTML(http.StatusInternalServerError, tplStatus500) |
| 202 | +} |
| 203 | + |
| 204 | +// NotFoundOrServerError use error check function to determine if the error |
| 205 | +// is about not found. It responds with 404 status code for not found error, |
| 206 | +// or error context description for logging purpose of 500 server error. |
| 207 | +func (ctx *Context) NotFoundOrServerError(logMsg string, errCheck func(error) bool, logErr error) { |
| 208 | + if errCheck(logErr) { |
| 209 | + ctx.notFoundInternal(logMsg, logErr) |
| 210 | + return |
| 211 | + } |
| 212 | + ctx.serverErrorInternal(logMsg, logErr) |
| 213 | +} |
| 214 | + |
| 215 | +// PlainTextBytes renders bytes as plain text |
| 216 | +func (ctx *Context) plainTextInternal(skip, status int, bs []byte) { |
| 217 | + statusPrefix := status / 100 |
| 218 | + if statusPrefix == 4 || statusPrefix == 5 { |
| 219 | + log.Log(skip, log.TRACE, "plainTextInternal (status=%d): %s", status, string(bs)) |
| 220 | + } |
| 221 | + ctx.Resp.Header().Set("Content-Type", "text/plain;charset=utf-8") |
| 222 | + ctx.Resp.Header().Set("X-Content-Type-Options", "nosniff") |
| 223 | + ctx.Resp.WriteHeader(status) |
| 224 | + if _, err := ctx.Resp.Write(bs); err != nil { |
| 225 | + log.ErrorWithSkip(skip, "plainTextInternal (status=%d): write bytes failed: %v", status, err) |
| 226 | + } |
| 227 | +} |
| 228 | + |
| 229 | +// PlainTextBytes renders bytes as plain text |
| 230 | +func (ctx *Context) PlainTextBytes(status int, bs []byte) { |
| 231 | + ctx.plainTextInternal(2, status, bs) |
| 232 | +} |
| 233 | + |
| 234 | +// PlainText renders content as plain text |
| 235 | +func (ctx *Context) PlainText(status int, text string) { |
| 236 | + ctx.plainTextInternal(2, status, []byte(text)) |
| 237 | +} |
| 238 | + |
| 239 | +// RespHeader returns the response header |
| 240 | +func (ctx *Context) RespHeader() http.Header { |
| 241 | + return ctx.Resp.Header() |
| 242 | +} |
| 243 | + |
| 244 | +// Error returned an error to web browser |
| 245 | +func (ctx *Context) Error(status int, contents ...string) { |
| 246 | + v := http.StatusText(status) |
| 247 | + if len(contents) > 0 { |
| 248 | + v = contents[0] |
| 249 | + } |
| 250 | + http.Error(ctx.Resp, v, status) |
| 251 | +} |
| 252 | + |
| 253 | +// JSON render content as JSON |
| 254 | +func (ctx *Context) JSON(status int, content interface{}) { |
| 255 | + ctx.Resp.Header().Set("Content-Type", "application/json;charset=utf-8") |
| 256 | + ctx.Resp.WriteHeader(status) |
| 257 | + if err := json.NewEncoder(ctx.Resp).Encode(content); err != nil { |
| 258 | + ctx.ServerError("Render JSON failed", err) |
| 259 | + } |
| 260 | +} |
| 261 | + |
| 262 | +// Redirect redirects the request |
| 263 | +func (ctx *Context) Redirect(location string, status ...int) { |
| 264 | + code := http.StatusSeeOther |
| 265 | + if len(status) == 1 { |
| 266 | + code = status[0] |
| 267 | + } |
| 268 | + |
| 269 | + if strings.Contains(location, "://") || strings.HasPrefix(location, "//") { |
| 270 | + // Some browsers (Safari) have buggy behavior for Cookie + Cache + External Redirection, eg: /my-path => https://other/path |
| 271 | + // 1. the first request to "/my-path" contains cookie |
| 272 | + // 2. some time later, the request to "/my-path" doesn't contain cookie (caused by Prevent web tracking) |
| 273 | + // 3. Gitea's Sessioner doesn't see the session cookie, so it generates a new session id, and returns it to browser |
| 274 | + // 4. then the browser accepts the empty session, then the user is logged out |
| 275 | + // So in this case, we should remove the session cookie from the response header |
| 276 | + removeSessionCookieHeader(ctx.Resp) |
| 277 | + } |
| 278 | + http.Redirect(ctx.Resp, ctx.Req, location, code) |
| 279 | +} |
0 commit comments