middleware.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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/authtoken"
  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 authtoken.UserAuthTokenService) macaron.Handler {
  24. return func(c *macaron.Context) {
  25. ctx := &m.ReqContext{
  26. Context: c,
  27. SignedInUser: &m.SignedInUser{},
  28. Session: session.GetSession(), // should only be used by auth_proxy
  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 initContextWithToken(ats, ctx, orgId):
  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. // update last seen every 5min
  56. if ctx.ShouldUpdateLastSeenAt() {
  57. ctx.Logger.Debug("Updating last user_seen_at", "user_id", ctx.UserId)
  58. if err := bus.Dispatch(&m.UpdateUserLastSeenAtCommand{UserId: ctx.UserId}); err != nil {
  59. ctx.Logger.Error("Failed to update last_seen_at", "error", err)
  60. }
  61. }
  62. }
  63. }
  64. func initContextWithAnonymousUser(ctx *m.ReqContext) bool {
  65. if !setting.AnonymousEnabled {
  66. return false
  67. }
  68. orgQuery := m.GetOrgByNameQuery{Name: setting.AnonymousOrgName}
  69. if err := bus.Dispatch(&orgQuery); err != nil {
  70. log.Error(3, "Anonymous access organization error: '%s': %s", setting.AnonymousOrgName, err)
  71. return false
  72. }
  73. ctx.IsSignedIn = false
  74. ctx.AllowAnonymous = true
  75. ctx.SignedInUser = &m.SignedInUser{IsAnonymous: true}
  76. ctx.OrgRole = m.RoleType(setting.AnonymousOrgRole)
  77. ctx.OrgId = orgQuery.Result.Id
  78. ctx.OrgName = orgQuery.Result.Name
  79. return true
  80. }
  81. func initContextWithApiKey(ctx *m.ReqContext) bool {
  82. var keyString string
  83. if keyString = getApiKey(ctx); keyString == "" {
  84. return false
  85. }
  86. // base64 decode key
  87. decoded, err := apikeygen.Decode(keyString)
  88. if err != nil {
  89. ctx.JsonApiErr(401, "Invalid API key", err)
  90. return true
  91. }
  92. // fetch key
  93. keyQuery := m.GetApiKeyByNameQuery{KeyName: decoded.Name, OrgId: decoded.OrgId}
  94. if err := bus.Dispatch(&keyQuery); err != nil {
  95. ctx.JsonApiErr(401, "Invalid API key", err)
  96. return true
  97. }
  98. apikey := keyQuery.Result
  99. // validate api key
  100. if !apikeygen.IsValid(decoded, apikey.Key) {
  101. ctx.JsonApiErr(401, "Invalid API key", err)
  102. return true
  103. }
  104. ctx.IsSignedIn = true
  105. ctx.SignedInUser = &m.SignedInUser{}
  106. ctx.OrgRole = apikey.Role
  107. ctx.ApiKeyId = apikey.Id
  108. ctx.OrgId = apikey.OrgId
  109. return true
  110. }
  111. func initContextWithBasicAuth(ctx *m.ReqContext, orgId int64) bool {
  112. if !setting.BasicAuthEnabled {
  113. return false
  114. }
  115. header := ctx.Req.Header.Get("Authorization")
  116. if header == "" {
  117. return false
  118. }
  119. username, password, err := util.DecodeBasicAuthHeader(header)
  120. if err != nil {
  121. ctx.JsonApiErr(401, "Invalid Basic Auth Header", err)
  122. return true
  123. }
  124. loginQuery := m.GetUserByLoginQuery{LoginOrEmail: username}
  125. if err := bus.Dispatch(&loginQuery); err != nil {
  126. ctx.JsonApiErr(401, "Basic auth failed", err)
  127. return true
  128. }
  129. user := loginQuery.Result
  130. loginUserQuery := m.LoginUserQuery{Username: username, Password: password, User: user}
  131. if err := bus.Dispatch(&loginUserQuery); err != nil {
  132. ctx.JsonApiErr(401, "Invalid username or password", err)
  133. return true
  134. }
  135. query := m.GetSignedInUserQuery{UserId: user.Id, OrgId: orgId}
  136. if err := bus.Dispatch(&query); err != nil {
  137. ctx.JsonApiErr(401, "Authentication error", err)
  138. return true
  139. }
  140. ctx.SignedInUser = query.Result
  141. ctx.IsSignedIn = true
  142. return true
  143. }
  144. func initContextWithToken(authTokenService authtoken.UserAuthTokenService, ctx *m.ReqContext, orgID int64) bool {
  145. rawToken := ctx.GetCookie(setting.LoginCookieName)
  146. if rawToken == "" {
  147. return false
  148. }
  149. token, err := authTokenService.LookupToken(rawToken)
  150. if err != nil {
  151. ctx.Logger.Error("failed to look up user based on cookie", "error", err)
  152. return false
  153. }
  154. query := m.GetSignedInUserQuery{UserId: token.GetUserId(), OrgId: orgID}
  155. if err := bus.Dispatch(&query); err != nil {
  156. ctx.Logger.Error("failed to get user with id", "userId", token.GetUserId(), "error", err)
  157. return false
  158. }
  159. ctx.SignedInUser = query.Result
  160. ctx.IsSignedIn = true
  161. ctx.UserToken = token
  162. rotated, err := authTokenService.TryRotateToken(token, ctx.RemoteAddr(), ctx.Req.UserAgent())
  163. if err != nil {
  164. ctx.Logger.Error("failed to rotate token", "error", err)
  165. return true
  166. }
  167. if rotated {
  168. WriteSessionCookie(ctx, token.GetToken(), setting.LoginMaxLifetimeDays)
  169. }
  170. return true
  171. }
  172. func WriteSessionCookie(ctx *m.ReqContext, value string, maxLifetimeDays int) {
  173. if setting.Env == setting.DEV {
  174. ctx.Logger.Info("new token", "unhashed token", value)
  175. }
  176. var maxAge int
  177. if maxLifetimeDays <= 0 {
  178. maxAge = -1
  179. } else {
  180. maxAgeHours := (time.Duration(setting.LoginMaxLifetimeDays) * 24 * time.Hour) + time.Hour
  181. maxAge = int(maxAgeHours.Seconds())
  182. }
  183. ctx.Resp.Header().Del("Set-Cookie")
  184. cookie := http.Cookie{
  185. Name: setting.LoginCookieName,
  186. Value: url.QueryEscape(value),
  187. HttpOnly: true,
  188. Path: setting.AppSubUrl + "/",
  189. Secure: setting.CookieSecure,
  190. MaxAge: maxAge,
  191. SameSite: setting.CookieSameSite,
  192. }
  193. http.SetCookie(ctx.Resp, &cookie)
  194. }
  195. func AddDefaultResponseHeaders() macaron.Handler {
  196. return func(ctx *m.ReqContext) {
  197. if ctx.IsApiRequest() && ctx.Req.Method == "GET" {
  198. ctx.Resp.Header().Add("Cache-Control", "no-cache")
  199. ctx.Resp.Header().Add("Pragma", "no-cache")
  200. ctx.Resp.Header().Add("Expires", "-1")
  201. }
  202. }
  203. }