auth.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. if err := bus.Dispatch(&userQuery); err != nil {
  41. return
  42. }
  43. usingQuery := m.GetAccountByIdQuery{Id: userQuery.Result.UsingAccountId}
  44. if err := bus.Dispatch(&usingQuery); err != nil {
  45. return
  46. }
  47. c.UserAccount = userQuery.Result
  48. c.Account = usingQuery.Result
  49. }
  50. func authBySession(c *Context, sess session.Store) {
  51. accountId, err := authGetRequestAccountId(c, sess)
  52. if err != nil && c.Req.URL.Path != "/login" {
  53. authDenied(c)
  54. return
  55. }
  56. userQuery := m.GetAccountByIdQuery{Id: accountId}
  57. if err := bus.Dispatch(&userQuery); err != nil {
  58. authDenied(c)
  59. return
  60. }
  61. usingQuery := m.GetAccountByIdQuery{Id: userQuery.Result.UsingAccountId}
  62. if err := bus.Dispatch(&usingQuery); err != nil {
  63. authDenied(c)
  64. return
  65. }
  66. c.UserAccount = userQuery.Result
  67. c.Account = usingQuery.Result
  68. }
  69. func Auth() macaron.Handler {
  70. return func(c *Context, sess session.Store) {
  71. authByToken(c)
  72. if c.UserAccount == nil {
  73. authBySession(c, sess)
  74. }
  75. }
  76. }