auth.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package middleware
  2. import (
  3. "net/url"
  4. "strings"
  5. "github.com/Unknwon/macaron"
  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 authDenied(c *Context) {
  30. if c.IsApiRequest() {
  31. c.JsonApiErr(401, "Access 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 RoleAuth(roles ...m.RoleType) macaron.Handler {
  38. return func(c *Context) {
  39. ok := false
  40. for _, role := range roles {
  41. if role == c.OrgRole {
  42. ok = true
  43. break
  44. }
  45. }
  46. if !ok {
  47. authDenied(c)
  48. }
  49. }
  50. }
  51. func Auth(options *AuthOptions) macaron.Handler {
  52. return func(c *Context) {
  53. if !c.IsGrafanaAdmin && options.ReqGrafanaAdmin {
  54. authDenied(c)
  55. return
  56. }
  57. if !c.IsSignedIn && options.ReqSignedIn && !c.AllowAnonymous {
  58. authDenied(c)
  59. return
  60. }
  61. }
  62. }