middleware.go 5.3 KB

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