auth.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. )
  10. type AuthOptions struct {
  11. ReqGrafanaAdmin bool
  12. ReqSignedIn bool
  13. }
  14. func getRequestUserId(c *m.ReqContext) int64 {
  15. userId := c.Session.Get(session.SESS_KEY_USERID)
  16. if userId != nil {
  17. return userId.(int64)
  18. }
  19. return 0
  20. }
  21. func getApiKey(c *m.ReqContext) string {
  22. header := c.Req.Header.Get("Authorization")
  23. parts := strings.SplitN(header, " ", 2)
  24. if len(parts) == 2 && parts[0] == "Bearer" {
  25. key := parts[1]
  26. return key
  27. }
  28. return ""
  29. }
  30. func accessForbidden(c *m.ReqContext) {
  31. if c.IsApiRequest() {
  32. c.JsonApiErr(403, "Permission denied", nil)
  33. return
  34. }
  35. c.Redirect(setting.AppSubUrl + "/")
  36. }
  37. func notAuthorized(c *m.ReqContext) {
  38. if c.IsApiRequest() {
  39. c.JsonApiErr(401, "Unauthorized", nil)
  40. return
  41. }
  42. c.SetCookie("redirect_to", url.QueryEscape(setting.AppSubUrl+c.Req.RequestURI), 0, setting.AppSubUrl+"/", nil, false, true)
  43. c.Redirect(setting.AppSubUrl + "/login")
  44. }
  45. func RoleAuth(roles ...m.RoleType) macaron.Handler {
  46. return func(c *m.ReqContext) {
  47. ok := false
  48. for _, role := range roles {
  49. if role == c.OrgRole {
  50. ok = true
  51. break
  52. }
  53. }
  54. if !ok {
  55. accessForbidden(c)
  56. }
  57. }
  58. }
  59. func Auth(options *AuthOptions) macaron.Handler {
  60. return func(c *m.ReqContext) {
  61. if !c.IsSignedIn && options.ReqSignedIn && !c.AllowAnonymous {
  62. notAuthorized(c)
  63. return
  64. }
  65. if !c.IsGrafanaAdmin && options.ReqGrafanaAdmin {
  66. accessForbidden(c)
  67. return
  68. }
  69. }
  70. }