middleware.go 6.4 KB

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