middleware.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package middleware
  2. import (
  3. "encoding/json"
  4. "strconv"
  5. "strings"
  6. "github.com/Unknwon/macaron"
  7. "github.com/macaron-contrib/session"
  8. "github.com/torkelo/grafana-pro/pkg/bus"
  9. "github.com/torkelo/grafana-pro/pkg/log"
  10. m "github.com/torkelo/grafana-pro/pkg/models"
  11. "github.com/torkelo/grafana-pro/pkg/setting"
  12. )
  13. type Context struct {
  14. *macaron.Context
  15. *m.SignInUser
  16. Session session.Store
  17. IsSignedIn bool
  18. }
  19. func GetContextHandler() macaron.Handler {
  20. return func(c *macaron.Context, sess session.Store) {
  21. ctx := &Context{
  22. Context: c,
  23. Session: sess,
  24. }
  25. // try get account id from request
  26. if accountId, err := getRequestAccountId(ctx); err == nil {
  27. query := m.GetSignedInUserQuery{AccountId: accountId}
  28. if err := bus.Dispatch(&query); err != nil {
  29. log.Error(3, "Failed to get user by id, %v, %v", accountId, err)
  30. } else {
  31. ctx.IsSignedIn = true
  32. ctx.SignInUser = query.Result
  33. }
  34. }
  35. c.Map(ctx)
  36. }
  37. }
  38. // Handle handles and logs error by given status.
  39. func (ctx *Context) Handle(status int, title string, err error) {
  40. if err != nil {
  41. log.Error(4, "%s: %v", title, err)
  42. if macaron.Env != macaron.PROD {
  43. ctx.Data["ErrorMsg"] = err
  44. }
  45. }
  46. switch status {
  47. case 404:
  48. ctx.Data["Title"] = "Page Not Found"
  49. case 500:
  50. ctx.Data["Title"] = "Internal Server Error"
  51. }
  52. ctx.HTML(status, strconv.Itoa(status))
  53. }
  54. func (ctx *Context) JsonOK(message string) {
  55. resp := make(map[string]interface{})
  56. resp["message"] = message
  57. ctx.JSON(200, resp)
  58. }
  59. func (ctx *Context) IsApiRequest() bool {
  60. return strings.HasPrefix(ctx.Req.URL.Path, "/api")
  61. }
  62. func (ctx *Context) JsonApiErr(status int, message string, err error) {
  63. resp := make(map[string]interface{})
  64. if err != nil {
  65. log.Error(4, "%s: %v", message, err)
  66. if setting.Env != setting.PROD {
  67. resp["error"] = err.Error()
  68. }
  69. }
  70. switch status {
  71. case 404:
  72. resp["message"] = "Not Found"
  73. case 500:
  74. resp["message"] = "Internal Server Error"
  75. }
  76. if message != "" {
  77. resp["message"] = message
  78. }
  79. ctx.JSON(status, resp)
  80. }
  81. func (ctx *Context) JsonBody(model interface{}) bool {
  82. b, _ := ctx.Req.Body().Bytes()
  83. err := json.Unmarshal(b, &model)
  84. return err == nil
  85. }