auth.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package middleware
  2. import (
  3. "net/url"
  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 getRequestUserId(c *Context) int64 {
  14. userId := c.Session.Get("userId")
  15. if userId != nil {
  16. return userId.(int64)
  17. }
  18. // TODO: figure out a way to secure this
  19. if c.Query("render") == "1" {
  20. userId := c.QueryInt64("userId")
  21. c.Session.Set("userId", userId)
  22. return userId
  23. }
  24. return 0
  25. }
  26. func getApiKey(c *Context) string {
  27. header := c.Req.Header.Get("Authorization")
  28. parts := strings.SplitN(header, " ", 2)
  29. if len(parts) == 2 || parts[0] == "Bearer" {
  30. key := parts[1]
  31. return key
  32. }
  33. return ""
  34. }
  35. func authDenied(c *Context) {
  36. if c.IsApiRequest() {
  37. c.JsonApiErr(401, "Access denied", nil)
  38. return
  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.AccountRole {
  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.IsGrafanaAdmin && options.ReqGrafanaAdmin {
  59. authDenied(c)
  60. return
  61. }
  62. if !c.IsSignedIn && options.ReqSignedIn && !c.HasAnonymousAccess {
  63. c.SetCookie("redirect_to", url.QueryEscape(setting.AppSubUrl+c.Req.RequestURI), 0, setting.AppSubUrl+"/")
  64. authDenied(c)
  65. return
  66. }
  67. }
  68. }