auth.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. }