Files
Gogs/internal/context/context.go

334 lines
9.4 KiB
Go
Raw Normal View History

// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
2016-03-11 11:56:52 -05:00
package context
import (
2014-03-15 09:17:16 -04:00
"fmt"
2014-04-16 00:27:29 +08:00
"io"
"net/http"
"path"
2014-03-22 16:40:09 -04:00
"strings"
2014-03-19 21:57:55 +08:00
"time"
2015-10-15 21:28:12 -04:00
"github.com/go-macaron/cache"
"github.com/go-macaron/csrf"
"github.com/go-macaron/i18n"
"github.com/go-macaron/session"
"github.com/unknwon/com"
2015-10-15 21:28:12 -04:00
"gopkg.in/macaron.v1"
log "unknwon.dev/clog/v2"
2014-03-21 21:06:47 +08:00
"gogs.io/gogs/internal/auth"
"gogs.io/gogs/internal/db"
"gogs.io/gogs/internal/db/errors"
"gogs.io/gogs/internal/form"
"gogs.io/gogs/internal/setting"
"gogs.io/gogs/internal/template"
)
2014-03-15 09:17:16 -04:00
// Context represents context of a request.
type Context struct {
2014-07-26 00:24:27 -04:00
*macaron.Context
Cache cache.Cache
csrf csrf.CSRF
2014-07-26 00:24:27 -04:00
Flash *session.Flash
Session session.Store
Link string // Current request URL
User *db.User
2017-04-06 23:48:49 -04:00
IsLogged bool
2014-11-18 11:07:16 -05:00
IsBasicAuth bool
IsTokenAuth bool
2014-03-16 00:03:23 +08:00
2016-03-11 11:56:52 -05:00
Repo *Repository
2016-03-13 17:37:44 -04:00
Org *Organization
}
2017-04-07 00:49:30 -04:00
// Title sets "Title" field in template data.
func (c *Context) Title(locale string) {
c.Data["Title"] = c.Tr(locale)
}
// PageIs sets "PageIsxxx" field in template data.
func (c *Context) PageIs(name string) {
c.Data["PageIs"+name] = true
}
// Require sets "Requirexxx" field in template data.
func (c *Context) Require(name string) {
c.Data["Require"+name] = true
}
func (c *Context) RequireHighlightJS() {
c.Require("HighlightJS")
}
func (c *Context) RequireSimpleMDE() {
c.Require("SimpleMDE")
}
func (c *Context) RequireAutosize() {
c.Require("Autosize")
}
func (c *Context) RequireDropzone() {
c.Require("Dropzone")
}
2017-04-07 00:49:30 -04:00
// FormErr sets "Err_xxx" field in template data.
func (c *Context) FormErr(names ...string) {
for i := range names {
c.Data["Err_"+names[i]] = true
}
}
2017-04-06 23:48:49 -04:00
// UserID returns ID of current logged in user.
// It returns 0 if visitor is anonymous.
func (c *Context) UserID() int64 {
if !c.IsLogged {
return 0
}
2017-04-06 23:48:49 -04:00
return c.User.ID
}
2014-05-05 13:08:01 -04:00
// HasError returns true if error occurs in form validation.
2017-06-03 07:26:09 -04:00
func (c *Context) HasApiError() bool {
hasErr, ok := c.Data["HasError"]
2014-05-05 13:08:01 -04:00
if !ok {
return false
}
return hasErr.(bool)
}
2017-06-03 07:26:09 -04:00
func (c *Context) GetErrMsg() string {
return c.Data["ErrorMsg"].(string)
2014-05-05 13:08:01 -04:00
}
2014-03-15 10:52:14 -04:00
// HasError returns true if error occurs in form validation.
2017-06-03 07:26:09 -04:00
func (c *Context) HasError() bool {
hasErr, ok := c.Data["HasError"]
2014-03-15 10:52:14 -04:00
if !ok {
return false
}
2017-06-03 07:26:09 -04:00
c.Flash.ErrorMsg = c.Data["ErrorMsg"].(string)
c.Data["Flash"] = c.Flash
2014-03-15 10:52:14 -04:00
return hasErr.(bool)
}
2015-07-08 19:47:56 +08:00
// HasValue returns true if value of given name exists.
2017-06-03 07:26:09 -04:00
func (c *Context) HasValue(name string) bool {
_, ok := c.Data[name]
2015-07-08 19:47:56 +08:00
return ok
}
// HTML responses template with given status.
2017-06-03 07:26:09 -04:00
func (c *Context) HTML(status int, name string) {
2017-02-09 19:29:59 -05:00
log.Trace("Template: %s", name)
2017-06-03 07:26:09 -04:00
c.Context.HTML(status, name)
2014-03-20 07:50:26 -04:00
}
// Success responses template with status http.StatusOK.
2017-04-05 09:17:21 -04:00
func (c *Context) Success(name string) {
c.HTML(http.StatusOK, name)
}
2017-04-06 00:14:30 -04:00
// JSONSuccess responses JSON with status http.StatusOK.
func (c *Context) JSONSuccess(data interface{}) {
c.JSON(http.StatusOK, data)
}
// RawRedirect simply calls underlying Redirect method with no escape.
func (c *Context) RawRedirect(location string, status ...int) {
c.Context.Redirect(location, status...)
}
// Redirect responses redirection wtih given location and status.
// It escapes special characters in the location string.
func (c *Context) Redirect(location string, status ...int) {
c.Context.Redirect(template.EscapePound(location), status...)
}
2017-04-07 00:49:30 -04:00
// SubURLRedirect responses redirection wtih given location and status.
// It prepends setting.AppSubURL to the location string.
func (c *Context) SubURLRedirect(location string, status ...int) {
c.Redirect(setting.AppSubURL+location, status...)
2017-04-07 00:49:30 -04:00
}
2014-03-15 10:52:14 -04:00
// RenderWithErr used for page has form validation but need to prompt error to users.
2017-06-03 07:26:09 -04:00
func (c *Context) RenderWithErr(msg, tpl string, f interface{}) {
if f != nil {
2017-06-03 07:26:09 -04:00
form.Assign(f, c.Data)
2014-04-03 15:50:55 -04:00
}
2017-06-03 07:26:09 -04:00
c.Flash.ErrorMsg = msg
c.Data["Flash"] = c.Flash
c.HTML(http.StatusOK, tpl)
2014-03-15 10:52:14 -04:00
}
2014-03-15 09:17:16 -04:00
// Handle handles and logs error by given status.
func (c *Context) Handle(status int, msg string, err error) {
2014-05-01 18:53:41 -04:00
switch status {
case http.StatusNotFound:
2017-06-03 07:26:09 -04:00
c.Data["Title"] = "Page Not Found"
case http.StatusInternalServerError:
2017-06-03 07:26:09 -04:00
c.Data["Title"] = "Internal Server Error"
log.Error("%s: %v", msg, err)
2017-06-03 07:26:09 -04:00
if !setting.ProdMode || (c.IsLogged && c.User.IsAdmin) {
c.Data["ErrorMsg"] = err
2017-02-10 16:05:11 -05:00
}
2014-05-01 18:53:41 -04:00
}
2017-06-03 07:26:09 -04:00
c.HTML(status, fmt.Sprintf("status/%d", status))
}
// NotFound renders the 404 page.
2017-06-03 07:26:09 -04:00
func (c *Context) NotFound() {
c.Handle(http.StatusNotFound, "", nil)
}
// ServerError renders the 500 page.
func (c *Context) ServerError(msg string, err error) {
c.Handle(http.StatusInternalServerError, msg, err)
2017-02-10 16:05:11 -05:00
}
2016-08-30 02:08:38 -07:00
// NotFoundOrServerError use error check function to determine if the error
// is about not found. It responses with 404 status code for not found error,
// or error context description for logging purpose of 500 server error.
func (c *Context) NotFoundOrServerError(msg string, errck func(error) bool, err error) {
2016-07-26 02:48:17 +08:00
if errck(err) {
c.NotFound()
2016-07-26 02:48:17 +08:00
return
}
c.ServerError(msg, err)
2016-07-26 02:48:17 +08:00
}
func (c *Context) HandleText(status int, msg string) {
c.PlainText(status, []byte(msg))
}
2017-06-03 07:26:09 -04:00
func (c *Context) ServeContent(name string, r io.ReadSeeker, params ...interface{}) {
2014-04-16 00:27:29 +08:00
modtime := time.Now()
for _, p := range params {
switch v := p.(type) {
case time.Time:
modtime = v
}
}
2017-06-03 07:26:09 -04:00
c.Resp.Header().Set("Content-Description", "File Transfer")
c.Resp.Header().Set("Content-Type", "application/octet-stream")
c.Resp.Header().Set("Content-Disposition", "attachment; filename="+name)
c.Resp.Header().Set("Content-Transfer-Encoding", "binary")
c.Resp.Header().Set("Expires", "0")
c.Resp.Header().Set("Cache-Control", "must-revalidate")
c.Resp.Header().Set("Pragma", "public")
http.ServeContent(c.Resp, c.Req.Request, name, modtime, r)
2014-04-10 14:37:43 -04:00
}
2014-07-26 00:24:27 -04:00
// Contexter initializes a classic context for a request.
func Contexter() macaron.Handler {
return func(ctx *macaron.Context, l i18n.Locale, cache cache.Cache, sess session.Store, f *session.Flash, x csrf.CSRF) {
c := &Context{
Context: ctx,
Cache: cache,
csrf: x,
2014-07-26 00:24:27 -04:00
Flash: f,
Session: sess,
Link: setting.AppSubURL + strings.TrimSuffix(ctx.Req.URL.Path, "/"),
2016-03-11 11:56:52 -05:00
Repo: &Repository{
PullRequest: &PullRequest{},
2016-03-06 23:57:46 -05:00
},
2016-03-13 17:37:44 -04:00
Org: &Organization{},
}
c.Data["Link"] = template.EscapePound(c.Link)
c.Data["PageStartTime"] = time.Now()
// Quick responses appropriate go-get meta with status 200
// regardless of if user have access to the repository,
// or the repository does not exist at all.
// This is particular a workaround for "go get" command which does not respect
// .netrc file.
if c.Query("go-get") == "1" {
2017-06-03 07:26:09 -04:00
ownerName := c.Params(":username")
repoName := c.Params(":reponame")
branchName := "master"
owner, err := db.GetUserByName(ownerName)
if err != nil {
c.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err)
return
}
repo, err := db.GetRepositoryByName(owner.ID, repoName)
if err == nil && len(repo.DefaultBranch) > 0 {
branchName = repo.DefaultBranch
}
prefix := setting.AppURL + path.Join(ownerName, repoName, "src", branchName)
insecureFlag := ""
if !strings.HasPrefix(setting.AppURL, "https://") {
insecureFlag = "--insecure "
}
c.PlainText(http.StatusOK, []byte(com.Expand(`<!doctype html>
<html>
<head>
<meta name="go-import" content="{GoGetImport} git {CloneLink}">
<meta name="go-source" content="{GoGetImport} _ {GoDocDirectory} {GoDocFile}">
</head>
<body>
go get {InsecureFlag}{GoGetImport}
</body>
</html>
`, map[string]string{
"GoGetImport": path.Join(setting.HostAddress, setting.AppSubURL, repo.FullName()),
"CloneLink": db.ComposeHTTPSCloneURL(ownerName, repoName),
"GoDocDirectory": prefix + "{/dir}",
"GoDocFile": prefix + "{/dir}/{file}#L{line}",
"InsecureFlag": insecureFlag,
})))
return
}
2014-04-10 14:37:43 -04:00
if len(setting.HTTP.AccessControlAllowOrigin) > 0 {
c.Header().Set("Access-Control-Allow-Origin", setting.HTTP.AccessControlAllowOrigin)
c.Header().Set("'Access-Control-Allow-Credentials' ", "true")
c.Header().Set("Access-Control-Max-Age", "3600")
c.Header().Set("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With")
}
2014-03-22 20:49:53 +08:00
// Get user from session or header when possible
c.User, c.IsBasicAuth, c.IsTokenAuth = auth.SignedInUser(c.Context, c.Session)
if c.User != nil {
c.IsLogged = true
c.Data["IsLogged"] = c.IsLogged
c.Data["LoggedUser"] = c.User
c.Data["LoggedUserID"] = c.User.ID
c.Data["LoggedUserName"] = c.User.Name
c.Data["IsAdmin"] = c.User.IsAdmin
2014-11-06 22:06:41 -05:00
} else {
c.Data["LoggedUserID"] = 0
c.Data["LoggedUserName"] = ""
2014-03-15 20:50:17 +08:00
}
2014-07-24 15:19:59 +02:00
// If request sends files, parse them here otherwise the Query() can't be parsed and the CsrfToken will be invalid.
if c.Req.Method == "POST" && strings.Contains(c.Req.Header.Get("Content-Type"), "multipart/form-data") {
if err := c.Req.ParseMultipartForm(setting.AttachmentMaxSize << 20); err != nil && !strings.Contains(err.Error(), "EOF") { // 32MB max size
c.ServerError("ParseMultipartForm", err)
2014-07-24 15:19:59 +02:00
return
}
}
c.Data["CSRFToken"] = x.GetToken()
c.Data["CSRFTokenHTML"] = template.Safe(`<input type="hidden" name="_csrf" value="` + x.GetToken() + `">`)
2017-02-09 19:29:59 -05:00
log.Trace("Session ID: %s", sess.ID())
log.Trace("CSRF Token: %v", c.Data["CSRFToken"])
2014-03-19 21:57:55 +08:00
c.Data["ShowRegistrationButton"] = setting.Service.ShowRegistrationButton
c.Data["ShowFooterBranding"] = setting.ShowFooterBranding
2015-02-06 21:16:23 -05:00
c.renderNoticeBanner()
ctx.Map(c)
}
}