auth.go 1.5 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.Redirect(setting.AppSubUrl + "/")
  35. }
  36. func notAuthorized(c *Context) {
  37. if c.IsApiRequest() {
  38. c.JsonApiErr(401, "Unauthorized", nil)
  39. return
  40. }
  41. c.SetCookie("redirect_to", url.QueryEscape(setting.AppSubUrl+c.Req.RequestURI), 0, setting.AppSubUrl+"/", nil, false, true)
  42. c.Redirect(setting.AppSubUrl + "/login")
  43. }
  44. func RoleAuth(roles ...m.RoleType) macaron.Handler {
  45. return func(c *Context) {
  46. ok := false
  47. for _, role := range roles {
  48. if role == c.OrgRole {
  49. ok = true
  50. break
  51. }
  52. }
  53. if !ok {
  54. accessForbidden(c)
  55. }
  56. }
  57. }
  58. func Auth(options *AuthOptions) macaron.Handler {
  59. return func(c *Context) {
  60. if !c.IsSignedIn && options.ReqSignedIn && !c.AllowAnonymous {
  61. notAuthorized(c)
  62. return
  63. }
  64. if !c.IsGrafanaAdmin && options.ReqGrafanaAdmin {
  65. accessForbidden(c)
  66. return
  67. }
  68. }
  69. }