middleware.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. package middleware
  2. import (
  3. "strconv"
  4. "strings"
  5. "github.com/Unknwon/macaron"
  6. "github.com/grafana/grafana/pkg/bus"
  7. "github.com/grafana/grafana/pkg/components/apikeygen"
  8. "github.com/grafana/grafana/pkg/log"
  9. "github.com/grafana/grafana/pkg/metrics"
  10. m "github.com/grafana/grafana/pkg/models"
  11. "github.com/grafana/grafana/pkg/setting"
  12. )
  13. type Context struct {
  14. *macaron.Context
  15. *m.SignedInUser
  16. Session SessionStore
  17. IsSignedIn bool
  18. AllowAnonymous bool
  19. }
  20. func GetContextHandler() macaron.Handler {
  21. return func(c *macaron.Context) {
  22. ctx := &Context{
  23. Context: c,
  24. SignedInUser: &m.SignedInUser{},
  25. Session: GetSession(),
  26. IsSignedIn: false,
  27. AllowAnonymous: false,
  28. }
  29. // the order in which these are tested are important
  30. // look for api key in Authorization header first
  31. // then init session and look for userId in session
  32. // then look for api key in session (special case for render calls via api)
  33. // then test if anonymous access is enabled
  34. if initContextWithApiKey(ctx) ||
  35. initContextWithAuthProxy(ctx) ||
  36. initContextWithUserSessionCookie(ctx) ||
  37. initContextWithApiKeyFromSession(ctx) ||
  38. initContextWithAnonymousUser(ctx) {
  39. }
  40. c.Map(ctx)
  41. }
  42. }
  43. func initContextWithAnonymousUser(ctx *Context) bool {
  44. if !setting.AnonymousEnabled {
  45. return false
  46. }
  47. orgQuery := m.GetOrgByNameQuery{Name: setting.AnonymousOrgName}
  48. if err := bus.Dispatch(&orgQuery); err != nil {
  49. log.Error(3, "Anonymous access organization error: '%s': %s", setting.AnonymousOrgName, err)
  50. return false
  51. } else {
  52. ctx.IsSignedIn = false
  53. ctx.AllowAnonymous = true
  54. ctx.SignedInUser = &m.SignedInUser{}
  55. ctx.OrgRole = m.RoleType(setting.AnonymousOrgRole)
  56. ctx.OrgId = orgQuery.Result.Id
  57. ctx.OrgName = orgQuery.Result.Name
  58. return true
  59. }
  60. }
  61. func initContextWithUserSessionCookie(ctx *Context) bool {
  62. // initialize session
  63. if err := ctx.Session.Start(ctx); err != nil {
  64. log.Error(3, "Failed to start session", err)
  65. return false
  66. }
  67. var userId int64
  68. if userId = getRequestUserId(ctx); userId == 0 {
  69. return false
  70. }
  71. query := m.GetSignedInUserQuery{UserId: userId}
  72. if err := bus.Dispatch(&query); err != nil {
  73. log.Error(3, "Failed to get user with id %v", userId)
  74. return false
  75. } else {
  76. ctx.SignedInUser = query.Result
  77. ctx.IsSignedIn = true
  78. return true
  79. }
  80. }
  81. func initContextWithApiKey(ctx *Context) bool {
  82. var keyString string
  83. if keyString = getApiKey(ctx); keyString == "" {
  84. return false
  85. }
  86. // base64 decode key
  87. decoded, err := apikeygen.Decode(keyString)
  88. if err != nil {
  89. ctx.JsonApiErr(401, "Invalid API key", err)
  90. return true
  91. }
  92. // fetch key
  93. keyQuery := m.GetApiKeyByNameQuery{KeyName: decoded.Name, OrgId: decoded.OrgId}
  94. if err := bus.Dispatch(&keyQuery); err != nil {
  95. ctx.JsonApiErr(401, "Invalid API key", err)
  96. return true
  97. } else {
  98. apikey := keyQuery.Result
  99. // validate api key
  100. if !apikeygen.IsValid(decoded, apikey.Key) {
  101. ctx.JsonApiErr(401, "Invalid API key", err)
  102. return true
  103. }
  104. ctx.IsSignedIn = true
  105. ctx.SignedInUser = &m.SignedInUser{}
  106. ctx.OrgRole = apikey.Role
  107. ctx.ApiKeyId = apikey.Id
  108. ctx.OrgId = apikey.OrgId
  109. return true
  110. }
  111. }
  112. // special case for panel render calls with api key
  113. func initContextWithApiKeyFromSession(ctx *Context) bool {
  114. keyId := ctx.Session.Get(SESS_KEY_APIKEY)
  115. if keyId == nil {
  116. return false
  117. }
  118. keyQuery := m.GetApiKeyByIdQuery{ApiKeyId: keyId.(int64)}
  119. if err := bus.Dispatch(&keyQuery); err != nil {
  120. log.Error(3, "Failed to get api key by id", err)
  121. return false
  122. } else {
  123. apikey := keyQuery.Result
  124. ctx.IsSignedIn = true
  125. ctx.SignedInUser = &m.SignedInUser{}
  126. ctx.OrgRole = apikey.Role
  127. ctx.ApiKeyId = apikey.Id
  128. ctx.OrgId = apikey.OrgId
  129. return true
  130. }
  131. }
  132. // Handle handles and logs error by given status.
  133. func (ctx *Context) Handle(status int, title string, err error) {
  134. if err != nil {
  135. log.Error(4, "%s: %v", title, err)
  136. if setting.Env != setting.PROD {
  137. ctx.Data["ErrorMsg"] = err
  138. }
  139. }
  140. switch status {
  141. case 200:
  142. metrics.M_Page_Status_200.Inc(1)
  143. case 404:
  144. metrics.M_Page_Status_404.Inc(1)
  145. case 500:
  146. metrics.M_Page_Status_500.Inc(1)
  147. }
  148. ctx.Data["Title"] = title
  149. ctx.HTML(status, strconv.Itoa(status))
  150. }
  151. func (ctx *Context) JsonOK(message string) {
  152. resp := make(map[string]interface{})
  153. resp["message"] = message
  154. ctx.JSON(200, resp)
  155. }
  156. func (ctx *Context) IsApiRequest() bool {
  157. return strings.HasPrefix(ctx.Req.URL.Path, "/api")
  158. }
  159. func (ctx *Context) JsonApiErr(status int, message string, err error) {
  160. resp := make(map[string]interface{})
  161. if err != nil {
  162. log.Error(4, "%s: %v", message, err)
  163. if setting.Env != setting.PROD {
  164. resp["error"] = err.Error()
  165. }
  166. }
  167. switch status {
  168. case 404:
  169. resp["message"] = "Not Found"
  170. metrics.M_Api_Status_500.Inc(1)
  171. case 500:
  172. metrics.M_Api_Status_404.Inc(1)
  173. resp["message"] = "Internal Server Error"
  174. }
  175. if message != "" {
  176. resp["message"] = message
  177. }
  178. ctx.JSON(status, resp)
  179. }