auth.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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/models"
  8. )
  9. func authGetRequestAccountId(c *Context, sess session.Store) (int64, error) {
  10. accountId := sess.Get("accountId")
  11. urlQuery := c.Req.URL.Query()
  12. if len(urlQuery["render"]) > 0 {
  13. accId, _ := strconv.Atoi(urlQuery["accountId"][0])
  14. sess.Set("accountId", accId)
  15. accountId = accId
  16. }
  17. if accountId == nil {
  18. return -1, errors.New("Auth: session account id not found")
  19. }
  20. return accountId.(int64), nil
  21. }
  22. func authDenied(c *Context) {
  23. c.Redirect("/login")
  24. }
  25. func Auth() macaron.Handler {
  26. return func(c *Context, sess session.Store) {
  27. accountId, err := authGetRequestAccountId(c, sess)
  28. if err != nil && c.Req.URL.Path != "/login" {
  29. authDenied(c)
  30. return
  31. }
  32. account, err := models.GetAccount(accountId)
  33. if err != nil {
  34. authDenied(c)
  35. return
  36. }
  37. usingAccount, err := models.GetAccount(account.UsingAccountId)
  38. if err != nil {
  39. authDenied(c)
  40. return
  41. }
  42. c.UserAccount = account
  43. c.Account = usingAccount
  44. }
  45. }