auth.go 2.0 KB

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