auth.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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/setting"
  8. )
  9. type AuthOptions struct {
  10. ReqGrafanaAdmin bool
  11. ReqSignedIn bool
  12. }
  13. func getRequestUserId(c *Context) int64 {
  14. userId := c.Session.Get(SESS_KEY_USERID)
  15. if userId != nil {
  16. return userId.(int64)
  17. }
  18. return 0
  19. }
  20. func getApiKey(c *Context) string {
  21. header := c.Req.Header.Get("Authorization")
  22. parts := strings.SplitN(header, " ", 2)
  23. if len(parts) == 2 && parts[0] == "Bearer" {
  24. key := parts[1]
  25. return key
  26. }
  27. return ""
  28. }
  29. func accessForbidden(c *Context) {
  30. if c.IsApiRequest() {
  31. c.JsonApiErr(403, "Permission denied", nil)
  32. return
  33. }
  34. c.SetCookie("redirect_to", url.QueryEscape(setting.AppSubUrl+c.Req.RequestURI), 0, setting.AppSubUrl+"/")
  35. c.Redirect(setting.AppSubUrl + "/login")
  36. }
  37. func notAuthorized(c *Context) {
  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+"/")
  43. c.Redirect(setting.AppSubUrl + "/login")
  44. }
  45. func RoleAuth(roles ...m.RoleType) macaron.Handler {
  46. return func(c *Context) {
  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 *Context) {
  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. }