middleware.go 6.9 KB

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