middleware.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. package middleware
  2. import (
  3. "strconv"
  4. "strings"
  5. "gopkg.in/macaron.v1"
  6. "github.com/grafana/grafana/pkg/bus"
  7. "github.com/grafana/grafana/pkg/components/apikeygen"
  8. "github.com/grafana/grafana/pkg/log"
  9. l "github.com/grafana/grafana/pkg/login"
  10. "github.com/grafana/grafana/pkg/metrics"
  11. m "github.com/grafana/grafana/pkg/models"
  12. "github.com/grafana/grafana/pkg/setting"
  13. "github.com/grafana/grafana/pkg/util"
  14. )
  15. type Context struct {
  16. *macaron.Context
  17. *m.SignedInUser
  18. Session SessionStore
  19. IsSignedIn bool
  20. IsRenderCall bool
  21. AllowAnonymous bool
  22. Logger log.Logger
  23. }
  24. func GetContextHandler() macaron.Handler {
  25. return func(c *macaron.Context) {
  26. ctx := &Context{
  27. Context: c,
  28. SignedInUser: &m.SignedInUser{},
  29. Session: GetSession(),
  30. IsSignedIn: false,
  31. AllowAnonymous: 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. if initContextWithRenderAuth(ctx) ||
  45. initContextWithApiKey(ctx) ||
  46. initContextWithBasicAuth(ctx, orgId) ||
  47. initContextWithAuthProxy(ctx, orgId) ||
  48. initContextWithUserSessionCookie(ctx, orgId) ||
  49. initContextWithAnonymousUser(ctx) {
  50. }
  51. ctx.Logger = log.New("context", "userId", ctx.UserId, "orgId", ctx.OrgId, "uname", ctx.Login)
  52. ctx.Data["ctx"] = ctx
  53. c.Map(ctx)
  54. }
  55. }
  56. func initContextWithAnonymousUser(ctx *Context) bool {
  57. if !setting.AnonymousEnabled {
  58. return false
  59. }
  60. orgQuery := m.GetOrgByNameQuery{Name: setting.AnonymousOrgName}
  61. if err := bus.Dispatch(&orgQuery); err != nil {
  62. log.Error(3, "Anonymous access organization error: '%s': %s", setting.AnonymousOrgName, err)
  63. return false
  64. }
  65. ctx.IsSignedIn = false
  66. ctx.AllowAnonymous = true
  67. ctx.SignedInUser = &m.SignedInUser{}
  68. ctx.OrgRole = m.RoleType(setting.AnonymousOrgRole)
  69. ctx.OrgId = orgQuery.Result.Id
  70. ctx.OrgName = orgQuery.Result.Name
  71. return true
  72. }
  73. func initContextWithUserSessionCookie(ctx *Context, orgId int64) bool {
  74. // initialize session
  75. if err := ctx.Session.Start(ctx); err != nil {
  76. ctx.Logger.Error("Failed to start session", "error", err)
  77. return false
  78. }
  79. var userId int64
  80. if userId = getRequestUserId(ctx); userId == 0 {
  81. return false
  82. }
  83. query := m.GetSignedInUserQuery{UserId: userId, OrgId: orgId}
  84. if err := bus.Dispatch(&query); err != nil {
  85. ctx.Logger.Error("Failed to get user with id", "userId", userId)
  86. return false
  87. }
  88. ctx.SignedInUser = query.Result
  89. ctx.IsSignedIn = true
  90. return true
  91. }
  92. func initContextWithApiKey(ctx *Context) bool {
  93. var keyString string
  94. if keyString = getApiKey(ctx); keyString == "" {
  95. return false
  96. }
  97. // base64 decode key
  98. decoded, err := apikeygen.Decode(keyString)
  99. if err != nil {
  100. ctx.JsonApiErr(401, "Invalid API key", err)
  101. return true
  102. }
  103. // fetch key
  104. keyQuery := m.GetApiKeyByNameQuery{KeyName: decoded.Name, OrgId: decoded.OrgId}
  105. if err := bus.Dispatch(&keyQuery); err != nil {
  106. ctx.JsonApiErr(401, "Invalid API key", err)
  107. return true
  108. }
  109. apikey := keyQuery.Result
  110. // validate api key
  111. if !apikeygen.IsValid(decoded, apikey.Key) {
  112. ctx.JsonApiErr(401, "Invalid API key", err)
  113. return true
  114. }
  115. ctx.IsSignedIn = true
  116. ctx.SignedInUser = &m.SignedInUser{}
  117. ctx.OrgRole = apikey.Role
  118. ctx.ApiKeyId = apikey.Id
  119. ctx.OrgId = apikey.OrgId
  120. return true
  121. }
  122. func initContextWithBasicAuth(ctx *Context, orgId int64) bool {
  123. if !setting.BasicAuthEnabled {
  124. return false
  125. }
  126. header := ctx.Req.Header.Get("Authorization")
  127. if header == "" {
  128. return false
  129. }
  130. username, password, err := util.DecodeBasicAuthHeader(header)
  131. if err != nil {
  132. ctx.JsonApiErr(401, "Invalid Basic Auth Header", err)
  133. return true
  134. }
  135. loginQuery := m.GetUserByLoginQuery{LoginOrEmail: username}
  136. if err := bus.Dispatch(&loginQuery); err != nil {
  137. ctx.JsonApiErr(401, "Basic auth failed", err)
  138. return true
  139. }
  140. user := loginQuery.Result
  141. loginUserQuery := l.LoginUserQuery{Username: username, Password: password, User: user}
  142. if err := bus.Dispatch(&loginUserQuery); err != nil {
  143. ctx.JsonApiErr(401, "Invalid username or password", err)
  144. return true
  145. }
  146. query := m.GetSignedInUserQuery{UserId: user.Id, OrgId: orgId}
  147. if err := bus.Dispatch(&query); err != nil {
  148. ctx.JsonApiErr(401, "Authentication error", err)
  149. return true
  150. }
  151. ctx.SignedInUser = query.Result
  152. ctx.IsSignedIn = true
  153. return true
  154. }
  155. // Handle handles and logs error by given status.
  156. func (ctx *Context) Handle(status int, title string, err error) {
  157. if err != nil {
  158. ctx.Logger.Error(title, "error", err)
  159. if setting.Env != setting.PROD {
  160. ctx.Data["ErrorMsg"] = err
  161. }
  162. }
  163. ctx.Data["Title"] = title
  164. ctx.Data["AppSubUrl"] = setting.AppSubUrl
  165. ctx.HTML(status, strconv.Itoa(status))
  166. }
  167. func (ctx *Context) JsonOK(message string) {
  168. resp := make(map[string]interface{})
  169. resp["message"] = message
  170. ctx.JSON(200, resp)
  171. }
  172. func (ctx *Context) IsApiRequest() bool {
  173. return strings.HasPrefix(ctx.Req.URL.Path, "/api")
  174. }
  175. func (ctx *Context) JsonApiErr(status int, message string, err error) {
  176. resp := make(map[string]interface{})
  177. if err != nil {
  178. ctx.Logger.Error(message, "error", err)
  179. if setting.Env != setting.PROD {
  180. resp["error"] = err.Error()
  181. }
  182. }
  183. switch status {
  184. case 404:
  185. resp["message"] = "Not Found"
  186. case 500:
  187. resp["message"] = "Internal Server Error"
  188. }
  189. if message != "" {
  190. resp["message"] = message
  191. }
  192. ctx.JSON(status, resp)
  193. }
  194. func (ctx *Context) HasUserRole(role m.RoleType) bool {
  195. return ctx.OrgRole.Includes(role)
  196. }
  197. func (ctx *Context) HasHelpFlag(flag m.HelpFlags1) bool {
  198. return ctx.HelpFlags1.HasFlag(flag)
  199. }
  200. func (ctx *Context) TimeRequest(timer metrics.Timer) {
  201. ctx.Data["perfmon.timer"] = timer
  202. }