middleware.go 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. package middleware
  2. import (
  3. "strconv"
  4. "strings"
  5. "github.com/Unknwon/macaron"
  6. "github.com/macaron-contrib/session"
  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/setting"
  12. )
  13. type Context struct {
  14. *macaron.Context
  15. *m.SignedInUser
  16. Session session.Store
  17. IsSignedIn bool
  18. AllowAnonymous bool
  19. }
  20. func GetContextHandler() macaron.Handler {
  21. return func(c *macaron.Context, sess session.Store) {
  22. ctx := &Context{
  23. Context: c,
  24. Session: sess,
  25. SignedInUser: &m.SignedInUser{},
  26. IsSignedIn: false,
  27. AllowAnonymous: false,
  28. }
  29. // try get account id from request
  30. if userId := getRequestUserId(ctx); userId != 0 {
  31. query := m.GetSignedInUserQuery{UserId: userId}
  32. if err := bus.Dispatch(&query); err != nil {
  33. log.Error(3, "Failed to get user by id, %v, %v", userId, err)
  34. } else {
  35. ctx.SignedInUser = query.Result
  36. ctx.IsSignedIn = true
  37. }
  38. } else if keyString := getApiKey(ctx); keyString != "" {
  39. // base64 decode key
  40. decoded, err := apikeygen.Decode(keyString)
  41. if err != nil {
  42. ctx.JsonApiErr(401, "Invalid API key", err)
  43. return
  44. }
  45. // fetch key
  46. keyQuery := m.GetApiKeyByNameQuery{KeyName: decoded.Name, OrgId: decoded.OrgId}
  47. if err := bus.Dispatch(&keyQuery); err != nil {
  48. ctx.JsonApiErr(401, "Invalid API key", err)
  49. return
  50. } else {
  51. apikey := keyQuery.Result
  52. // validate api key
  53. if !apikeygen.IsValid(decoded, apikey.Key) {
  54. ctx.JsonApiErr(401, "Invalid API key", err)
  55. return
  56. }
  57. ctx.IsSignedIn = true
  58. ctx.SignedInUser = &m.SignedInUser{}
  59. // TODO: fix this
  60. ctx.OrgRole = apikey.Role
  61. ctx.ApiKeyId = apikey.Id
  62. ctx.OrgId = apikey.OrgId
  63. }
  64. } else if setting.AnonymousEnabled {
  65. orgQuery := m.GetOrgByNameQuery{Name: setting.AnonymousOrgName}
  66. if err := bus.Dispatch(&orgQuery); err != nil {
  67. log.Error(3, "Anonymous access organization error: '%s': %s", setting.AnonymousOrgName, err)
  68. } else {
  69. ctx.IsSignedIn = false
  70. ctx.AllowAnonymous = true
  71. ctx.SignedInUser = &m.SignedInUser{}
  72. ctx.OrgRole = m.RoleType(setting.AnonymousOrgRole)
  73. ctx.OrgId = orgQuery.Result.Id
  74. ctx.OrgName = orgQuery.Result.Name
  75. }
  76. }
  77. c.Map(ctx)
  78. }
  79. }
  80. // Handle handles and logs error by given status.
  81. func (ctx *Context) Handle(status int, title string, err error) {
  82. if err != nil {
  83. log.Error(4, "%s: %v", title, err)
  84. if setting.Env != setting.PROD {
  85. ctx.Data["ErrorMsg"] = err
  86. }
  87. }
  88. ctx.Data["Title"] = title
  89. ctx.HTML(status, strconv.Itoa(status))
  90. }
  91. func (ctx *Context) JsonOK(message string) {
  92. resp := make(map[string]interface{})
  93. resp["message"] = message
  94. ctx.JSON(200, resp)
  95. }
  96. func (ctx *Context) IsApiRequest() bool {
  97. return strings.HasPrefix(ctx.Req.URL.Path, "/api")
  98. }
  99. func (ctx *Context) JsonApiErr(status int, message string, err error) {
  100. resp := make(map[string]interface{})
  101. if err != nil {
  102. log.Error(4, "%s: %v", message, err)
  103. if setting.Env != setting.PROD {
  104. resp["error"] = err.Error()
  105. }
  106. }
  107. switch status {
  108. case 404:
  109. resp["message"] = "Not Found"
  110. case 500:
  111. resp["message"] = "Internal Server Error"
  112. }
  113. if message != "" {
  114. resp["message"] = message
  115. }
  116. ctx.JSON(status, resp)
  117. }