auth.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package middleware
  2. import (
  3. "errors"
  4. "github.com/Unknwon/macaron"
  5. "github.com/macaron-contrib/session"
  6. "strconv"
  7. "strings"
  8. "github.com/torkelo/grafana-pro/pkg/bus"
  9. m "github.com/torkelo/grafana-pro/pkg/models"
  10. "github.com/torkelo/grafana-pro/pkg/setting"
  11. )
  12. func authGetRequestAccountId(c *Context, sess session.Store) (int64, error) {
  13. accountId := sess.Get("accountId")
  14. urlQuery := c.Req.URL.Query()
  15. // TODO: check that this is a localhost request
  16. if len(urlQuery["render"]) > 0 {
  17. accId, _ := strconv.ParseInt(urlQuery["accountId"][0], 10, 64)
  18. sess.Set("accountId", accId)
  19. accountId = accId
  20. }
  21. if accountId == nil {
  22. if setting.Anonymous {
  23. return setting.AnonymousAccountId, nil
  24. }
  25. return -1, errors.New("Auth: session account id not found")
  26. }
  27. return accountId.(int64), nil
  28. }
  29. func authDenied(c *Context) {
  30. c.Redirect(setting.AppSubUrl + "/login")
  31. }
  32. func authByToken(c *Context) {
  33. header := c.Req.Header.Get("Authorization")
  34. parts := strings.SplitN(header, " ", 2)
  35. if len(parts) != 2 || parts[0] != "Bearer" {
  36. return
  37. }
  38. token := parts[1]
  39. userQuery := m.GetAccountByTokenQuery{Token: token}
  40. err := bus.Dispatch(&userQuery)
  41. if err != nil {
  42. return
  43. }
  44. usingQuery := m.GetAccountByIdQuery{Id: userQuery.Result.UsingAccountId}
  45. err = bus.Dispatch(&usingQuery)
  46. if err != nil {
  47. return
  48. }
  49. c.UserAccount = userQuery.Result
  50. c.Account = usingQuery.Result
  51. }
  52. func authBySession(c *Context, sess session.Store) {
  53. accountId, err := authGetRequestAccountId(c, sess)
  54. if err != nil && c.Req.URL.Path != "/login" {
  55. authDenied(c)
  56. return
  57. }
  58. userQuery := m.GetAccountByIdQuery{Id: accountId}
  59. err = bus.Dispatch(&userQuery)
  60. if err != nil {
  61. authDenied(c)
  62. return
  63. }
  64. usingQuery := m.GetAccountByIdQuery{Id: userQuery.Result.UsingAccountId}
  65. err = bus.Dispatch(&usingQuery)
  66. if err != nil {
  67. authDenied(c)
  68. return
  69. }
  70. c.UserAccount = userQuery.Result
  71. c.Account = usingQuery.Result
  72. }
  73. func Auth() macaron.Handler {
  74. return func(c *Context, sess session.Store) {
  75. authByToken(c)
  76. if c.UserAccount == nil {
  77. authBySession(c, sess)
  78. }
  79. }
  80. }