middleware.go 5.0 KB

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