middleware.go 5.1 KB

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