auth.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package middleware
  2. import (
  3. "net/url"
  4. "strings"
  5. "github.com/Unknwon/macaron"
  6. m "github.com/grafana/grafana/pkg/models"
  7. "github.com/grafana/grafana/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(SESS_KEY_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(SESS_KEY_USERID)
  21. c.Session.Set(SESS_KEY_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.OrgRole {
  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. c.SetCookie("redirect_to", url.QueryEscape(setting.AppSubUrl+c.Req.RequestURI), 0, setting.AppSubUrl+"/")
  60. authDenied(c)
  61. return
  62. }
  63. if !c.IsSignedIn && options.ReqSignedIn && !c.HasAnonymousAccess {
  64. c.SetCookie("redirect_to", url.QueryEscape(setting.AppSubUrl+c.Req.RequestURI), 0, setting.AppSubUrl+"/")
  65. authDenied(c)
  66. return
  67. }
  68. }
  69. }