middleware.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. package middleware
  2. import (
  3. "strconv"
  4. "gopkg.in/macaron.v1"
  5. "github.com/grafana/grafana/pkg/bus"
  6. "github.com/grafana/grafana/pkg/components/apikeygen"
  7. "github.com/grafana/grafana/pkg/log"
  8. m "github.com/grafana/grafana/pkg/models"
  9. "github.com/grafana/grafana/pkg/services/session"
  10. "github.com/grafana/grafana/pkg/setting"
  11. "github.com/grafana/grafana/pkg/util"
  12. )
  13. var (
  14. ReqGrafanaAdmin = Auth(&AuthOptions{ReqSignedIn: true, ReqGrafanaAdmin: true})
  15. ReqSignedIn = Auth(&AuthOptions{ReqSignedIn: true})
  16. ReqEditorRole = RoleAuth(m.ROLE_EDITOR, m.ROLE_ADMIN)
  17. ReqOrgAdmin = RoleAuth(m.ROLE_ADMIN)
  18. )
  19. func GetContextHandler() macaron.Handler {
  20. return func(c *macaron.Context) {
  21. ctx := &m.ReqContext{
  22. Context: c,
  23. SignedInUser: &m.SignedInUser{},
  24. Session: session.GetSession(),
  25. IsSignedIn: false,
  26. AllowAnonymous: false,
  27. SkipCache: false,
  28. Logger: log.New("context"),
  29. }
  30. orgId := int64(0)
  31. orgIdHeader := ctx.Req.Header.Get("X-Grafana-Org-Id")
  32. if orgIdHeader != "" {
  33. orgId, _ = strconv.ParseInt(orgIdHeader, 10, 64)
  34. }
  35. // the order in which these are tested are important
  36. // look for api key in Authorization header first
  37. // then init session and look for userId in session
  38. // then look for api key in session (special case for render calls via api)
  39. // then test if anonymous access is enabled
  40. switch {
  41. case initContextWithRenderAuth(ctx):
  42. case initContextWithApiKey(ctx):
  43. case initContextWithBasicAuth(ctx, orgId):
  44. case initContextWithAuthProxy(ctx, orgId):
  45. case initContextWithUserSessionCookie(ctx, orgId):
  46. case initContextWithAnonymousUser(ctx):
  47. }
  48. ctx.Logger = log.New("context", "userId", ctx.UserId, "orgId", ctx.OrgId, "uname", ctx.Login)
  49. ctx.Data["ctx"] = ctx
  50. c.Map(ctx)
  51. // update last seen every 5min
  52. if ctx.ShouldUpdateLastSeenAt() {
  53. ctx.Logger.Debug("Updating last user_seen_at", "user_id", ctx.UserId)
  54. if err := bus.Dispatch(&m.UpdateUserLastSeenAtCommand{UserId: ctx.UserId}); err != nil {
  55. ctx.Logger.Error("Failed to update last_seen_at", "error", err)
  56. }
  57. }
  58. }
  59. }
  60. func initContextWithAnonymousUser(ctx *m.ReqContext) bool {
  61. if !setting.AnonymousEnabled {
  62. return false
  63. }
  64. orgQuery := m.GetOrgByNameQuery{Name: setting.AnonymousOrgName}
  65. if err := bus.Dispatch(&orgQuery); err != nil {
  66. log.Error(3, "Anonymous access organization error: '%s': %s", setting.AnonymousOrgName, err)
  67. return false
  68. }
  69. ctx.IsSignedIn = false
  70. ctx.AllowAnonymous = true
  71. ctx.SignedInUser = &m.SignedInUser{IsAnonymous: true}
  72. ctx.OrgRole = m.RoleType(setting.AnonymousOrgRole)
  73. ctx.OrgId = orgQuery.Result.Id
  74. ctx.OrgName = orgQuery.Result.Name
  75. return true
  76. }
  77. func initContextWithUserSessionCookie(ctx *m.ReqContext, orgId int64) bool {
  78. // initialize session
  79. if err := ctx.Session.Start(ctx.Context); err != nil {
  80. ctx.Logger.Error("Failed to start session", "error", err)
  81. return false
  82. }
  83. var userId int64
  84. if userId = getRequestUserId(ctx); userId == 0 {
  85. return false
  86. }
  87. query := m.GetSignedInUserQuery{UserId: userId, OrgId: orgId}
  88. if err := bus.Dispatch(&query); err != nil {
  89. ctx.Logger.Error("Failed to get user with id", "userId", userId, "error", err)
  90. return false
  91. }
  92. ctx.SignedInUser = query.Result
  93. ctx.IsSignedIn = true
  94. return true
  95. }
  96. func initContextWithApiKey(ctx *m.ReqContext) bool {
  97. var keyString string
  98. if keyString = getApiKey(ctx); keyString == "" {
  99. return false
  100. }
  101. // base64 decode key
  102. decoded, err := apikeygen.Decode(keyString)
  103. if err != nil {
  104. ctx.JsonApiErr(401, "Invalid API key", err)
  105. return true
  106. }
  107. // fetch key
  108. keyQuery := m.GetApiKeyByNameQuery{KeyName: decoded.Name, OrgId: decoded.OrgId}
  109. if err := bus.Dispatch(&keyQuery); err != nil {
  110. ctx.JsonApiErr(401, "Invalid API key", err)
  111. return true
  112. }
  113. apikey := keyQuery.Result
  114. // validate api key
  115. if !apikeygen.IsValid(decoded, apikey.Key) {
  116. ctx.JsonApiErr(401, "Invalid API key", err)
  117. return true
  118. }
  119. ctx.IsSignedIn = true
  120. ctx.SignedInUser = &m.SignedInUser{}
  121. ctx.OrgRole = apikey.Role
  122. ctx.ApiKeyId = apikey.Id
  123. ctx.OrgId = apikey.OrgId
  124. return true
  125. }
  126. func initContextWithBasicAuth(ctx *m.ReqContext, orgId int64) bool {
  127. if !setting.BasicAuthEnabled {
  128. return false
  129. }
  130. header := ctx.Req.Header.Get("Authorization")
  131. if header == "" {
  132. return false
  133. }
  134. username, password, err := util.DecodeBasicAuthHeader(header)
  135. if err != nil {
  136. ctx.JsonApiErr(401, "Invalid Basic Auth Header", err)
  137. return true
  138. }
  139. loginQuery := m.GetUserByLoginQuery{LoginOrEmail: username}
  140. if err := bus.Dispatch(&loginQuery); err != nil {
  141. ctx.JsonApiErr(401, "Basic auth failed", err)
  142. return true
  143. }
  144. user := loginQuery.Result
  145. loginUserQuery := m.LoginUserQuery{Username: username, Password: password, User: user}
  146. if err := bus.Dispatch(&loginUserQuery); err != nil {
  147. ctx.JsonApiErr(401, "Invalid username or password", err)
  148. return true
  149. }
  150. query := m.GetSignedInUserQuery{UserId: user.Id, OrgId: orgId}
  151. if err := bus.Dispatch(&query); err != nil {
  152. ctx.JsonApiErr(401, "Authentication error", err)
  153. return true
  154. }
  155. ctx.SignedInUser = query.Result
  156. ctx.IsSignedIn = true
  157. return true
  158. }
  159. func AddDefaultResponseHeaders() macaron.Handler {
  160. return func(ctx *m.ReqContext) {
  161. if ctx.IsApiRequest() && ctx.Req.Method == "GET" {
  162. ctx.Resp.Header().Add("Cache-Control", "no-cache")
  163. ctx.Resp.Header().Add("Pragma", "no-cache")
  164. ctx.Resp.Header().Add("Expires", "-1")
  165. }
  166. }
  167. }