auth.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package middleware
  2. import (
  3. "errors"
  4. "strconv"
  5. "strings"
  6. "github.com/Unknwon/macaron"
  7. "github.com/torkelo/grafana-pro/pkg/bus"
  8. m "github.com/torkelo/grafana-pro/pkg/models"
  9. "github.com/torkelo/grafana-pro/pkg/setting"
  10. )
  11. type AuthOptions struct {
  12. ReqGrafanaAdmin bool
  13. ReqSignedIn bool
  14. }
  15. func getRequestAccountId(c *Context) (int64, error) {
  16. accountId := c.Session.Get("accountId")
  17. if accountId != nil {
  18. return accountId.(int64), nil
  19. }
  20. // localhost render query
  21. urlQuery := c.Req.URL.Query()
  22. if len(urlQuery["render"]) > 0 {
  23. accId, _ := strconv.ParseInt(urlQuery["accountId"][0], 10, 64)
  24. c.Session.Set("accountId", accId)
  25. accountId = accId
  26. }
  27. // check api token
  28. header := c.Req.Header.Get("Authorization")
  29. parts := strings.SplitN(header, " ", 2)
  30. if len(parts) == 2 || parts[0] == "Bearer" {
  31. token := parts[1]
  32. userQuery := m.GetAccountByTokenQuery{Token: token}
  33. if err := bus.Dispatch(&userQuery); err != nil {
  34. return -1, err
  35. }
  36. return userQuery.Result.Id, nil
  37. }
  38. // anonymous gues user
  39. if setting.Anonymous {
  40. return setting.AnonymousAccountId, nil
  41. }
  42. return -1, errors.New("Auth: session account id not found")
  43. }
  44. func authDenied(c *Context) {
  45. if c.IsApiRequest() {
  46. c.JsonApiErr(401, "Access denied", nil)
  47. }
  48. c.Redirect(setting.AppSubUrl + "/login")
  49. }
  50. func RoleAuth(roles ...m.RoleType) macaron.Handler {
  51. return func(c *Context) {
  52. ok := false
  53. for _, role := range roles {
  54. if role == c.UserRole {
  55. ok = true
  56. break
  57. }
  58. }
  59. if !ok {
  60. authDenied(c)
  61. }
  62. }
  63. }
  64. func Auth(options *AuthOptions) macaron.Handler {
  65. return func(c *Context) {
  66. if !c.IsSignedIn && options.ReqSignedIn {
  67. authDenied(c)
  68. return
  69. }
  70. if !c.IsGrafanaAdmin && options.ReqGrafanaAdmin {
  71. authDenied(c)
  72. return
  73. }
  74. }
  75. }