auth.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package middleware
  2. import (
  3. "errors"
  4. "strconv"
  5. "github.com/Unknwon/macaron"
  6. "github.com/macaron-contrib/session"
  7. "github.com/torkelo/grafana-pro/pkg/bus"
  8. m "github.com/torkelo/grafana-pro/pkg/models"
  9. )
  10. func authGetRequestAccountId(c *Context, sess session.Store) (int64, error) {
  11. accountId := sess.Get("accountId")
  12. urlQuery := c.Req.URL.Query()
  13. if len(urlQuery["render"]) > 0 {
  14. accId, _ := strconv.ParseInt(urlQuery["accountId"][0], 10, 64)
  15. sess.Set("accountId", accId)
  16. accountId = accId
  17. }
  18. if accountId == nil {
  19. return -1, errors.New("Auth: session account id not found")
  20. }
  21. return accountId.(int64), nil
  22. }
  23. func authDenied(c *Context) {
  24. c.Redirect("/login")
  25. }
  26. func Auth() macaron.Handler {
  27. return func(c *Context, sess session.Store) {
  28. accountId, err := authGetRequestAccountId(c, sess)
  29. if err != nil && c.Req.URL.Path != "/login" {
  30. authDenied(c)
  31. return
  32. }
  33. userQuery := m.GetAccountByIdQuery{Id: accountId}
  34. err = bus.Dispatch(&userQuery)
  35. if err != nil {
  36. authDenied(c)
  37. return
  38. }
  39. usingQuery := m.GetAccountByIdQuery{Id: userQuery.Result.UsingAccountId}
  40. err = bus.Dispatch(&usingQuery)
  41. if err != nil {
  42. authDenied(c)
  43. return
  44. }
  45. c.UserAccount = userQuery.Result
  46. c.Account = usingQuery.Result
  47. }
  48. }