auth.go 1.4 KB

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