middleware.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. package middleware
  2. import (
  3. "net/http"
  4. "net/url"
  5. "strconv"
  6. "github.com/grafana/grafana/pkg/bus"
  7. "github.com/grafana/grafana/pkg/components/apikeygen"
  8. "github.com/grafana/grafana/pkg/log"
  9. m "github.com/grafana/grafana/pkg/models"
  10. "github.com/grafana/grafana/pkg/services/auth"
  11. "github.com/grafana/grafana/pkg/services/session"
  12. "github.com/grafana/grafana/pkg/setting"
  13. "github.com/grafana/grafana/pkg/util"
  14. macaron "gopkg.in/macaron.v1"
  15. )
  16. var (
  17. ReqGrafanaAdmin = Auth(&AuthOptions{ReqSignedIn: true, ReqGrafanaAdmin: true})
  18. ReqSignedIn = Auth(&AuthOptions{ReqSignedIn: true})
  19. ReqEditorRole = RoleAuth(m.ROLE_EDITOR, m.ROLE_ADMIN)
  20. ReqOrgAdmin = RoleAuth(m.ROLE_ADMIN)
  21. )
  22. func GetContextHandler(ats *auth.UserAuthTokenService) macaron.Handler {
  23. return func(c *macaron.Context) {
  24. ctx := &m.ReqContext{
  25. Context: c,
  26. SignedInUser: &m.SignedInUser{},
  27. Session: session.GetSession(),
  28. IsSignedIn: false,
  29. AllowAnonymous: false,
  30. SkipCache: false,
  31. Logger: log.New("context"),
  32. }
  33. orgId := int64(0)
  34. orgIdHeader := ctx.Req.Header.Get("X-Grafana-Org-Id")
  35. if orgIdHeader != "" {
  36. orgId, _ = strconv.ParseInt(orgIdHeader, 10, 64)
  37. }
  38. // the order in which these are tested are important
  39. // look for api key in Authorization header first
  40. // then init session and look for userId in session
  41. // then look for api key in session (special case for render calls via api)
  42. // then test if anonymous access is enabled
  43. switch {
  44. case initContextWithRenderAuth(ctx):
  45. case initContextWithApiKey(ctx):
  46. case initContextWithBasicAuth(ctx, orgId):
  47. case initContextWithAuthProxy(ctx, orgId):
  48. //case initContextWithUserSessionCookie(ctx, orgId):
  49. case initContextWithToken(ctx, orgId, ats):
  50. case initContextWithAnonymousUser(ctx):
  51. }
  52. ctx.Logger = log.New("context", "userId", ctx.UserId, "orgId", ctx.OrgId, "uname", ctx.Login)
  53. ctx.Data["ctx"] = ctx
  54. c.Map(ctx)
  55. //if signed in with token
  56. rotated, err := ats.RefreshToken(ctx.UserToken, ctx.RemoteAddr(), ctx.Req.UserAgent())
  57. if err != nil {
  58. ctx.Logger.Error("failed to rotate token", "error", err)
  59. return
  60. }
  61. if rotated {
  62. ctx.Logger.Info("new token", "unhashed token", ctx.UserToken.UnhashedToken)
  63. ctx.Resp.Header().Del("Set-Cookie")
  64. cookie := http.Cookie{
  65. Name: "grafana_session",
  66. Value: url.QueryEscape(ctx.UserToken.UnhashedToken),
  67. HttpOnly: true,
  68. //MaxAge: 600,
  69. Domain: setting.Domain,
  70. Path: setting.AppSubUrl + "/",
  71. }
  72. ctx.Resp.Header().Add("Set-Cookie", cookie.String())
  73. }
  74. // update last seen every 5min
  75. if ctx.ShouldUpdateLastSeenAt() {
  76. ctx.Logger.Debug("Updating last user_seen_at", "user_id", ctx.UserId)
  77. if err := bus.Dispatch(&m.UpdateUserLastSeenAtCommand{UserId: ctx.UserId}); err != nil {
  78. ctx.Logger.Error("Failed to update last_seen_at", "error", err)
  79. }
  80. }
  81. }
  82. }
  83. func initContextWithAnonymousUser(ctx *m.ReqContext) bool {
  84. if !setting.AnonymousEnabled {
  85. return false
  86. }
  87. orgQuery := m.GetOrgByNameQuery{Name: setting.AnonymousOrgName}
  88. if err := bus.Dispatch(&orgQuery); err != nil {
  89. log.Error(3, "Anonymous access organization error: '%s': %s", setting.AnonymousOrgName, err)
  90. return false
  91. }
  92. ctx.IsSignedIn = false
  93. ctx.AllowAnonymous = true
  94. ctx.SignedInUser = &m.SignedInUser{IsAnonymous: true}
  95. ctx.OrgRole = m.RoleType(setting.AnonymousOrgRole)
  96. ctx.OrgId = orgQuery.Result.Id
  97. ctx.OrgName = orgQuery.Result.Name
  98. return true
  99. }
  100. func initContextWithToken(ctx *m.ReqContext, orgID int64, ts *auth.UserAuthTokenService) bool {
  101. unhashedToken := ctx.GetCookie("grafana_session")
  102. if unhashedToken == "" {
  103. return false
  104. }
  105. user, err := ts.LookupToken(unhashedToken)
  106. if err != nil {
  107. ctx.Logger.Info("failed to look up user based on cookie")
  108. return false
  109. }
  110. query := m.GetSignedInUserQuery{UserId: user.UserId, OrgId: orgID}
  111. if err := bus.Dispatch(&query); err != nil {
  112. ctx.Logger.Error("Failed to get user with id", "userId", user.UserId, "error", err)
  113. return false
  114. }
  115. ctx.SignedInUser = query.Result
  116. ctx.IsSignedIn = true
  117. ctx.UserToken = user
  118. return true
  119. }
  120. func initContextWithUserSessionCookie(ctx *m.ReqContext, orgId int64) bool {
  121. // initialize session
  122. if err := ctx.Session.Start(ctx.Context); err != nil {
  123. ctx.Logger.Error("Failed to start session", "error", err)
  124. return false
  125. }
  126. var userId int64
  127. if userId = getRequestUserId(ctx); userId == 0 {
  128. return false
  129. }
  130. query := m.GetSignedInUserQuery{UserId: userId, OrgId: orgId}
  131. if err := bus.Dispatch(&query); err != nil {
  132. ctx.Logger.Error("Failed to get user with id", "userId", userId, "error", err)
  133. return false
  134. }
  135. ctx.SignedInUser = query.Result
  136. ctx.IsSignedIn = true
  137. return true
  138. }
  139. func initContextWithApiKey(ctx *m.ReqContext) bool {
  140. var keyString string
  141. if keyString = getApiKey(ctx); keyString == "" {
  142. return false
  143. }
  144. // base64 decode key
  145. decoded, err := apikeygen.Decode(keyString)
  146. if err != nil {
  147. ctx.JsonApiErr(401, "Invalid API key", err)
  148. return true
  149. }
  150. // fetch key
  151. keyQuery := m.GetApiKeyByNameQuery{KeyName: decoded.Name, OrgId: decoded.OrgId}
  152. if err := bus.Dispatch(&keyQuery); err != nil {
  153. ctx.JsonApiErr(401, "Invalid API key", err)
  154. return true
  155. }
  156. apikey := keyQuery.Result
  157. // validate api key
  158. if !apikeygen.IsValid(decoded, apikey.Key) {
  159. ctx.JsonApiErr(401, "Invalid API key", err)
  160. return true
  161. }
  162. ctx.IsSignedIn = true
  163. ctx.SignedInUser = &m.SignedInUser{}
  164. ctx.OrgRole = apikey.Role
  165. ctx.ApiKeyId = apikey.Id
  166. ctx.OrgId = apikey.OrgId
  167. return true
  168. }
  169. func initContextWithBasicAuth(ctx *m.ReqContext, orgId int64) bool {
  170. if !setting.BasicAuthEnabled {
  171. return false
  172. }
  173. header := ctx.Req.Header.Get("Authorization")
  174. if header == "" {
  175. return false
  176. }
  177. username, password, err := util.DecodeBasicAuthHeader(header)
  178. if err != nil {
  179. ctx.JsonApiErr(401, "Invalid Basic Auth Header", err)
  180. return true
  181. }
  182. loginQuery := m.GetUserByLoginQuery{LoginOrEmail: username}
  183. if err := bus.Dispatch(&loginQuery); err != nil {
  184. ctx.JsonApiErr(401, "Basic auth failed", err)
  185. return true
  186. }
  187. user := loginQuery.Result
  188. loginUserQuery := m.LoginUserQuery{Username: username, Password: password, User: user}
  189. if err := bus.Dispatch(&loginUserQuery); err != nil {
  190. ctx.JsonApiErr(401, "Invalid username or password", err)
  191. return true
  192. }
  193. query := m.GetSignedInUserQuery{UserId: user.Id, OrgId: orgId}
  194. if err := bus.Dispatch(&query); err != nil {
  195. ctx.JsonApiErr(401, "Authentication error", err)
  196. return true
  197. }
  198. ctx.SignedInUser = query.Result
  199. ctx.IsSignedIn = true
  200. return true
  201. }
  202. func AddDefaultResponseHeaders() macaron.Handler {
  203. return func(ctx *m.ReqContext) {
  204. if ctx.IsApiRequest() && ctx.Req.Method == "GET" {
  205. ctx.Resp.Header().Add("Cache-Control", "no-cache")
  206. ctx.Resp.Header().Add("Pragma", "no-cache")
  207. ctx.Resp.Header().Add("Expires", "-1")
  208. }
  209. }
  210. }