move Context and session out of middleware
This commit is contained in:
@@ -7,6 +7,7 @@ import (
|
||||
"gopkg.in/macaron.v1"
|
||||
|
||||
m "github.com/grafana/grafana/pkg/models"
|
||||
"github.com/grafana/grafana/pkg/services/session"
|
||||
"github.com/grafana/grafana/pkg/setting"
|
||||
)
|
||||
|
||||
@@ -15,8 +16,8 @@ type AuthOptions struct {
|
||||
ReqSignedIn bool
|
||||
}
|
||||
|
||||
func getRequestUserId(c *Context) int64 {
|
||||
userId := c.Session.Get(SESS_KEY_USERID)
|
||||
func getRequestUserId(c *m.Context) int64 {
|
||||
userId := c.Session.Get(session.SESS_KEY_USERID)
|
||||
|
||||
if userId != nil {
|
||||
return userId.(int64)
|
||||
@@ -25,7 +26,7 @@ func getRequestUserId(c *Context) int64 {
|
||||
return 0
|
||||
}
|
||||
|
||||
func getApiKey(c *Context) string {
|
||||
func getApiKey(c *m.Context) string {
|
||||
header := c.Req.Header.Get("Authorization")
|
||||
parts := strings.SplitN(header, " ", 2)
|
||||
if len(parts) == 2 && parts[0] == "Bearer" {
|
||||
@@ -36,7 +37,7 @@ func getApiKey(c *Context) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func accessForbidden(c *Context) {
|
||||
func accessForbidden(c *m.Context) {
|
||||
if c.IsApiRequest() {
|
||||
c.JsonApiErr(403, "Permission denied", nil)
|
||||
return
|
||||
@@ -45,7 +46,7 @@ func accessForbidden(c *Context) {
|
||||
c.Redirect(setting.AppSubUrl + "/")
|
||||
}
|
||||
|
||||
func notAuthorized(c *Context) {
|
||||
func notAuthorized(c *m.Context) {
|
||||
if c.IsApiRequest() {
|
||||
c.JsonApiErr(401, "Unauthorized", nil)
|
||||
return
|
||||
@@ -57,7 +58,7 @@ func notAuthorized(c *Context) {
|
||||
}
|
||||
|
||||
func RoleAuth(roles ...m.RoleType) macaron.Handler {
|
||||
return func(c *Context) {
|
||||
return func(c *m.Context) {
|
||||
ok := false
|
||||
for _, role := range roles {
|
||||
if role == c.OrgRole {
|
||||
@@ -72,7 +73,7 @@ func RoleAuth(roles ...m.RoleType) macaron.Handler {
|
||||
}
|
||||
|
||||
func Auth(options *AuthOptions) macaron.Handler {
|
||||
return func(c *Context) {
|
||||
return func(c *m.Context) {
|
||||
if !c.IsSignedIn && options.ReqSignedIn && !c.AllowAnonymous {
|
||||
notAuthorized(c)
|
||||
return
|
||||
|
||||
@@ -10,10 +10,11 @@ import (
|
||||
"github.com/grafana/grafana/pkg/log"
|
||||
"github.com/grafana/grafana/pkg/login"
|
||||
m "github.com/grafana/grafana/pkg/models"
|
||||
"github.com/grafana/grafana/pkg/services/session"
|
||||
"github.com/grafana/grafana/pkg/setting"
|
||||
)
|
||||
|
||||
func initContextWithAuthProxy(ctx *Context, orgId int64) bool {
|
||||
func initContextWithAuthProxy(ctx *m.Context, orgId int64) bool {
|
||||
if !setting.AuthProxyEnabled {
|
||||
return false
|
||||
}
|
||||
@@ -58,7 +59,7 @@ func initContextWithAuthProxy(ctx *Context, orgId int64) bool {
|
||||
}
|
||||
|
||||
// initialize session
|
||||
if err := ctx.Session.Start(ctx); err != nil {
|
||||
if err := ctx.Session.Start(ctx.Context); err != nil {
|
||||
log.Error(3, "Failed to start session", err)
|
||||
return false
|
||||
}
|
||||
@@ -66,12 +67,12 @@ func initContextWithAuthProxy(ctx *Context, orgId int64) bool {
|
||||
// Make sure that we cannot share a session between different users!
|
||||
if getRequestUserId(ctx) > 0 && getRequestUserId(ctx) != query.Result.UserId {
|
||||
// remove session
|
||||
if err := ctx.Session.Destory(ctx); err != nil {
|
||||
if err := ctx.Session.Destory(ctx.Context); err != nil {
|
||||
log.Error(3, "Failed to destroy session, err")
|
||||
}
|
||||
|
||||
// initialize a new session
|
||||
if err := ctx.Session.Start(ctx); err != nil {
|
||||
if err := ctx.Session.Start(ctx.Context); err != nil {
|
||||
log.Error(3, "Failed to start session", err)
|
||||
}
|
||||
}
|
||||
@@ -89,17 +90,17 @@ func initContextWithAuthProxy(ctx *Context, orgId int64) bool {
|
||||
|
||||
ctx.SignedInUser = query.Result
|
||||
ctx.IsSignedIn = true
|
||||
ctx.Session.Set(SESS_KEY_USERID, ctx.UserId)
|
||||
ctx.Session.Set(session.SESS_KEY_USERID, ctx.UserId)
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
var syncGrafanaUserWithLdapUser = func(ctx *Context, query *m.GetSignedInUserQuery) error {
|
||||
var syncGrafanaUserWithLdapUser = func(ctx *m.Context, query *m.GetSignedInUserQuery) error {
|
||||
if setting.LdapEnabled {
|
||||
expireEpoch := time.Now().Add(time.Duration(-setting.AuthProxyLdapSyncTtl) * time.Minute).Unix()
|
||||
|
||||
var lastLdapSync int64
|
||||
if lastLdapSyncInSession := ctx.Session.Get(SESS_KEY_LASTLDAPSYNC); lastLdapSyncInSession != nil {
|
||||
if lastLdapSyncInSession := ctx.Session.Get(session.SESS_KEY_LASTLDAPSYNC); lastLdapSyncInSession != nil {
|
||||
lastLdapSync = lastLdapSyncInSession.(int64)
|
||||
}
|
||||
|
||||
@@ -113,14 +114,14 @@ var syncGrafanaUserWithLdapUser = func(ctx *Context, query *m.GetSignedInUserQue
|
||||
}
|
||||
}
|
||||
|
||||
ctx.Session.Set(SESS_KEY_LASTLDAPSYNC, time.Now().Unix())
|
||||
ctx.Session.Set(session.SESS_KEY_LASTLDAPSYNC, time.Now().Unix())
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func checkAuthenticationProxy(ctx *Context, proxyHeaderValue string) error {
|
||||
func checkAuthenticationProxy(ctx *m.Context, proxyHeaderValue string) error {
|
||||
if len(strings.TrimSpace(setting.AuthProxyWhitelist)) > 0 {
|
||||
proxies := strings.Split(setting.AuthProxyWhitelist, ",")
|
||||
remoteAddrSplit := strings.Split(ctx.Req.RemoteAddr, ":")
|
||||
|
||||
@@ -6,8 +6,10 @@ import (
|
||||
|
||||
"github.com/grafana/grafana/pkg/login"
|
||||
m "github.com/grafana/grafana/pkg/models"
|
||||
"github.com/grafana/grafana/pkg/services/session"
|
||||
"github.com/grafana/grafana/pkg/setting"
|
||||
. "github.com/smartystreets/goconvey/convey"
|
||||
"gopkg.in/macaron.v1"
|
||||
)
|
||||
|
||||
func TestAuthProxyWithLdapEnabled(t *testing.T) {
|
||||
@@ -29,45 +31,45 @@ func TestAuthProxyWithLdapEnabled(t *testing.T) {
|
||||
|
||||
Convey("When session variable lastLdapSync not set, call syncSignedInUser and set lastLdapSync", func() {
|
||||
// arrange
|
||||
session := mockSession{}
|
||||
ctx := Context{Session: &session}
|
||||
So(session.Get(SESS_KEY_LASTLDAPSYNC), ShouldBeNil)
|
||||
sess := mockSession{}
|
||||
ctx := m.Context{Session: &sess}
|
||||
So(sess.Get(session.SESS_KEY_LASTLDAPSYNC), ShouldBeNil)
|
||||
|
||||
// act
|
||||
syncGrafanaUserWithLdapUser(&ctx, &query)
|
||||
|
||||
// assert
|
||||
So(mockLdapAuther.syncSignedInUserCalled, ShouldBeTrue)
|
||||
So(session.Get(SESS_KEY_LASTLDAPSYNC), ShouldBeGreaterThan, 0)
|
||||
So(sess.Get(session.SESS_KEY_LASTLDAPSYNC), ShouldBeGreaterThan, 0)
|
||||
})
|
||||
|
||||
Convey("When session variable not expired, don't sync and don't change session var", func() {
|
||||
// arrange
|
||||
session := mockSession{}
|
||||
ctx := Context{Session: &session}
|
||||
sess := mockSession{}
|
||||
ctx := m.Context{Session: &sess}
|
||||
now := time.Now().Unix()
|
||||
session.Set(SESS_KEY_LASTLDAPSYNC, now)
|
||||
sess.Set(session.SESS_KEY_LASTLDAPSYNC, now)
|
||||
|
||||
// act
|
||||
syncGrafanaUserWithLdapUser(&ctx, &query)
|
||||
|
||||
// assert
|
||||
So(session.Get(SESS_KEY_LASTLDAPSYNC), ShouldEqual, now)
|
||||
So(sess.Get(session.SESS_KEY_LASTLDAPSYNC), ShouldEqual, now)
|
||||
So(mockLdapAuther.syncSignedInUserCalled, ShouldBeFalse)
|
||||
})
|
||||
|
||||
Convey("When lastldapsync is expired, session variable should be updated", func() {
|
||||
// arrange
|
||||
session := mockSession{}
|
||||
ctx := Context{Session: &session}
|
||||
sess := mockSession{}
|
||||
ctx := m.Context{Session: &sess}
|
||||
expiredTime := time.Now().Add(time.Duration(-120) * time.Minute).Unix()
|
||||
session.Set(SESS_KEY_LASTLDAPSYNC, expiredTime)
|
||||
sess.Set(session.SESS_KEY_LASTLDAPSYNC, expiredTime)
|
||||
|
||||
// act
|
||||
syncGrafanaUserWithLdapUser(&ctx, &query)
|
||||
|
||||
// assert
|
||||
So(session.Get(SESS_KEY_LASTLDAPSYNC), ShouldBeGreaterThan, expiredTime)
|
||||
So(sess.Get(session.SESS_KEY_LASTLDAPSYNC), ShouldBeGreaterThan, expiredTime)
|
||||
So(mockLdapAuther.syncSignedInUserCalled, ShouldBeTrue)
|
||||
})
|
||||
})
|
||||
@@ -77,7 +79,7 @@ type mockSession struct {
|
||||
value interface{}
|
||||
}
|
||||
|
||||
func (s *mockSession) Start(c *Context) error {
|
||||
func (s *mockSession) Start(c *macaron.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -102,11 +104,11 @@ func (s *mockSession) Release() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *mockSession) Destory(c *Context) error {
|
||||
func (s *mockSession) Destory(c *macaron.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *mockSession) RegenerateId(c *Context) error {
|
||||
func (s *mockSession) RegenerateId(c *macaron.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ func getDashboardUrlBySlug(orgId int64, slug string) (string, error) {
|
||||
}
|
||||
|
||||
func RedirectFromLegacyDashboardUrl() macaron.Handler {
|
||||
return func(c *Context) {
|
||||
return func(c *m.Context) {
|
||||
slug := c.Params("slug")
|
||||
|
||||
if slug != "" {
|
||||
@@ -34,7 +34,7 @@ func RedirectFromLegacyDashboardUrl() macaron.Handler {
|
||||
}
|
||||
|
||||
func RedirectFromLegacyDashboardSoloUrl() macaron.Handler {
|
||||
return func(c *Context) {
|
||||
return func(c *m.Context) {
|
||||
slug := c.Params("slug")
|
||||
|
||||
if slug != "" {
|
||||
|
||||
@@ -19,6 +19,7 @@ import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
m "github.com/grafana/grafana/pkg/models"
|
||||
"github.com/grafana/grafana/pkg/setting"
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"gopkg.in/macaron.v1"
|
||||
@@ -47,7 +48,7 @@ func Logger() macaron.Handler {
|
||||
}
|
||||
|
||||
if ctx, ok := c.Data["ctx"]; ok {
|
||||
ctxTyped := ctx.(*Context)
|
||||
ctxTyped := ctx.(*m.Context)
|
||||
if status == 500 {
|
||||
ctxTyped.Logger.Error("Request Completed", "method", req.Method, "path", req.URL.Path, "status", status, "remote_addr", c.RemoteAddr(), "time_ms", int64(timeTakenMs), "size", rw.Size(), "referer", req.Referer())
|
||||
} else {
|
||||
|
||||
@@ -2,7 +2,6 @@ package middleware
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"gopkg.in/macaron.v1"
|
||||
|
||||
@@ -11,29 +10,17 @@ import (
|
||||
"github.com/grafana/grafana/pkg/log"
|
||||
l "github.com/grafana/grafana/pkg/login"
|
||||
m "github.com/grafana/grafana/pkg/models"
|
||||
"github.com/grafana/grafana/pkg/services/session"
|
||||
"github.com/grafana/grafana/pkg/setting"
|
||||
"github.com/grafana/grafana/pkg/util"
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
)
|
||||
|
||||
type Context struct {
|
||||
*macaron.Context
|
||||
*m.SignedInUser
|
||||
|
||||
Session SessionStore
|
||||
|
||||
IsSignedIn bool
|
||||
IsRenderCall bool
|
||||
AllowAnonymous bool
|
||||
Logger log.Logger
|
||||
}
|
||||
|
||||
func GetContextHandler() macaron.Handler {
|
||||
return func(c *macaron.Context) {
|
||||
ctx := &Context{
|
||||
ctx := &m.Context{
|
||||
Context: c,
|
||||
SignedInUser: &m.SignedInUser{},
|
||||
Session: GetSession(),
|
||||
Session: session.GetSession(),
|
||||
IsSignedIn: false,
|
||||
AllowAnonymous: false,
|
||||
Logger: log.New("context"),
|
||||
@@ -74,7 +61,7 @@ func GetContextHandler() macaron.Handler {
|
||||
}
|
||||
}
|
||||
|
||||
func initContextWithAnonymousUser(ctx *Context) bool {
|
||||
func initContextWithAnonymousUser(ctx *m.Context) bool {
|
||||
if !setting.AnonymousEnabled {
|
||||
return false
|
||||
}
|
||||
@@ -94,9 +81,9 @@ func initContextWithAnonymousUser(ctx *Context) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func initContextWithUserSessionCookie(ctx *Context, orgId int64) bool {
|
||||
func initContextWithUserSessionCookie(ctx *m.Context, orgId int64) bool {
|
||||
// initialize session
|
||||
if err := ctx.Session.Start(ctx); err != nil {
|
||||
if err := ctx.Session.Start(ctx.Context); err != nil {
|
||||
ctx.Logger.Error("Failed to start session", "error", err)
|
||||
return false
|
||||
}
|
||||
@@ -117,7 +104,7 @@ func initContextWithUserSessionCookie(ctx *Context, orgId int64) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func initContextWithApiKey(ctx *Context) bool {
|
||||
func initContextWithApiKey(ctx *m.Context) bool {
|
||||
var keyString string
|
||||
if keyString = getApiKey(ctx); keyString == "" {
|
||||
return false
|
||||
@@ -153,7 +140,7 @@ func initContextWithApiKey(ctx *Context) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func initContextWithBasicAuth(ctx *Context, orgId int64) bool {
|
||||
func initContextWithBasicAuth(ctx *m.Context, orgId int64) bool {
|
||||
|
||||
if !setting.BasicAuthEnabled {
|
||||
return false
|
||||
@@ -195,70 +182,8 @@ func initContextWithBasicAuth(ctx *Context, orgId int64) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// Handle handles and logs error by given status.
|
||||
func (ctx *Context) Handle(status int, title string, err error) {
|
||||
if err != nil {
|
||||
ctx.Logger.Error(title, "error", err)
|
||||
if setting.Env != setting.PROD {
|
||||
ctx.Data["ErrorMsg"] = err
|
||||
}
|
||||
}
|
||||
|
||||
ctx.Data["Title"] = title
|
||||
ctx.Data["AppSubUrl"] = setting.AppSubUrl
|
||||
ctx.Data["Theme"] = "dark"
|
||||
|
||||
ctx.HTML(status, "error")
|
||||
}
|
||||
|
||||
func (ctx *Context) JsonOK(message string) {
|
||||
resp := make(map[string]interface{})
|
||||
resp["message"] = message
|
||||
ctx.JSON(200, resp)
|
||||
}
|
||||
|
||||
func (ctx *Context) IsApiRequest() bool {
|
||||
return strings.HasPrefix(ctx.Req.URL.Path, "/api")
|
||||
}
|
||||
|
||||
func (ctx *Context) JsonApiErr(status int, message string, err error) {
|
||||
resp := make(map[string]interface{})
|
||||
|
||||
if err != nil {
|
||||
ctx.Logger.Error(message, "error", err)
|
||||
if setting.Env != setting.PROD {
|
||||
resp["error"] = err.Error()
|
||||
}
|
||||
}
|
||||
|
||||
switch status {
|
||||
case 404:
|
||||
resp["message"] = "Not Found"
|
||||
case 500:
|
||||
resp["message"] = "Internal Server Error"
|
||||
}
|
||||
|
||||
if message != "" {
|
||||
resp["message"] = message
|
||||
}
|
||||
|
||||
ctx.JSON(status, resp)
|
||||
}
|
||||
|
||||
func (ctx *Context) HasUserRole(role m.RoleType) bool {
|
||||
return ctx.OrgRole.Includes(role)
|
||||
}
|
||||
|
||||
func (ctx *Context) HasHelpFlag(flag m.HelpFlags1) bool {
|
||||
return ctx.HelpFlags1.HasFlag(flag)
|
||||
}
|
||||
|
||||
func (ctx *Context) TimeRequest(timer prometheus.Summary) {
|
||||
ctx.Data["perfmon.timer"] = timer
|
||||
}
|
||||
|
||||
func AddDefaultResponseHeaders() macaron.Handler {
|
||||
return func(ctx *Context) {
|
||||
return func(ctx *m.Context) {
|
||||
if ctx.IsApiRequest() && ctx.Req.Method == "GET" {
|
||||
ctx.Resp.Header().Add("Cache-Control", "no-cache")
|
||||
ctx.Resp.Header().Add("Pragma", "no-cache")
|
||||
|
||||
@@ -7,10 +7,11 @@ import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/go-macaron/session"
|
||||
ms "github.com/go-macaron/session"
|
||||
"github.com/grafana/grafana/pkg/bus"
|
||||
l "github.com/grafana/grafana/pkg/login"
|
||||
m "github.com/grafana/grafana/pkg/models"
|
||||
"github.com/grafana/grafana/pkg/services/session"
|
||||
"github.com/grafana/grafana/pkg/setting"
|
||||
"github.com/grafana/grafana/pkg/util"
|
||||
. "github.com/smartystreets/goconvey/convey"
|
||||
@@ -130,8 +131,8 @@ func TestMiddlewareContext(t *testing.T) {
|
||||
|
||||
middlewareScenario("UserId in session", func(sc *scenarioContext) {
|
||||
|
||||
sc.fakeReq("GET", "/").handler(func(c *Context) {
|
||||
c.Session.Set(SESS_KEY_USERID, int64(12))
|
||||
sc.fakeReq("GET", "/").handler(func(c *m.Context) {
|
||||
c.Session.Set(session.SESS_KEY_USERID, int64(12))
|
||||
}).exec()
|
||||
|
||||
bus.AddHandler("test", func(query *m.GetSignedInUserQuery) error {
|
||||
@@ -276,8 +277,8 @@ func TestMiddlewareContext(t *testing.T) {
|
||||
})
|
||||
|
||||
// create session
|
||||
sc.fakeReq("GET", "/").handler(func(c *Context) {
|
||||
c.Session.Set(SESS_KEY_USERID, int64(33))
|
||||
sc.fakeReq("GET", "/").handler(func(c *m.Context) {
|
||||
c.Session.Set(session.SESS_KEY_USERID, int64(33))
|
||||
}).exec()
|
||||
|
||||
oldSessionID := sc.context.Session.ID()
|
||||
@@ -300,7 +301,7 @@ func TestMiddlewareContext(t *testing.T) {
|
||||
setting.LdapEnabled = true
|
||||
|
||||
called := false
|
||||
syncGrafanaUserWithLdapUser = func(ctx *Context, query *m.GetSignedInUserQuery) error {
|
||||
syncGrafanaUserWithLdapUser = func(ctx *m.Context, query *m.GetSignedInUserQuery) error {
|
||||
called = true
|
||||
return nil
|
||||
}
|
||||
@@ -336,12 +337,12 @@ func middlewareScenario(desc string, fn scenarioFunc) {
|
||||
|
||||
sc.m.Use(GetContextHandler())
|
||||
// mock out gc goroutine
|
||||
startSessionGC = func() {}
|
||||
sc.m.Use(Sessioner(&session.Options{}))
|
||||
session.StartSessionGC = func() {}
|
||||
sc.m.Use(Sessioner(&ms.Options{}))
|
||||
sc.m.Use(OrgRedirect())
|
||||
sc.m.Use(AddDefaultResponseHeaders())
|
||||
|
||||
sc.defaultHandler = func(c *Context) {
|
||||
sc.defaultHandler = func(c *m.Context) {
|
||||
sc.context = c
|
||||
if sc.handlerFunc != nil {
|
||||
sc.handlerFunc(sc.context)
|
||||
@@ -356,7 +357,7 @@ func middlewareScenario(desc string, fn scenarioFunc) {
|
||||
|
||||
type scenarioContext struct {
|
||||
m *macaron.Macaron
|
||||
context *Context
|
||||
context *m.Context
|
||||
resp *httptest.ResponseRecorder
|
||||
apiKey string
|
||||
authHeader string
|
||||
@@ -436,4 +437,4 @@ func (sc *scenarioContext) exec() {
|
||||
}
|
||||
|
||||
type scenarioFunc func(c *scenarioContext)
|
||||
type handlerFunc func(c *Context)
|
||||
type handlerFunc func(c *m.Context)
|
||||
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/grafana/grafana/pkg/bus"
|
||||
"github.com/grafana/grafana/pkg/models"
|
||||
m "github.com/grafana/grafana/pkg/models"
|
||||
"github.com/grafana/grafana/pkg/setting"
|
||||
|
||||
"gopkg.in/macaron.v1"
|
||||
@@ -22,7 +22,7 @@ func OrgRedirect() macaron.Handler {
|
||||
return
|
||||
}
|
||||
|
||||
ctx, ok := c.Data["ctx"].(*Context)
|
||||
ctx, ok := c.Data["ctx"].(*m.Context)
|
||||
if !ok || !ctx.IsSignedIn {
|
||||
return
|
||||
}
|
||||
@@ -31,7 +31,7 @@ func OrgRedirect() macaron.Handler {
|
||||
return
|
||||
}
|
||||
|
||||
cmd := models.SetUsingOrgCommand{UserId: ctx.UserId, OrgId: orgId}
|
||||
cmd := m.SetUsingOrgCommand{UserId: ctx.UserId, OrgId: orgId}
|
||||
if err := bus.Dispatch(&cmd); err != nil {
|
||||
if ctx.IsApiRequest() {
|
||||
ctx.JsonApiErr(404, "Not found", nil)
|
||||
|
||||
@@ -6,7 +6,8 @@ import (
|
||||
"fmt"
|
||||
|
||||
"github.com/grafana/grafana/pkg/bus"
|
||||
"github.com/grafana/grafana/pkg/models"
|
||||
m "github.com/grafana/grafana/pkg/models"
|
||||
"github.com/grafana/grafana/pkg/services/session"
|
||||
. "github.com/smartystreets/goconvey/convey"
|
||||
)
|
||||
|
||||
@@ -14,16 +15,16 @@ func TestOrgRedirectMiddleware(t *testing.T) {
|
||||
|
||||
Convey("Can redirect to correct org", t, func() {
|
||||
middlewareScenario("when setting a correct org for the user", func(sc *scenarioContext) {
|
||||
sc.fakeReq("GET", "/").handler(func(c *Context) {
|
||||
c.Session.Set(SESS_KEY_USERID, int64(12))
|
||||
sc.fakeReq("GET", "/").handler(func(c *m.Context) {
|
||||
c.Session.Set(session.SESS_KEY_USERID, int64(12))
|
||||
}).exec()
|
||||
|
||||
bus.AddHandler("test", func(query *models.SetUsingOrgCommand) error {
|
||||
bus.AddHandler("test", func(query *m.SetUsingOrgCommand) error {
|
||||
return nil
|
||||
})
|
||||
|
||||
bus.AddHandler("test", func(query *models.GetSignedInUserQuery) error {
|
||||
query.Result = &models.SignedInUser{OrgId: 1, UserId: 12}
|
||||
bus.AddHandler("test", func(query *m.GetSignedInUserQuery) error {
|
||||
query.Result = &m.SignedInUser{OrgId: 1, UserId: 12}
|
||||
return nil
|
||||
})
|
||||
|
||||
@@ -36,16 +37,16 @@ func TestOrgRedirectMiddleware(t *testing.T) {
|
||||
})
|
||||
|
||||
middlewareScenario("when setting an invalid org for user", func(sc *scenarioContext) {
|
||||
sc.fakeReq("GET", "/").handler(func(c *Context) {
|
||||
c.Session.Set(SESS_KEY_USERID, int64(12))
|
||||
sc.fakeReq("GET", "/").handler(func(c *m.Context) {
|
||||
c.Session.Set(session.SESS_KEY_USERID, int64(12))
|
||||
}).exec()
|
||||
|
||||
bus.AddHandler("test", func(query *models.SetUsingOrgCommand) error {
|
||||
bus.AddHandler("test", func(query *m.SetUsingOrgCommand) error {
|
||||
return fmt.Errorf("")
|
||||
})
|
||||
|
||||
bus.AddHandler("test", func(query *models.GetSignedInUserQuery) error {
|
||||
query.Result = &models.SignedInUser{OrgId: 1, UserId: 12}
|
||||
bus.AddHandler("test", func(query *m.GetSignedInUserQuery) error {
|
||||
query.Result = &m.SignedInUser{OrgId: 1, UserId: 12}
|
||||
return nil
|
||||
})
|
||||
|
||||
|
||||
@@ -4,9 +4,11 @@ import (
|
||||
"net/http"
|
||||
|
||||
"gopkg.in/macaron.v1"
|
||||
|
||||
m "github.com/grafana/grafana/pkg/models"
|
||||
)
|
||||
|
||||
func MeasureRequestTime() macaron.Handler {
|
||||
return func(res http.ResponseWriter, req *http.Request, c *Context) {
|
||||
return func(res http.ResponseWriter, req *http.Request, c *m.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,12 +5,13 @@ import (
|
||||
|
||||
"github.com/grafana/grafana/pkg/bus"
|
||||
m "github.com/grafana/grafana/pkg/models"
|
||||
"github.com/grafana/grafana/pkg/services/session"
|
||||
"github.com/grafana/grafana/pkg/setting"
|
||||
"gopkg.in/macaron.v1"
|
||||
)
|
||||
|
||||
func Quota(target string) macaron.Handler {
|
||||
return func(c *Context) {
|
||||
return func(c *m.Context) {
|
||||
limitReached, err := QuotaReached(c, target)
|
||||
if err != nil {
|
||||
c.JsonApiErr(500, "failed to get quota", err)
|
||||
@@ -23,7 +24,7 @@ func Quota(target string) macaron.Handler {
|
||||
}
|
||||
}
|
||||
|
||||
func QuotaReached(c *Context, target string) (bool, error) {
|
||||
func QuotaReached(c *m.Context, target string) (bool, error) {
|
||||
if !setting.Quota.Enabled {
|
||||
return false, nil
|
||||
}
|
||||
@@ -46,7 +47,7 @@ func QuotaReached(c *Context, target string) (bool, error) {
|
||||
return true, nil
|
||||
}
|
||||
if target == "session" {
|
||||
usedSessions := getSessionCount()
|
||||
usedSessions := session.GetSessionCount()
|
||||
if int64(usedSessions) > scope.DefaultLimit {
|
||||
c.Logger.Debug("Sessions limit reached", "active", usedSessions, "limit", scope.DefaultLimit)
|
||||
return true, nil
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
|
||||
"github.com/grafana/grafana/pkg/bus"
|
||||
m "github.com/grafana/grafana/pkg/models"
|
||||
"github.com/grafana/grafana/pkg/services/session"
|
||||
"github.com/grafana/grafana/pkg/setting"
|
||||
. "github.com/smartystreets/goconvey/convey"
|
||||
)
|
||||
@@ -12,7 +13,7 @@ import (
|
||||
func TestMiddlewareQuota(t *testing.T) {
|
||||
|
||||
Convey("Given the grafana quota middleware", t, func() {
|
||||
getSessionCount = func() int {
|
||||
session.GetSessionCount = func() int {
|
||||
return 4
|
||||
}
|
||||
|
||||
@@ -74,8 +75,8 @@ func TestMiddlewareQuota(t *testing.T) {
|
||||
|
||||
middlewareScenario("with user logged in", func(sc *scenarioContext) {
|
||||
// log us in, so we have a user_id and org_id in the context
|
||||
sc.fakeReq("GET", "/").handler(func(c *Context) {
|
||||
c.Session.Set(SESS_KEY_USERID, int64(12))
|
||||
sc.fakeReq("GET", "/").handler(func(c *m.Context) {
|
||||
c.Session.Set(session.SESS_KEY_USERID, int64(12))
|
||||
}).exec()
|
||||
|
||||
bus.AddHandler("test", func(query *m.GetSignedInUserQuery) error {
|
||||
|
||||
@@ -24,6 +24,7 @@ import (
|
||||
"gopkg.in/macaron.v1"
|
||||
|
||||
"github.com/grafana/grafana/pkg/log"
|
||||
m "github.com/grafana/grafana/pkg/models"
|
||||
"github.com/grafana/grafana/pkg/setting"
|
||||
)
|
||||
|
||||
@@ -106,7 +107,7 @@ func Recovery() macaron.Handler {
|
||||
panicLogger := log.Root
|
||||
// try to get request logger
|
||||
if ctx, ok := c.Data["ctx"]; ok {
|
||||
ctxTyped := ctx.(*Context)
|
||||
ctxTyped := ctx.(*m.Context)
|
||||
panicLogger = ctxTyped.Logger
|
||||
}
|
||||
|
||||
@@ -123,7 +124,7 @@ func Recovery() macaron.Handler {
|
||||
c.Data["ErrorMsg"] = string(stack)
|
||||
}
|
||||
|
||||
ctx, ok := c.Data["ctx"].(*Context)
|
||||
ctx, ok := c.Data["ctx"].(*m.Context)
|
||||
|
||||
if ok && ctx.IsApiRequest() {
|
||||
resp := make(map[string]interface{})
|
||||
|
||||
@@ -4,8 +4,10 @@ import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/go-macaron/session"
|
||||
ms "github.com/go-macaron/session"
|
||||
"github.com/grafana/grafana/pkg/bus"
|
||||
m "github.com/grafana/grafana/pkg/models"
|
||||
"github.com/grafana/grafana/pkg/services/session"
|
||||
. "github.com/smartystreets/goconvey/convey"
|
||||
"gopkg.in/macaron.v1"
|
||||
)
|
||||
@@ -37,7 +39,7 @@ func TestRecoveryMiddleware(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func PanicHandler(c *Context) {
|
||||
func PanicHandler(c *m.Context) {
|
||||
panic("Handler has panicked")
|
||||
}
|
||||
|
||||
@@ -60,12 +62,12 @@ func recoveryScenario(desc string, url string, fn scenarioFunc) {
|
||||
|
||||
sc.m.Use(GetContextHandler())
|
||||
// mock out gc goroutine
|
||||
startSessionGC = func() {}
|
||||
sc.m.Use(Sessioner(&session.Options{}))
|
||||
session.StartSessionGC = func() {}
|
||||
sc.m.Use(Sessioner(&ms.Options{}))
|
||||
sc.m.Use(OrgRedirect())
|
||||
sc.m.Use(AddDefaultResponseHeaders())
|
||||
|
||||
sc.defaultHandler = func(c *Context) {
|
||||
sc.defaultHandler = func(c *m.Context) {
|
||||
sc.context = c
|
||||
if sc.handlerFunc != nil {
|
||||
sc.handlerFunc(sc.context)
|
||||
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
var renderKeysLock sync.Mutex
|
||||
var renderKeys map[string]*m.SignedInUser = make(map[string]*m.SignedInUser)
|
||||
|
||||
func initContextWithRenderAuth(ctx *Context) bool {
|
||||
func initContextWithRenderAuth(ctx *m.Context) bool {
|
||||
key := ctx.GetCookie("renderKey")
|
||||
if key == "" {
|
||||
return false
|
||||
|
||||
+8
-157
@@ -1,170 +1,21 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"math/rand"
|
||||
"time"
|
||||
|
||||
"github.com/go-macaron/session"
|
||||
_ "github.com/go-macaron/session/memcache"
|
||||
_ "github.com/go-macaron/session/mysql"
|
||||
_ "github.com/go-macaron/session/postgres"
|
||||
_ "github.com/go-macaron/session/redis"
|
||||
"github.com/grafana/grafana/pkg/log"
|
||||
ms "github.com/go-macaron/session"
|
||||
"gopkg.in/macaron.v1"
|
||||
|
||||
m "github.com/grafana/grafana/pkg/models"
|
||||
"github.com/grafana/grafana/pkg/services/session"
|
||||
)
|
||||
|
||||
const (
|
||||
SESS_KEY_USERID = "uid"
|
||||
SESS_KEY_OAUTH_STATE = "state"
|
||||
SESS_KEY_APIKEY = "apikey_id" // used for render requests with api keys
|
||||
SESS_KEY_LASTLDAPSYNC = "last_ldap_sync"
|
||||
)
|
||||
func Sessioner(options *ms.Options) macaron.Handler {
|
||||
session.Init(options)
|
||||
|
||||
var sessionManager *session.Manager
|
||||
var sessionOptions *session.Options
|
||||
var startSessionGC func()
|
||||
var getSessionCount func() int
|
||||
var sessionLogger = log.New("session")
|
||||
|
||||
func init() {
|
||||
startSessionGC = func() {
|
||||
sessionManager.GC()
|
||||
sessionLogger.Debug("Session GC")
|
||||
time.AfterFunc(time.Duration(sessionOptions.Gclifetime)*time.Second, startSessionGC)
|
||||
}
|
||||
getSessionCount = func() int {
|
||||
return sessionManager.Count()
|
||||
}
|
||||
}
|
||||
|
||||
func prepareOptions(opt *session.Options) *session.Options {
|
||||
if len(opt.Provider) == 0 {
|
||||
opt.Provider = "memory"
|
||||
}
|
||||
if len(opt.ProviderConfig) == 0 {
|
||||
opt.ProviderConfig = "data/sessions"
|
||||
}
|
||||
if len(opt.CookieName) == 0 {
|
||||
opt.CookieName = "grafana_sess"
|
||||
}
|
||||
if len(opt.CookiePath) == 0 {
|
||||
opt.CookiePath = "/"
|
||||
}
|
||||
if opt.Gclifetime == 0 {
|
||||
opt.Gclifetime = 3600
|
||||
}
|
||||
if opt.Maxlifetime == 0 {
|
||||
opt.Maxlifetime = opt.Gclifetime
|
||||
}
|
||||
if opt.IDLength == 0 {
|
||||
opt.IDLength = 16
|
||||
}
|
||||
|
||||
return opt
|
||||
}
|
||||
|
||||
func Sessioner(options *session.Options) macaron.Handler {
|
||||
var err error
|
||||
sessionOptions = prepareOptions(options)
|
||||
sessionManager, err = session.NewManager(options.Provider, *options)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// start GC threads after some random seconds
|
||||
rndSeconds := 10 + rand.Int63n(180)
|
||||
time.AfterFunc(time.Duration(rndSeconds)*time.Second, startSessionGC)
|
||||
|
||||
return func(ctx *Context) {
|
||||
return func(ctx *m.Context) {
|
||||
ctx.Next()
|
||||
|
||||
if err = ctx.Session.Release(); err != nil {
|
||||
if err := ctx.Session.Release(); err != nil {
|
||||
panic("session(release): " + err.Error())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func GetSession() SessionStore {
|
||||
return &SessionWrapper{manager: sessionManager}
|
||||
}
|
||||
|
||||
type SessionStore interface {
|
||||
// Set sets value to given key in session.
|
||||
Set(interface{}, interface{}) error
|
||||
// Get gets value by given key in session.
|
||||
Get(interface{}) interface{}
|
||||
// Delete deletes a key from session.
|
||||
Delete(interface{}) interface{}
|
||||
// ID returns current session ID.
|
||||
ID() string
|
||||
// Release releases session resource and save data to provider.
|
||||
Release() error
|
||||
// Destory deletes a session.
|
||||
Destory(*Context) error
|
||||
// init
|
||||
Start(*Context) error
|
||||
// RegenerateId regenerates the session id
|
||||
RegenerateId(*Context) error
|
||||
}
|
||||
|
||||
type SessionWrapper struct {
|
||||
session session.RawStore
|
||||
manager *session.Manager
|
||||
}
|
||||
|
||||
func (s *SessionWrapper) Start(c *Context) error {
|
||||
var err error
|
||||
s.session, err = s.manager.Start(c.Context)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *SessionWrapper) RegenerateId(c *Context) error {
|
||||
var err error
|
||||
s.session, err = s.manager.RegenerateId(c.Context)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *SessionWrapper) Set(k interface{}, v interface{}) error {
|
||||
if s.session != nil {
|
||||
return s.session.Set(k, v)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *SessionWrapper) Get(k interface{}) interface{} {
|
||||
if s.session != nil {
|
||||
return s.session.Get(k)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *SessionWrapper) Delete(k interface{}) interface{} {
|
||||
if s.session != nil {
|
||||
return s.session.Delete(k)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *SessionWrapper) ID() string {
|
||||
if s.session != nil {
|
||||
return s.session.ID()
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (s *SessionWrapper) Release() error {
|
||||
if s.session != nil {
|
||||
return s.session.Release()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *SessionWrapper) Destory(c *Context) error {
|
||||
if s.session != nil {
|
||||
if err := s.manager.Destory(c.Context); err != nil {
|
||||
return err
|
||||
}
|
||||
s.session = nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -3,12 +3,13 @@ package middleware
|
||||
import (
|
||||
"strings"
|
||||
|
||||
m "github.com/grafana/grafana/pkg/models"
|
||||
"github.com/grafana/grafana/pkg/setting"
|
||||
"gopkg.in/macaron.v1"
|
||||
)
|
||||
|
||||
func ValidateHostHeader(domain string) macaron.Handler {
|
||||
return func(c *Context) {
|
||||
return func(c *m.Context) {
|
||||
// ignore local render calls
|
||||
if c.IsRenderCall {
|
||||
return
|
||||
|
||||
Reference in New Issue
Block a user