You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

context.go 8.9 kB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package middleware
  5. import (
  6. "crypto/hmac"
  7. "crypto/sha1"
  8. "encoding/base64"
  9. "fmt"
  10. "html/template"
  11. "io"
  12. "net/http"
  13. "net/url"
  14. "path/filepath"
  15. "strconv"
  16. "strings"
  17. "time"
  18. "github.com/go-martini/martini"
  19. "github.com/gogits/cache"
  20. "github.com/gogits/git"
  21. "github.com/gogits/session"
  22. "github.com/gogits/gogs/models"
  23. "github.com/gogits/gogs/modules/auth"
  24. "github.com/gogits/gogs/modules/base"
  25. "github.com/gogits/gogs/modules/log"
  26. "github.com/gogits/gogs/modules/setting"
  27. )
  28. // Context represents context of a request.
  29. type Context struct {
  30. *Render
  31. c martini.Context
  32. p martini.Params
  33. Req *http.Request
  34. Res http.ResponseWriter
  35. Flash *Flash
  36. Session session.SessionStore
  37. Cache cache.Cache
  38. User *models.User
  39. IsSigned bool
  40. csrfToken string
  41. Repo struct {
  42. IsOwner bool
  43. IsTrueOwner bool
  44. IsWatching bool
  45. IsBranch bool
  46. IsTag bool
  47. IsCommit bool
  48. HasAccess bool
  49. Repository *models.Repository
  50. Owner *models.User
  51. Commit *git.Commit
  52. Tag *git.Tag
  53. GitRepo *git.Repository
  54. BranchName string
  55. TagName string
  56. CommitId string
  57. RepoLink string
  58. CloneLink struct {
  59. SSH string
  60. HTTPS string
  61. Git string
  62. }
  63. Mirror *models.Mirror
  64. }
  65. }
  66. // Query querys form parameter.
  67. func (ctx *Context) Query(name string) string {
  68. ctx.Req.ParseForm()
  69. return ctx.Req.Form.Get(name)
  70. }
  71. // func (ctx *Context) Param(name string) string {
  72. // return ctx.p[name]
  73. // }
  74. // HasError returns true if error occurs in form validation.
  75. func (ctx *Context) HasApiError() bool {
  76. hasErr, ok := ctx.Data["HasError"]
  77. if !ok {
  78. return false
  79. }
  80. return hasErr.(bool)
  81. }
  82. func (ctx *Context) GetErrMsg() string {
  83. return ctx.Data["ErrorMsg"].(string)
  84. }
  85. // HasError returns true if error occurs in form validation.
  86. func (ctx *Context) HasError() bool {
  87. hasErr, ok := ctx.Data["HasError"]
  88. if !ok {
  89. return false
  90. }
  91. ctx.Flash.ErrorMsg = ctx.Data["ErrorMsg"].(string)
  92. ctx.Data["Flash"] = ctx.Flash
  93. return hasErr.(bool)
  94. }
  95. // HTML calls render.HTML underlying but reduce one argument.
  96. func (ctx *Context) HTML(status int, name base.TplName, htmlOpt ...HTMLOptions) {
  97. ctx.Render.HTML(status, string(name), ctx.Data, htmlOpt...)
  98. }
  99. // RenderWithErr used for page has form validation but need to prompt error to users.
  100. func (ctx *Context) RenderWithErr(msg string, tpl base.TplName, form auth.Form) {
  101. if form != nil {
  102. auth.AssignForm(form, ctx.Data)
  103. }
  104. ctx.Flash.ErrorMsg = msg
  105. ctx.Data["Flash"] = ctx.Flash
  106. ctx.HTML(200, tpl)
  107. }
  108. // Handle handles and logs error by given status.
  109. func (ctx *Context) Handle(status int, title string, err error) {
  110. if err != nil {
  111. log.Error("%s: %v", title, err)
  112. if martini.Dev != martini.Prod {
  113. ctx.Data["ErrorMsg"] = err
  114. }
  115. }
  116. switch status {
  117. case 404:
  118. ctx.Data["Title"] = "Page Not Found"
  119. case 500:
  120. ctx.Data["Title"] = "Internal Server Error"
  121. }
  122. ctx.HTML(status, base.TplName(fmt.Sprintf("status/%d", status)))
  123. }
  124. func (ctx *Context) GetCookie(name string) string {
  125. cookie, err := ctx.Req.Cookie(name)
  126. if err != nil {
  127. return ""
  128. }
  129. return cookie.Value
  130. }
  131. func (ctx *Context) SetCookie(name string, value string, others ...interface{}) {
  132. cookie := http.Cookie{}
  133. cookie.Name = name
  134. cookie.Value = value
  135. if len(others) > 0 {
  136. switch v := others[0].(type) {
  137. case int:
  138. cookie.MaxAge = v
  139. case int64:
  140. cookie.MaxAge = int(v)
  141. case int32:
  142. cookie.MaxAge = int(v)
  143. }
  144. }
  145. // default "/"
  146. if len(others) > 1 {
  147. if v, ok := others[1].(string); ok && len(v) > 0 {
  148. cookie.Path = v
  149. }
  150. } else {
  151. cookie.Path = "/"
  152. }
  153. // default empty
  154. if len(others) > 2 {
  155. if v, ok := others[2].(string); ok && len(v) > 0 {
  156. cookie.Domain = v
  157. }
  158. }
  159. // default empty
  160. if len(others) > 3 {
  161. switch v := others[3].(type) {
  162. case bool:
  163. cookie.Secure = v
  164. default:
  165. if others[3] != nil {
  166. cookie.Secure = true
  167. }
  168. }
  169. }
  170. // default false. for session cookie default true
  171. if len(others) > 4 {
  172. if v, ok := others[4].(bool); ok && v {
  173. cookie.HttpOnly = true
  174. }
  175. }
  176. ctx.Res.Header().Add("Set-Cookie", cookie.String())
  177. }
  178. // Get secure cookie from request by a given key.
  179. func (ctx *Context) GetSecureCookie(Secret, key string) (string, bool) {
  180. val := ctx.GetCookie(key)
  181. if val == "" {
  182. return "", false
  183. }
  184. parts := strings.SplitN(val, "|", 3)
  185. if len(parts) != 3 {
  186. return "", false
  187. }
  188. vs := parts[0]
  189. timestamp := parts[1]
  190. sig := parts[2]
  191. h := hmac.New(sha1.New, []byte(Secret))
  192. fmt.Fprintf(h, "%s%s", vs, timestamp)
  193. if fmt.Sprintf("%02x", h.Sum(nil)) != sig {
  194. return "", false
  195. }
  196. res, _ := base64.URLEncoding.DecodeString(vs)
  197. return string(res), true
  198. }
  199. // Set Secure cookie for response.
  200. func (ctx *Context) SetSecureCookie(Secret, name, value string, others ...interface{}) {
  201. vs := base64.URLEncoding.EncodeToString([]byte(value))
  202. timestamp := strconv.FormatInt(time.Now().UnixNano(), 10)
  203. h := hmac.New(sha1.New, []byte(Secret))
  204. fmt.Fprintf(h, "%s%s", vs, timestamp)
  205. sig := fmt.Sprintf("%02x", h.Sum(nil))
  206. cookie := strings.Join([]string{vs, timestamp, sig}, "|")
  207. ctx.SetCookie(name, cookie, others...)
  208. }
  209. func (ctx *Context) CsrfToken() string {
  210. if len(ctx.csrfToken) > 0 {
  211. return ctx.csrfToken
  212. }
  213. token := ctx.GetCookie("_csrf")
  214. if len(token) == 0 {
  215. token = base.GetRandomString(30)
  216. ctx.SetCookie("_csrf", token)
  217. }
  218. ctx.csrfToken = token
  219. return token
  220. }
  221. func (ctx *Context) CsrfTokenValid() bool {
  222. token := ctx.Query("_csrf")
  223. if token == "" {
  224. token = ctx.Req.Header.Get("X-Csrf-Token")
  225. }
  226. if token == "" {
  227. return false
  228. } else if ctx.csrfToken != token {
  229. return false
  230. }
  231. return true
  232. }
  233. func (ctx *Context) ServeFile(file string, names ...string) {
  234. var name string
  235. if len(names) > 0 {
  236. name = names[0]
  237. } else {
  238. name = filepath.Base(file)
  239. }
  240. ctx.Res.Header().Set("Content-Description", "File Transfer")
  241. ctx.Res.Header().Set("Content-Type", "application/octet-stream")
  242. ctx.Res.Header().Set("Content-Disposition", "attachment; filename="+name)
  243. ctx.Res.Header().Set("Content-Transfer-Encoding", "binary")
  244. ctx.Res.Header().Set("Expires", "0")
  245. ctx.Res.Header().Set("Cache-Control", "must-revalidate")
  246. ctx.Res.Header().Set("Pragma", "public")
  247. http.ServeFile(ctx.Res, ctx.Req, file)
  248. }
  249. func (ctx *Context) ServeContent(name string, r io.ReadSeeker, params ...interface{}) {
  250. modtime := time.Now()
  251. for _, p := range params {
  252. switch v := p.(type) {
  253. case time.Time:
  254. modtime = v
  255. }
  256. }
  257. ctx.Res.Header().Set("Content-Description", "File Transfer")
  258. ctx.Res.Header().Set("Content-Type", "application/octet-stream")
  259. ctx.Res.Header().Set("Content-Disposition", "attachment; filename="+name)
  260. ctx.Res.Header().Set("Content-Transfer-Encoding", "binary")
  261. ctx.Res.Header().Set("Expires", "0")
  262. ctx.Res.Header().Set("Cache-Control", "must-revalidate")
  263. ctx.Res.Header().Set("Pragma", "public")
  264. http.ServeContent(ctx.Res, ctx.Req, name, modtime, r)
  265. }
  266. type Flash struct {
  267. url.Values
  268. ErrorMsg, SuccessMsg string
  269. }
  270. func (f *Flash) Error(msg string) {
  271. f.Set("error", msg)
  272. f.ErrorMsg = msg
  273. }
  274. func (f *Flash) Success(msg string) {
  275. f.Set("success", msg)
  276. f.SuccessMsg = msg
  277. }
  278. // InitContext initializes a classic context for a request.
  279. func InitContext() martini.Handler {
  280. return func(res http.ResponseWriter, r *http.Request, c martini.Context, rd *Render) {
  281. ctx := &Context{
  282. c: c,
  283. // p: p,
  284. Req: r,
  285. Res: res,
  286. Cache: setting.Cache,
  287. Render: rd,
  288. }
  289. ctx.Data["PageStartTime"] = time.Now()
  290. // start session
  291. ctx.Session = setting.SessionManager.SessionStart(res, r)
  292. // Get flash.
  293. values, err := url.ParseQuery(ctx.GetCookie("gogs_flash"))
  294. if err != nil {
  295. log.Error("InitContext.ParseQuery(flash): %v", err)
  296. } else if len(values) > 0 {
  297. ctx.Flash = &Flash{Values: values}
  298. ctx.Flash.ErrorMsg = ctx.Flash.Get("error")
  299. ctx.Flash.SuccessMsg = ctx.Flash.Get("success")
  300. ctx.Data["Flash"] = ctx.Flash
  301. ctx.SetCookie("gogs_flash", "", -1)
  302. }
  303. ctx.Flash = &Flash{Values: url.Values{}}
  304. rw := res.(martini.ResponseWriter)
  305. rw.Before(func(martini.ResponseWriter) {
  306. ctx.Session.SessionRelease(res)
  307. if flash := ctx.Flash.Encode(); len(flash) > 0 {
  308. ctx.SetCookie("gogs_flash", flash, 0)
  309. }
  310. })
  311. // Get user from session if logined.
  312. user := auth.SignedInUser(ctx.req.Header, ctx.Session)
  313. ctx.User = user
  314. ctx.IsSigned = user != nil
  315. ctx.Data["IsSigned"] = ctx.IsSigned
  316. if user != nil {
  317. ctx.Data["SignedUser"] = user
  318. ctx.Data["SignedUserId"] = user.Id
  319. ctx.Data["SignedUserName"] = user.Name
  320. ctx.Data["IsAdmin"] = ctx.User.IsAdmin
  321. }
  322. // get or create csrf token
  323. ctx.Data["CsrfToken"] = ctx.CsrfToken()
  324. ctx.Data["CsrfTokenHtml"] = template.HTML(`<input type="hidden" name="_csrf" value="` + ctx.csrfToken + `">`)
  325. c.Map(ctx)
  326. c.Next()
  327. }
  328. }