middleware.go 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. package middleware
  2. import (
  3. "strconv"
  4. "strings"
  5. "github.com/Unknwon/macaron"
  6. "github.com/macaron-contrib/session"
  7. "github.com/grafana/grafana/pkg/bus"
  8. "github.com/grafana/grafana/pkg/components/apikeygen"
  9. "github.com/grafana/grafana/pkg/log"
  10. "github.com/grafana/grafana/pkg/metrics"
  11. m "github.com/grafana/grafana/pkg/models"
  12. "github.com/grafana/grafana/pkg/setting"
  13. )
  14. type Context struct {
  15. *macaron.Context
  16. *m.SignedInUser
  17. Session session.Store
  18. IsSignedIn bool
  19. AllowAnonymous bool
  20. }
  21. func GetContextHandler() macaron.Handler {
  22. return func(c *macaron.Context, sess session.Store) {
  23. ctx := &Context{
  24. Context: c,
  25. Session: sess,
  26. SignedInUser: &m.SignedInUser{},
  27. IsSignedIn: false,
  28. AllowAnonymous: false,
  29. }
  30. // try get account id from request
  31. if userId := getRequestUserId(ctx); userId != 0 {
  32. query := m.GetSignedInUserQuery{UserId: userId}
  33. if err := bus.Dispatch(&query); err != nil {
  34. log.Error(3, "Failed to get user by id, %v, %v", userId, err)
  35. } else {
  36. ctx.SignedInUser = query.Result
  37. ctx.IsSignedIn = true
  38. }
  39. } else if keyString := getApiKey(ctx); keyString != "" {
  40. // base64 decode key
  41. decoded, err := apikeygen.Decode(keyString)
  42. if err != nil {
  43. ctx.JsonApiErr(401, "Invalid API key", err)
  44. return
  45. }
  46. // fetch key
  47. keyQuery := m.GetApiKeyByNameQuery{KeyName: decoded.Name, OrgId: decoded.OrgId}
  48. if err := bus.Dispatch(&keyQuery); err != nil {
  49. ctx.JsonApiErr(401, "Invalid API key", err)
  50. return
  51. } else {
  52. apikey := keyQuery.Result
  53. // validate api key
  54. if !apikeygen.IsValid(decoded, apikey.Key) {
  55. ctx.JsonApiErr(401, "Invalid API key", err)
  56. return
  57. }
  58. ctx.IsSignedIn = true
  59. ctx.SignedInUser = &m.SignedInUser{}
  60. // TODO: fix this
  61. ctx.OrgRole = apikey.Role
  62. ctx.ApiKeyId = apikey.Id
  63. ctx.OrgId = apikey.OrgId
  64. }
  65. } else if setting.AnonymousEnabled {
  66. orgQuery := m.GetOrgByNameQuery{Name: setting.AnonymousOrgName}
  67. if err := bus.Dispatch(&orgQuery); err != nil {
  68. log.Error(3, "Anonymous access organization error: '%s': %s", setting.AnonymousOrgName, err)
  69. } else {
  70. ctx.IsSignedIn = false
  71. ctx.AllowAnonymous = true
  72. ctx.SignedInUser = &m.SignedInUser{}
  73. ctx.OrgRole = m.RoleType(setting.AnonymousOrgRole)
  74. ctx.OrgId = orgQuery.Result.Id
  75. ctx.OrgName = orgQuery.Result.Name
  76. }
  77. }
  78. c.Map(ctx)
  79. }
  80. }
  81. // Handle handles and logs error by given status.
  82. func (ctx *Context) Handle(status int, title string, err error) {
  83. if err != nil {
  84. log.Error(4, "%s: %v", title, err)
  85. if setting.Env != setting.PROD {
  86. ctx.Data["ErrorMsg"] = err
  87. }
  88. }
  89. switch status {
  90. case 200:
  91. metrics.M_Page_Status_200.Inc(1)
  92. case 404:
  93. metrics.M_Page_Status_404.Inc(1)
  94. case 500:
  95. metrics.M_Page_Status_500.Inc(1)
  96. }
  97. ctx.Data["Title"] = title
  98. ctx.HTML(status, strconv.Itoa(status))
  99. }
  100. func (ctx *Context) JsonOK(message string) {
  101. resp := make(map[string]interface{})
  102. resp["message"] = message
  103. ctx.JSON(200, resp)
  104. }
  105. func (ctx *Context) IsApiRequest() bool {
  106. return strings.HasPrefix(ctx.Req.URL.Path, "/api")
  107. }
  108. func (ctx *Context) JsonApiErr(status int, message string, err error) {
  109. resp := make(map[string]interface{})
  110. if err != nil {
  111. log.Error(4, "%s: %v", message, err)
  112. if setting.Env != setting.PROD {
  113. resp["error"] = err.Error()
  114. }
  115. }
  116. switch status {
  117. case 404:
  118. resp["message"] = "Not Found"
  119. metrics.M_Api_Status_500.Inc(1)
  120. case 500:
  121. metrics.M_Api_Status_404.Inc(1)
  122. resp["message"] = "Internal Server Error"
  123. }
  124. if message != "" {
  125. resp["message"] = message
  126. }
  127. ctx.JSON(status, resp)
  128. }