auth.go 1.3 KB

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