middleware.go 5.3 KB

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