auth.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package middleware
  2. import (
  3. "net/url"
  4. "strings"
  5. "gopkg.in/macaron.v1"
  6. m "github.com/grafana/grafana/pkg/models"
  7. "github.com/grafana/grafana/pkg/services/session"
  8. "github.com/grafana/grafana/pkg/setting"
  9. "github.com/grafana/grafana/pkg/util"
  10. )
  11. type AuthOptions struct {
  12. ReqGrafanaAdmin bool
  13. ReqSignedIn bool
  14. }
  15. func getRequestUserId(c *m.ReqContext) int64 {
  16. userID := c.Session.Get(session.SESS_KEY_USERID)
  17. if userID != nil {
  18. return userID.(int64)
  19. }
  20. return 0
  21. }
  22. func getApiKey(c *m.ReqContext) string {
  23. header := c.Req.Header.Get("Authorization")
  24. parts := strings.SplitN(header, " ", 2)
  25. if len(parts) == 2 && parts[0] == "Bearer" {
  26. key := parts[1]
  27. return key
  28. }
  29. username, password, err := util.DecodeBasicAuthHeader(header)
  30. if err == nil && username == "api_key" {
  31. return password
  32. }
  33. return ""
  34. }
  35. func accessForbidden(c *m.ReqContext) {
  36. if c.IsApiRequest() {
  37. c.JsonApiErr(403, "Permission denied", nil)
  38. return
  39. }
  40. c.Redirect(setting.AppSubUrl + "/")
  41. }
  42. func notAuthorized(c *m.ReqContext) {
  43. if c.IsApiRequest() {
  44. c.JsonApiErr(401, "Unauthorized", nil)
  45. return
  46. }
  47. c.SetCookie("redirect_to", url.QueryEscape(setting.AppSubUrl+c.Req.RequestURI), 0, setting.AppSubUrl+"/", nil, false, true)
  48. c.Redirect(setting.AppSubUrl + "/login")
  49. }
  50. func RoleAuth(roles ...m.RoleType) macaron.Handler {
  51. return func(c *m.ReqContext) {
  52. ok := false
  53. for _, role := range roles {
  54. if role == c.OrgRole {
  55. ok = true
  56. break
  57. }
  58. }
  59. if !ok {
  60. accessForbidden(c)
  61. }
  62. }
  63. }
  64. func Auth(options *AuthOptions) macaron.Handler {
  65. return func(c *m.ReqContext) {
  66. if !c.IsSignedIn && options.ReqSignedIn && !c.AllowAnonymous {
  67. notAuthorized(c)
  68. return
  69. }
  70. if !c.IsGrafanaAdmin && options.ReqGrafanaAdmin {
  71. accessForbidden(c)
  72. return
  73. }
  74. }
  75. }