middleware.go 4.8 KB

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