auth.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. type AuthOptions struct {
  12. ReqAdmin bool
  13. ReqSignedIn bool
  14. }
  15. func getRequestAccountId(c *Context) (int64, error) {
  16. accountId := c.Session.Get("accountId")
  17. if accountId != nil {
  18. return accountId.(int64), nil
  19. }
  20. // localhost render query
  21. urlQuery := c.Req.URL.Query()
  22. if len(urlQuery["render"]) > 0 {
  23. accId, _ := strconv.ParseInt(urlQuery["accountId"][0], 10, 64)
  24. c.Session.Set("accountId", accId)
  25. accountId = accId
  26. }
  27. // check api token
  28. header := c.Req.Header.Get("Authorization")
  29. parts := strings.SplitN(header, " ", 2)
  30. if len(parts) == 2 || parts[0] == "Bearer" {
  31. token := parts[1]
  32. userQuery := m.GetAccountByTokenQuery{Token: token}
  33. if err := bus.Dispatch(&userQuery); err != nil {
  34. return -1, err
  35. }
  36. return userQuery.Result.Id, nil
  37. }
  38. // anonymous gues user
  39. if setting.Anonymous {
  40. return setting.AnonymousAccountId, nil
  41. }
  42. return -1, errors.New("Auth: session account id not found")
  43. }
  44. func authDenied(c *Context) {
  45. if c.IsApiRequest() {
  46. c.JsonApiErr(401, "Access denied", nil)
  47. }
  48. c.Redirect(setting.AppSubUrl + "/login")
  49. }
  50. func Auth(options *AuthOptions) macaron.Handler {
  51. return func(c *Context) {
  52. if !c.IsSignedIn && options.ReqSignedIn {
  53. authDenied(c)
  54. return
  55. }
  56. if !c.IsAdmin && options.ReqAdmin {
  57. authDenied(c)
  58. return
  59. }
  60. }
  61. }