auth.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. package middleware
  2. import (
  3. "net/url"
  4. "strings"
  5. macaron "gopkg.in/macaron.v1"
  6. m "github.com/grafana/grafana/pkg/models"
  7. "github.com/grafana/grafana/pkg/setting"
  8. "github.com/grafana/grafana/pkg/util"
  9. )
  10. type AuthOptions struct {
  11. ReqGrafanaAdmin bool
  12. ReqSignedIn bool
  13. }
  14. func getApiKey(c *m.ReqContext) string {
  15. header := c.Req.Header.Get("Authorization")
  16. parts := strings.SplitN(header, " ", 2)
  17. if len(parts) == 2 && parts[0] == "Bearer" {
  18. key := parts[1]
  19. return key
  20. }
  21. username, password, err := util.DecodeBasicAuthHeader(header)
  22. if err == nil && username == "api_key" {
  23. return password
  24. }
  25. return ""
  26. }
  27. func accessForbidden(c *m.ReqContext) {
  28. if c.IsApiRequest() {
  29. c.JsonApiErr(403, "Permission denied", nil)
  30. return
  31. }
  32. c.Redirect(setting.AppSubUrl + "/")
  33. }
  34. func notAuthorized(c *m.ReqContext) {
  35. if c.IsApiRequest() {
  36. c.JsonApiErr(401, "Unauthorized", nil)
  37. return
  38. }
  39. c.SetCookie("redirect_to", url.QueryEscape(setting.AppSubUrl+c.Req.RequestURI), 0, setting.AppSubUrl+"/", nil, false, true)
  40. c.Redirect(setting.AppSubUrl + "/login")
  41. }
  42. func EnsureEditorOrViewerCanEdit(c *m.ReqContext) {
  43. if !c.SignedInUser.HasRole(m.ROLE_EDITOR) && !setting.ViewersCanEdit {
  44. accessForbidden(c)
  45. }
  46. }
  47. func RoleAuth(roles ...m.RoleType) macaron.Handler {
  48. return func(c *m.ReqContext) {
  49. ok := false
  50. for _, role := range roles {
  51. if role == c.OrgRole {
  52. ok = true
  53. break
  54. }
  55. }
  56. if !ok {
  57. accessForbidden(c)
  58. }
  59. }
  60. }
  61. func Auth(options *AuthOptions) macaron.Handler {
  62. return func(c *m.ReqContext) {
  63. if !c.IsSignedIn && options.ReqSignedIn && !c.AllowAnonymous {
  64. notAuthorized(c)
  65. return
  66. }
  67. if !c.IsGrafanaAdmin && options.ReqGrafanaAdmin {
  68. accessForbidden(c)
  69. return
  70. }
  71. }
  72. }
  73. // AdminOrFeatureEnabled creates a middleware that allows access
  74. // if the signed in user is either an Org Admin or if the
  75. // feature flag is enabled.
  76. // Intended for when feature flags open up access to APIs that
  77. // are otherwise only available to admins.
  78. func AdminOrFeatureEnabled(enabled bool) macaron.Handler {
  79. return func(c *m.ReqContext) {
  80. if c.OrgRole == m.ROLE_ADMIN {
  81. return
  82. }
  83. if !enabled {
  84. accessForbidden(c)
  85. }
  86. }
  87. }