auth.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package middleware
  2. import (
  3. "strconv"
  4. "strings"
  5. "github.com/Unknwon/macaron"
  6. m "github.com/torkelo/grafana-pro/pkg/models"
  7. "github.com/torkelo/grafana-pro/pkg/setting"
  8. )
  9. type AuthOptions struct {
  10. ReqGrafanaAdmin bool
  11. ReqSignedIn bool
  12. }
  13. func getRequestAccountId(c *Context) int64 {
  14. accountId := c.Session.Get("accountId")
  15. if accountId != nil {
  16. return accountId.(int64)
  17. }
  18. // localhost render query
  19. urlQuery := c.Req.URL.Query()
  20. if len(urlQuery["render"]) > 0 {
  21. accId, _ := strconv.ParseInt(urlQuery["accountId"][0], 10, 64)
  22. c.Session.Set("accountId", accId)
  23. accountId = accId
  24. }
  25. return 0
  26. }
  27. func getApiToken(c *Context) string {
  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. return token
  33. }
  34. return ""
  35. }
  36. func authDenied(c *Context) {
  37. if c.IsApiRequest() {
  38. c.JsonApiErr(401, "Access denied", nil)
  39. }
  40. c.Redirect(setting.AppSubUrl + "/login")
  41. }
  42. func RoleAuth(roles ...m.RoleType) macaron.Handler {
  43. return func(c *Context) {
  44. ok := false
  45. for _, role := range roles {
  46. if role == c.UserRole {
  47. ok = true
  48. break
  49. }
  50. }
  51. if !ok {
  52. authDenied(c)
  53. }
  54. }
  55. }
  56. func Auth(options *AuthOptions) macaron.Handler {
  57. return func(c *Context) {
  58. if !c.IsSignedIn && options.ReqSignedIn {
  59. authDenied(c)
  60. return
  61. }
  62. if !c.IsGrafanaAdmin && options.ReqGrafanaAdmin {
  63. authDenied(c)
  64. return
  65. }
  66. }
  67. }