diff --git a/pkg/api/admin.go b/pkg/api/admin.go index 54a86724f0c..bc265e48aa5 100644 --- a/pkg/api/admin.go +++ b/pkg/api/admin.go @@ -5,11 +5,11 @@ import ( "strings" "github.com/grafana/grafana/pkg/bus" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/setting" ) -func AdminGetSettings(c *m.ReqContext) { +func AdminGetSettings(c *models.ReqContext) { settings := make(map[string]interface{}) for _, section := range setting.Raw.Sections() { @@ -38,9 +38,9 @@ func AdminGetSettings(c *m.ReqContext) { c.JSON(200, settings) } -func AdminGetStats(c *m.ReqContext) { +func AdminGetStats(c *models.ReqContext) { - statsQuery := m.GetAdminStatsQuery{} + statsQuery := models.GetAdminStatsQuery{} if err := bus.Dispatch(&statsQuery); err != nil { c.JsonApiErr(500, "Failed to get admin stats from database", err) diff --git a/pkg/api/admin_users_test.go b/pkg/api/admin_users_test.go index 75f0be3c072..bed74a2c688 100644 --- a/pkg/api/admin_users_test.go +++ b/pkg/api/admin_users_test.go @@ -6,22 +6,22 @@ import ( "github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/simplejson" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/auth" . "github.com/smartystreets/goconvey/convey" ) func TestAdminApiEndpoint(t *testing.T) { - role := m.ROLE_ADMIN + role := models.ROLE_ADMIN Convey("Given a server admin attempts to remove themself as an admin", t, func() { updateCmd := dtos.AdminUpdateUserPermissionsForm{ IsGrafanaAdmin: false, } - bus.AddHandler("test", func(cmd *m.UpdateUserPermissionsCommand) error { - return m.ErrLastGrafanaAdmin + bus.AddHandler("test", func(cmd *models.UpdateUserPermissionsCommand) error { + return models.ErrLastGrafanaAdmin }) putAdminScenario("When calling PUT on", "/api/admin/users/1/permissions", "/api/admin/users/:id/permissions", role, updateCmd, func(sc *scenarioContext) { @@ -31,8 +31,8 @@ func TestAdminApiEndpoint(t *testing.T) { }) Convey("When a server admin attempts to logout himself from all devices", t, func() { - bus.AddHandler("test", func(cmd *m.GetUserByIdQuery) error { - cmd.Result = &m.User{Id: TestUserID} + bus.AddHandler("test", func(cmd *models.GetUserByIdQuery) error { + cmd.Result = &models.User{Id: TestUserID} return nil }) @@ -44,9 +44,9 @@ func TestAdminApiEndpoint(t *testing.T) { Convey("When a server admin attempts to logout a non-existing user from all devices", t, func() { userId := int64(0) - bus.AddHandler("test", func(cmd *m.GetUserByIdQuery) error { + bus.AddHandler("test", func(cmd *models.GetUserByIdQuery) error { userId = cmd.Id - return m.ErrUserNotFound + return models.ErrUserNotFound }) adminLogoutUserScenario("Should return not found when calling POST on", "/api/admin/users/200/logout", "/api/admin/users/:id/logout", func(sc *scenarioContext) { @@ -58,12 +58,12 @@ func TestAdminApiEndpoint(t *testing.T) { Convey("When a server admin attempts to revoke an auth token for a non-existing user", t, func() { userId := int64(0) - bus.AddHandler("test", func(cmd *m.GetUserByIdQuery) error { + bus.AddHandler("test", func(cmd *models.GetUserByIdQuery) error { userId = cmd.Id - return m.ErrUserNotFound + return models.ErrUserNotFound }) - cmd := m.RevokeAuthTokenCmd{AuthTokenId: 2} + cmd := models.RevokeAuthTokenCmd{AuthTokenId: 2} adminRevokeUserAuthTokenScenario("Should return not found when calling POST on", "/api/admin/users/200/revoke-auth-token", "/api/admin/users/:id/revoke-auth-token", cmd, func(sc *scenarioContext) { sc.fakeReqWithParams("POST", sc.url, map[string]string{}).exec() @@ -74,9 +74,9 @@ func TestAdminApiEndpoint(t *testing.T) { Convey("When a server admin gets auth tokens for a non-existing user", t, func() { userId := int64(0) - bus.AddHandler("test", func(cmd *m.GetUserByIdQuery) error { + bus.AddHandler("test", func(cmd *models.GetUserByIdQuery) error { userId = cmd.Id - return m.ErrUserNotFound + return models.ErrUserNotFound }) adminGetUserAuthTokensScenario("Should return not found when calling GET on", "/api/admin/users/200/auth-tokens", "/api/admin/users/:id/auth-tokens", func(sc *scenarioContext) { @@ -89,14 +89,14 @@ func TestAdminApiEndpoint(t *testing.T) { Convey("When a server admin attempts to enable/disable a nonexistent user", t, func() { var userId int64 isDisabled := false - bus.AddHandler("test", func(cmd *m.GetAuthInfoQuery) error { - return m.ErrUserNotFound + bus.AddHandler("test", func(cmd *models.GetAuthInfoQuery) error { + return models.ErrUserNotFound }) - bus.AddHandler("test", func(cmd *m.DisableUserCommand) error { + bus.AddHandler("test", func(cmd *models.DisableUserCommand) error { userId = cmd.UserId isDisabled = cmd.IsDisabled - return m.ErrUserNotFound + return models.ErrUserNotFound }) adminDisableUserScenario("Should return user not found on a POST request", "enable", "/api/admin/users/42/enable", "/api/admin/users/:id/enable", func(sc *scenarioContext) { @@ -128,7 +128,7 @@ func TestAdminApiEndpoint(t *testing.T) { Convey("When a server admin attempts to disable/enable external user", t, func() { userId := int64(0) - bus.AddHandler("test", func(cmd *m.GetAuthInfoQuery) error { + bus.AddHandler("test", func(cmd *models.GetAuthInfoQuery) error { userId = cmd.UserId return nil }) @@ -158,9 +158,9 @@ func TestAdminApiEndpoint(t *testing.T) { Convey("When a server admin attempts to delete a nonexistent user", t, func() { var userId int64 - bus.AddHandler("test", func(cmd *m.DeleteUserCommand) error { + bus.AddHandler("test", func(cmd *models.DeleteUserCommand) error { userId = cmd.UserId - return m.ErrUserNotFound + return models.ErrUserNotFound }) adminDeleteUserScenario("Should return user not found error", "/api/admin/users/42", "/api/admin/users/:id", func(sc *scenarioContext) { @@ -177,12 +177,12 @@ func TestAdminApiEndpoint(t *testing.T) { }) } -func putAdminScenario(desc string, url string, routePattern string, role m.RoleType, cmd dtos.AdminUpdateUserPermissionsForm, fn scenarioFunc) { +func putAdminScenario(desc string, url string, routePattern string, role models.RoleType, cmd dtos.AdminUpdateUserPermissionsForm, fn scenarioFunc) { Convey(desc+" "+url, func() { defer bus.ClearBusHandlers() sc := setupScenarioContext(url) - sc.defaultHandler = Wrap(func(c *m.ReqContext) { + sc.defaultHandler = Wrap(func(c *models.ReqContext) { sc.context = c sc.context.UserId = TestUserID sc.context.OrgId = TestOrgID @@ -207,11 +207,11 @@ func adminLogoutUserScenario(desc string, url string, routePattern string, fn sc } sc := setupScenarioContext(url) - sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { + sc.defaultHandler = Wrap(func(c *models.ReqContext) Response { sc.context = c sc.context.UserId = TestUserID sc.context.OrgId = TestOrgID - sc.context.OrgRole = m.ROLE_ADMIN + sc.context.OrgRole = models.ROLE_ADMIN return hs.AdminLogoutUser(c) }) @@ -222,7 +222,7 @@ func adminLogoutUserScenario(desc string, url string, routePattern string, fn sc }) } -func adminRevokeUserAuthTokenScenario(desc string, url string, routePattern string, cmd m.RevokeAuthTokenCmd, fn scenarioFunc) { +func adminRevokeUserAuthTokenScenario(desc string, url string, routePattern string, cmd models.RevokeAuthTokenCmd, fn scenarioFunc) { Convey(desc+" "+url, func() { defer bus.ClearBusHandlers() @@ -235,11 +235,11 @@ func adminRevokeUserAuthTokenScenario(desc string, url string, routePattern stri sc := setupScenarioContext(url) sc.userAuthTokenService = fakeAuthTokenService - sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { + sc.defaultHandler = Wrap(func(c *models.ReqContext) Response { sc.context = c sc.context.UserId = TestUserID sc.context.OrgId = TestOrgID - sc.context.OrgRole = m.ROLE_ADMIN + sc.context.OrgRole = models.ROLE_ADMIN return hs.AdminRevokeUserAuthToken(c, cmd) }) @@ -263,11 +263,11 @@ func adminGetUserAuthTokensScenario(desc string, url string, routePattern string sc := setupScenarioContext(url) sc.userAuthTokenService = fakeAuthTokenService - sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { + sc.defaultHandler = Wrap(func(c *models.ReqContext) Response { sc.context = c sc.context.UserId = TestUserID sc.context.OrgId = TestOrgID - sc.context.OrgRole = m.ROLE_ADMIN + sc.context.OrgRole = models.ROLE_ADMIN return hs.AdminGetUserAuthTokens(c) }) @@ -290,7 +290,7 @@ func adminDisableUserScenario(desc string, action string, url string, routePatte } sc := setupScenarioContext(url) - sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { + sc.defaultHandler = Wrap(func(c *models.ReqContext) Response { sc.context = c sc.context.UserId = TestUserID @@ -312,7 +312,7 @@ func adminDeleteUserScenario(desc string, url string, routePattern string, fn sc defer bus.ClearBusHandlers() sc := setupScenarioContext(url) - sc.defaultHandler = Wrap(func(c *m.ReqContext) { + sc.defaultHandler = Wrap(func(c *models.ReqContext) { sc.context = c sc.context.UserId = TestUserID diff --git a/pkg/api/annotations.go b/pkg/api/annotations.go index 4720b38f522..362d1ba664c 100644 --- a/pkg/api/annotations.go +++ b/pkg/api/annotations.go @@ -4,13 +4,13 @@ import ( "strings" "github.com/grafana/grafana/pkg/api/dtos" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/annotations" "github.com/grafana/grafana/pkg/services/guardian" "github.com/grafana/grafana/pkg/util" ) -func GetAnnotations(c *m.ReqContext) Response { +func GetAnnotations(c *models.ReqContext) Response { query := &annotations.ItemQuery{ From: c.QueryInt64("from"), @@ -50,7 +50,7 @@ func (e *CreateAnnotationError) Error() string { return e.message } -func PostAnnotation(c *m.ReqContext, cmd dtos.PostAnnotationsCmd) Response { +func PostAnnotation(c *models.ReqContext, cmd dtos.PostAnnotationsCmd) Response { if canSave, err := canSaveByDashboardID(c, cmd.DashboardId); err != nil || !canSave { return dashboardGuardianResponse(err) } @@ -94,7 +94,7 @@ func formatGraphiteAnnotation(what string, data string) string { return text } -func PostGraphiteAnnotation(c *m.ReqContext, cmd dtos.PostGraphiteAnnotationsCmd) Response { +func PostGraphiteAnnotation(c *models.ReqContext, cmd dtos.PostGraphiteAnnotationsCmd) Response { repo := annotations.GetRepository() if cmd.What == "" { @@ -145,7 +145,7 @@ func PostGraphiteAnnotation(c *m.ReqContext, cmd dtos.PostGraphiteAnnotationsCmd }) } -func UpdateAnnotation(c *m.ReqContext, cmd dtos.UpdateAnnotationsCmd) Response { +func UpdateAnnotation(c *models.ReqContext, cmd dtos.UpdateAnnotationsCmd) Response { annotationID := c.ParamsInt64(":annotationId") repo := annotations.GetRepository() @@ -171,7 +171,7 @@ func UpdateAnnotation(c *m.ReqContext, cmd dtos.UpdateAnnotationsCmd) Response { return Success("Annotation updated") } -func PatchAnnotation(c *m.ReqContext, cmd dtos.PatchAnnotationsCmd) Response { +func PatchAnnotation(c *models.ReqContext, cmd dtos.PatchAnnotationsCmd) Response { annotationID := c.ParamsInt64(":annotationId") repo := annotations.GetRepository() @@ -219,7 +219,7 @@ func PatchAnnotation(c *m.ReqContext, cmd dtos.PatchAnnotationsCmd) Response { return Success("Annotation patched") } -func DeleteAnnotations(c *m.ReqContext, cmd dtos.DeleteAnnotationsCmd) Response { +func DeleteAnnotations(c *models.ReqContext, cmd dtos.DeleteAnnotationsCmd) Response { repo := annotations.GetRepository() err := repo.Delete(&annotations.DeleteParams{ @@ -236,7 +236,7 @@ func DeleteAnnotations(c *m.ReqContext, cmd dtos.DeleteAnnotationsCmd) Response return Success("Annotations deleted") } -func DeleteAnnotationByID(c *m.ReqContext) Response { +func DeleteAnnotationByID(c *models.ReqContext) Response { repo := annotations.GetRepository() annotationID := c.ParamsInt64(":annotationId") @@ -256,8 +256,8 @@ func DeleteAnnotationByID(c *m.ReqContext) Response { return Success("Annotation deleted") } -func canSaveByDashboardID(c *m.ReqContext, dashboardID int64) (bool, error) { - if dashboardID == 0 && !c.SignedInUser.HasRole(m.ROLE_EDITOR) { +func canSaveByDashboardID(c *models.ReqContext, dashboardID int64) (bool, error) { + if dashboardID == 0 && !c.SignedInUser.HasRole(models.ROLE_EDITOR) { return false, nil } @@ -271,7 +271,7 @@ func canSaveByDashboardID(c *m.ReqContext, dashboardID int64) (bool, error) { return true, nil } -func canSave(c *m.ReqContext, repo annotations.Repository, annotationID int64) Response { +func canSave(c *models.ReqContext, repo annotations.Repository, annotationID int64) Response { items, err := repo.Find(&annotations.ItemQuery{AnnotationId: annotationID, OrgId: c.OrgId}) if err != nil || len(items) == 0 { diff --git a/pkg/api/annotations_test.go b/pkg/api/annotations_test.go index 7b9cbf4d119..1ec021557dc 100644 --- a/pkg/api/annotations_test.go +++ b/pkg/api/annotations_test.go @@ -5,7 +5,7 @@ import ( "github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/bus" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/annotations" . "github.com/smartystreets/goconvey/convey" @@ -32,7 +32,7 @@ func TestAnnotationsApiEndpoint(t *testing.T) { } Convey("When user is an Org Viewer", func() { - role := m.ROLE_VIEWER + role := models.ROLE_VIEWER Convey("Should not be allowed to save an annotation", func() { postAnnotationScenario("When calling POST on", "/api/annotations", "/api/annotations", role, cmd, func(sc *scenarioContext) { sc.fakeReqWithParams("POST", sc.url, map[string]string{}).exec() @@ -58,7 +58,7 @@ func TestAnnotationsApiEndpoint(t *testing.T) { }) Convey("When user is an Org Editor", func() { - role := m.ROLE_EDITOR + role := models.ROLE_EDITOR Convey("Should be able to save an annotation", func() { postAnnotationScenario("When calling POST on", "/api/annotations", "/api/annotations", role, cmd, func(sc *scenarioContext) { sc.fakeReqWithParams("POST", sc.url, map[string]string{}).exec() @@ -112,26 +112,26 @@ func TestAnnotationsApiEndpoint(t *testing.T) { PanelId: 1, } - viewerRole := m.ROLE_VIEWER - editorRole := m.ROLE_EDITOR + viewerRole := models.ROLE_VIEWER + editorRole := models.ROLE_EDITOR - aclMockResp := []*m.DashboardAclInfoDTO{ - {Role: &viewerRole, Permission: m.PERMISSION_VIEW}, - {Role: &editorRole, Permission: m.PERMISSION_EDIT}, + aclMockResp := []*models.DashboardAclInfoDTO{ + {Role: &viewerRole, Permission: models.PERMISSION_VIEW}, + {Role: &editorRole, Permission: models.PERMISSION_EDIT}, } - bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error { + bus.AddHandler("test", func(query *models.GetDashboardAclInfoListQuery) error { query.Result = aclMockResp return nil }) - bus.AddHandler("test", func(query *m.GetTeamsByUserQuery) error { - query.Result = []*m.TeamDTO{} + bus.AddHandler("test", func(query *models.GetTeamsByUserQuery) error { + query.Result = []*models.TeamDTO{} return nil }) Convey("When user is an Org Viewer", func() { - role := m.ROLE_VIEWER + role := models.ROLE_VIEWER Convey("Should not be allowed to save an annotation", func() { postAnnotationScenario("When calling POST on", "/api/annotations", "/api/annotations", role, cmd, func(sc *scenarioContext) { sc.fakeReqWithParams("POST", sc.url, map[string]string{}).exec() @@ -157,7 +157,7 @@ func TestAnnotationsApiEndpoint(t *testing.T) { }) Convey("When user is an Org Editor", func() { - role := m.ROLE_EDITOR + role := models.ROLE_EDITOR Convey("Should be able to save an annotation", func() { postAnnotationScenario("When calling POST on", "/api/annotations", "/api/annotations", role, cmd, func(sc *scenarioContext) { sc.fakeReqWithParams("POST", sc.url, map[string]string{}).exec() @@ -183,7 +183,7 @@ func TestAnnotationsApiEndpoint(t *testing.T) { }) Convey("When user is an Admin", func() { - role := m.ROLE_ADMIN + role := models.ROLE_ADMIN Convey("Should be able to do anything", func() { postAnnotationScenario("When calling POST on", "/api/annotations", "/api/annotations", role, cmd, func(sc *scenarioContext) { sc.fakeReqWithParams("POST", sc.url, map[string]string{}).exec() @@ -229,12 +229,12 @@ func (repo *fakeAnnotationsRepo) Find(query *annotations.ItemQuery) ([]*annotati var fakeAnnoRepo *fakeAnnotationsRepo -func postAnnotationScenario(desc string, url string, routePattern string, role m.RoleType, cmd dtos.PostAnnotationsCmd, fn scenarioFunc) { +func postAnnotationScenario(desc string, url string, routePattern string, role models.RoleType, cmd dtos.PostAnnotationsCmd, fn scenarioFunc) { Convey(desc+" "+url, func() { defer bus.ClearBusHandlers() sc := setupScenarioContext(url) - sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { + sc.defaultHandler = Wrap(func(c *models.ReqContext) Response { sc.context = c sc.context.UserId = TestUserID sc.context.OrgId = TestOrgID @@ -252,12 +252,12 @@ func postAnnotationScenario(desc string, url string, routePattern string, role m }) } -func putAnnotationScenario(desc string, url string, routePattern string, role m.RoleType, cmd dtos.UpdateAnnotationsCmd, fn scenarioFunc) { +func putAnnotationScenario(desc string, url string, routePattern string, role models.RoleType, cmd dtos.UpdateAnnotationsCmd, fn scenarioFunc) { Convey(desc+" "+url, func() { defer bus.ClearBusHandlers() sc := setupScenarioContext(url) - sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { + sc.defaultHandler = Wrap(func(c *models.ReqContext) Response { sc.context = c sc.context.UserId = TestUserID sc.context.OrgId = TestOrgID @@ -275,12 +275,12 @@ func putAnnotationScenario(desc string, url string, routePattern string, role m. }) } -func patchAnnotationScenario(desc string, url string, routePattern string, role m.RoleType, cmd dtos.PatchAnnotationsCmd, fn scenarioFunc) { +func patchAnnotationScenario(desc string, url string, routePattern string, role models.RoleType, cmd dtos.PatchAnnotationsCmd, fn scenarioFunc) { Convey(desc+" "+url, func() { defer bus.ClearBusHandlers() sc := setupScenarioContext(url) - sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { + sc.defaultHandler = Wrap(func(c *models.ReqContext) Response { sc.context = c sc.context.UserId = TestUserID sc.context.OrgId = TestOrgID @@ -298,12 +298,12 @@ func patchAnnotationScenario(desc string, url string, routePattern string, role }) } -func deleteAnnotationsScenario(desc string, url string, routePattern string, role m.RoleType, cmd dtos.DeleteAnnotationsCmd, fn scenarioFunc) { +func deleteAnnotationsScenario(desc string, url string, routePattern string, role models.RoleType, cmd dtos.DeleteAnnotationsCmd, fn scenarioFunc) { Convey(desc+" "+url, func() { defer bus.ClearBusHandlers() sc := setupScenarioContext(url) - sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { + sc.defaultHandler = Wrap(func(c *models.ReqContext) Response { sc.context = c sc.context.UserId = TestUserID sc.context.OrgId = TestOrgID diff --git a/pkg/api/app_routes.go b/pkg/api/app_routes.go index 8e462e176fc..82232df9e40 100644 --- a/pkg/api/app_routes.go +++ b/pkg/api/app_routes.go @@ -9,7 +9,7 @@ import ( "github.com/grafana/grafana/pkg/api/pluginproxy" "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/middleware" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/plugins" "github.com/grafana/grafana/pkg/util" macaron "gopkg.in/macaron.v1" @@ -40,10 +40,10 @@ func (hs *HTTPServer) initAppPluginRoutes(r *macaron.Macaron) { })) if route.ReqRole != "" { - if route.ReqRole == m.ROLE_ADMIN { - handlers = append(handlers, middleware.RoleAuth(m.ROLE_ADMIN)) - } else if route.ReqRole == m.ROLE_EDITOR { - handlers = append(handlers, middleware.RoleAuth(m.ROLE_EDITOR, m.ROLE_ADMIN)) + if route.ReqRole == models.ROLE_ADMIN { + handlers = append(handlers, middleware.RoleAuth(models.ROLE_ADMIN)) + } else if route.ReqRole == models.ROLE_EDITOR { + handlers = append(handlers, middleware.RoleAuth(models.ROLE_EDITOR, models.ROLE_ADMIN)) } } handlers = append(handlers, AppPluginRoute(route, plugin.Id, hs)) @@ -54,7 +54,7 @@ func (hs *HTTPServer) initAppPluginRoutes(r *macaron.Macaron) { } func AppPluginRoute(route *plugins.AppPluginRoute, appID string, hs *HTTPServer) macaron.Handler { - return func(c *m.ReqContext) { + return func(c *models.ReqContext) { path := c.Params("*") proxy := pluginproxy.NewApiPluginProxy(c, path, route, appID, hs.Cfg) diff --git a/pkg/api/common.go b/pkg/api/common.go index 796495fee81..19dc976b2c8 100644 --- a/pkg/api/common.go +++ b/pkg/api/common.go @@ -4,7 +4,7 @@ import ( "encoding/json" "net/http" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/setting" "gopkg.in/macaron.v1" ) @@ -19,7 +19,7 @@ var ( ) type Response interface { - WriteTo(ctx *m.ReqContext) + WriteTo(ctx *models.ReqContext) } type NormalResponse struct { @@ -32,7 +32,7 @@ type NormalResponse struct { func Wrap(action interface{}) macaron.Handler { - return func(c *m.ReqContext) { + return func(c *models.ReqContext) { var res Response val, err := c.Invoke(action) if err == nil && val != nil && len(val) > 0 { @@ -45,7 +45,7 @@ func Wrap(action interface{}) macaron.Handler { } } -func (r *NormalResponse) WriteTo(ctx *m.ReqContext) { +func (r *NormalResponse) WriteTo(ctx *models.ReqContext) { if r.err != nil { ctx.Logger.Error(r.errMessage, "error", r.err, "remote_addr", ctx.RemoteAddr()) @@ -143,7 +143,7 @@ type RedirectResponse struct { location string } -func (r *RedirectResponse) WriteTo(ctx *m.ReqContext) { +func (r *RedirectResponse) WriteTo(ctx *models.ReqContext) { ctx.Redirect(r.location) } diff --git a/pkg/api/common_test.go b/pkg/api/common_test.go index c1185c1fbe8..c01108cb5f0 100644 --- a/pkg/api/common_test.go +++ b/pkg/api/common_test.go @@ -7,22 +7,22 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/middleware" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/auth" . "github.com/smartystreets/goconvey/convey" "gopkg.in/macaron.v1" ) func loggedInUserScenario(desc string, url string, fn scenarioFunc) { - loggedInUserScenarioWithRole(desc, "GET", url, url, m.ROLE_EDITOR, fn) + loggedInUserScenarioWithRole(desc, "GET", url, url, models.ROLE_EDITOR, fn) } -func loggedInUserScenarioWithRole(desc string, method string, url string, routePattern string, role m.RoleType, fn scenarioFunc) { +func loggedInUserScenarioWithRole(desc string, method string, url string, routePattern string, role models.RoleType, fn scenarioFunc) { Convey(desc+" "+url, func() { defer bus.ClearBusHandlers() sc := setupScenarioContext(url) - sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { + sc.defaultHandler = Wrap(func(c *models.ReqContext) Response { sc.context = c sc.context.UserId = TestUserID sc.context.OrgId = TestOrgID @@ -50,7 +50,7 @@ func anonymousUserScenario(desc string, method string, url string, routePattern defer bus.ClearBusHandlers() sc := setupScenarioContext(url) - sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { + sc.defaultHandler = Wrap(func(c *models.ReqContext) Response { sc.context = c if sc.handlerFunc != nil { return sc.handlerFunc(sc.context) @@ -115,7 +115,7 @@ func (sc *scenarioContext) fakeReqNoAssertionsWithCookie(method, url string, coo type scenarioContext struct { m *macaron.Macaron - context *m.ReqContext + context *models.ReqContext resp *httptest.ResponseRecorder handlerFunc handlerFunc defaultHandler macaron.Handler @@ -129,7 +129,7 @@ func (sc *scenarioContext) exec() { } type scenarioFunc func(c *scenarioContext) -type handlerFunc func(c *m.ReqContext) Response +type handlerFunc func(c *models.ReqContext) Response func setupScenarioContext(url string) *scenarioContext { sc := &scenarioContext{ diff --git a/pkg/api/dashboard.go b/pkg/api/dashboard.go index cff14815e81..17d6aace4b0 100644 --- a/pkg/api/dashboard.go +++ b/pkg/api/dashboard.go @@ -7,6 +7,7 @@ import ( "path" "path/filepath" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/alerting" "github.com/grafana/grafana/pkg/services/dashboards" @@ -16,7 +17,6 @@ import ( "github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/metrics" - m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/plugins" "github.com/grafana/grafana/pkg/services/guardian" "github.com/grafana/grafana/pkg/setting" @@ -27,12 +27,12 @@ const ( anonString = "Anonymous" ) -func isDashboardStarredByUser(c *m.ReqContext, dashID int64) (bool, error) { +func isDashboardStarredByUser(c *models.ReqContext, dashID int64) (bool, error) { if !c.IsSignedIn { return false, nil } - query := m.IsStarredByUserQuery{UserId: c.UserId, DashboardId: dashID} + query := models.IsStarredByUserQuery{UserId: c.UserId, DashboardId: dashID} if err := bus.Dispatch(&query); err != nil { return false, err } @@ -48,7 +48,7 @@ func dashboardGuardianResponse(err error) Response { return Error(403, "Access denied to this dashboard", nil) } -func (hs *HTTPServer) GetDashboard(c *m.ReqContext) Response { +func (hs *HTTPServer) GetDashboard(c *models.ReqContext) Response { dash, rsp := getDashboardHelper(c.OrgId, c.Params(":slug"), 0, c.Params(":uid")) if rsp != nil { return rsp @@ -80,7 +80,7 @@ func (hs *HTTPServer) GetDashboard(c *m.ReqContext) Response { meta := dtos.DashboardMeta{ IsStarred: isStarred, Slug: dash.Slug, - Type: m.DashTypeDB, + Type: models.DashTypeDB, CanStar: c.IsSignedIn, CanSave: canSave, CanEdit: canEdit, @@ -99,7 +99,7 @@ func (hs *HTTPServer) GetDashboard(c *m.ReqContext) Response { // lookup folder title if dash.FolderId > 0 { - query := m.GetDashboardQuery{Id: dash.FolderId, OrgId: c.OrgId} + query := models.GetDashboardQuery{Id: dash.FolderId, OrgId: c.OrgId} if err := bus.Dispatch(&query); err != nil { return Error(500, "Dashboard folder could not be read", err) } @@ -142,7 +142,7 @@ func (hs *HTTPServer) GetDashboard(c *m.ReqContext) Response { } func getUserLogin(userID int64) string { - query := m.GetUserByIdQuery{Id: userID} + query := models.GetUserByIdQuery{Id: userID} err := bus.Dispatch(&query) if err != nil { return anonString @@ -150,13 +150,13 @@ func getUserLogin(userID int64) string { return query.Result.Login } -func getDashboardHelper(orgID int64, slug string, id int64, uid string) (*m.Dashboard, Response) { - var query m.GetDashboardQuery +func getDashboardHelper(orgID int64, slug string, id int64, uid string) (*models.Dashboard, Response) { + var query models.GetDashboardQuery if len(uid) > 0 { - query = m.GetDashboardQuery{Uid: uid, Id: id, OrgId: orgID} + query = models.GetDashboardQuery{Uid: uid, Id: id, OrgId: orgID} } else { - query = m.GetDashboardQuery{Slug: slug, Id: id, OrgId: orgID} + query = models.GetDashboardQuery{Slug: slug, Id: id, OrgId: orgID} } if err := bus.Dispatch(&query); err != nil { @@ -166,25 +166,25 @@ func getDashboardHelper(orgID int64, slug string, id int64, uid string) (*m.Dash return query.Result, nil } -func DeleteDashboardBySlug(c *m.ReqContext) Response { - query := m.GetDashboardsBySlugQuery{OrgId: c.OrgId, Slug: c.Params(":slug")} +func DeleteDashboardBySlug(c *models.ReqContext) Response { + query := models.GetDashboardsBySlugQuery{OrgId: c.OrgId, Slug: c.Params(":slug")} if err := bus.Dispatch(&query); err != nil { return Error(500, "Failed to retrieve dashboards by slug", err) } if len(query.Result) > 1 { - return JSON(412, util.DynMap{"status": "multiple-slugs-exists", "message": m.ErrDashboardsWithSameSlugExists.Error()}) + return JSON(412, util.DynMap{"status": "multiple-slugs-exists", "message": models.ErrDashboardsWithSameSlugExists.Error()}) } return deleteDashboard(c) } -func DeleteDashboardByUID(c *m.ReqContext) Response { +func DeleteDashboardByUID(c *models.ReqContext) Response { return deleteDashboard(c) } -func deleteDashboard(c *m.ReqContext) Response { +func deleteDashboard(c *models.ReqContext) Response { dash, rsp := getDashboardHelper(c.OrgId, c.Params(":slug"), 0, c.Params(":uid")) if rsp != nil { return rsp @@ -196,7 +196,7 @@ func deleteDashboard(c *m.ReqContext) Response { } err := dashboards.NewService().DeleteDashboard(dash.Id, c.OrgId) - if err == m.ErrDashboardCannotDeleteProvisionedDashboard { + if err == models.ErrDashboardCannotDeleteProvisionedDashboard { return Error(400, "Dashboard cannot be deleted because it was provisioned", err) } else if err != nil { return Error(500, "Failed to delete dashboard", err) @@ -208,7 +208,7 @@ func deleteDashboard(c *m.ReqContext) Response { }) } -func (hs *HTTPServer) PostDashboard(c *m.ReqContext, cmd m.SaveDashboardCommand) Response { +func (hs *HTTPServer) PostDashboard(c *models.ReqContext, cmd models.SaveDashboardCommand) Response { cmd.OrgId = c.OrgId cmd.UserId = c.UserId @@ -268,22 +268,22 @@ func (hs *HTTPServer) PostDashboard(c *m.ReqContext, cmd m.SaveDashboardCommand) } func dashboardSaveErrorToApiResponse(err error) Response { - if err == m.ErrDashboardTitleEmpty || - err == m.ErrDashboardWithSameNameAsFolder || - err == m.ErrDashboardFolderWithSameNameAsDashboard || - err == m.ErrDashboardTypeMismatch || - err == m.ErrDashboardInvalidUid || - err == m.ErrDashboardUidToLong || - err == m.ErrDashboardWithSameUIDExists || - err == m.ErrFolderNotFound || - err == m.ErrDashboardFolderCannotHaveParent || - err == m.ErrDashboardFolderNameExists || - err == m.ErrDashboardRefreshIntervalTooShort || - err == m.ErrDashboardCannotSaveProvisionedDashboard { + if err == models.ErrDashboardTitleEmpty || + err == models.ErrDashboardWithSameNameAsFolder || + err == models.ErrDashboardFolderWithSameNameAsDashboard || + err == models.ErrDashboardTypeMismatch || + err == models.ErrDashboardInvalidUid || + err == models.ErrDashboardUidToLong || + err == models.ErrDashboardWithSameUIDExists || + err == models.ErrFolderNotFound || + err == models.ErrDashboardFolderCannotHaveParent || + err == models.ErrDashboardFolderNameExists || + err == models.ErrDashboardRefreshIntervalTooShort || + err == models.ErrDashboardCannotSaveProvisionedDashboard { return Error(400, err.Error(), nil) } - if err == m.ErrDashboardUpdateAccessDenied { + if err == models.ErrDashboardUpdateAccessDenied { return Error(403, err.Error(), err) } @@ -291,15 +291,15 @@ func dashboardSaveErrorToApiResponse(err error) Response { return Error(422, validationErr.Error(), nil) } - if err == m.ErrDashboardWithSameNameInFolderExists { + if err == models.ErrDashboardWithSameNameInFolderExists { return JSON(412, util.DynMap{"status": "name-exists", "message": err.Error()}) } - if err == m.ErrDashboardVersionMismatch { + if err == models.ErrDashboardVersionMismatch { return JSON(412, util.DynMap{"status": "version-mismatch", "message": err.Error()}) } - if pluginErr, ok := err.(m.UpdatePluginDashboardError); ok { + if pluginErr, ok := err.(models.UpdatePluginDashboardError); ok { message := "The dashboard belongs to plugin " + pluginErr.PluginId + "." // look up plugin name if pluginDef, exist := plugins.Plugins[pluginErr.PluginId]; exist { @@ -308,24 +308,24 @@ func dashboardSaveErrorToApiResponse(err error) Response { return JSON(412, util.DynMap{"status": "plugin-dashboard", "message": message}) } - if err == m.ErrDashboardNotFound { + if err == models.ErrDashboardNotFound { return JSON(404, util.DynMap{"status": "not-found", "message": err.Error()}) } return Error(500, "Failed to save dashboard", err) } -func GetHomeDashboard(c *m.ReqContext) Response { - prefsQuery := m.GetPreferencesWithDefaultsQuery{User: c.SignedInUser} +func GetHomeDashboard(c *models.ReqContext) Response { + prefsQuery := models.GetPreferencesWithDefaultsQuery{User: c.SignedInUser} if err := bus.Dispatch(&prefsQuery); err != nil { return Error(500, "Failed to get preferences", err) } if prefsQuery.Result.HomeDashboardId != 0 { - slugQuery := m.GetDashboardRefByIdQuery{Id: prefsQuery.Result.HomeDashboardId} + slugQuery := models.GetDashboardRefByIdQuery{Id: prefsQuery.Result.HomeDashboardId} err := bus.Dispatch(&slugQuery) if err == nil { - url := m.GetDashboardUrl(slugQuery.Result.Uid, slugQuery.Result.Slug) + url := models.GetDashboardUrl(slugQuery.Result.Uid, slugQuery.Result.Slug) dashRedirect := dtos.DashboardRedirect{RedirectUri: url} return JSON(200, &dashRedirect) } @@ -341,7 +341,7 @@ func GetHomeDashboard(c *m.ReqContext) Response { dash := dtos.DashboardFullWithMeta{} dash.Meta.IsHome = true - dash.Meta.CanEdit = c.SignedInUser.HasRole(m.ROLE_EDITOR) + dash.Meta.CanEdit = c.SignedInUser.HasRole(models.ROLE_EDITOR) dash.Meta.FolderTitle = "General" jsonParser := json.NewDecoder(file) @@ -349,7 +349,7 @@ func GetHomeDashboard(c *m.ReqContext) Response { return Error(500, "Failed to load home dashboard", err) } - if c.HasUserRole(m.ROLE_ADMIN) && !c.HasHelpFlag(m.HelpFlagGettingStartedPanelDismissed) { + if c.HasUserRole(models.ROLE_ADMIN) && !c.HasHelpFlag(models.HelpFlagGettingStartedPanelDismissed) { addGettingStartedPanelToHomeDashboard(dash.Dashboard) } @@ -375,7 +375,7 @@ func addGettingStartedPanelToHomeDashboard(dash *simplejson.Json) { } // GetDashboardVersions returns all dashboard versions as JSON -func GetDashboardVersions(c *m.ReqContext) Response { +func GetDashboardVersions(c *models.ReqContext) Response { dashID := c.ParamsInt64(":dashboardId") guardian := guardian.New(dashID, c.OrgId, c.SignedInUser) @@ -383,7 +383,7 @@ func GetDashboardVersions(c *m.ReqContext) Response { return dashboardGuardianResponse(err) } - query := m.GetDashboardVersionsQuery{ + query := models.GetDashboardVersionsQuery{ OrgId: c.OrgId, DashboardId: dashID, Limit: c.QueryInt("limit"), @@ -414,7 +414,7 @@ func GetDashboardVersions(c *m.ReqContext) Response { } // GetDashboardVersion returns the dashboard version with the given ID. -func GetDashboardVersion(c *m.ReqContext) Response { +func GetDashboardVersion(c *models.ReqContext) Response { dashID := c.ParamsInt64(":dashboardId") guardian := guardian.New(dashID, c.OrgId, c.SignedInUser) @@ -422,7 +422,7 @@ func GetDashboardVersion(c *m.ReqContext) Response { return dashboardGuardianResponse(err) } - query := m.GetDashboardVersionQuery{ + query := models.GetDashboardVersionQuery{ OrgId: c.OrgId, DashboardId: dashID, Version: c.ParamsInt(":id"), @@ -437,7 +437,7 @@ func GetDashboardVersion(c *m.ReqContext) Response { creator = getUserLogin(query.Result.CreatedBy) } - dashVersionMeta := &m.DashboardVersionMeta{ + dashVersionMeta := &models.DashboardVersionMeta{ Id: query.Result.Id, DashboardId: query.Result.DashboardId, Data: query.Result.Data, @@ -453,7 +453,7 @@ func GetDashboardVersion(c *m.ReqContext) Response { } // POST /api/dashboards/calculate-diff performs diffs on two dashboards -func CalculateDashboardDiff(c *m.ReqContext, apiOptions dtos.CalculateDiffOptions) Response { +func CalculateDashboardDiff(c *models.ReqContext, apiOptions dtos.CalculateDiffOptions) Response { guardianBase := guardian.New(apiOptions.Base.DashboardId, c.OrgId, c.SignedInUser) if canSave, err := guardianBase.CanSave(); err != nil || !canSave { @@ -484,7 +484,7 @@ func CalculateDashboardDiff(c *m.ReqContext, apiOptions dtos.CalculateDiffOption result, err := dashdiffs.CalculateDiff(&options) if err != nil { - if err == m.ErrDashboardVersionNotFound { + if err == models.ErrDashboardVersionNotFound { return Error(404, "Dashboard version not found", err) } return Error(500, "Unable to compute diff", err) @@ -498,7 +498,7 @@ func CalculateDashboardDiff(c *m.ReqContext, apiOptions dtos.CalculateDiffOption } // RestoreDashboardVersion restores a dashboard to the given version. -func (hs *HTTPServer) RestoreDashboardVersion(c *m.ReqContext, apiCmd dtos.RestoreDashboardVersionCommand) Response { +func (hs *HTTPServer) RestoreDashboardVersion(c *models.ReqContext, apiCmd dtos.RestoreDashboardVersionCommand) Response { dash, rsp := getDashboardHelper(c.OrgId, "", c.ParamsInt64(":dashboardId"), "") if rsp != nil { return rsp @@ -509,14 +509,14 @@ func (hs *HTTPServer) RestoreDashboardVersion(c *m.ReqContext, apiCmd dtos.Resto return dashboardGuardianResponse(err) } - versionQuery := m.GetDashboardVersionQuery{DashboardId: dash.Id, Version: apiCmd.Version, OrgId: c.OrgId} + versionQuery := models.GetDashboardVersionQuery{DashboardId: dash.Id, Version: apiCmd.Version, OrgId: c.OrgId} if err := bus.Dispatch(&versionQuery); err != nil { return Error(404, "Dashboard version not found", nil) } version := versionQuery.Result - saveCmd := m.SaveDashboardCommand{} + saveCmd := models.SaveDashboardCommand{} saveCmd.RestoredFrom = version.Version saveCmd.OrgId = c.OrgId saveCmd.UserId = c.UserId @@ -529,8 +529,8 @@ func (hs *HTTPServer) RestoreDashboardVersion(c *m.ReqContext, apiCmd dtos.Resto return hs.PostDashboard(c, saveCmd) } -func GetDashboardTags(c *m.ReqContext) { - query := m.GetDashboardTagsQuery{OrgId: c.OrgId} +func GetDashboardTags(c *models.ReqContext) { + query := models.GetDashboardTagsQuery{OrgId: c.OrgId} err := bus.Dispatch(&query) if err != nil { c.JsonApiErr(500, "Failed to get tags from database", err) diff --git a/pkg/api/dashboard_permission.go b/pkg/api/dashboard_permission.go index 342eaf556c6..55a90d72241 100644 --- a/pkg/api/dashboard_permission.go +++ b/pkg/api/dashboard_permission.go @@ -5,11 +5,11 @@ import ( "github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/bus" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/guardian" ) -func GetDashboardPermissionList(c *m.ReqContext) Response { +func GetDashboardPermissionList(c *models.ReqContext) Response { dashID := c.ParamsInt64(":dashboardId") _, rsp := getDashboardHelper(c.OrgId, "", dashID, "") @@ -35,14 +35,14 @@ func GetDashboardPermissionList(c *m.ReqContext) Response { perm.TeamAvatarUrl = dtos.GetGravatarUrlWithDefault(perm.TeamEmail, perm.Team) } if perm.Slug != "" { - perm.Url = m.GetDashboardFolderUrl(perm.IsFolder, perm.Uid, perm.Slug) + perm.Url = models.GetDashboardFolderUrl(perm.IsFolder, perm.Uid, perm.Slug) } } return JSON(200, acl) } -func UpdateDashboardPermissions(c *m.ReqContext, apiCmd dtos.UpdateDashboardAclCommand) Response { +func UpdateDashboardPermissions(c *models.ReqContext, apiCmd dtos.UpdateDashboardAclCommand) Response { dashID := c.ParamsInt64(":dashboardId") _, rsp := getDashboardHelper(c.OrgId, "", dashID, "") @@ -55,11 +55,11 @@ func UpdateDashboardPermissions(c *m.ReqContext, apiCmd dtos.UpdateDashboardAclC return dashboardGuardianResponse(err) } - cmd := m.UpdateDashboardAclCommand{} + cmd := models.UpdateDashboardAclCommand{} cmd.DashboardId = dashID for _, item := range apiCmd.Items { - cmd.Items = append(cmd.Items, &m.DashboardAcl{ + cmd.Items = append(cmd.Items, &models.DashboardAcl{ OrgId: c.OrgId, DashboardId: dashID, UserId: item.UserId, @@ -71,7 +71,7 @@ func UpdateDashboardPermissions(c *m.ReqContext, apiCmd dtos.UpdateDashboardAclC }) } - if okToUpdate, err := g.CheckPermissionBeforeUpdate(m.PERMISSION_ADMIN, cmd.Items); err != nil || !okToUpdate { + if okToUpdate, err := g.CheckPermissionBeforeUpdate(models.PERMISSION_ADMIN, cmd.Items); err != nil || !okToUpdate { if err != nil { if err == guardian.ErrGuardianPermissionExists || err == guardian.ErrGuardianOverride { @@ -85,7 +85,7 @@ func UpdateDashboardPermissions(c *m.ReqContext, apiCmd dtos.UpdateDashboardAclC } if err := bus.Dispatch(&cmd); err != nil { - if err == m.ErrDashboardAclInfoMissing || err == m.ErrDashboardPermissionDashboardEmpty { + if err == models.ErrDashboardAclInfoMissing || err == models.ErrDashboardPermissionDashboardEmpty { return Error(409, err.Error(), err) } return Error(500, "Failed to create permission", err) diff --git a/pkg/api/dashboard_permission_test.go b/pkg/api/dashboard_permission_test.go index f65c5f1f5fa..7c61b094acb 100644 --- a/pkg/api/dashboard_permission_test.go +++ b/pkg/api/dashboard_permission_test.go @@ -6,7 +6,7 @@ import ( "github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/simplejson" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/guardian" . "github.com/smartystreets/goconvey/convey" @@ -15,18 +15,18 @@ import ( func TestDashboardPermissionApiEndpoint(t *testing.T) { Convey("Dashboard permissions test", t, func() { Convey("Given dashboard not exists", func() { - bus.AddHandler("test", func(query *m.GetDashboardQuery) error { - return m.ErrDashboardNotFound + bus.AddHandler("test", func(query *models.GetDashboardQuery) error { + return models.ErrDashboardNotFound }) - loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/1/permissions", "/api/dashboards/id/:id/permissions", m.ROLE_EDITOR, func(sc *scenarioContext) { + loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/1/permissions", "/api/dashboards/id/:id/permissions", models.ROLE_EDITOR, func(sc *scenarioContext) { callGetDashboardPermissions(sc) So(sc.resp.Code, ShouldEqual, 404) }) cmd := dtos.UpdateDashboardAclCommand{ Items: []dtos.DashboardAclUpdateItem{ - {UserId: 1000, Permission: m.PERMISSION_ADMIN}, + {UserId: 1000, Permission: models.PERMISSION_ADMIN}, }, } @@ -40,20 +40,20 @@ func TestDashboardPermissionApiEndpoint(t *testing.T) { origNewGuardian := guardian.New guardian.MockDashboardGuardian(&guardian.FakeDashboardGuardian{CanAdminValue: false}) - getDashboardQueryResult := m.NewDashboard("Dash") - bus.AddHandler("test", func(query *m.GetDashboardQuery) error { + getDashboardQueryResult := models.NewDashboard("Dash") + bus.AddHandler("test", func(query *models.GetDashboardQuery) error { query.Result = getDashboardQueryResult return nil }) - loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/1/permissions", "/api/dashboards/id/:id/permissions", m.ROLE_EDITOR, func(sc *scenarioContext) { + loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/1/permissions", "/api/dashboards/id/:id/permissions", models.ROLE_EDITOR, func(sc *scenarioContext) { callGetDashboardPermissions(sc) So(sc.resp.Code, ShouldEqual, 403) }) cmd := dtos.UpdateDashboardAclCommand{ Items: []dtos.DashboardAclUpdateItem{ - {UserId: 1000, Permission: m.PERMISSION_ADMIN}, + {UserId: 1000, Permission: models.PERMISSION_ADMIN}, }, } @@ -72,34 +72,34 @@ func TestDashboardPermissionApiEndpoint(t *testing.T) { guardian.MockDashboardGuardian(&guardian.FakeDashboardGuardian{ CanAdminValue: true, CheckPermissionBeforeUpdateValue: true, - GetAclValue: []*m.DashboardAclInfoDTO{ - {OrgId: 1, DashboardId: 1, UserId: 2, Permission: m.PERMISSION_VIEW}, - {OrgId: 1, DashboardId: 1, UserId: 3, Permission: m.PERMISSION_EDIT}, - {OrgId: 1, DashboardId: 1, UserId: 4, Permission: m.PERMISSION_ADMIN}, - {OrgId: 1, DashboardId: 1, TeamId: 1, Permission: m.PERMISSION_VIEW}, - {OrgId: 1, DashboardId: 1, TeamId: 2, Permission: m.PERMISSION_ADMIN}, + GetAclValue: []*models.DashboardAclInfoDTO{ + {OrgId: 1, DashboardId: 1, UserId: 2, Permission: models.PERMISSION_VIEW}, + {OrgId: 1, DashboardId: 1, UserId: 3, Permission: models.PERMISSION_EDIT}, + {OrgId: 1, DashboardId: 1, UserId: 4, Permission: models.PERMISSION_ADMIN}, + {OrgId: 1, DashboardId: 1, TeamId: 1, Permission: models.PERMISSION_VIEW}, + {OrgId: 1, DashboardId: 1, TeamId: 2, Permission: models.PERMISSION_ADMIN}, }, }) - getDashboardQueryResult := m.NewDashboard("Dash") - bus.AddHandler("test", func(query *m.GetDashboardQuery) error { + getDashboardQueryResult := models.NewDashboard("Dash") + bus.AddHandler("test", func(query *models.GetDashboardQuery) error { query.Result = getDashboardQueryResult return nil }) - loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/1/permissions", "/api/dashboards/id/:id/permissions", m.ROLE_ADMIN, func(sc *scenarioContext) { + loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/1/permissions", "/api/dashboards/id/:id/permissions", models.ROLE_ADMIN, func(sc *scenarioContext) { callGetDashboardPermissions(sc) So(sc.resp.Code, ShouldEqual, 200) respJSON, err := simplejson.NewJson(sc.resp.Body.Bytes()) So(err, ShouldBeNil) So(len(respJSON.MustArray()), ShouldEqual, 5) So(respJSON.GetIndex(0).Get("userId").MustInt(), ShouldEqual, 2) - So(respJSON.GetIndex(0).Get("permission").MustInt(), ShouldEqual, m.PERMISSION_VIEW) + So(respJSON.GetIndex(0).Get("permission").MustInt(), ShouldEqual, models.PERMISSION_VIEW) }) cmd := dtos.UpdateDashboardAclCommand{ Items: []dtos.DashboardAclUpdateItem{ - {UserId: 1000, Permission: m.PERMISSION_ADMIN}, + {UserId: 1000, Permission: models.PERMISSION_ADMIN}, }, } @@ -121,15 +121,15 @@ func TestDashboardPermissionApiEndpoint(t *testing.T) { CheckPermissionBeforeUpdateError: guardian.ErrGuardianPermissionExists, }) - getDashboardQueryResult := m.NewDashboard("Dash") - bus.AddHandler("test", func(query *m.GetDashboardQuery) error { + getDashboardQueryResult := models.NewDashboard("Dash") + bus.AddHandler("test", func(query *models.GetDashboardQuery) error { query.Result = getDashboardQueryResult return nil }) cmd := dtos.UpdateDashboardAclCommand{ Items: []dtos.DashboardAclUpdateItem{ - {UserId: 1000, Permission: m.PERMISSION_ADMIN}, + {UserId: 1000, Permission: models.PERMISSION_ADMIN}, }, } @@ -151,15 +151,15 @@ func TestDashboardPermissionApiEndpoint(t *testing.T) { CheckPermissionBeforeUpdateError: guardian.ErrGuardianOverride}, ) - getDashboardQueryResult := m.NewDashboard("Dash") - bus.AddHandler("test", func(query *m.GetDashboardQuery) error { + getDashboardQueryResult := models.NewDashboard("Dash") + bus.AddHandler("test", func(query *models.GetDashboardQuery) error { query.Result = getDashboardQueryResult return nil }) cmd := dtos.UpdateDashboardAclCommand{ Items: []dtos.DashboardAclUpdateItem{ - {UserId: 1000, Permission: m.PERMISSION_ADMIN}, + {UserId: 1000, Permission: models.PERMISSION_ADMIN}, }, } @@ -181,7 +181,7 @@ func callGetDashboardPermissions(sc *scenarioContext) { } func callUpdateDashboardPermissions(sc *scenarioContext) { - bus.AddHandler("test", func(cmd *m.UpdateDashboardAclCommand) error { + bus.AddHandler("test", func(cmd *models.UpdateDashboardAclCommand) error { return nil }) @@ -194,7 +194,7 @@ func updateDashboardPermissionScenario(desc string, url string, routePattern str sc := setupScenarioContext(url) - sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { + sc.defaultHandler = Wrap(func(c *models.ReqContext) Response { sc.context = c sc.context.OrgId = TestOrgID sc.context.UserId = TestUserID diff --git a/pkg/api/dashboard_snapshot.go b/pkg/api/dashboard_snapshot.go index 381c0e55910..eeda6ec3b1d 100644 --- a/pkg/api/dashboard_snapshot.go +++ b/pkg/api/dashboard_snapshot.go @@ -11,7 +11,7 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/infra/metrics" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/guardian" "github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/util" @@ -22,7 +22,7 @@ var client = &http.Client{ Transport: &http.Transport{Proxy: http.ProxyFromEnvironment}, } -func GetSharingOptions(c *m.ReqContext) { +func GetSharingOptions(c *models.ReqContext) { c.JSON(200, util.DynMap{ "externalSnapshotURL": setting.ExternalSnapshotUrl, "externalSnapshotName": setting.ExternalSnapshotName, @@ -37,7 +37,7 @@ type CreateExternalSnapshotResponse struct { DeleteUrl string `json:"deleteUrl"` } -func createExternalDashboardSnapshot(cmd m.CreateDashboardSnapshotCommand) (*CreateExternalSnapshotResponse, error) { +func createExternalDashboardSnapshot(cmd models.CreateDashboardSnapshotCommand) (*CreateExternalSnapshotResponse, error) { var createSnapshotResponse CreateExternalSnapshotResponse message := map[string]interface{}{ "name": cmd.Name, @@ -68,7 +68,7 @@ func createExternalDashboardSnapshot(cmd m.CreateDashboardSnapshotCommand) (*Cre } // POST /api/snapshots -func CreateDashboardSnapshot(c *m.ReqContext, cmd m.CreateDashboardSnapshotCommand) { +func CreateDashboardSnapshot(c *models.ReqContext, cmd models.CreateDashboardSnapshotCommand) { if cmd.Name == "" { cmd.Name = "Unnamed snapshot" } @@ -136,9 +136,9 @@ func CreateDashboardSnapshot(c *m.ReqContext, cmd m.CreateDashboardSnapshotComma } // GET /api/snapshots/:key -func GetDashboardSnapshot(c *m.ReqContext) { +func GetDashboardSnapshot(c *models.ReqContext) { key := c.Params(":key") - query := &m.GetDashboardSnapshotQuery{Key: key} + query := &models.GetDashboardSnapshotQuery{Key: key} err := bus.Dispatch(query) if err != nil { @@ -157,7 +157,7 @@ func GetDashboardSnapshot(c *m.ReqContext) { dto := dtos.DashboardFullWithMeta{ Dashboard: snapshot.Dashboard, Meta: dtos.DashboardMeta{ - Type: m.DashTypeSnapshot, + Type: models.DashTypeSnapshot, IsSnapshot: true, Created: snapshot.Created, Expires: snapshot.Expires, @@ -198,10 +198,10 @@ func deleteExternalDashboardSnapshot(externalUrl string) error { } // GET /api/snapshots-delete/:deleteKey -func DeleteDashboardSnapshotByDeleteKey(c *m.ReqContext) Response { +func DeleteDashboardSnapshotByDeleteKey(c *models.ReqContext) Response { key := c.Params(":deleteKey") - query := &m.GetDashboardSnapshotQuery{DeleteKey: key} + query := &models.GetDashboardSnapshotQuery{DeleteKey: key} err := bus.Dispatch(query) if err != nil { @@ -215,7 +215,7 @@ func DeleteDashboardSnapshotByDeleteKey(c *m.ReqContext) Response { } } - cmd := &m.DeleteDashboardSnapshotCommand{DeleteKey: query.Result.DeleteKey} + cmd := &models.DeleteDashboardSnapshotCommand{DeleteKey: query.Result.DeleteKey} if err := bus.Dispatch(cmd); err != nil { return Error(500, "Failed to delete dashboard snapshot", err) @@ -225,10 +225,10 @@ func DeleteDashboardSnapshotByDeleteKey(c *m.ReqContext) Response { } // DELETE /api/snapshots/:key -func DeleteDashboardSnapshot(c *m.ReqContext) Response { +func DeleteDashboardSnapshot(c *models.ReqContext) Response { key := c.Params(":key") - query := &m.GetDashboardSnapshotQuery{Key: key} + query := &models.GetDashboardSnapshotQuery{Key: key} err := bus.Dispatch(query) if err != nil { @@ -258,7 +258,7 @@ func DeleteDashboardSnapshot(c *m.ReqContext) Response { } } - cmd := &m.DeleteDashboardSnapshotCommand{DeleteKey: query.Result.DeleteKey} + cmd := &models.DeleteDashboardSnapshotCommand{DeleteKey: query.Result.DeleteKey} if err := bus.Dispatch(cmd); err != nil { return Error(500, "Failed to delete dashboard snapshot", err) @@ -268,7 +268,7 @@ func DeleteDashboardSnapshot(c *m.ReqContext) Response { } // GET /api/dashboard/snapshots -func SearchDashboardSnapshots(c *m.ReqContext) Response { +func SearchDashboardSnapshots(c *models.ReqContext) Response { query := c.Query("query") limit := c.QueryInt("limit") @@ -276,7 +276,7 @@ func SearchDashboardSnapshots(c *m.ReqContext) Response { limit = 1000 } - searchQuery := m.GetDashboardSnapshotsQuery{ + searchQuery := models.GetDashboardSnapshotsQuery{ Name: query, Limit: limit, OrgId: c.OrgId, @@ -288,9 +288,9 @@ func SearchDashboardSnapshots(c *m.ReqContext) Response { return Error(500, "Search failed", err) } - dtos := make([]*m.DashboardSnapshotDTO, len(searchQuery.Result)) + dtos := make([]*models.DashboardSnapshotDTO, len(searchQuery.Result)) for i, snapshot := range searchQuery.Result { - dtos[i] = &m.DashboardSnapshotDTO{ + dtos[i] = &models.DashboardSnapshotDTO{ Id: snapshot.Id, Name: snapshot.Name, Key: snapshot.Key, diff --git a/pkg/api/dashboard_snapshot_test.go b/pkg/api/dashboard_snapshot_test.go index 0154493df94..f3cd6bf3f58 100644 --- a/pkg/api/dashboard_snapshot_test.go +++ b/pkg/api/dashboard_snapshot_test.go @@ -9,7 +9,7 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/simplejson" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" . "github.com/smartystreets/goconvey/convey" ) @@ -19,7 +19,7 @@ func TestDashboardSnapshotApiEndpoint(t *testing.T) { var externalRequest *http.Request jsonModel, _ := simplejson.NewJson([]byte(`{"id":100}`)) - mockSnapshotResult := &m.DashboardSnapshot{ + mockSnapshotResult := &models.DashboardSnapshot{ Id: 1, Key: "12345", DeleteKey: "54321", @@ -29,25 +29,25 @@ func TestDashboardSnapshotApiEndpoint(t *testing.T) { External: true, } - bus.AddHandler("test", func(query *m.GetDashboardSnapshotQuery) error { + bus.AddHandler("test", func(query *models.GetDashboardSnapshotQuery) error { query.Result = mockSnapshotResult return nil }) - bus.AddHandler("test", func(cmd *m.DeleteDashboardSnapshotCommand) error { + bus.AddHandler("test", func(cmd *models.DeleteDashboardSnapshotCommand) error { return nil }) - viewerRole := m.ROLE_VIEWER - editorRole := m.ROLE_EDITOR - aclMockResp := []*m.DashboardAclInfoDTO{} - bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error { + viewerRole := models.ROLE_VIEWER + editorRole := models.ROLE_EDITOR + aclMockResp := []*models.DashboardAclInfoDTO{} + bus.AddHandler("test", func(query *models.GetDashboardAclInfoListQuery) error { query.Result = aclMockResp return nil }) - teamResp := []*m.TeamDTO{} - bus.AddHandler("test", func(query *m.GetTeamsByUserQuery) error { + teamResp := []*models.TeamDTO{} + bus.AddHandler("test", func(query *models.GetTeamsByUserQuery) error { query.Result = teamResp return nil }) @@ -60,7 +60,7 @@ func TestDashboardSnapshotApiEndpoint(t *testing.T) { Convey("When user has editor role and is not in the ACL", func() { Convey("Should not be able to delete snapshot", func() { - loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/snapshots/12345", "/api/snapshots/:key", m.ROLE_EDITOR, func(sc *scenarioContext) { + loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/snapshots/12345", "/api/snapshots/:key", models.ROLE_EDITOR, func(sc *scenarioContext) { ts := setupRemoteServer(func(rw http.ResponseWriter, req *http.Request) { externalRequest = req }) @@ -101,13 +101,13 @@ func TestDashboardSnapshotApiEndpoint(t *testing.T) { }) Convey("When user is editor and dashboard has default ACL", func() { - aclMockResp = []*m.DashboardAclInfoDTO{ - {Role: &viewerRole, Permission: m.PERMISSION_VIEW}, - {Role: &editorRole, Permission: m.PERMISSION_EDIT}, + aclMockResp = []*models.DashboardAclInfoDTO{ + {Role: &viewerRole, Permission: models.PERMISSION_VIEW}, + {Role: &editorRole, Permission: models.PERMISSION_EDIT}, } Convey("Should be able to delete a snapshot", func() { - loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/snapshots/12345", "/api/snapshots/:key", m.ROLE_EDITOR, func(sc *scenarioContext) { + loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/snapshots/12345", "/api/snapshots/:key", models.ROLE_EDITOR, func(sc *scenarioContext) { ts := setupRemoteServer(func(rw http.ResponseWriter, req *http.Request) { rw.WriteHeader(200) externalRequest = req @@ -129,12 +129,12 @@ func TestDashboardSnapshotApiEndpoint(t *testing.T) { }) Convey("When user is editor and is the creator of the snapshot", func() { - aclMockResp = []*m.DashboardAclInfoDTO{} + aclMockResp = []*models.DashboardAclInfoDTO{} mockSnapshotResult.UserId = TestUserID mockSnapshotResult.External = false Convey("Should be able to delete a snapshot", func() { - loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/snapshots/12345", "/api/snapshots/:key", m.ROLE_EDITOR, func(sc *scenarioContext) { + loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/snapshots/12345", "/api/snapshots/:key", models.ROLE_EDITOR, func(sc *scenarioContext) { sc.handlerFunc = DeleteDashboardSnapshot sc.fakeReqWithParams("DELETE", sc.url, map[string]string{"key": "12345"}).exec() @@ -148,12 +148,12 @@ func TestDashboardSnapshotApiEndpoint(t *testing.T) { }) Convey("When deleting an external snapshot", func() { - aclMockResp = []*m.DashboardAclInfoDTO{} + aclMockResp = []*models.DashboardAclInfoDTO{} mockSnapshotResult.UserId = TestUserID Convey("Should gracefully delete local snapshot when remote snapshot has already been removed", func() { var writeErr error - loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/snapshots/12345", "/api/snapshots/:key", m.ROLE_EDITOR, func(sc *scenarioContext) { + loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/snapshots/12345", "/api/snapshots/:key", models.ROLE_EDITOR, func(sc *scenarioContext) { ts := setupRemoteServer(func(rw http.ResponseWriter, req *http.Request) { _, writeErr = rw.Write([]byte(`{"message":"Failed to get dashboard snapshot"}`)) rw.WriteHeader(500) @@ -169,7 +169,7 @@ func TestDashboardSnapshotApiEndpoint(t *testing.T) { }) Convey("Should fail to delete local snapshot when an unexpected 500 error occurs", func() { - loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/snapshots/12345", "/api/snapshots/:key", m.ROLE_EDITOR, func(sc *scenarioContext) { + loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/snapshots/12345", "/api/snapshots/:key", models.ROLE_EDITOR, func(sc *scenarioContext) { var writeErr error ts := setupRemoteServer(func(rw http.ResponseWriter, req *http.Request) { rw.WriteHeader(500) @@ -186,7 +186,7 @@ func TestDashboardSnapshotApiEndpoint(t *testing.T) { }) Convey("Should fail to delete local snapshot when an unexpected remote error occurs", func() { - loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/snapshots/12345", "/api/snapshots/:key", m.ROLE_EDITOR, func(sc *scenarioContext) { + loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/snapshots/12345", "/api/snapshots/:key", models.ROLE_EDITOR, func(sc *scenarioContext) { ts := setupRemoteServer(func(rw http.ResponseWriter, req *http.Request) { rw.WriteHeader(404) }) diff --git a/pkg/api/dashboard_test.go b/pkg/api/dashboard_test.go index 4135f1794b2..f8f543dac77 100644 --- a/pkg/api/dashboard_test.go +++ b/pkg/api/dashboard_test.go @@ -8,7 +8,7 @@ import ( "github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/simplejson" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/alerting" "github.com/grafana/grafana/pkg/services/dashboards" "github.com/grafana/grafana/pkg/services/provisioning" @@ -25,45 +25,45 @@ import ( func TestDashboardApiEndpoint(t *testing.T) { Convey("Given a dashboard with a parent folder which does not have an acl", t, func() { - fakeDash := m.NewDashboard("Child dash") + fakeDash := models.NewDashboard("Child dash") fakeDash.Id = 1 fakeDash.FolderId = 1 fakeDash.HasAcl = false - bus.AddHandler("test", func(query *m.GetDashboardsBySlugQuery) error { - dashboards := []*m.Dashboard{fakeDash} + bus.AddHandler("test", func(query *models.GetDashboardsBySlugQuery) error { + dashboards := []*models.Dashboard{fakeDash} query.Result = dashboards return nil }) - var getDashboardQueries []*m.GetDashboardQuery + var getDashboardQueries []*models.GetDashboardQuery - bus.AddHandler("test", func(query *m.GetDashboardQuery) error { + bus.AddHandler("test", func(query *models.GetDashboardQuery) error { query.Result = fakeDash getDashboardQueries = append(getDashboardQueries, query) return nil }) - bus.AddHandler("test", func(query *m.GetProvisionedDashboardDataByIdQuery) error { + bus.AddHandler("test", func(query *models.GetProvisionedDashboardDataByIdQuery) error { query.Result = nil return nil }) - viewerRole := m.ROLE_VIEWER - editorRole := m.ROLE_EDITOR + viewerRole := models.ROLE_VIEWER + editorRole := models.ROLE_EDITOR - aclMockResp := []*m.DashboardAclInfoDTO{ - {Role: &viewerRole, Permission: m.PERMISSION_VIEW}, - {Role: &editorRole, Permission: m.PERMISSION_EDIT}, + aclMockResp := []*models.DashboardAclInfoDTO{ + {Role: &viewerRole, Permission: models.PERMISSION_VIEW}, + {Role: &editorRole, Permission: models.PERMISSION_EDIT}, } - bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error { + bus.AddHandler("test", func(query *models.GetDashboardAclInfoListQuery) error { query.Result = aclMockResp return nil }) - bus.AddHandler("test", func(query *m.GetTeamsByUserQuery) error { - query.Result = []*m.TeamDTO{} + bus.AddHandler("test", func(query *models.GetTeamsByUserQuery) error { + query.Result = []*models.TeamDTO{} return nil }) @@ -72,7 +72,7 @@ func TestDashboardApiEndpoint(t *testing.T) { // 2. user is an org editor Convey("When user is an Org Viewer", func() { - role := m.ROLE_VIEWER + role := models.ROLE_VIEWER loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) { dash := GetDashboardShouldReturn200(sc) @@ -132,7 +132,7 @@ func TestDashboardApiEndpoint(t *testing.T) { }) Convey("When user is an Org Editor", func() { - role := m.ROLE_EDITOR + role := models.ROLE_EDITOR loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) { dash := GetDashboardShouldReturn200(sc) @@ -193,46 +193,46 @@ func TestDashboardApiEndpoint(t *testing.T) { }) Convey("Given a dashboard with a parent folder which has an acl", t, func() { - fakeDash := m.NewDashboard("Child dash") + fakeDash := models.NewDashboard("Child dash") fakeDash.Id = 1 fakeDash.FolderId = 1 fakeDash.HasAcl = true setting.ViewersCanEdit = false - bus.AddHandler("test", func(query *m.GetProvisionedDashboardDataByIdQuery) error { + bus.AddHandler("test", func(query *models.GetProvisionedDashboardDataByIdQuery) error { query.Result = nil return nil }) - bus.AddHandler("test", func(query *m.GetDashboardsBySlugQuery) error { - dashboards := []*m.Dashboard{fakeDash} + bus.AddHandler("test", func(query *models.GetDashboardsBySlugQuery) error { + dashboards := []*models.Dashboard{fakeDash} query.Result = dashboards return nil }) - aclMockResp := []*m.DashboardAclInfoDTO{ + aclMockResp := []*models.DashboardAclInfoDTO{ { DashboardId: 1, - Permission: m.PERMISSION_EDIT, + Permission: models.PERMISSION_EDIT, UserId: 200, }, } - bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error { + bus.AddHandler("test", func(query *models.GetDashboardAclInfoListQuery) error { query.Result = aclMockResp return nil }) - var getDashboardQueries []*m.GetDashboardQuery + var getDashboardQueries []*models.GetDashboardQuery - bus.AddHandler("test", func(query *m.GetDashboardQuery) error { + bus.AddHandler("test", func(query *models.GetDashboardQuery) error { query.Result = fakeDash getDashboardQueries = append(getDashboardQueries, query) return nil }) - bus.AddHandler("test", func(query *m.GetTeamsByUserQuery) error { - query.Result = []*m.TeamDTO{} + bus.AddHandler("test", func(query *models.GetTeamsByUserQuery) error { + query.Result = []*models.TeamDTO{} return nil }) @@ -249,7 +249,7 @@ func TestDashboardApiEndpoint(t *testing.T) { // 6. user is an org editor AND has been granted a view permission Convey("When user is an Org Viewer and has no permissions for this dashboard", func() { - role := m.ROLE_VIEWER + role := models.ROLE_VIEWER loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) { sc.handlerFunc = hs.GetDashboard @@ -307,7 +307,7 @@ func TestDashboardApiEndpoint(t *testing.T) { }) Convey("When user is an Org Editor and has no permissions for this dashboard", func() { - role := m.ROLE_EDITOR + role := models.ROLE_EDITOR loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) { sc.handlerFunc = hs.GetDashboard @@ -365,13 +365,13 @@ func TestDashboardApiEndpoint(t *testing.T) { }) Convey("When user is an Org Viewer but has an edit permission", func() { - role := m.ROLE_VIEWER + role := models.ROLE_VIEWER - mockResult := []*m.DashboardAclInfoDTO{ - {OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_EDIT}, + mockResult := []*models.DashboardAclInfoDTO{ + {OrgId: 1, DashboardId: 2, UserId: 1, Permission: models.PERMISSION_EDIT}, } - bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error { + bus.AddHandler("test", func(query *models.GetDashboardAclInfoListQuery) error { query.Result = mockResult return nil }) @@ -434,14 +434,14 @@ func TestDashboardApiEndpoint(t *testing.T) { }) Convey("When user is an Org Viewer and viewers can edit", func() { - role := m.ROLE_VIEWER + role := models.ROLE_VIEWER setting.ViewersCanEdit = true - mockResult := []*m.DashboardAclInfoDTO{ - {OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_VIEW}, + mockResult := []*models.DashboardAclInfoDTO{ + {OrgId: 1, DashboardId: 2, UserId: 1, Permission: models.PERMISSION_VIEW}, } - bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error { + bus.AddHandler("test", func(query *models.GetDashboardAclInfoListQuery) error { query.Result = mockResult return nil }) @@ -494,13 +494,13 @@ func TestDashboardApiEndpoint(t *testing.T) { }) Convey("When user is an Org Viewer but has an admin permission", func() { - role := m.ROLE_VIEWER + role := models.ROLE_VIEWER - mockResult := []*m.DashboardAclInfoDTO{ - {OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_ADMIN}, + mockResult := []*models.DashboardAclInfoDTO{ + {OrgId: 1, DashboardId: 2, UserId: 1, Permission: models.PERMISSION_ADMIN}, } - bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error { + bus.AddHandler("test", func(query *models.GetDashboardAclInfoListQuery) error { query.Result = mockResult return nil }) @@ -563,13 +563,13 @@ func TestDashboardApiEndpoint(t *testing.T) { }) Convey("When user is an Org Editor but has a view permission", func() { - role := m.ROLE_EDITOR + role := models.ROLE_EDITOR - mockResult := []*m.DashboardAclInfoDTO{ - {OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_VIEW}, + mockResult := []*models.DashboardAclInfoDTO{ + {OrgId: 1, DashboardId: 2, UserId: 1, Permission: models.PERMISSION_VIEW}, } - bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error { + bus.AddHandler("test", func(query *models.GetDashboardAclInfoListQuery) error { query.Result = mockResult return nil }) @@ -631,28 +631,28 @@ func TestDashboardApiEndpoint(t *testing.T) { }) Convey("Given two dashboards with the same title in different folders", t, func() { - dashOne := m.NewDashboard("dash") + dashOne := models.NewDashboard("dash") dashOne.Id = 2 dashOne.FolderId = 1 dashOne.HasAcl = false - dashTwo := m.NewDashboard("dash") + dashTwo := models.NewDashboard("dash") dashTwo.Id = 4 dashTwo.FolderId = 3 dashTwo.HasAcl = false - bus.AddHandler("test", func(query *m.GetProvisionedDashboardDataByIdQuery) error { + bus.AddHandler("test", func(query *models.GetProvisionedDashboardDataByIdQuery) error { query.Result = nil return nil }) - bus.AddHandler("test", func(query *m.GetDashboardsBySlugQuery) error { - dashboards := []*m.Dashboard{dashOne, dashTwo} + bus.AddHandler("test", func(query *models.GetDashboardsBySlugQuery) error { + dashboards := []*models.Dashboard{dashOne, dashTwo} query.Result = dashboards return nil }) - role := m.ROLE_EDITOR + role := models.ROLE_EDITOR loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) { CallDeleteDashboardBySlug(sc) @@ -661,7 +661,7 @@ func TestDashboardApiEndpoint(t *testing.T) { So(sc.resp.Code, ShouldEqual, 412) result := sc.ToJSON() So(result.Get("status").MustString(), ShouldEqual, "multiple-slugs-exists") - So(result.Get("message").MustString(), ShouldEqual, m.ErrDashboardsWithSameSlugExists.Error()) + So(result.Get("message").MustString(), ShouldEqual, models.ErrDashboardsWithSameSlugExists.Error()) }) }) }) @@ -671,7 +671,7 @@ func TestDashboardApiEndpoint(t *testing.T) { // This tests that a valid request returns correct response Convey("Given a correct request for creating a dashboard", func() { - cmd := m.SaveDashboardCommand{ + cmd := models.SaveDashboardCommand{ OrgId: 1, UserId: 5, Dashboard: simplejson.NewFromAny(map[string]interface{}{ @@ -684,7 +684,7 @@ func TestDashboardApiEndpoint(t *testing.T) { } mock := &dashboards.FakeDashboardService{ - SaveDashboardResult: &m.Dashboard{ + SaveDashboardResult: &models.Dashboard{ Id: 2, Uid: "uid", Title: "Dash", @@ -724,27 +724,27 @@ func TestDashboardApiEndpoint(t *testing.T) { SaveError error ExpectedStatusCode int }{ - {SaveError: m.ErrDashboardNotFound, ExpectedStatusCode: 404}, - {SaveError: m.ErrFolderNotFound, ExpectedStatusCode: 400}, - {SaveError: m.ErrDashboardWithSameUIDExists, ExpectedStatusCode: 400}, - {SaveError: m.ErrDashboardWithSameNameInFolderExists, ExpectedStatusCode: 412}, - {SaveError: m.ErrDashboardVersionMismatch, ExpectedStatusCode: 412}, - {SaveError: m.ErrDashboardTitleEmpty, ExpectedStatusCode: 400}, - {SaveError: m.ErrDashboardFolderCannotHaveParent, ExpectedStatusCode: 400}, + {SaveError: models.ErrDashboardNotFound, ExpectedStatusCode: 404}, + {SaveError: models.ErrFolderNotFound, ExpectedStatusCode: 400}, + {SaveError: models.ErrDashboardWithSameUIDExists, ExpectedStatusCode: 400}, + {SaveError: models.ErrDashboardWithSameNameInFolderExists, ExpectedStatusCode: 412}, + {SaveError: models.ErrDashboardVersionMismatch, ExpectedStatusCode: 412}, + {SaveError: models.ErrDashboardTitleEmpty, ExpectedStatusCode: 400}, + {SaveError: models.ErrDashboardFolderCannotHaveParent, ExpectedStatusCode: 400}, {SaveError: alerting.ValidationError{Reason: "Mu"}, ExpectedStatusCode: 422}, - {SaveError: m.ErrDashboardFailedGenerateUniqueUid, ExpectedStatusCode: 500}, - {SaveError: m.ErrDashboardTypeMismatch, ExpectedStatusCode: 400}, - {SaveError: m.ErrDashboardFolderWithSameNameAsDashboard, ExpectedStatusCode: 400}, - {SaveError: m.ErrDashboardWithSameNameAsFolder, ExpectedStatusCode: 400}, - {SaveError: m.ErrDashboardFolderNameExists, ExpectedStatusCode: 400}, - {SaveError: m.ErrDashboardUpdateAccessDenied, ExpectedStatusCode: 403}, - {SaveError: m.ErrDashboardInvalidUid, ExpectedStatusCode: 400}, - {SaveError: m.ErrDashboardUidToLong, ExpectedStatusCode: 400}, - {SaveError: m.ErrDashboardCannotSaveProvisionedDashboard, ExpectedStatusCode: 400}, - {SaveError: m.UpdatePluginDashboardError{PluginId: "plug"}, ExpectedStatusCode: 412}, + {SaveError: models.ErrDashboardFailedGenerateUniqueUid, ExpectedStatusCode: 500}, + {SaveError: models.ErrDashboardTypeMismatch, ExpectedStatusCode: 400}, + {SaveError: models.ErrDashboardFolderWithSameNameAsDashboard, ExpectedStatusCode: 400}, + {SaveError: models.ErrDashboardWithSameNameAsFolder, ExpectedStatusCode: 400}, + {SaveError: models.ErrDashboardFolderNameExists, ExpectedStatusCode: 400}, + {SaveError: models.ErrDashboardUpdateAccessDenied, ExpectedStatusCode: 403}, + {SaveError: models.ErrDashboardInvalidUid, ExpectedStatusCode: 400}, + {SaveError: models.ErrDashboardUidToLong, ExpectedStatusCode: 400}, + {SaveError: models.ErrDashboardCannotSaveProvisionedDashboard, ExpectedStatusCode: 400}, + {SaveError: models.UpdatePluginDashboardError{PluginId: "plug"}, ExpectedStatusCode: 412}, } - cmd := m.SaveDashboardCommand{ + cmd := models.SaveDashboardCommand{ OrgId: 1, Dashboard: simplejson.NewFromAny(map[string]interface{}{ "title": "", @@ -765,19 +765,19 @@ func TestDashboardApiEndpoint(t *testing.T) { }) Convey("Given two dashboards being compared", t, func() { - mockResult := []*m.DashboardAclInfoDTO{} - bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error { + mockResult := []*models.DashboardAclInfoDTO{} + bus.AddHandler("test", func(query *models.GetDashboardAclInfoListQuery) error { query.Result = mockResult return nil }) - bus.AddHandler("test", func(query *m.GetProvisionedDashboardDataByIdQuery) error { + bus.AddHandler("test", func(query *models.GetProvisionedDashboardDataByIdQuery) error { query.Result = nil return nil }) - bus.AddHandler("test", func(query *m.GetDashboardVersionQuery) error { - query.Result = &m.DashboardVersion{ + bus.AddHandler("test", func(query *models.GetDashboardVersionQuery) error { + query.Result = &models.DashboardVersion{ Data: simplejson.NewFromAny(map[string]interface{}{ "title": "Dash" + string(query.DashboardId), }), @@ -798,7 +798,7 @@ func TestDashboardApiEndpoint(t *testing.T) { } Convey("when user does not have permission", func() { - role := m.ROLE_VIEWER + role := models.ROLE_VIEWER postDiffScenario("When calling POST on", "/api/dashboards/calculate-diff", "/api/dashboards/calculate-diff", cmd, role, func(sc *scenarioContext) { CallPostDashboard(sc) @@ -807,7 +807,7 @@ func TestDashboardApiEndpoint(t *testing.T) { }) Convey("when user does have permission", func() { - role := m.ROLE_ADMIN + role := models.ROLE_ADMIN postDiffScenario("When calling POST on", "/api/dashboards/calculate-diff", "/api/dashboards/calculate-diff", cmd, role, func(sc *scenarioContext) { CallPostDashboard(sc) @@ -817,18 +817,18 @@ func TestDashboardApiEndpoint(t *testing.T) { }) Convey("Given dashboard in folder being restored should restore to folder", t, func() { - fakeDash := m.NewDashboard("Child dash") + fakeDash := models.NewDashboard("Child dash") fakeDash.Id = 2 fakeDash.FolderId = 1 fakeDash.HasAcl = false - bus.AddHandler("test", func(query *m.GetDashboardQuery) error { + bus.AddHandler("test", func(query *models.GetDashboardQuery) error { query.Result = fakeDash return nil }) - bus.AddHandler("test", func(query *m.GetDashboardVersionQuery) error { - query.Result = &m.DashboardVersion{ + bus.AddHandler("test", func(query *models.GetDashboardVersionQuery) error { + query.Result = &models.DashboardVersion{ DashboardId: 2, Version: 1, Data: fakeDash.Data, @@ -837,7 +837,7 @@ func TestDashboardApiEndpoint(t *testing.T) { }) mock := &dashboards.FakeDashboardService{ - SaveDashboardResult: &m.Dashboard{ + SaveDashboardResult: &models.Dashboard{ Id: 2, Uid: "uid", Title: "Dash", @@ -861,17 +861,17 @@ func TestDashboardApiEndpoint(t *testing.T) { }) Convey("Given dashboard in general folder being restored should restore to general folder", t, func() { - fakeDash := m.NewDashboard("Child dash") + fakeDash := models.NewDashboard("Child dash") fakeDash.Id = 2 fakeDash.HasAcl = false - bus.AddHandler("test", func(query *m.GetDashboardQuery) error { + bus.AddHandler("test", func(query *models.GetDashboardQuery) error { query.Result = fakeDash return nil }) - bus.AddHandler("test", func(query *m.GetDashboardVersionQuery) error { - query.Result = &m.DashboardVersion{ + bus.AddHandler("test", func(query *models.GetDashboardVersionQuery) error { + query.Result = &models.DashboardVersion{ DashboardId: 2, Version: 1, Data: fakeDash.Data, @@ -880,7 +880,7 @@ func TestDashboardApiEndpoint(t *testing.T) { }) mock := &dashboards.FakeDashboardService{ - SaveDashboardResult: &m.Dashboard{ + SaveDashboardResult: &models.Dashboard{ Id: 2, Uid: "uid", Title: "Dash", @@ -905,48 +905,48 @@ func TestDashboardApiEndpoint(t *testing.T) { Convey("Given provisioned dashboard", t, func() { - bus.AddHandler("test", func(query *m.GetDashboardsBySlugQuery) error { - query.Result = []*m.Dashboard{{}} + bus.AddHandler("test", func(query *models.GetDashboardsBySlugQuery) error { + query.Result = []*models.Dashboard{{}} return nil }) - bus.AddHandler("test", func(query *m.GetDashboardQuery) error { - query.Result = &m.Dashboard{Id: 1, Data: &simplejson.Json{}} + bus.AddHandler("test", func(query *models.GetDashboardQuery) error { + query.Result = &models.Dashboard{Id: 1, Data: &simplejson.Json{}} return nil }) - bus.AddHandler("test", func(query *m.GetProvisionedDashboardDataByIdQuery) error { - query.Result = &m.DashboardProvisioning{ExternalId: "/tmp/grafana/dashboards/test/dashboard1.json"} + bus.AddHandler("test", func(query *models.GetProvisionedDashboardDataByIdQuery) error { + query.Result = &models.DashboardProvisioning{ExternalId: "/tmp/grafana/dashboards/test/dashboard1.json"} return nil }) - bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error { - query.Result = []*m.DashboardAclInfoDTO{ - {OrgId: TestOrgID, DashboardId: 1, UserId: TestUserID, Permission: m.PERMISSION_EDIT}, + bus.AddHandler("test", func(query *models.GetDashboardAclInfoListQuery) error { + query.Result = []*models.DashboardAclInfoDTO{ + {OrgId: TestOrgID, DashboardId: 1, UserId: TestUserID, Permission: models.PERMISSION_EDIT}, } return nil }) - loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/dash", "/api/dashboards/db/:slug", m.ROLE_EDITOR, func(sc *scenarioContext) { + loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/dash", "/api/dashboards/db/:slug", models.ROLE_EDITOR, func(sc *scenarioContext) { CallDeleteDashboardBySlug(sc) Convey("Should result in 400", func() { So(sc.resp.Code, ShouldEqual, 400) result := sc.ToJSON() - So(result.Get("error").MustString(), ShouldEqual, m.ErrDashboardCannotDeleteProvisionedDashboard.Error()) + So(result.Get("error").MustString(), ShouldEqual, models.ErrDashboardCannotDeleteProvisionedDashboard.Error()) }) }) - loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/abcdefghi", "/api/dashboards/db/:uid", m.ROLE_EDITOR, func(sc *scenarioContext) { + loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/abcdefghi", "/api/dashboards/db/:uid", models.ROLE_EDITOR, func(sc *scenarioContext) { CallDeleteDashboardByUID(sc) Convey("Should result in 400", func() { So(sc.resp.Code, ShouldEqual, 400) result := sc.ToJSON() - So(result.Get("error").MustString(), ShouldEqual, m.ErrDashboardCannotDeleteProvisionedDashboard.Error()) + So(result.Get("error").MustString(), ShouldEqual, models.ErrDashboardCannotDeleteProvisionedDashboard.Error()) }) }) - loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/dash", "/api/dashboards/uid/:uid", m.ROLE_EDITOR, func(sc *scenarioContext) { + loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/dash", "/api/dashboards/uid/:uid", models.ROLE_EDITOR, func(sc *scenarioContext) { mock := provisioning.NewProvisioningServiceMock() mock.GetDashboardProvisionerResolvedPathFunc = func(name string) string { return "/tmp/grafana/dashboards" @@ -959,7 +959,7 @@ func TestDashboardApiEndpoint(t *testing.T) { }) }) - loggedInUserScenarioWithRole("When allowUiUpdates is true and calling GET on", "GET", "/api/dashboards/uid/dash", "/api/dashboards/uid/:uid", m.ROLE_EDITOR, func(sc *scenarioContext) { + loggedInUserScenarioWithRole("When allowUiUpdates is true and calling GET on", "GET", "/api/dashboards/uid/dash", "/api/dashboards/uid/:uid", models.ROLE_EDITOR, func(sc *scenarioContext) { mock := provisioning.NewProvisioningServiceMock() mock.GetDashboardProvisionerResolvedPathFunc = func(name string) string { return "/tmp/grafana/dashboards" @@ -1018,8 +1018,8 @@ func CallGetDashboard(sc *scenarioContext, hs *HTTPServer) { } func CallGetDashboardVersion(sc *scenarioContext) { - bus.AddHandler("test", func(query *m.GetDashboardVersionQuery) error { - query.Result = &m.DashboardVersion{} + bus.AddHandler("test", func(query *models.GetDashboardVersionQuery) error { + query.Result = &models.DashboardVersion{} return nil }) @@ -1028,8 +1028,8 @@ func CallGetDashboardVersion(sc *scenarioContext) { } func CallGetDashboardVersions(sc *scenarioContext) { - bus.AddHandler("test", func(query *m.GetDashboardVersionsQuery) error { - query.Result = []*m.DashboardVersionDTO{} + bus.AddHandler("test", func(query *models.GetDashboardVersionsQuery) error { + query.Result = []*models.DashboardVersionDTO{} return nil }) @@ -1038,7 +1038,7 @@ func CallGetDashboardVersions(sc *scenarioContext) { } func CallDeleteDashboardBySlug(sc *scenarioContext) { - bus.AddHandler("test", func(cmd *m.DeleteDashboardCommand) error { + bus.AddHandler("test", func(cmd *models.DeleteDashboardCommand) error { return nil }) @@ -1047,7 +1047,7 @@ func CallDeleteDashboardBySlug(sc *scenarioContext) { } func CallDeleteDashboardByUID(sc *scenarioContext) { - bus.AddHandler("test", func(cmd *m.DeleteDashboardCommand) error { + bus.AddHandler("test", func(cmd *models.DeleteDashboardCommand) error { return nil }) @@ -1073,7 +1073,7 @@ func (m mockDashboardProvisioningService) DeleteProvisionedDashboard(dashboardId panic("implement me") } -func postDashboardScenario(desc string, url string, routePattern string, mock *dashboards.FakeDashboardService, cmd m.SaveDashboardCommand, fn scenarioFunc) { +func postDashboardScenario(desc string, url string, routePattern string, mock *dashboards.FakeDashboardService, cmd models.SaveDashboardCommand, fn scenarioFunc) { Convey(desc+" "+url, func() { defer bus.ClearBusHandlers() @@ -1084,9 +1084,9 @@ func postDashboardScenario(desc string, url string, routePattern string, mock *d } sc := setupScenarioContext(url) - sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { + sc.defaultHandler = Wrap(func(c *models.ReqContext) Response { sc.context = c - sc.context.SignedInUser = &m.SignedInUser{OrgId: cmd.OrgId, UserId: cmd.UserId} + sc.context.SignedInUser = &models.SignedInUser{OrgId: cmd.OrgId, UserId: cmd.UserId} return hs.PostDashboard(c, cmd) }) @@ -1110,14 +1110,14 @@ func postDashboardScenario(desc string, url string, routePattern string, mock *d }) } -func postDiffScenario(desc string, url string, routePattern string, cmd dtos.CalculateDiffOptions, role m.RoleType, fn scenarioFunc) { +func postDiffScenario(desc string, url string, routePattern string, cmd dtos.CalculateDiffOptions, role models.RoleType, fn scenarioFunc) { Convey(desc+" "+url, func() { defer bus.ClearBusHandlers() sc := setupScenarioContext(url) - sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { + sc.defaultHandler = Wrap(func(c *models.ReqContext) Response { sc.context = c - sc.context.SignedInUser = &m.SignedInUser{ + sc.context.SignedInUser = &models.SignedInUser{ OrgId: TestOrgID, UserId: TestUserID, } @@ -1143,13 +1143,13 @@ func restoreDashboardVersionScenario(desc string, url string, routePattern strin } sc := setupScenarioContext(url) - sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { + sc.defaultHandler = Wrap(func(c *models.ReqContext) Response { sc.context = c - sc.context.SignedInUser = &m.SignedInUser{ + sc.context.SignedInUser = &models.SignedInUser{ OrgId: TestOrgID, UserId: TestUserID, } - sc.context.OrgRole = m.ROLE_ADMIN + sc.context.OrgRole = models.ROLE_ADMIN return hs.RestoreDashboardVersion(c, cmd) }) @@ -1183,20 +1183,20 @@ func (sc *scenarioContext) ToJSON() *simplejson.Json { type mockDashboardProvisioningService struct { } -func (m mockDashboardProvisioningService) SaveProvisionedDashboard(dto *dashboards.SaveDashboardDTO, provisioning *m.DashboardProvisioning) (*m.Dashboard, error) { +func (m mockDashboardProvisioningService) SaveProvisionedDashboard(dto *dashboards.SaveDashboardDTO, provisioning *models.DashboardProvisioning) (*models.Dashboard, error) { panic("implement me") } -func (m mockDashboardProvisioningService) SaveFolderForProvisionedDashboards(*dashboards.SaveDashboardDTO) (*m.Dashboard, error) { +func (m mockDashboardProvisioningService) SaveFolderForProvisionedDashboards(*dashboards.SaveDashboardDTO) (*models.Dashboard, error) { panic("implement me") } -func (m mockDashboardProvisioningService) GetProvisionedDashboardData(name string) ([]*m.DashboardProvisioning, error) { +func (m mockDashboardProvisioningService) GetProvisionedDashboardData(name string) ([]*models.DashboardProvisioning, error) { panic("implement me") } -func (mock mockDashboardProvisioningService) GetProvisionedDashboardDataByDashboardId(dashboardId int64) (*m.DashboardProvisioning, error) { - return &m.DashboardProvisioning{}, nil +func (mock mockDashboardProvisioningService) GetProvisionedDashboardDataByDashboardId(dashboardId int64) (*models.DashboardProvisioning, error) { + return &models.DashboardProvisioning{}, nil } func (m mockDashboardProvisioningService) UnprovisionDashboard(dashboardId int64) error { diff --git a/pkg/api/dataproxy.go b/pkg/api/dataproxy.go index 54e18e70f3a..290ed274541 100644 --- a/pkg/api/dataproxy.go +++ b/pkg/api/dataproxy.go @@ -3,17 +3,18 @@ package api import ( "github.com/grafana/grafana/pkg/api/pluginproxy" "github.com/grafana/grafana/pkg/infra/metrics" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/plugins" ) -func (hs *HTTPServer) ProxyDataSourceRequest(c *m.ReqContext) { +// ProxyDataSourceRequest proxies datasource requests +func (hs *HTTPServer) ProxyDataSourceRequest(c *models.ReqContext) { c.TimeRequest(metrics.MDataSourceProxyReqTimer) - dsId := c.ParamsInt64(":id") - ds, err := hs.DatasourceCache.GetDatasource(dsId, c.SignedInUser, c.SkipCache) + dsID := c.ParamsInt64(":id") + ds, err := hs.DatasourceCache.GetDatasource(dsID, c.SignedInUser, c.SkipCache) if err != nil { - if err == m.ErrDataSourceAccessDenied { + if err == models.ErrDataSourceAccessDenied { c.JsonApiErr(403, "Access denied to datasource", err) return } diff --git a/pkg/api/datasources.go b/pkg/api/datasources.go index c543f4c2891..f6d59a26f16 100644 --- a/pkg/api/datasources.go +++ b/pkg/api/datasources.go @@ -5,14 +5,14 @@ import ( "github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/bus" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/plugins" "github.com/grafana/grafana/pkg/plugins/backendplugin" "github.com/grafana/grafana/pkg/util" ) -func GetDataSources(c *m.ReqContext) Response { - query := m.GetDataSourcesQuery{OrgId: c.OrgId} +func GetDataSources(c *models.ReqContext) Response { + query := models.GetDataSourcesQuery{OrgId: c.OrgId} if err := bus.Dispatch(&query); err != nil { return Error(500, "Failed to query datasources", err) @@ -50,14 +50,14 @@ func GetDataSources(c *m.ReqContext) Response { return JSON(200, &result) } -func GetDataSourceById(c *m.ReqContext) Response { - query := m.GetDataSourceByIdQuery{ +func GetDataSourceById(c *models.ReqContext) Response { + query := models.GetDataSourceByIdQuery{ Id: c.ParamsInt64(":id"), OrgId: c.OrgId, } if err := bus.Dispatch(&query); err != nil { - if err == m.ErrDataSourceNotFound { + if err == models.ErrDataSourceNotFound { return Error(404, "Data source not found", nil) } return Error(500, "Failed to query datasources", err) @@ -69,7 +69,7 @@ func GetDataSourceById(c *m.ReqContext) Response { return JSON(200, &dtos) } -func DeleteDataSourceById(c *m.ReqContext) Response { +func DeleteDataSourceById(c *models.ReqContext) Response { id := c.ParamsInt64(":id") if id <= 0 { @@ -85,7 +85,7 @@ func DeleteDataSourceById(c *m.ReqContext) Response { return Error(403, "Cannot delete read-only data source", nil) } - cmd := &m.DeleteDataSourceByIdCommand{Id: id, OrgId: c.OrgId} + cmd := &models.DeleteDataSourceByIdCommand{Id: id, OrgId: c.OrgId} err = bus.Dispatch(cmd) if err != nil { @@ -95,16 +95,16 @@ func DeleteDataSourceById(c *m.ReqContext) Response { return Success("Data source deleted") } -func DeleteDataSourceByName(c *m.ReqContext) Response { +func DeleteDataSourceByName(c *models.ReqContext) Response { name := c.Params(":name") if name == "" { return Error(400, "Missing valid datasource name", nil) } - getCmd := &m.GetDataSourceByNameQuery{Name: name, OrgId: c.OrgId} + getCmd := &models.GetDataSourceByNameQuery{Name: name, OrgId: c.OrgId} if err := bus.Dispatch(getCmd); err != nil { - if err == m.ErrDataSourceNotFound { + if err == models.ErrDataSourceNotFound { return Error(404, "Data source not found", nil) } return Error(500, "Failed to delete datasource", err) @@ -114,7 +114,7 @@ func DeleteDataSourceByName(c *m.ReqContext) Response { return Error(403, "Cannot delete read-only data source", nil) } - cmd := &m.DeleteDataSourceByNameCommand{Name: name, OrgId: c.OrgId} + cmd := &models.DeleteDataSourceByNameCommand{Name: name, OrgId: c.OrgId} err := bus.Dispatch(cmd) if err != nil { return Error(500, "Failed to delete datasource", err) @@ -123,11 +123,11 @@ func DeleteDataSourceByName(c *m.ReqContext) Response { return Success("Data source deleted") } -func AddDataSource(c *m.ReqContext, cmd m.AddDataSourceCommand) Response { +func AddDataSource(c *models.ReqContext, cmd models.AddDataSourceCommand) Response { cmd.OrgId = c.OrgId if err := bus.Dispatch(&cmd); err != nil { - if err == m.ErrDataSourceNameExists { + if err == models.ErrDataSourceNameExists { return Error(409, err.Error(), err) } @@ -143,7 +143,7 @@ func AddDataSource(c *m.ReqContext, cmd m.AddDataSourceCommand) Response { }) } -func UpdateDataSource(c *m.ReqContext, cmd m.UpdateDataSourceCommand) Response { +func UpdateDataSource(c *models.ReqContext, cmd models.UpdateDataSourceCommand) Response { cmd.OrgId = c.OrgId cmd.Id = c.ParamsInt64(":id") @@ -154,19 +154,19 @@ func UpdateDataSource(c *m.ReqContext, cmd m.UpdateDataSourceCommand) Response { err = bus.Dispatch(&cmd) if err != nil { - if err == m.ErrDataSourceUpdatingOldVersion { + if err == models.ErrDataSourceUpdatingOldVersion { return Error(500, "Failed to update datasource. Reload new version and try again", err) } return Error(500, "Failed to update datasource", err) } - query := m.GetDataSourceByIdQuery{ + query := models.GetDataSourceByIdQuery{ Id: cmd.Id, OrgId: c.OrgId, } if err := bus.Dispatch(&query); err != nil { - if err == m.ErrDataSourceNotFound { + if err == models.ErrDataSourceNotFound { return Error(404, "Data source not found", nil) } return Error(500, "Failed to query datasources", err) @@ -182,7 +182,7 @@ func UpdateDataSource(c *m.ReqContext, cmd m.UpdateDataSourceCommand) Response { }) } -func fillWithSecureJSONData(cmd *m.UpdateDataSourceCommand) error { +func fillWithSecureJSONData(cmd *models.UpdateDataSourceCommand) error { if len(cmd.SecureJsonData) == 0 { return nil } @@ -193,7 +193,7 @@ func fillWithSecureJSONData(cmd *m.UpdateDataSourceCommand) error { } if ds.ReadOnly { - return m.ErrDatasourceIsReadOnly + return models.ErrDatasourceIsReadOnly } secureJSONData := ds.SecureJsonData.Decrypt() @@ -207,8 +207,8 @@ func fillWithSecureJSONData(cmd *m.UpdateDataSourceCommand) error { return nil } -func getRawDataSourceById(id int64, orgID int64) (*m.DataSource, error) { - query := m.GetDataSourceByIdQuery{ +func getRawDataSourceById(id int64, orgID int64) (*models.DataSource, error) { + query := models.GetDataSourceByIdQuery{ Id: id, OrgId: orgID, } @@ -221,11 +221,11 @@ func getRawDataSourceById(id int64, orgID int64) (*m.DataSource, error) { } // Get /api/datasources/name/:name -func GetDataSourceByName(c *m.ReqContext) Response { - query := m.GetDataSourceByNameQuery{Name: c.Params(":name"), OrgId: c.OrgId} +func GetDataSourceByName(c *models.ReqContext) Response { + query := models.GetDataSourceByNameQuery{Name: c.Params(":name"), OrgId: c.OrgId} if err := bus.Dispatch(&query); err != nil { - if err == m.ErrDataSourceNotFound { + if err == models.ErrDataSourceNotFound { return Error(404, "Data source not found", nil) } return Error(500, "Failed to query datasources", err) @@ -236,11 +236,11 @@ func GetDataSourceByName(c *m.ReqContext) Response { } // Get /api/datasources/id/:name -func GetDataSourceIdByName(c *m.ReqContext) Response { - query := m.GetDataSourceByNameQuery{Name: c.Params(":name"), OrgId: c.OrgId} +func GetDataSourceIdByName(c *models.ReqContext) Response { + query := models.GetDataSourceByNameQuery{Name: c.Params(":name"), OrgId: c.OrgId} if err := bus.Dispatch(&query); err != nil { - if err == m.ErrDataSourceNotFound { + if err == models.ErrDataSourceNotFound { return Error(404, "Data source not found", nil) } return Error(500, "Failed to query datasources", err) @@ -255,11 +255,11 @@ func GetDataSourceIdByName(c *m.ReqContext) Response { } // /api/datasources/:id/resources/* -func (hs *HTTPServer) CallDatasourceResource(c *m.ReqContext) { +func (hs *HTTPServer) CallDatasourceResource(c *models.ReqContext) { datasourceID := c.ParamsInt64(":id") ds, err := hs.DatasourceCache.GetDatasource(datasourceID, c.SignedInUser, c.SkipCache) if err != nil { - if err == m.ErrDataSourceAccessDenied { + if err == models.ErrDataSourceAccessDenied { c.JsonApiErr(403, "Access denied to datasource", err) return } @@ -294,7 +294,7 @@ func (hs *HTTPServer) CallDatasourceResource(c *m.ReqContext) { hs.BackendPluginManager.CallResource(config, c, c.Params("*")) } -func convertModelToDtos(ds *m.DataSource) dtos.DataSource { +func convertModelToDtos(ds *models.DataSource) dtos.DataSource { dto := dtos.DataSource{ Id: ds.Id, OrgId: ds.OrgId, diff --git a/pkg/api/dtos/acl.go b/pkg/api/dtos/acl.go index 6c74e68ce0d..b80fdc97f9f 100644 --- a/pkg/api/dtos/acl.go +++ b/pkg/api/dtos/acl.go @@ -1,16 +1,14 @@ package dtos -import ( - m "github.com/grafana/grafana/pkg/models" -) +import "github.com/grafana/grafana/pkg/models" type UpdateDashboardAclCommand struct { Items []DashboardAclUpdateItem `json:"items"` } type DashboardAclUpdateItem struct { - UserId int64 `json:"userId"` - TeamId int64 `json:"teamId"` - Role *m.RoleType `json:"role,omitempty"` - Permission m.PermissionType `json:"permission"` + UserId int64 `json:"userId"` + TeamId int64 `json:"teamId"` + Role *models.RoleType `json:"role,omitempty"` + Permission models.PermissionType `json:"permission"` } diff --git a/pkg/api/dtos/datasource.go b/pkg/api/dtos/datasource.go index f760486c561..73809ea9a4f 100644 --- a/pkg/api/dtos/datasource.go +++ b/pkg/api/dtos/datasource.go @@ -4,7 +4,7 @@ import ( "strings" "github.com/grafana/grafana/pkg/components/simplejson" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" ) type DataSource struct { @@ -13,7 +13,7 @@ type DataSource struct { Name string `json:"name"` Type string `json:"type"` TypeLogoUrl string `json:"typeLogoUrl"` - Access m.DsAccess `json:"access"` + Access models.DsAccess `json:"access"` Url string `json:"url"` Password string `json:"password"` User string `json:"user"` @@ -35,7 +35,7 @@ type DataSourceListItemDTO struct { Name string `json:"name"` Type string `json:"type"` TypeLogoUrl string `json:"typeLogoUrl"` - Access m.DsAccess `json:"access"` + Access models.DsAccess `json:"access"` Url string `json:"url"` Password string `json:"password"` User string `json:"user"` diff --git a/pkg/api/dtos/models.go b/pkg/api/dtos/models.go index 8c5ad7187e9..af3d4faafc4 100644 --- a/pkg/api/dtos/models.go +++ b/pkg/api/dtos/models.go @@ -8,7 +8,7 @@ import ( "github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/infra/log" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/setting" ) @@ -23,22 +23,22 @@ type LoginCommand struct { } type CurrentUser struct { - IsSignedIn bool `json:"isSignedIn"` - Id int64 `json:"id"` - Login string `json:"login"` - Email string `json:"email"` - Name string `json:"name"` - LightTheme bool `json:"lightTheme"` - OrgCount int `json:"orgCount"` - OrgId int64 `json:"orgId"` - OrgName string `json:"orgName"` - OrgRole m.RoleType `json:"orgRole"` - IsGrafanaAdmin bool `json:"isGrafanaAdmin"` - GravatarUrl string `json:"gravatarUrl"` - Timezone string `json:"timezone"` - Locale string `json:"locale"` - HelpFlags1 m.HelpFlags1 `json:"helpFlags1"` - HasEditPermissionInFolders bool `json:"hasEditPermissionInFolders"` + IsSignedIn bool `json:"isSignedIn"` + Id int64 `json:"id"` + Login string `json:"login"` + Email string `json:"email"` + Name string `json:"name"` + LightTheme bool `json:"lightTheme"` + OrgCount int `json:"orgCount"` + OrgId int64 `json:"orgId"` + OrgName string `json:"orgName"` + OrgRole models.RoleType `json:"orgRole"` + IsGrafanaAdmin bool `json:"isGrafanaAdmin"` + GravatarUrl string `json:"gravatarUrl"` + Timezone string `json:"timezone"` + Locale string `json:"locale"` + HelpFlags1 models.HelpFlags1 `json:"helpFlags1"` + HasEditPermissionInFolders bool `json:"hasEditPermissionInFolders"` } type MetricRequest struct { diff --git a/pkg/api/folder.go b/pkg/api/folder.go index bf55aeee30f..b0900a83a95 100644 --- a/pkg/api/folder.go +++ b/pkg/api/folder.go @@ -4,13 +4,13 @@ import ( "fmt" "github.com/grafana/grafana/pkg/api/dtos" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/dashboards" "github.com/grafana/grafana/pkg/services/guardian" "github.com/grafana/grafana/pkg/util" ) -func GetFolders(c *m.ReqContext) Response { +func GetFolders(c *models.ReqContext) Response { s := dashboards.NewFolderService(c.OrgId, c.SignedInUser) folders, err := s.GetFolders(c.QueryInt64("limit")) @@ -31,7 +31,7 @@ func GetFolders(c *m.ReqContext) Response { return JSON(200, result) } -func GetFolderByUID(c *m.ReqContext) Response { +func GetFolderByUID(c *models.ReqContext) Response { s := dashboards.NewFolderService(c.OrgId, c.SignedInUser) folder, err := s.GetFolderByUID(c.Params(":uid")) @@ -43,7 +43,7 @@ func GetFolderByUID(c *m.ReqContext) Response { return JSON(200, toFolderDto(g, folder)) } -func GetFolderByID(c *m.ReqContext) Response { +func GetFolderByID(c *models.ReqContext) Response { s := dashboards.NewFolderService(c.OrgId, c.SignedInUser) folder, err := s.GetFolderByID(c.ParamsInt64(":id")) if err != nil { @@ -54,7 +54,7 @@ func GetFolderByID(c *m.ReqContext) Response { return JSON(200, toFolderDto(g, folder)) } -func (hs *HTTPServer) CreateFolder(c *m.ReqContext, cmd m.CreateFolderCommand) Response { +func (hs *HTTPServer) CreateFolder(c *models.ReqContext, cmd models.CreateFolderCommand) Response { s := dashboards.NewFolderService(c.OrgId, c.SignedInUser) err := s.CreateFolder(&cmd) if err != nil { @@ -71,7 +71,7 @@ func (hs *HTTPServer) CreateFolder(c *m.ReqContext, cmd m.CreateFolderCommand) R return JSON(200, toFolderDto(g, cmd.Result)) } -func UpdateFolder(c *m.ReqContext, cmd m.UpdateFolderCommand) Response { +func UpdateFolder(c *models.ReqContext, cmd models.UpdateFolderCommand) Response { s := dashboards.NewFolderService(c.OrgId, c.SignedInUser) err := s.UpdateFolder(c.Params(":uid"), &cmd) if err != nil { @@ -82,7 +82,7 @@ func UpdateFolder(c *m.ReqContext, cmd m.UpdateFolderCommand) Response { return JSON(200, toFolderDto(g, cmd.Result)) } -func DeleteFolder(c *m.ReqContext) Response { +func DeleteFolder(c *models.ReqContext) Response { s := dashboards.NewFolderService(c.OrgId, c.SignedInUser) f, err := s.DeleteFolder(c.Params(":uid")) if err != nil { @@ -95,7 +95,7 @@ func DeleteFolder(c *m.ReqContext) Response { }) } -func toFolderDto(g guardian.DashboardGuardian, folder *m.Folder) dtos.Folder { +func toFolderDto(g guardian.DashboardGuardian, folder *models.Folder) dtos.Folder { canEdit, _ := g.CanEdit() canSave, _ := g.CanSave() canAdmin, _ := g.CanAdmin() @@ -127,25 +127,25 @@ func toFolderDto(g guardian.DashboardGuardian, folder *m.Folder) dtos.Folder { } func toFolderError(err error) Response { - if err == m.ErrFolderTitleEmpty || - err == m.ErrFolderSameNameExists || - err == m.ErrFolderWithSameUIDExists || - err == m.ErrDashboardTypeMismatch || - err == m.ErrDashboardInvalidUid || - err == m.ErrDashboardUidToLong { + if err == models.ErrFolderTitleEmpty || + err == models.ErrFolderSameNameExists || + err == models.ErrFolderWithSameUIDExists || + err == models.ErrDashboardTypeMismatch || + err == models.ErrDashboardInvalidUid || + err == models.ErrDashboardUidToLong { return Error(400, err.Error(), nil) } - if err == m.ErrFolderAccessDenied { + if err == models.ErrFolderAccessDenied { return Error(403, "Access denied", err) } - if err == m.ErrFolderNotFound { - return JSON(404, util.DynMap{"status": "not-found", "message": m.ErrFolderNotFound.Error()}) + if err == models.ErrFolderNotFound { + return JSON(404, util.DynMap{"status": "not-found", "message": models.ErrFolderNotFound.Error()}) } - if err == m.ErrFolderVersionMismatch { - return JSON(412, util.DynMap{"status": "version-mismatch", "message": m.ErrFolderVersionMismatch.Error()}) + if err == models.ErrFolderVersionMismatch { + return JSON(412, util.DynMap{"status": "version-mismatch", "message": models.ErrFolderVersionMismatch.Error()}) } return Error(500, "Folder API error", err) diff --git a/pkg/api/folder_permission.go b/pkg/api/folder_permission.go index d19ec848ab2..f8a8310ed26 100644 --- a/pkg/api/folder_permission.go +++ b/pkg/api/folder_permission.go @@ -5,12 +5,12 @@ import ( "github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/bus" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/dashboards" "github.com/grafana/grafana/pkg/services/guardian" ) -func GetFolderPermissionList(c *m.ReqContext) Response { +func GetFolderPermissionList(c *models.ReqContext) Response { s := dashboards.NewFolderService(c.OrgId, c.SignedInUser) folder, err := s.GetFolderByUID(c.Params(":uid")) @@ -21,7 +21,7 @@ func GetFolderPermissionList(c *m.ReqContext) Response { g := guardian.New(folder.Id, c.OrgId, c.SignedInUser) if canAdmin, err := g.CanAdmin(); err != nil || !canAdmin { - return toFolderError(m.ErrFolderAccessDenied) + return toFolderError(models.ErrFolderAccessDenied) } acl, err := g.GetAcl() @@ -40,14 +40,14 @@ func GetFolderPermissionList(c *m.ReqContext) Response { } if perm.Slug != "" { - perm.Url = m.GetDashboardFolderUrl(perm.IsFolder, perm.Uid, perm.Slug) + perm.Url = models.GetDashboardFolderUrl(perm.IsFolder, perm.Uid, perm.Slug) } } return JSON(200, acl) } -func UpdateFolderPermissions(c *m.ReqContext, apiCmd dtos.UpdateDashboardAclCommand) Response { +func UpdateFolderPermissions(c *models.ReqContext, apiCmd dtos.UpdateDashboardAclCommand) Response { s := dashboards.NewFolderService(c.OrgId, c.SignedInUser) folder, err := s.GetFolderByUID(c.Params(":uid")) @@ -62,14 +62,14 @@ func UpdateFolderPermissions(c *m.ReqContext, apiCmd dtos.UpdateDashboardAclComm } if !canAdmin { - return toFolderError(m.ErrFolderAccessDenied) + return toFolderError(models.ErrFolderAccessDenied) } - cmd := m.UpdateDashboardAclCommand{} + cmd := models.UpdateDashboardAclCommand{} cmd.DashboardId = folder.Id for _, item := range apiCmd.Items { - cmd.Items = append(cmd.Items, &m.DashboardAcl{ + cmd.Items = append(cmd.Items, &models.DashboardAcl{ OrgId: c.OrgId, DashboardId: folder.Id, UserId: item.UserId, @@ -81,7 +81,7 @@ func UpdateFolderPermissions(c *m.ReqContext, apiCmd dtos.UpdateDashboardAclComm }) } - if okToUpdate, err := g.CheckPermissionBeforeUpdate(m.PERMISSION_ADMIN, cmd.Items); err != nil || !okToUpdate { + if okToUpdate, err := g.CheckPermissionBeforeUpdate(models.PERMISSION_ADMIN, cmd.Items); err != nil || !okToUpdate { if err != nil { if err == guardian.ErrGuardianPermissionExists || err == guardian.ErrGuardianOverride { @@ -95,14 +95,14 @@ func UpdateFolderPermissions(c *m.ReqContext, apiCmd dtos.UpdateDashboardAclComm } if err := bus.Dispatch(&cmd); err != nil { - if err == m.ErrDashboardAclInfoMissing { - err = m.ErrFolderAclInfoMissing + if err == models.ErrDashboardAclInfoMissing { + err = models.ErrFolderAclInfoMissing } - if err == m.ErrDashboardPermissionDashboardEmpty { - err = m.ErrFolderPermissionFolderEmpty + if err == models.ErrDashboardPermissionDashboardEmpty { + err = models.ErrFolderPermissionFolderEmpty } - if err == m.ErrFolderAclInfoMissing || err == m.ErrFolderPermissionFolderEmpty { + if err == models.ErrFolderAclInfoMissing || err == models.ErrFolderPermissionFolderEmpty { return Error(409, err.Error(), err) } diff --git a/pkg/api/folder_permission_test.go b/pkg/api/folder_permission_test.go index 64a746ca937..25e848552b5 100644 --- a/pkg/api/folder_permission_test.go +++ b/pkg/api/folder_permission_test.go @@ -6,7 +6,7 @@ import ( "github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/simplejson" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/dashboards" "github.com/grafana/grafana/pkg/services/guardian" @@ -17,20 +17,20 @@ func TestFolderPermissionApiEndpoint(t *testing.T) { Convey("Folder permissions test", t, func() { Convey("Given folder not exists", func() { mock := &fakeFolderService{ - GetFolderByUIDError: m.ErrFolderNotFound, + GetFolderByUIDError: models.ErrFolderNotFound, } origNewFolderService := dashboards.NewFolderService mockFolderService(mock) - loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/folders/uid/permissions", "/api/folders/:uid/permissions", m.ROLE_EDITOR, func(sc *scenarioContext) { + loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/folders/uid/permissions", "/api/folders/:uid/permissions", models.ROLE_EDITOR, func(sc *scenarioContext) { callGetFolderPermissions(sc) So(sc.resp.Code, ShouldEqual, 404) }) cmd := dtos.UpdateDashboardAclCommand{ Items: []dtos.DashboardAclUpdateItem{ - {UserId: 1000, Permission: m.PERMISSION_ADMIN}, + {UserId: 1000, Permission: models.PERMISSION_ADMIN}, }, } @@ -49,7 +49,7 @@ func TestFolderPermissionApiEndpoint(t *testing.T) { guardian.MockDashboardGuardian(&guardian.FakeDashboardGuardian{CanAdminValue: false}) mock := &fakeFolderService{ - GetFolderByUIDResult: &m.Folder{ + GetFolderByUIDResult: &models.Folder{ Id: 1, Uid: "uid", Title: "Folder", @@ -59,14 +59,14 @@ func TestFolderPermissionApiEndpoint(t *testing.T) { origNewFolderService := dashboards.NewFolderService mockFolderService(mock) - loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/folders/uid/permissions", "/api/folders/:uid/permissions", m.ROLE_EDITOR, func(sc *scenarioContext) { + loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/folders/uid/permissions", "/api/folders/:uid/permissions", models.ROLE_EDITOR, func(sc *scenarioContext) { callGetFolderPermissions(sc) So(sc.resp.Code, ShouldEqual, 403) }) cmd := dtos.UpdateDashboardAclCommand{ Items: []dtos.DashboardAclUpdateItem{ - {UserId: 1000, Permission: m.PERMISSION_ADMIN}, + {UserId: 1000, Permission: models.PERMISSION_ADMIN}, }, } @@ -86,17 +86,17 @@ func TestFolderPermissionApiEndpoint(t *testing.T) { guardian.MockDashboardGuardian(&guardian.FakeDashboardGuardian{ CanAdminValue: true, CheckPermissionBeforeUpdateValue: true, - GetAclValue: []*m.DashboardAclInfoDTO{ - {OrgId: 1, DashboardId: 1, UserId: 2, Permission: m.PERMISSION_VIEW}, - {OrgId: 1, DashboardId: 1, UserId: 3, Permission: m.PERMISSION_EDIT}, - {OrgId: 1, DashboardId: 1, UserId: 4, Permission: m.PERMISSION_ADMIN}, - {OrgId: 1, DashboardId: 1, TeamId: 1, Permission: m.PERMISSION_VIEW}, - {OrgId: 1, DashboardId: 1, TeamId: 2, Permission: m.PERMISSION_ADMIN}, + GetAclValue: []*models.DashboardAclInfoDTO{ + {OrgId: 1, DashboardId: 1, UserId: 2, Permission: models.PERMISSION_VIEW}, + {OrgId: 1, DashboardId: 1, UserId: 3, Permission: models.PERMISSION_EDIT}, + {OrgId: 1, DashboardId: 1, UserId: 4, Permission: models.PERMISSION_ADMIN}, + {OrgId: 1, DashboardId: 1, TeamId: 1, Permission: models.PERMISSION_VIEW}, + {OrgId: 1, DashboardId: 1, TeamId: 2, Permission: models.PERMISSION_ADMIN}, }, }) mock := &fakeFolderService{ - GetFolderByUIDResult: &m.Folder{ + GetFolderByUIDResult: &models.Folder{ Id: 1, Uid: "uid", Title: "Folder", @@ -106,19 +106,19 @@ func TestFolderPermissionApiEndpoint(t *testing.T) { origNewFolderService := dashboards.NewFolderService mockFolderService(mock) - loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/folders/uid/permissions", "/api/folders/:uid/permissions", m.ROLE_ADMIN, func(sc *scenarioContext) { + loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/folders/uid/permissions", "/api/folders/:uid/permissions", models.ROLE_ADMIN, func(sc *scenarioContext) { callGetFolderPermissions(sc) So(sc.resp.Code, ShouldEqual, 200) respJSON, err := simplejson.NewJson(sc.resp.Body.Bytes()) So(err, ShouldBeNil) So(len(respJSON.MustArray()), ShouldEqual, 5) So(respJSON.GetIndex(0).Get("userId").MustInt(), ShouldEqual, 2) - So(respJSON.GetIndex(0).Get("permission").MustInt(), ShouldEqual, m.PERMISSION_VIEW) + So(respJSON.GetIndex(0).Get("permission").MustInt(), ShouldEqual, models.PERMISSION_VIEW) }) cmd := dtos.UpdateDashboardAclCommand{ Items: []dtos.DashboardAclUpdateItem{ - {UserId: 1000, Permission: m.PERMISSION_ADMIN}, + {UserId: 1000, Permission: models.PERMISSION_ADMIN}, }, } @@ -142,7 +142,7 @@ func TestFolderPermissionApiEndpoint(t *testing.T) { }) mock := &fakeFolderService{ - GetFolderByUIDResult: &m.Folder{ + GetFolderByUIDResult: &models.Folder{ Id: 1, Uid: "uid", Title: "Folder", @@ -154,7 +154,7 @@ func TestFolderPermissionApiEndpoint(t *testing.T) { cmd := dtos.UpdateDashboardAclCommand{ Items: []dtos.DashboardAclUpdateItem{ - {UserId: 1000, Permission: m.PERMISSION_ADMIN}, + {UserId: 1000, Permission: models.PERMISSION_ADMIN}, }, } @@ -178,7 +178,7 @@ func TestFolderPermissionApiEndpoint(t *testing.T) { ) mock := &fakeFolderService{ - GetFolderByUIDResult: &m.Folder{ + GetFolderByUIDResult: &models.Folder{ Id: 1, Uid: "uid", Title: "Folder", @@ -190,7 +190,7 @@ func TestFolderPermissionApiEndpoint(t *testing.T) { cmd := dtos.UpdateDashboardAclCommand{ Items: []dtos.DashboardAclUpdateItem{ - {UserId: 1000, Permission: m.PERMISSION_ADMIN}, + {UserId: 1000, Permission: models.PERMISSION_ADMIN}, }, } @@ -213,7 +213,7 @@ func callGetFolderPermissions(sc *scenarioContext) { } func callUpdateFolderPermissions(sc *scenarioContext) { - bus.AddHandler("test", func(cmd *m.UpdateDashboardAclCommand) error { + bus.AddHandler("test", func(cmd *models.UpdateDashboardAclCommand) error { return nil }) @@ -226,7 +226,7 @@ func updateFolderPermissionScenario(desc string, url string, routePattern string sc := setupScenarioContext(url) - sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { + sc.defaultHandler = Wrap(func(c *models.ReqContext) Response { sc.context = c sc.context.OrgId = TestOrgID sc.context.UserId = TestUserID diff --git a/pkg/api/folder_test.go b/pkg/api/folder_test.go index f96e107b968..af1dd8f94e6 100644 --- a/pkg/api/folder_test.go +++ b/pkg/api/folder_test.go @@ -7,7 +7,7 @@ import ( "github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/bus" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/dashboards" "github.com/grafana/grafana/pkg/setting" @@ -17,13 +17,13 @@ import ( func TestFoldersApiEndpoint(t *testing.T) { Convey("Create/update folder response tests", t, func() { Convey("Given a correct request for creating a folder", func() { - cmd := m.CreateFolderCommand{ + cmd := models.CreateFolderCommand{ Uid: "uid", Title: "Folder", } mock := &fakeFolderService{ - CreateFolderResult: &m.Folder{Id: 1, Uid: "uid", Title: "Folder"}, + CreateFolderResult: &models.Folder{Id: 1, Uid: "uid", Title: "Folder"}, } createFolderScenario("When calling POST on", "/api/folders", "/api/folders", mock, cmd, func(sc *scenarioContext) { @@ -45,18 +45,18 @@ func TestFoldersApiEndpoint(t *testing.T) { Error error ExpectedStatusCode int }{ - {Error: m.ErrFolderWithSameUIDExists, ExpectedStatusCode: 400}, - {Error: m.ErrFolderTitleEmpty, ExpectedStatusCode: 400}, - {Error: m.ErrFolderSameNameExists, ExpectedStatusCode: 400}, - {Error: m.ErrDashboardInvalidUid, ExpectedStatusCode: 400}, - {Error: m.ErrDashboardUidToLong, ExpectedStatusCode: 400}, - {Error: m.ErrFolderAccessDenied, ExpectedStatusCode: 403}, - {Error: m.ErrFolderNotFound, ExpectedStatusCode: 404}, - {Error: m.ErrFolderVersionMismatch, ExpectedStatusCode: 412}, - {Error: m.ErrFolderFailedGenerateUniqueUid, ExpectedStatusCode: 500}, + {Error: models.ErrFolderWithSameUIDExists, ExpectedStatusCode: 400}, + {Error: models.ErrFolderTitleEmpty, ExpectedStatusCode: 400}, + {Error: models.ErrFolderSameNameExists, ExpectedStatusCode: 400}, + {Error: models.ErrDashboardInvalidUid, ExpectedStatusCode: 400}, + {Error: models.ErrDashboardUidToLong, ExpectedStatusCode: 400}, + {Error: models.ErrFolderAccessDenied, ExpectedStatusCode: 403}, + {Error: models.ErrFolderNotFound, ExpectedStatusCode: 404}, + {Error: models.ErrFolderVersionMismatch, ExpectedStatusCode: 412}, + {Error: models.ErrFolderFailedGenerateUniqueUid, ExpectedStatusCode: 500}, } - cmd := m.CreateFolderCommand{ + cmd := models.CreateFolderCommand{ Uid: "uid", Title: "Folder", } @@ -76,12 +76,12 @@ func TestFoldersApiEndpoint(t *testing.T) { }) Convey("Given a correct request for updating a folder", func() { - cmd := m.UpdateFolderCommand{ + cmd := models.UpdateFolderCommand{ Title: "Folder upd", } mock := &fakeFolderService{ - UpdateFolderResult: &m.Folder{Id: 1, Uid: "uid", Title: "Folder upd"}, + UpdateFolderResult: &models.Folder{Id: 1, Uid: "uid", Title: "Folder upd"}, } updateFolderScenario("When calling PUT on", "/api/folders/uid", "/api/folders/:uid", mock, cmd, func(sc *scenarioContext) { @@ -103,18 +103,18 @@ func TestFoldersApiEndpoint(t *testing.T) { Error error ExpectedStatusCode int }{ - {Error: m.ErrFolderWithSameUIDExists, ExpectedStatusCode: 400}, - {Error: m.ErrFolderTitleEmpty, ExpectedStatusCode: 400}, - {Error: m.ErrFolderSameNameExists, ExpectedStatusCode: 400}, - {Error: m.ErrDashboardInvalidUid, ExpectedStatusCode: 400}, - {Error: m.ErrDashboardUidToLong, ExpectedStatusCode: 400}, - {Error: m.ErrFolderAccessDenied, ExpectedStatusCode: 403}, - {Error: m.ErrFolderNotFound, ExpectedStatusCode: 404}, - {Error: m.ErrFolderVersionMismatch, ExpectedStatusCode: 412}, - {Error: m.ErrFolderFailedGenerateUniqueUid, ExpectedStatusCode: 500}, + {Error: models.ErrFolderWithSameUIDExists, ExpectedStatusCode: 400}, + {Error: models.ErrFolderTitleEmpty, ExpectedStatusCode: 400}, + {Error: models.ErrFolderSameNameExists, ExpectedStatusCode: 400}, + {Error: models.ErrDashboardInvalidUid, ExpectedStatusCode: 400}, + {Error: models.ErrDashboardUidToLong, ExpectedStatusCode: 400}, + {Error: models.ErrFolderAccessDenied, ExpectedStatusCode: 403}, + {Error: models.ErrFolderNotFound, ExpectedStatusCode: 404}, + {Error: models.ErrFolderVersionMismatch, ExpectedStatusCode: 412}, + {Error: models.ErrFolderFailedGenerateUniqueUid, ExpectedStatusCode: 500}, } - cmd := m.UpdateFolderCommand{ + cmd := models.UpdateFolderCommand{ Title: "Folder upd", } @@ -138,7 +138,7 @@ func callCreateFolder(sc *scenarioContext) { sc.fakeReqWithParams("POST", sc.url, map[string]string{}).exec() } -func createFolderScenario(desc string, url string, routePattern string, mock *fakeFolderService, cmd m.CreateFolderCommand, fn scenarioFunc) { +func createFolderScenario(desc string, url string, routePattern string, mock *fakeFolderService, cmd models.CreateFolderCommand, fn scenarioFunc) { Convey(desc+" "+url, func() { defer bus.ClearBusHandlers() @@ -148,9 +148,9 @@ func createFolderScenario(desc string, url string, routePattern string, mock *fa } sc := setupScenarioContext(url) - sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { + sc.defaultHandler = Wrap(func(c *models.ReqContext) Response { sc.context = c - sc.context.SignedInUser = &m.SignedInUser{OrgId: TestOrgID, UserId: TestUserID} + sc.context.SignedInUser = &models.SignedInUser{OrgId: TestOrgID, UserId: TestUserID} return hs.CreateFolder(c, cmd) }) @@ -172,14 +172,14 @@ func callUpdateFolder(sc *scenarioContext) { sc.fakeReqWithParams("PUT", sc.url, map[string]string{}).exec() } -func updateFolderScenario(desc string, url string, routePattern string, mock *fakeFolderService, cmd m.UpdateFolderCommand, fn scenarioFunc) { +func updateFolderScenario(desc string, url string, routePattern string, mock *fakeFolderService, cmd models.UpdateFolderCommand, fn scenarioFunc) { Convey(desc+" "+url, func() { defer bus.ClearBusHandlers() sc := setupScenarioContext(url) - sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { + sc.defaultHandler = Wrap(func(c *models.ReqContext) Response { sc.context = c - sc.context.SignedInUser = &m.SignedInUser{OrgId: TestOrgID, UserId: TestUserID} + sc.context.SignedInUser = &models.SignedInUser{OrgId: TestOrgID, UserId: TestUserID} return UpdateFolder(c, cmd) }) @@ -198,50 +198,50 @@ func updateFolderScenario(desc string, url string, routePattern string, mock *fa } type fakeFolderService struct { - GetFoldersResult []*m.Folder + GetFoldersResult []*models.Folder GetFoldersError error - GetFolderByUIDResult *m.Folder + GetFolderByUIDResult *models.Folder GetFolderByUIDError error - GetFolderByIDResult *m.Folder + GetFolderByIDResult *models.Folder GetFolderByIDError error - CreateFolderResult *m.Folder + CreateFolderResult *models.Folder CreateFolderError error - UpdateFolderResult *m.Folder + UpdateFolderResult *models.Folder UpdateFolderError error - DeleteFolderResult *m.Folder + DeleteFolderResult *models.Folder DeleteFolderError error DeletedFolderUids []string } -func (s *fakeFolderService) GetFolders(limit int64) ([]*m.Folder, error) { +func (s *fakeFolderService) GetFolders(limit int64) ([]*models.Folder, error) { return s.GetFoldersResult, s.GetFoldersError } -func (s *fakeFolderService) GetFolderByID(id int64) (*m.Folder, error) { +func (s *fakeFolderService) GetFolderByID(id int64) (*models.Folder, error) { return s.GetFolderByIDResult, s.GetFolderByIDError } -func (s *fakeFolderService) GetFolderByUID(uid string) (*m.Folder, error) { +func (s *fakeFolderService) GetFolderByUID(uid string) (*models.Folder, error) { return s.GetFolderByUIDResult, s.GetFolderByUIDError } -func (s *fakeFolderService) CreateFolder(cmd *m.CreateFolderCommand) error { +func (s *fakeFolderService) CreateFolder(cmd *models.CreateFolderCommand) error { cmd.Result = s.CreateFolderResult return s.CreateFolderError } -func (s *fakeFolderService) UpdateFolder(existingUID string, cmd *m.UpdateFolderCommand) error { +func (s *fakeFolderService) UpdateFolder(existingUID string, cmd *models.UpdateFolderCommand) error { cmd.Result = s.UpdateFolderResult return s.UpdateFolderError } -func (s *fakeFolderService) DeleteFolder(uid string) (*m.Folder, error) { +func (s *fakeFolderService) DeleteFolder(uid string) (*models.Folder, error) { s.DeletedFolderUids = append(s.DeletedFolderUids, uid) return s.DeleteFolderResult, s.DeleteFolderError } func mockFolderService(mock *fakeFolderService) { - dashboards.NewFolderService = func(orgId int64, user *m.SignedInUser) dashboards.FolderService { + dashboards.NewFolderService = func(orgId int64, user *models.SignedInUser) dashboards.FolderService { return mock } } diff --git a/pkg/api/frontendsettings.go b/pkg/api/frontendsettings.go index 0a74d8de0bc..19d3f833841 100644 --- a/pkg/api/frontendsettings.go +++ b/pkg/api/frontendsettings.go @@ -3,6 +3,7 @@ package api import ( "strconv" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/rendering" "github.com/grafana/grafana/pkg/components/simplejson" @@ -10,24 +11,23 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/infra/log" - m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/plugins" "github.com/grafana/grafana/pkg/setting" ) // getFrontendSettingsMap returns a json object with all the settings needed for front end initialisation. -func (hs *HTTPServer) getFrontendSettingsMap(c *m.ReqContext) (map[string]interface{}, error) { - orgDataSources := make([]*m.DataSource, 0) +func (hs *HTTPServer) getFrontendSettingsMap(c *models.ReqContext) (map[string]interface{}, error) { + orgDataSources := make([]*models.DataSource, 0) if c.OrgId != 0 { - query := m.GetDataSourcesQuery{OrgId: c.OrgId} + query := models.GetDataSourcesQuery{OrgId: c.OrgId} err := bus.Dispatch(&query) if err != nil { return nil, err } - dsFilterQuery := m.DatasourcesPermissionFilterQuery{ + dsFilterQuery := models.DatasourcesPermissionFilterQuery{ User: c.SignedInUser, Datasources: query.Result, } @@ -62,7 +62,7 @@ func (hs *HTTPServer) getFrontendSettingsMap(c *m.ReqContext) (map[string]interf for _, ds := range orgDataSources { url := ds.Url - if ds.Access == m.DS_ACCESS_PROXY { + if ds.Access == models.DS_ACCESS_PROXY { url = "/api/datasources/proxy/" + strconv.FormatInt(ds.Id, 10) } @@ -96,7 +96,7 @@ func (hs *HTTPServer) getFrontendSettingsMap(c *m.ReqContext) (map[string]interf dsMap["jsonData"] = jsonData - if ds.Access == m.DS_ACCESS_DIRECT { + if ds.Access == models.DS_ACCESS_DIRECT { if ds.BasicAuth { dsMap["basicAuth"] = util.GetBasicAuthHeader(ds.BasicAuthUser, ds.DecryptedBasicAuthPassword()) } @@ -104,24 +104,24 @@ func (hs *HTTPServer) getFrontendSettingsMap(c *m.ReqContext) (map[string]interf dsMap["withCredentials"] = ds.WithCredentials } - if ds.Type == m.DS_INFLUXDB_08 { + if ds.Type == models.DS_INFLUXDB_08 { dsMap["username"] = ds.User dsMap["password"] = ds.DecryptedPassword() dsMap["url"] = url + "/db/" + ds.Database } - if ds.Type == m.DS_INFLUXDB { + if ds.Type == models.DS_INFLUXDB { dsMap["username"] = ds.User dsMap["password"] = ds.DecryptedPassword() dsMap["url"] = url } } - if (ds.Type == m.DS_INFLUXDB) || (ds.Type == m.DS_ES) { + if (ds.Type == models.DS_INFLUXDB) || (ds.Type == models.DS_ES) { dsMap["database"] = ds.Database } - if ds.Type == m.DS_PROMETHEUS { + if ds.Type == models.DS_PROMETHEUS { // add unproxied server URL for link to Prometheus web UI jsonData.Set("directUrl", ds.Url) } @@ -247,7 +247,7 @@ func getPanelSort(id string) int { return sort } -func (hs *HTTPServer) GetFrontendSettings(c *m.ReqContext) { +func (hs *HTTPServer) GetFrontendSettings(c *models.ReqContext) { settings, err := hs.getFrontendSettingsMap(c) if err != nil { c.JsonApiErr(400, "Failed to get frontend settings", err) diff --git a/pkg/api/grafana_com_proxy.go b/pkg/api/grafana_com_proxy.go index 2a7a5427c7a..2c0e258df63 100644 --- a/pkg/api/grafana_com_proxy.go +++ b/pkg/api/grafana_com_proxy.go @@ -7,7 +7,7 @@ import ( "net/url" "time" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/util" ) @@ -40,7 +40,7 @@ func ReverseProxyGnetReq(proxyPath string) *httputil.ReverseProxy { return &httputil.ReverseProxy{Director: director} } -func ProxyGnetRequest(c *m.ReqContext) { +func ProxyGnetRequest(c *models.ReqContext) { proxyPath := c.Params("*") proxy := ReverseProxyGnetReq(proxyPath) proxy.Transport = grafanaComProxyTransport diff --git a/pkg/api/index.go b/pkg/api/index.go index b6537510768..49b67bbd7e0 100644 --- a/pkg/api/index.go +++ b/pkg/api/index.go @@ -7,7 +7,7 @@ import ( "github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/bus" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/plugins" "github.com/grafana/grafana/pkg/setting" ) @@ -18,13 +18,13 @@ const ( darkName = "dark" ) -func (hs *HTTPServer) setIndexViewData(c *m.ReqContext) (*dtos.IndexViewData, error) { +func (hs *HTTPServer) setIndexViewData(c *models.ReqContext) (*dtos.IndexViewData, error) { settings, err := hs.getFrontendSettingsMap(c) if err != nil { return nil, err } - prefsQuery := m.GetPreferencesWithDefaultsQuery{User: c.SignedInUser} + prefsQuery := models.GetPreferencesWithDefaultsQuery{User: c.SignedInUser} if err := bus.Dispatch(&prefsQuery); err != nil { return nil, err } @@ -49,7 +49,7 @@ func (hs *HTTPServer) setIndexViewData(c *m.ReqContext) (*dtos.IndexViewData, er settings["appSubUrl"] = "" } - hasEditPermissionInFoldersQuery := m.HasEditPermissionInFoldersQuery{SignedInUser: c.SignedInUser} + hasEditPermissionInFoldersQuery := models.HasEditPermissionInFoldersQuery{SignedInUser: c.SignedInUser} if err := bus.Dispatch(&hasEditPermissionInFoldersQuery); err != nil { return nil, err } @@ -112,7 +112,7 @@ func (hs *HTTPServer) setIndexViewData(c *m.ReqContext) (*dtos.IndexViewData, er {Text: "Dashboard", Icon: "gicon gicon-dashboard-new", Url: setting.AppSubUrl + "/dashboard/new"}, } - if c.OrgRole == m.ROLE_ADMIN || c.OrgRole == m.ROLE_EDITOR { + if c.OrgRole == models.ROLE_ADMIN || c.OrgRole == models.ROLE_EDITOR { children = append(children, &dtos.NavLink{Text: "Folder", SubTitle: "Create a new folder to organize your dashboards", Id: "folder", Icon: "gicon gicon-folder-new", Url: setting.AppSubUrl + "/dashboards/folder/new"}) } @@ -146,7 +146,7 @@ func (hs *HTTPServer) setIndexViewData(c *m.ReqContext) (*dtos.IndexViewData, er Children: dashboardChildNavs, }) - if setting.ExploreEnabled && (c.OrgRole == m.ROLE_ADMIN || c.OrgRole == m.ROLE_EDITOR || setting.ViewersCanEdit) { + if setting.ExploreEnabled && (c.OrgRole == models.ROLE_ADMIN || c.OrgRole == models.ROLE_EDITOR || setting.ViewersCanEdit) { data.NavTree = append(data.NavTree, &dtos.NavLink{ Text: "Explore", Id: "explore", @@ -192,7 +192,7 @@ func (hs *HTTPServer) setIndexViewData(c *m.ReqContext) (*dtos.IndexViewData, er data.NavTree = append(data.NavTree, profileNode) } - if setting.AlertingEnabled && (c.OrgRole == m.ROLE_ADMIN || c.OrgRole == m.ROLE_EDITOR) { + if setting.AlertingEnabled && (c.OrgRole == models.ROLE_ADMIN || c.OrgRole == models.ROLE_EDITOR) { alertChildNavs := []*dtos.NavLink{ {Text: "Alert Rules", Id: "alert-list", Url: setting.AppSubUrl + "/alerting/list", Icon: "gicon gicon-alert-rules"}, {Text: "Notification channels", Id: "channels", Url: setting.AppSubUrl + "/alerting/notifications", Icon: "gicon gicon-alert-notification-channel"}, @@ -257,7 +257,7 @@ func (hs *HTTPServer) setIndexViewData(c *m.ReqContext) (*dtos.IndexViewData, er } } - if len(appLink.Children) > 0 && c.OrgRole == m.ROLE_ADMIN { + if len(appLink.Children) > 0 && c.OrgRole == models.ROLE_ADMIN { appLink.Children = append(appLink.Children, &dtos.NavLink{Divider: true}) appLink.Children = append(appLink.Children, &dtos.NavLink{Text: "Plugin Config", Icon: "gicon gicon-cog", Url: setting.AppSubUrl + "/plugins/" + plugin.Id + "/"}) } @@ -270,7 +270,7 @@ func (hs *HTTPServer) setIndexViewData(c *m.ReqContext) (*dtos.IndexViewData, er configNodes := []*dtos.NavLink{} - if c.OrgRole == m.ROLE_ADMIN { + if c.OrgRole == models.ROLE_ADMIN { configNodes = append(configNodes, &dtos.NavLink{ Text: "Data Sources", Icon: "gicon gicon-datasources", @@ -287,7 +287,7 @@ func (hs *HTTPServer) setIndexViewData(c *m.ReqContext) (*dtos.IndexViewData, er }) } - if c.OrgRole == m.ROLE_ADMIN || (hs.Cfg.EditorsCanAdmin && c.OrgRole == m.ROLE_EDITOR) { + if c.OrgRole == models.ROLE_ADMIN || (hs.Cfg.EditorsCanAdmin && c.OrgRole == models.ROLE_EDITOR) { configNodes = append(configNodes, &dtos.NavLink{ Text: "Teams", Id: "teams", @@ -305,7 +305,7 @@ func (hs *HTTPServer) setIndexViewData(c *m.ReqContext) (*dtos.IndexViewData, er Url: setting.AppSubUrl + "/plugins", }) - if c.OrgRole == m.ROLE_ADMIN { + if c.OrgRole == models.ROLE_ADMIN { configNodes = append(configNodes, &dtos.NavLink{ Text: "Preferences", Id: "org-settings", @@ -377,7 +377,7 @@ func (hs *HTTPServer) setIndexViewData(c *m.ReqContext) (*dtos.IndexViewData, er return &data, nil } -func (hs *HTTPServer) Index(c *m.ReqContext) { +func (hs *HTTPServer) Index(c *models.ReqContext) { data, err := hs.setIndexViewData(c) if err != nil { c.Handle(500, "Failed to get settings", err) @@ -386,7 +386,7 @@ func (hs *HTTPServer) Index(c *m.ReqContext) { c.HTML(200, "index", data) } -func (hs *HTTPServer) NotFoundHandler(c *m.ReqContext) { +func (hs *HTTPServer) NotFoundHandler(c *models.ReqContext) { if c.IsApiRequest() { c.JsonApiErr(404, "Not found", nil) return diff --git a/pkg/api/live/stream_manager.go b/pkg/api/live/stream_manager.go index d7c7dc43a51..60354981089 100644 --- a/pkg/api/live/stream_manager.go +++ b/pkg/api/live/stream_manager.go @@ -7,7 +7,7 @@ import ( "github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/infra/log" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" ) type StreamManager struct { @@ -51,11 +51,11 @@ func (sm *StreamManager) Serve(w http.ResponseWriter, r *http.Request) { c.readPump() } -func (s *StreamManager) GetStreamList() m.StreamList { - list := make(m.StreamList, 0) +func (s *StreamManager) GetStreamList() models.StreamList { + list := make(models.StreamList, 0) for _, stream := range s.streams { - list = append(list, &m.StreamInfo{ + list = append(list, &models.StreamInfo{ Name: stream.name, }) } @@ -63,7 +63,7 @@ func (s *StreamManager) GetStreamList() m.StreamList { return list } -func (s *StreamManager) Push(packet *m.StreamPacket) { +func (s *StreamManager) Push(packet *models.StreamPacket) { stream, exist := s.streams[packet.Stream] if !exist { @@ -87,7 +87,7 @@ func NewStream(name string) *Stream { } } -func (s *Stream) Push(packet *m.StreamPacket) { +func (s *Stream) Push(packet *models.StreamPacket) { messageBytes, _ := simplejson.NewFromAny(packet).Encode() diff --git a/pkg/api/login_oauth.go b/pkg/api/login_oauth.go index db6c696b2ab..5aae3a78220 100644 --- a/pkg/api/login_oauth.go +++ b/pkg/api/login_oauth.go @@ -21,7 +21,7 @@ import ( "github.com/grafana/grafana/pkg/login" "github.com/grafana/grafana/pkg/login/social" "github.com/grafana/grafana/pkg/middleware" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/setting" ) @@ -39,7 +39,7 @@ func GenStateString() (string, error) { return base64.URLEncoding.EncodeToString(rnd), nil } -func (hs *HTTPServer) OAuthLogin(ctx *m.ReqContext) { +func (hs *HTTPServer) OAuthLogin(ctx *models.ReqContext) { if setting.OAuthService == nil { ctx.Handle(404, "OAuth not enabled", nil) return @@ -172,19 +172,19 @@ func (hs *HTTPServer) OAuthLogin(ctx *m.ReqContext) { return } - extUser := &m.ExternalUserInfo{ + extUser := &models.ExternalUserInfo{ AuthModule: "oauth_" + name, OAuthToken: token, AuthId: userInfo.Id, Name: userInfo.Name, Login: userInfo.Login, Email: userInfo.Email, - OrgRoles: map[int64]m.RoleType{}, + OrgRoles: map[int64]models.RoleType{}, Groups: userInfo.Groups, } if userInfo.Role != "" { - rt := m.RoleType(userInfo.Role) + rt := models.RoleType(userInfo.Role) if rt.IsValid() { var orgID int64 if setting.AutoAssignOrg && setting.AutoAssignOrgId > 0 { @@ -197,7 +197,7 @@ func (hs *HTTPServer) OAuthLogin(ctx *m.ReqContext) { } // add/update user in grafana - cmd := &m.UpsertUserCommand{ + cmd := &models.UpsertUserCommand{ ReqContext: ctx, ExternalUser: extUser, SignupAllowed: connect.IsSignupAllowed(), @@ -236,7 +236,7 @@ func hashStatecode(code, seed string) string { return hex.EncodeToString(hashBytes[:]) } -func (hs *HTTPServer) redirectWithError(ctx *m.ReqContext, err error, v ...interface{}) { +func (hs *HTTPServer) redirectWithError(ctx *models.ReqContext, err error, v ...interface{}) { ctx.Logger.Error(err.Error(), v...) if err := hs.trySetEncryptedCookie(ctx, LoginErrorCookieName, err.Error(), 60); err != nil { oauthLogger.Error("Failed to set encrypted cookie", "err", err) diff --git a/pkg/api/metrics.go b/pkg/api/metrics.go index a0ca62cfc23..4f4edda2f2a 100644 --- a/pkg/api/metrics.go +++ b/pkg/api/metrics.go @@ -4,20 +4,20 @@ import ( "context" "sort" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/plugins" "github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/simplejson" - m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/tsdb" "github.com/grafana/grafana/pkg/tsdb/testdatasource" "github.com/grafana/grafana/pkg/util" ) // POST /api/ds/query DataSource query w/ expressions -func (hs *HTTPServer) QueryMetricsV2(c *m.ReqContext, reqDto dtos.MetricRequest) Response { +func (hs *HTTPServer) QueryMetricsV2(c *models.ReqContext, reqDto dtos.MetricRequest) Response { if !setting.IsExpressionsEnabled() { return Error(404, "Expressions feature toggle is not enabled", nil) } @@ -32,7 +32,7 @@ func (hs *HTTPServer) QueryMetricsV2(c *m.ReqContext, reqDto dtos.MetricRequest) } expr := false - var ds *m.DataSource + var ds *models.DataSource for i, query := range reqDto.Queries { name, err := query.Get("datasource").String() if err != nil { @@ -50,12 +50,13 @@ func (hs *HTTPServer) QueryMetricsV2(c *m.ReqContext, reqDto dtos.MetricRequest) if i == 0 && !expr { ds, err = hs.DatasourceCache.GetDatasource(datasourceID, c.SignedInUser, c.SkipCache) if err != nil { - if err == m.ErrDataSourceAccessDenied { + if err == models.ErrDataSourceAccessDenied { return Error(403, "Access denied to datasource", err) } return Error(500, "Unable to load datasource meta data", err) } } + request.Queries = append(request.Queries, &tsdb.Query{ RefId: query.Get("refId").MustString("A"), MaxDataPoints: query.Get("maxDataPoints").MustInt64(100), @@ -63,7 +64,6 @@ func (hs *HTTPServer) QueryMetricsV2(c *m.ReqContext, reqDto dtos.MetricRequest) Model: query, DataSource: ds, }) - } var resp *tsdb.Response @@ -93,7 +93,7 @@ func (hs *HTTPServer) QueryMetricsV2(c *m.ReqContext, reqDto dtos.MetricRequest) } // POST /api/tsdb/query -func (hs *HTTPServer) QueryMetrics(c *m.ReqContext, reqDto dtos.MetricRequest) Response { +func (hs *HTTPServer) QueryMetrics(c *models.ReqContext, reqDto dtos.MetricRequest) Response { timeRange := tsdb.NewTimeRange(reqDto.From, reqDto.To) if len(reqDto.Queries) == 0 { @@ -107,7 +107,7 @@ func (hs *HTTPServer) QueryMetrics(c *m.ReqContext, reqDto dtos.MetricRequest) R ds, err := hs.DatasourceCache.GetDatasource(datasourceId, c.SignedInUser, c.SkipCache) if err != nil { - if err == m.ErrDataSourceAccessDenied { + if err == models.ErrDataSourceAccessDenied { return Error(403, "Access denied to datasource", err) } return Error(500, "Unable to load datasource meta data", err) @@ -143,7 +143,7 @@ func (hs *HTTPServer) QueryMetrics(c *m.ReqContext, reqDto dtos.MetricRequest) R } // GET /api/tsdb/testdata/scenarios -func GetTestDataScenarios(c *m.ReqContext) Response { +func GetTestDataScenarios(c *models.ReqContext) Response { result := make([]interface{}, 0) scenarioIds := make([]string, 0) @@ -166,15 +166,15 @@ func GetTestDataScenarios(c *m.ReqContext) Response { } // Generates a index out of range error -func GenerateError(c *m.ReqContext) Response { +func GenerateError(c *models.ReqContext) Response { var array []string // nolint: govet return JSON(200, array[20]) } // GET /api/tsdb/testdata/gensql -func GenerateSQLTestData(c *m.ReqContext) Response { - if err := bus.Dispatch(&m.InsertSqlTestDataCommand{}); err != nil { +func GenerateSQLTestData(c *models.ReqContext) Response { + if err := bus.Dispatch(&models.InsertSqlTestDataCommand{}); err != nil { return Error(500, "Failed to insert test data", err) } @@ -182,7 +182,7 @@ func GenerateSQLTestData(c *m.ReqContext) Response { } // GET /api/tsdb/testdata/random-walk -func GetTestDataRandomWalk(c *m.ReqContext) Response { +func GetTestDataRandomWalk(c *models.ReqContext) Response { from := c.Query("from") to := c.Query("to") intervalMs := c.QueryInt64("intervalMs") @@ -190,7 +190,7 @@ func GetTestDataRandomWalk(c *m.ReqContext) Response { timeRange := tsdb.NewTimeRange(from, to) request := &tsdb.TsdbQuery{TimeRange: timeRange} - dsInfo := &m.DataSource{Type: "testdata"} + dsInfo := &models.DataSource{Type: "testdata"} request.Queries = append(request.Queries, &tsdb.Query{ RefId: "A", IntervalMs: intervalMs, diff --git a/pkg/api/org.go b/pkg/api/org.go index c35fe092c82..cb518d4ae78 100644 --- a/pkg/api/org.go +++ b/pkg/api/org.go @@ -4,36 +4,36 @@ import ( "github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/infra/metrics" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/util" ) // GET /api/org -func GetOrgCurrent(c *m.ReqContext) Response { +func GetOrgCurrent(c *models.ReqContext) Response { return getOrgHelper(c.OrgId) } // GET /api/orgs/:orgId -func GetOrgByID(c *m.ReqContext) Response { +func GetOrgByID(c *models.ReqContext) Response { return getOrgHelper(c.ParamsInt64(":orgId")) } // Get /api/orgs/name/:name -func GetOrgByName(c *m.ReqContext) Response { - query := m.GetOrgByNameQuery{Name: c.Params(":name")} +func GetOrgByName(c *models.ReqContext) Response { + query := models.GetOrgByNameQuery{Name: c.Params(":name")} if err := bus.Dispatch(&query); err != nil { - if err == m.ErrOrgNotFound { + if err == models.ErrOrgNotFound { return Error(404, "Organization not found", err) } return Error(500, "Failed to get organization", err) } org := query.Result - result := m.OrgDetailsDTO{ + result := models.OrgDetailsDTO{ Id: org.Id, Name: org.Name, - Address: m.Address{ + Address: models.Address{ Address1: org.Address1, Address2: org.Address2, City: org.City, @@ -47,10 +47,10 @@ func GetOrgByName(c *m.ReqContext) Response { } func getOrgHelper(orgID int64) Response { - query := m.GetOrgByIdQuery{Id: orgID} + query := models.GetOrgByIdQuery{Id: orgID} if err := bus.Dispatch(&query); err != nil { - if err == m.ErrOrgNotFound { + if err == models.ErrOrgNotFound { return Error(404, "Organization not found", err) } @@ -58,10 +58,10 @@ func getOrgHelper(orgID int64) Response { } org := query.Result - result := m.OrgDetailsDTO{ + result := models.OrgDetailsDTO{ Id: org.Id, Name: org.Name, - Address: m.Address{ + Address: models.Address{ Address1: org.Address1, Address2: org.Address2, City: org.City, @@ -75,14 +75,14 @@ func getOrgHelper(orgID int64) Response { } // POST /api/orgs -func CreateOrg(c *m.ReqContext, cmd m.CreateOrgCommand) Response { +func CreateOrg(c *models.ReqContext, cmd models.CreateOrgCommand) Response { if !c.IsSignedIn || (!setting.AllowUserOrgCreate && !c.IsGrafanaAdmin) { return Error(403, "Access denied", nil) } cmd.UserId = c.UserId if err := bus.Dispatch(&cmd); err != nil { - if err == m.ErrOrgNameTaken { + if err == models.ErrOrgNameTaken { return Error(409, "Organization name taken", err) } return Error(500, "Failed to create organization", err) @@ -97,19 +97,19 @@ func CreateOrg(c *m.ReqContext, cmd m.CreateOrgCommand) Response { } // PUT /api/org -func UpdateOrgCurrent(c *m.ReqContext, form dtos.UpdateOrgForm) Response { +func UpdateOrgCurrent(c *models.ReqContext, form dtos.UpdateOrgForm) Response { return updateOrgHelper(form, c.OrgId) } // PUT /api/orgs/:orgId -func UpdateOrg(c *m.ReqContext, form dtos.UpdateOrgForm) Response { +func UpdateOrg(c *models.ReqContext, form dtos.UpdateOrgForm) Response { return updateOrgHelper(form, c.ParamsInt64(":orgId")) } func updateOrgHelper(form dtos.UpdateOrgForm, orgID int64) Response { - cmd := m.UpdateOrgCommand{Name: form.Name, OrgId: orgID} + cmd := models.UpdateOrgCommand{Name: form.Name, OrgId: orgID} if err := bus.Dispatch(&cmd); err != nil { - if err == m.ErrOrgNameTaken { + if err == models.ErrOrgNameTaken { return Error(400, "Organization name taken", err) } return Error(500, "Failed to update organization", err) @@ -119,19 +119,19 @@ func updateOrgHelper(form dtos.UpdateOrgForm, orgID int64) Response { } // PUT /api/org/address -func UpdateOrgAddressCurrent(c *m.ReqContext, form dtos.UpdateOrgAddressForm) Response { +func UpdateOrgAddressCurrent(c *models.ReqContext, form dtos.UpdateOrgAddressForm) Response { return updateOrgAddressHelper(form, c.OrgId) } // PUT /api/orgs/:orgId/address -func UpdateOrgAddress(c *m.ReqContext, form dtos.UpdateOrgAddressForm) Response { +func UpdateOrgAddress(c *models.ReqContext, form dtos.UpdateOrgAddressForm) Response { return updateOrgAddressHelper(form, c.ParamsInt64(":orgId")) } func updateOrgAddressHelper(form dtos.UpdateOrgAddressForm, orgID int64) Response { - cmd := m.UpdateOrgAddressCommand{ + cmd := models.UpdateOrgAddressCommand{ OrgId: orgID, - Address: m.Address{ + Address: models.Address{ Address1: form.Address1, Address2: form.Address2, City: form.City, @@ -149,9 +149,9 @@ func updateOrgAddressHelper(form dtos.UpdateOrgAddressForm, orgID int64) Respons } // GET /api/orgs/:orgId -func DeleteOrgByID(c *m.ReqContext) Response { - if err := bus.Dispatch(&m.DeleteOrgCommand{Id: c.ParamsInt64(":orgId")}); err != nil { - if err == m.ErrOrgNotFound { +func DeleteOrgByID(c *models.ReqContext) Response { + if err := bus.Dispatch(&models.DeleteOrgCommand{Id: c.ParamsInt64(":orgId")}); err != nil { + if err == models.ErrOrgNotFound { return Error(404, "Failed to delete organization. ID not found", nil) } return Error(500, "Failed to update organization", err) @@ -159,8 +159,8 @@ func DeleteOrgByID(c *m.ReqContext) Response { return Success("Organization deleted") } -func SearchOrgs(c *m.ReqContext) Response { - query := m.SearchOrgsQuery{ +func SearchOrgs(c *models.ReqContext) Response { + query := models.SearchOrgsQuery{ Query: c.Query("query"), Name: c.Query("name"), Page: 0, diff --git a/pkg/api/org_invite.go b/pkg/api/org_invite.go index 70c10705704..80b5ed34eac 100644 --- a/pkg/api/org_invite.go +++ b/pkg/api/org_invite.go @@ -7,13 +7,13 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/events" "github.com/grafana/grafana/pkg/infra/metrics" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/util" ) -func GetPendingOrgInvites(c *m.ReqContext) Response { - query := m.GetTempUsersQuery{OrgId: c.OrgId, Status: m.TmpUserInvitePending} +func GetPendingOrgInvites(c *models.ReqContext) Response { + query := models.GetTempUsersQuery{OrgId: c.OrgId, Status: models.TmpUserInvitePending} if err := bus.Dispatch(&query); err != nil { return Error(500, "Failed to get invites from db", err) @@ -26,15 +26,15 @@ func GetPendingOrgInvites(c *m.ReqContext) Response { return JSON(200, query.Result) } -func AddOrgInvite(c *m.ReqContext, inviteDto dtos.AddInviteForm) Response { +func AddOrgInvite(c *models.ReqContext, inviteDto dtos.AddInviteForm) Response { if !inviteDto.Role.IsValid() { return Error(400, "Invalid role specified", nil) } // first try get existing user - userQuery := m.GetUserByLoginQuery{LoginOrEmail: inviteDto.LoginOrEmail} + userQuery := models.GetUserByLoginQuery{LoginOrEmail: inviteDto.LoginOrEmail} if err := bus.Dispatch(&userQuery); err != nil { - if err != m.ErrUserNotFound { + if err != models.ErrUserNotFound { return Error(500, "Failed to query db for existing user check", err) } } else { @@ -45,11 +45,11 @@ func AddOrgInvite(c *m.ReqContext, inviteDto dtos.AddInviteForm) Response { return Error(400, "Cannot invite when login is disabled.", nil) } - cmd := m.CreateTempUserCommand{} + cmd := models.CreateTempUserCommand{} cmd.OrgId = c.OrgId cmd.Email = inviteDto.LoginOrEmail cmd.Name = inviteDto.Name - cmd.Status = m.TmpUserInvitePending + cmd.Status = models.TmpUserInvitePending cmd.InvitedByUserId = c.UserId var err error cmd.Code, err = util.GetRandomString(30) @@ -65,7 +65,7 @@ func AddOrgInvite(c *m.ReqContext, inviteDto dtos.AddInviteForm) Response { // send invite email if inviteDto.SendEmail && util.IsEmail(inviteDto.LoginOrEmail) { - emailCmd := m.SendEmailCommand{ + emailCmd := models.SendEmailCommand{ To: []string{inviteDto.LoginOrEmail}, Template: "new_user_invite.html", Data: map[string]interface{}{ @@ -78,13 +78,13 @@ func AddOrgInvite(c *m.ReqContext, inviteDto dtos.AddInviteForm) Response { } if err := bus.Dispatch(&emailCmd); err != nil { - if err == m.ErrSmtpNotEnabled { + if err == models.ErrSmtpNotEnabled { return Error(412, err.Error(), err) } return Error(500, "Failed to send email invite", err) } - emailSentCmd := m.UpdateTempUserWithEmailSentCommand{Code: cmd.Result.Code} + emailSentCmd := models.UpdateTempUserWithEmailSentCommand{Code: cmd.Result.Code} if err := bus.Dispatch(&emailSentCmd); err != nil { return Error(500, "Failed to update invite with email sent info", err) } @@ -95,18 +95,18 @@ func AddOrgInvite(c *m.ReqContext, inviteDto dtos.AddInviteForm) Response { return Success(fmt.Sprintf("Created invite for %s", inviteDto.LoginOrEmail)) } -func inviteExistingUserToOrg(c *m.ReqContext, user *m.User, inviteDto *dtos.AddInviteForm) Response { +func inviteExistingUserToOrg(c *models.ReqContext, user *models.User, inviteDto *dtos.AddInviteForm) Response { // user exists, add org role - createOrgUserCmd := m.AddOrgUserCommand{OrgId: c.OrgId, UserId: user.Id, Role: inviteDto.Role} + createOrgUserCmd := models.AddOrgUserCommand{OrgId: c.OrgId, UserId: user.Id, Role: inviteDto.Role} if err := bus.Dispatch(&createOrgUserCmd); err != nil { - if err == m.ErrOrgUserAlreadyAdded { + if err == models.ErrOrgUserAlreadyAdded { return Error(412, fmt.Sprintf("User %s is already added to organization", inviteDto.LoginOrEmail), err) } return Error(500, "Error while trying to create org user", err) } if inviteDto.SendEmail && util.IsEmail(user.Email) { - emailCmd := m.SendEmailCommand{ + emailCmd := models.SendEmailCommand{ To: []string{user.Email}, Template: "invited_to_org.html", Data: map[string]interface{}{ @@ -124,8 +124,8 @@ func inviteExistingUserToOrg(c *m.ReqContext, user *m.User, inviteDto *dtos.AddI return Success(fmt.Sprintf("Existing Grafana user %s added to org %s", user.NameOrFallback(), c.OrgName)) } -func RevokeInvite(c *m.ReqContext) Response { - if ok, rsp := updateTempUserStatus(c.Params(":code"), m.TmpUserRevoked); !ok { +func RevokeInvite(c *models.ReqContext) Response { + if ok, rsp := updateTempUserStatus(c.Params(":code"), models.TmpUserRevoked); !ok { return rsp } @@ -135,17 +135,17 @@ func RevokeInvite(c *m.ReqContext) Response { // GetInviteInfoByCode gets a pending user invite corresponding to a certain code. // A response containing an InviteInfo object is returned if the invite is found. // If a (pending) invite is not found, 404 is returned. -func GetInviteInfoByCode(c *m.ReqContext) Response { - query := m.GetTempUserByCodeQuery{Code: c.Params(":code")} +func GetInviteInfoByCode(c *models.ReqContext) Response { + query := models.GetTempUserByCodeQuery{Code: c.Params(":code")} if err := bus.Dispatch(&query); err != nil { - if err == m.ErrTempUserNotFound { + if err == models.ErrTempUserNotFound { return Error(404, "Invite not found", nil) } return Error(500, "Failed to get invite", err) } invite := query.Result - if invite.Status != m.TmpUserInvitePending { + if invite.Status != models.TmpUserInvitePending { return Error(404, "Invite not found", nil) } @@ -157,22 +157,22 @@ func GetInviteInfoByCode(c *m.ReqContext) Response { }) } -func (hs *HTTPServer) CompleteInvite(c *m.ReqContext, completeInvite dtos.CompleteInviteForm) Response { - query := m.GetTempUserByCodeQuery{Code: completeInvite.InviteCode} +func (hs *HTTPServer) CompleteInvite(c *models.ReqContext, completeInvite dtos.CompleteInviteForm) Response { + query := models.GetTempUserByCodeQuery{Code: completeInvite.InviteCode} if err := bus.Dispatch(&query); err != nil { - if err == m.ErrTempUserNotFound { + if err == models.ErrTempUserNotFound { return Error(404, "Invite not found", nil) } return Error(500, "Failed to get invite", err) } invite := query.Result - if invite.Status != m.TmpUserInvitePending { + if invite.Status != models.TmpUserInvitePending { return Error(412, fmt.Sprintf("Invite cannot be used in status %s", invite.Status), nil) } - cmd := m.CreateUserCommand{ + cmd := models.CreateUserCommand{ Email: completeInvite.Email, Name: completeInvite.Name, Login: completeInvite.Username, @@ -205,9 +205,9 @@ func (hs *HTTPServer) CompleteInvite(c *m.ReqContext, completeInvite dtos.Comple return Success("User created and logged in") } -func updateTempUserStatus(code string, status m.TempUserStatus) (bool, Response) { +func updateTempUserStatus(code string, status models.TempUserStatus) (bool, Response) { // update temp user status - updateTmpUserCmd := m.UpdateTempUserStatusCommand{Code: code, Status: status} + updateTmpUserCmd := models.UpdateTempUserStatusCommand{Code: code, Status: status} if err := bus.Dispatch(&updateTmpUserCmd); err != nil { return false, Error(500, "Failed to update invite status", err) } @@ -215,23 +215,23 @@ func updateTempUserStatus(code string, status m.TempUserStatus) (bool, Response) return true, nil } -func applyUserInvite(user *m.User, invite *m.TempUserDTO, setActive bool) (bool, Response) { +func applyUserInvite(user *models.User, invite *models.TempUserDTO, setActive bool) (bool, Response) { // add to org - addOrgUserCmd := m.AddOrgUserCommand{OrgId: invite.OrgId, UserId: user.Id, Role: invite.Role} + addOrgUserCmd := models.AddOrgUserCommand{OrgId: invite.OrgId, UserId: user.Id, Role: invite.Role} if err := bus.Dispatch(&addOrgUserCmd); err != nil { - if err != m.ErrOrgUserAlreadyAdded { + if err != models.ErrOrgUserAlreadyAdded { return false, Error(500, "Error while trying to create org user", err) } } // update temp user status - if ok, rsp := updateTempUserStatus(invite.Code, m.TmpUserCompleted); !ok { + if ok, rsp := updateTempUserStatus(invite.Code, models.TmpUserCompleted); !ok { return false, rsp } if setActive { // set org to active - if err := bus.Dispatch(&m.SetUsingOrgCommand{OrgId: invite.OrgId, UserId: user.Id}); err != nil { + if err := bus.Dispatch(&models.SetUsingOrgCommand{OrgId: invite.OrgId, UserId: user.Id}); err != nil { return false, Error(500, "Failed to set org as active", err) } } diff --git a/pkg/api/password.go b/pkg/api/password.go index 57eacf05ea9..bb524397578 100644 --- a/pkg/api/password.go +++ b/pkg/api/password.go @@ -3,12 +3,12 @@ package api import ( "github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/bus" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/util" ) -func SendResetPasswordEmail(c *m.ReqContext, form dtos.SendResetPasswordEmailForm) Response { +func SendResetPasswordEmail(c *models.ReqContext, form dtos.SendResetPasswordEmailForm) Response { if setting.LDAPEnabled || setting.AuthProxyEnabled { return Error(401, "Not allowed to reset password when LDAP or Auth Proxy is enabled", nil) } @@ -16,14 +16,14 @@ func SendResetPasswordEmail(c *m.ReqContext, form dtos.SendResetPasswordEmailFor return Error(401, "Not allowed to reset password when login form is disabled", nil) } - userQuery := m.GetUserByLoginQuery{LoginOrEmail: form.UserOrEmail} + userQuery := models.GetUserByLoginQuery{LoginOrEmail: form.UserOrEmail} if err := bus.Dispatch(&userQuery); err != nil { c.Logger.Info("Requested password reset for user that was not found", "user", userQuery.LoginOrEmail) return Error(200, "Email sent", err) } - emailCmd := m.SendResetPasswordEmailCommand{User: userQuery.Result} + emailCmd := models.SendResetPasswordEmailCommand{User: userQuery.Result} if err := bus.Dispatch(&emailCmd); err != nil { return Error(500, "Failed to send email", err) } @@ -31,11 +31,11 @@ func SendResetPasswordEmail(c *m.ReqContext, form dtos.SendResetPasswordEmailFor return Success("Email sent") } -func ResetPassword(c *m.ReqContext, form dtos.ResetUserPasswordForm) Response { - query := m.ValidateResetPasswordCodeQuery{Code: form.Code} +func ResetPassword(c *models.ReqContext, form dtos.ResetUserPasswordForm) Response { + query := models.ValidateResetPasswordCodeQuery{Code: form.Code} if err := bus.Dispatch(&query); err != nil { - if err == m.ErrInvalidEmailCode { + if err == models.ErrInvalidEmailCode { return Error(400, "Invalid or expired reset password code", nil) } return Error(500, "Unknown error validating email code", err) @@ -45,7 +45,7 @@ func ResetPassword(c *m.ReqContext, form dtos.ResetUserPasswordForm) Response { return Error(400, "Passwords do not match", nil) } - cmd := m.ChangeUserPasswordCommand{} + cmd := models.ChangeUserPasswordCommand{} cmd.UserId = query.Result.Id var err error cmd.NewPassword, err = util.EncodePassword(form.NewPassword, query.Result.Salt) diff --git a/pkg/api/playlist.go b/pkg/api/playlist.go index bfc9f1b978c..72181772e52 100644 --- a/pkg/api/playlist.go +++ b/pkg/api/playlist.go @@ -4,13 +4,12 @@ import ( "net/http" "github.com/grafana/grafana/pkg/bus" - _ "github.com/grafana/grafana/pkg/infra/log" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" ) -func ValidateOrgPlaylist(c *m.ReqContext) { +func ValidateOrgPlaylist(c *models.ReqContext) { id := c.ParamsInt64(":id") - query := m.GetPlaylistByIdQuery{Id: id} + query := models.GetPlaylistByIdQuery{Id: id} err := bus.Dispatch(&query) if err != nil { @@ -41,7 +40,7 @@ func ValidateOrgPlaylist(c *m.ReqContext) { } } -func SearchPlaylists(c *m.ReqContext) Response { +func SearchPlaylists(c *models.ReqContext) Response { query := c.Query("query") limit := c.QueryInt("limit") @@ -49,7 +48,7 @@ func SearchPlaylists(c *m.ReqContext) Response { limit = 1000 } - searchQuery := m.GetPlaylistsQuery{ + searchQuery := models.GetPlaylistsQuery{ Name: query, Limit: limit, OrgId: c.OrgId, @@ -63,9 +62,9 @@ func SearchPlaylists(c *m.ReqContext) Response { return JSON(200, searchQuery.Result) } -func GetPlaylist(c *m.ReqContext) Response { +func GetPlaylist(c *models.ReqContext) Response { id := c.ParamsInt64(":id") - cmd := m.GetPlaylistByIdQuery{Id: id} + cmd := models.GetPlaylistByIdQuery{Id: id} if err := bus.Dispatch(&cmd); err != nil { return Error(500, "Playlist not found", err) @@ -73,7 +72,7 @@ func GetPlaylist(c *m.ReqContext) Response { playlistDTOs, _ := LoadPlaylistItemDTOs(id) - dto := &m.PlaylistDTO{ + dto := &models.PlaylistDTO{ Id: cmd.Result.Id, Name: cmd.Result.Name, Interval: cmd.Result.Interval, @@ -84,17 +83,17 @@ func GetPlaylist(c *m.ReqContext) Response { return JSON(200, dto) } -func LoadPlaylistItemDTOs(id int64) ([]m.PlaylistItemDTO, error) { +func LoadPlaylistItemDTOs(id int64) ([]models.PlaylistItemDTO, error) { playlistitems, err := LoadPlaylistItems(id) if err != nil { return nil, err } - playlistDTOs := make([]m.PlaylistItemDTO, 0) + playlistDTOs := make([]models.PlaylistItemDTO, 0) for _, item := range playlistitems { - playlistDTOs = append(playlistDTOs, m.PlaylistItemDTO{ + playlistDTOs = append(playlistDTOs, models.PlaylistItemDTO{ Id: item.Id, PlaylistId: item.PlaylistId, Type: item.Type, @@ -107,8 +106,8 @@ func LoadPlaylistItemDTOs(id int64) ([]m.PlaylistItemDTO, error) { return playlistDTOs, nil } -func LoadPlaylistItems(id int64) ([]m.PlaylistItem, error) { - itemQuery := m.GetPlaylistItemsByIdQuery{PlaylistId: id} +func LoadPlaylistItems(id int64) ([]models.PlaylistItem, error) { + itemQuery := models.GetPlaylistItemsByIdQuery{PlaylistId: id} if err := bus.Dispatch(&itemQuery); err != nil { return nil, err } @@ -116,7 +115,7 @@ func LoadPlaylistItems(id int64) ([]m.PlaylistItem, error) { return *itemQuery.Result, nil } -func GetPlaylistItems(c *m.ReqContext) Response { +func GetPlaylistItems(c *models.ReqContext) Response { id := c.ParamsInt64(":id") playlistDTOs, err := LoadPlaylistItemDTOs(id) @@ -128,7 +127,7 @@ func GetPlaylistItems(c *m.ReqContext) Response { return JSON(200, playlistDTOs) } -func GetPlaylistDashboards(c *m.ReqContext) Response { +func GetPlaylistDashboards(c *models.ReqContext) Response { playlistID := c.ParamsInt64(":id") playlists, err := LoadPlaylistDashboards(c.OrgId, c.SignedInUser, playlistID) @@ -139,10 +138,10 @@ func GetPlaylistDashboards(c *m.ReqContext) Response { return JSON(200, playlists) } -func DeletePlaylist(c *m.ReqContext) Response { +func DeletePlaylist(c *models.ReqContext) Response { id := c.ParamsInt64(":id") - cmd := m.DeletePlaylistCommand{Id: id, OrgId: c.OrgId} + cmd := models.DeletePlaylistCommand{Id: id, OrgId: c.OrgId} if err := bus.Dispatch(&cmd); err != nil { return Error(500, "Failed to delete playlist", err) } @@ -150,7 +149,7 @@ func DeletePlaylist(c *m.ReqContext) Response { return JSON(200, "") } -func CreatePlaylist(c *m.ReqContext, cmd m.CreatePlaylistCommand) Response { +func CreatePlaylist(c *models.ReqContext, cmd models.CreatePlaylistCommand) Response { cmd.OrgId = c.OrgId if err := bus.Dispatch(&cmd); err != nil { @@ -160,7 +159,7 @@ func CreatePlaylist(c *m.ReqContext, cmd m.CreatePlaylistCommand) Response { return JSON(200, cmd.Result) } -func UpdatePlaylist(c *m.ReqContext, cmd m.UpdatePlaylistCommand) Response { +func UpdatePlaylist(c *models.ReqContext, cmd models.UpdatePlaylistCommand) Response { cmd.OrgId = c.OrgId cmd.Id = c.ParamsInt64(":id") diff --git a/pkg/api/playlist_play.go b/pkg/api/playlist_play.go index 53eab8908d7..647a6734cf9 100644 --- a/pkg/api/playlist_play.go +++ b/pkg/api/playlist_play.go @@ -7,7 +7,7 @@ import ( "github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/bus" _ "github.com/grafana/grafana/pkg/infra/log" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/search" ) @@ -15,7 +15,7 @@ func populateDashboardsByID(dashboardByIDs []int64, dashboardIDOrder map[int64]i result := make(dtos.PlaylistDashboardsSlice, 0) if len(dashboardByIDs) > 0 { - dashboardQuery := m.GetDashboardsQuery{DashboardIds: dashboardByIDs} + dashboardQuery := models.GetDashboardsQuery{DashboardIds: dashboardByIDs} if err := bus.Dispatch(&dashboardQuery); err != nil { return result, err } @@ -26,7 +26,7 @@ func populateDashboardsByID(dashboardByIDs []int64, dashboardIDOrder map[int64]i Slug: item.Slug, Title: item.Title, Uri: "db/" + item.Slug, - Url: m.GetDashboardUrl(item.Uid, item.Slug), + Url: models.GetDashboardUrl(item.Uid, item.Slug), Order: dashboardIDOrder[item.Id], }) } @@ -35,7 +35,7 @@ func populateDashboardsByID(dashboardByIDs []int64, dashboardIDOrder map[int64]i return result, nil } -func populateDashboardsByTag(orgID int64, signedInUser *m.SignedInUser, dashboardByTag []string, dashboardTagOrder map[string]int) dtos.PlaylistDashboardsSlice { +func populateDashboardsByTag(orgID int64, signedInUser *models.SignedInUser, dashboardByTag []string, dashboardTagOrder map[string]int) dtos.PlaylistDashboardsSlice { result := make(dtos.PlaylistDashboardsSlice, 0) for _, tag := range dashboardByTag { @@ -65,7 +65,7 @@ func populateDashboardsByTag(orgID int64, signedInUser *m.SignedInUser, dashboar return result } -func LoadPlaylistDashboards(orgID int64, signedInUser *m.SignedInUser, playlistID int64) (dtos.PlaylistDashboardsSlice, error) { +func LoadPlaylistDashboards(orgID int64, signedInUser *models.SignedInUser, playlistID int64) (dtos.PlaylistDashboardsSlice, error) { playlistItems, _ := LoadPlaylistItems(playlistID) dashboardByIDs := make([]int64, 0) diff --git a/pkg/api/pluginproxy/ds_auth_provider.go b/pkg/api/pluginproxy/ds_auth_provider.go index e4147d494b9..2be38df2f90 100644 --- a/pkg/api/pluginproxy/ds_auth_provider.go +++ b/pkg/api/pluginproxy/ds_auth_provider.go @@ -7,14 +7,14 @@ import ( "net/url" "strings" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/plugins" "github.com/grafana/grafana/pkg/util" "golang.org/x/oauth2/google" ) //ApplyRoute should use the plugin route data to set auth headers and custom headers -func ApplyRoute(ctx context.Context, req *http.Request, proxyPath string, route *plugins.AppPluginRoute, ds *m.DataSource) { +func ApplyRoute(ctx context.Context, req *http.Request, proxyPath string, route *plugins.AppPluginRoute, ds *models.DataSource) { proxyPath = strings.TrimPrefix(proxyPath, route.Path) data := templateData{ diff --git a/pkg/api/pluginproxy/ds_proxy.go b/pkg/api/pluginproxy/ds_proxy.go index 8c4d69bafcf..9a241689a76 100644 --- a/pkg/api/pluginproxy/ds_proxy.go +++ b/pkg/api/pluginproxy/ds_proxy.go @@ -19,7 +19,7 @@ import ( "github.com/grafana/grafana/pkg/bus" glog "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/login/social" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/plugins" "github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/util" @@ -32,8 +32,8 @@ var ( ) type DataSourceProxy struct { - ds *m.DataSource - ctx *m.ReqContext + ds *models.DataSource + ctx *models.ReqContext targetUrl *url.URL proxyPath string route *plugins.AppPluginRoute @@ -70,7 +70,7 @@ func (lw *logWrapper) Write(p []byte) (n int, err error) { } // NewDataSourceProxy creates a new Datasource proxy -func NewDataSourceProxy(ds *m.DataSource, plugin *plugins.DataSourcePlugin, ctx *m.ReqContext, proxyPath string, cfg *setting.Cfg) *DataSourceProxy { +func NewDataSourceProxy(ds *models.DataSource, plugin *plugins.DataSourcePlugin, ctx *models.ReqContext, proxyPath string, cfg *setting.Cfg) *DataSourceProxy { targetURL, _ := url.Parse(ds.Url) return &DataSourceProxy{ @@ -154,12 +154,12 @@ func (proxy *DataSourceProxy) getDirector() func(req *http.Request) { reqQueryVals := req.URL.Query() - if proxy.ds.Type == m.DS_INFLUXDB_08 { + if proxy.ds.Type == models.DS_INFLUXDB_08 { req.URL.Path = util.JoinURLFragments(proxy.targetUrl.Path, "db/"+proxy.ds.Database+"/"+proxy.proxyPath) reqQueryVals.Add("u", proxy.ds.User) reqQueryVals.Add("p", proxy.ds.DecryptedPassword()) req.URL.RawQuery = reqQueryVals.Encode() - } else if proxy.ds.Type == m.DS_INFLUXDB { + } else if proxy.ds.Type == models.DS_INFLUXDB { req.URL.Path = util.JoinURLFragments(proxy.targetUrl.Path, proxy.proxyPath) req.URL.RawQuery = reqQueryVals.Encode() if !proxy.ds.BasicAuth { @@ -216,7 +216,7 @@ func (proxy *DataSourceProxy) validateRequest() error { return errors.New("Target url is not a valid target") } - if proxy.ds.Type == m.DS_PROMETHEUS { + if proxy.ds.Type == models.DS_PROMETHEUS { if proxy.ctx.Req.Request.Method == "DELETE" { return errors.New("Deletes not allowed on proxied Prometheus datasource") } @@ -228,7 +228,7 @@ func (proxy *DataSourceProxy) validateRequest() error { } } - if proxy.ds.Type == m.DS_ES { + if proxy.ds.Type == models.DS_ES { if proxy.ctx.Req.Request.Method == "DELETE" { return errors.New("Deletes not allowed on proxied Elasticsearch datasource") } @@ -288,7 +288,7 @@ func (proxy *DataSourceProxy) logRequest() { "body", body) } -func checkWhiteList(c *m.ReqContext, host string) bool { +func checkWhiteList(c *models.ReqContext, host string) bool { if host != "" && len(setting.DataProxyWhiteList) > 0 { if _, exists := setting.DataProxyWhiteList[host]; !exists { c.JsonApiErr(403, "Data proxy hostname and ip are not included in whitelist", nil) @@ -299,8 +299,8 @@ func checkWhiteList(c *m.ReqContext, host string) bool { return true } -func addOAuthPassThruAuth(c *m.ReqContext, req *http.Request) { - authInfoQuery := &m.GetAuthInfoQuery{UserId: c.UserId} +func addOAuthPassThruAuth(c *models.ReqContext, req *http.Request) { + authInfoQuery := &models.GetAuthInfoQuery{UserId: c.UserId} if err := bus.Dispatch(authInfoQuery); err != nil { logger.Error("Error feching oauth information for user", "error", err) return @@ -327,7 +327,7 @@ func addOAuthPassThruAuth(c *m.ReqContext, req *http.Request) { // If the tokens are not the same, update the entry in the DB if token.AccessToken != authInfoQuery.Result.OAuthAccessToken { - updateAuthCommand := &m.UpdateAuthInfoCommand{ + updateAuthCommand := &models.UpdateAuthInfoCommand{ UserId: authInfoQuery.Result.UserId, AuthModule: authInfoQuery.Result.AuthModule, AuthId: authInfoQuery.Result.AuthId, diff --git a/pkg/api/pluginproxy/ds_proxy_test.go b/pkg/api/pluginproxy/ds_proxy_test.go index 9a562fb40fc..509d015329f 100644 --- a/pkg/api/pluginproxy/ds_proxy_test.go +++ b/pkg/api/pluginproxy/ds_proxy_test.go @@ -11,6 +11,7 @@ import ( "time" "github.com/grafana/grafana/pkg/components/securejsondata" + "github.com/grafana/grafana/pkg/models" "golang.org/x/oauth2" macaron "gopkg.in/macaron.v1" @@ -18,7 +19,6 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/login/social" - m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/plugins" "github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/util" @@ -34,7 +34,7 @@ func TestDSRouteRule(t *testing.T) { { Path: "api/v4/", Url: "https://www.google.com", - ReqRole: m.ROLE_EDITOR, + ReqRole: models.ROLE_EDITOR, Headers: []plugins.AppPluginRouteHeader{ {Name: "x-header", Content: "my secret {{.SecureJsonData.key}}"}, }, @@ -42,7 +42,7 @@ func TestDSRouteRule(t *testing.T) { { Path: "api/admin", Url: "https://www.google.com", - ReqRole: m.ROLE_ADMIN, + ReqRole: models.ROLE_ADMIN, Headers: []plugins.AppPluginRouteHeader{ {Name: "x-header", Content: "my secret {{.SecureJsonData.key}}"}, }, @@ -67,7 +67,7 @@ func TestDSRouteRule(t *testing.T) { setting.SecretKey = "password" //nolint:goconst key, _ := util.Encrypt([]byte("123"), "password") - ds := &m.DataSource{ + ds := &models.DataSource{ JsonData: simplejson.NewFromAny(map[string]interface{}{ "clientId": "asd", "dynamicUrl": "https://dynamic.grafana.com", @@ -78,11 +78,11 @@ func TestDSRouteRule(t *testing.T) { } req, _ := http.NewRequest("GET", "http://localhost/asd", nil) - ctx := &m.ReqContext{ + ctx := &models.ReqContext{ Context: &macaron.Context{ Req: macaron.Request{Request: req}, }, - SignedInUser: &m.SignedInUser{OrgRole: m.ROLE_EDITOR}, + SignedInUser: &models.SignedInUser{OrgRole: models.ROLE_EDITOR}, } Convey("When matching route path", func() { @@ -121,7 +121,7 @@ func TestDSRouteRule(t *testing.T) { }) Convey("plugin route with admin role and user is admin", func() { - ctx.SignedInUser.OrgRole = m.ROLE_ADMIN + ctx.SignedInUser.OrgRole = models.ROLE_ADMIN proxy := NewDataSourceProxy(ds, plugin, ctx, "api/admin", &setting.Cfg{}) err := proxy.validateRequest() So(err, ShouldBeNil) @@ -164,7 +164,7 @@ func TestDSRouteRule(t *testing.T) { setting.SecretKey = "password" key, _ := util.Encrypt([]byte("123"), "password") - ds := &m.DataSource{ + ds := &models.DataSource{ JsonData: simplejson.NewFromAny(map[string]interface{}{ "clientId": "asd", "tenantId": "mytenantId", @@ -175,11 +175,11 @@ func TestDSRouteRule(t *testing.T) { } req, _ := http.NewRequest("GET", "http://localhost/asd", nil) - ctx := &m.ReqContext{ + ctx := &models.ReqContext{ Context: &macaron.Context{ Req: macaron.Request{Request: req}, }, - SignedInUser: &m.SignedInUser{OrgRole: m.ROLE_EDITOR}, + SignedInUser: &models.SignedInUser{OrgRole: models.ROLE_EDITOR}, } Convey("When creating and caching access tokens", func() { @@ -238,8 +238,8 @@ func TestDSRouteRule(t *testing.T) { Convey("When proxying graphite", func() { setting.BuildVersion = "5.3.0" plugin := &plugins.DataSourcePlugin{} - ds := &m.DataSource{Url: "htttp://graphite:8080", Type: m.DS_GRAPHITE} - ctx := &m.ReqContext{} + ds := &models.DataSource{Url: "htttp://graphite:8080", Type: models.DS_GRAPHITE} + ctx := &models.ReqContext{} proxy := NewDataSourceProxy(ds, plugin, ctx, "/render", &setting.Cfg{}) req, err := http.NewRequest(http.MethodGet, "http://grafana.com/sub", nil) @@ -257,15 +257,15 @@ func TestDSRouteRule(t *testing.T) { Convey("When proxying InfluxDB", func() { plugin := &plugins.DataSourcePlugin{} - ds := &m.DataSource{ - Type: m.DS_INFLUXDB_08, + ds := &models.DataSource{ + Type: models.DS_INFLUXDB_08, Url: "http://influxdb:8083", Database: "site", User: "user", Password: "password", } - ctx := &m.ReqContext{} + ctx := &models.ReqContext{} proxy := NewDataSourceProxy(ds, plugin, ctx, "", &setting.Cfg{}) req, err := http.NewRequest(http.MethodGet, "http://grafana.com/sub", nil) @@ -283,13 +283,13 @@ func TestDSRouteRule(t *testing.T) { json, _ := simplejson.NewJson([]byte(`{"keepCookies": []}`)) - ds := &m.DataSource{ - Type: m.DS_GRAPHITE, + ds := &models.DataSource{ + Type: models.DS_GRAPHITE, Url: "http://graphite:8086", JsonData: json, } - ctx := &m.ReqContext{} + ctx := &models.ReqContext{} proxy := NewDataSourceProxy(ds, plugin, ctx, "", &setting.Cfg{}) requestURL, _ := url.Parse("http://grafana.com/sub") @@ -309,13 +309,13 @@ func TestDSRouteRule(t *testing.T) { json, _ := simplejson.NewJson([]byte(`{"keepCookies": ["JSESSION_ID"]}`)) - ds := &m.DataSource{ - Type: m.DS_GRAPHITE, + ds := &models.DataSource{ + Type: models.DS_GRAPHITE, Url: "http://graphite:8086", JsonData: json, } - ctx := &m.ReqContext{} + ctx := &models.ReqContext{} proxy := NewDataSourceProxy(ds, plugin, ctx, "", &setting.Cfg{}) requestURL, _ := url.Parse("http://grafana.com/sub") @@ -332,11 +332,11 @@ func TestDSRouteRule(t *testing.T) { Convey("When proxying a custom datasource", func() { plugin := &plugins.DataSourcePlugin{} - ds := &m.DataSource{ + ds := &models.DataSource{ Type: "custom-datasource", Url: "http://host/root/", } - ctx := &m.ReqContext{} + ctx := &models.ReqContext{} proxy := NewDataSourceProxy(ds, plugin, ctx, "/path/to/folder/", &setting.Cfg{}) req, err := http.NewRequest(http.MethodGet, "http://grafana.com/sub", nil) req.Header.Add("Origin", "grafana.com") @@ -364,8 +364,8 @@ func TestDSRouteRule(t *testing.T) { }, } - bus.AddHandler("test", func(query *m.GetAuthInfoQuery) error { - query.Result = &m.UserAuth{ + bus.AddHandler("test", func(query *models.GetAuthInfoQuery) error { + query.Result = &models.UserAuth{ Id: 1, UserId: 1, AuthModule: "generic_oauth", @@ -378,7 +378,7 @@ func TestDSRouteRule(t *testing.T) { }) plugin := &plugins.DataSourcePlugin{} - ds := &m.DataSource{ + ds := &models.DataSource{ Type: "custom-datasource", Url: "http://host/root/", JsonData: simplejson.NewFromAny(map[string]interface{}{ @@ -387,8 +387,8 @@ func TestDSRouteRule(t *testing.T) { } req, _ := http.NewRequest("GET", "http://localhost/asd", nil) - ctx := &m.ReqContext{ - SignedInUser: &m.SignedInUser{UserId: 1}, + ctx := &models.ReqContext{ + SignedInUser: &models.SignedInUser{UserId: 1}, Context: &macaron.Context{ Req: macaron.Request{Request: req}, }, @@ -407,8 +407,8 @@ func TestDSRouteRule(t *testing.T) { Convey("When SendUserHeader config is enabled", func() { req := getDatasourceProxiedRequest( - &m.ReqContext{ - SignedInUser: &m.SignedInUser{ + &models.ReqContext{ + SignedInUser: &models.SignedInUser{ Login: "test_user", }, }, @@ -421,8 +421,8 @@ func TestDSRouteRule(t *testing.T) { Convey("When SendUserHeader config is disabled", func() { req := getDatasourceProxiedRequest( - &m.ReqContext{ - SignedInUser: &m.SignedInUser{ + &models.ReqContext{ + SignedInUser: &models.SignedInUser{ Login: "test_user", }, }, @@ -436,8 +436,8 @@ func TestDSRouteRule(t *testing.T) { Convey("When SendUserHeader config is enabled but user is anonymous", func() { req := getDatasourceProxiedRequest( - &m.ReqContext{ - SignedInUser: &m.SignedInUser{IsAnonymous: true}, + &models.ReqContext{ + SignedInUser: &models.SignedInUser{IsAnonymous: true}, }, &setting.Cfg{SendUserHeader: true}, ) @@ -449,21 +449,21 @@ func TestDSRouteRule(t *testing.T) { Convey("When proxying data source proxy should handle authentication", func() { tests := []*Test{ - createAuthTest(m.DS_INFLUXDB_08, AUTHTYPE_PASSWORD, AUTHCHECK_QUERY, false), - createAuthTest(m.DS_INFLUXDB_08, AUTHTYPE_PASSWORD, AUTHCHECK_QUERY, true), - createAuthTest(m.DS_INFLUXDB, AUTHTYPE_PASSWORD, AUTHCHECK_HEADER, true), - createAuthTest(m.DS_INFLUXDB, AUTHTYPE_PASSWORD, AUTHCHECK_HEADER, false), - createAuthTest(m.DS_INFLUXDB, AUTHTYPE_BASIC, AUTHCHECK_HEADER, true), - createAuthTest(m.DS_INFLUXDB, AUTHTYPE_BASIC, AUTHCHECK_HEADER, false), + createAuthTest(models.DS_INFLUXDB_08, AUTHTYPE_PASSWORD, AUTHCHECK_QUERY, false), + createAuthTest(models.DS_INFLUXDB_08, AUTHTYPE_PASSWORD, AUTHCHECK_QUERY, true), + createAuthTest(models.DS_INFLUXDB, AUTHTYPE_PASSWORD, AUTHCHECK_HEADER, true), + createAuthTest(models.DS_INFLUXDB, AUTHTYPE_PASSWORD, AUTHCHECK_HEADER, false), + createAuthTest(models.DS_INFLUXDB, AUTHTYPE_BASIC, AUTHCHECK_HEADER, true), + createAuthTest(models.DS_INFLUXDB, AUTHTYPE_BASIC, AUTHCHECK_HEADER, false), // These two should be enough for any other datasource at the moment. Proxy has special handling // only for Influx, others have the same path and only BasicAuth. Non BasicAuth datasources // do not go through proxy but through TSDB API which is not tested here. - createAuthTest(m.DS_ES, AUTHTYPE_BASIC, AUTHCHECK_HEADER, false), - createAuthTest(m.DS_ES, AUTHTYPE_BASIC, AUTHCHECK_HEADER, true), + createAuthTest(models.DS_ES, AUTHTYPE_BASIC, AUTHCHECK_HEADER, false), + createAuthTest(models.DS_ES, AUTHTYPE_BASIC, AUTHCHECK_HEADER, true), } for _, test := range tests { - m.ClearDSDecryptionCache() + models.ClearDSDecryptionCache() runDatasourceAuthTest(test) } }) @@ -478,21 +478,21 @@ func TestDSRouteRule(t *testing.T) { defer backend.Close() plugin := &plugins.DataSourcePlugin{} - ds := &m.DataSource{Url: backend.URL, Type: m.DS_GRAPHITE} + ds := &models.DataSource{Url: backend.URL, Type: models.DS_GRAPHITE} responseRecorder := &CloseNotifierResponseRecorder{ ResponseRecorder: httptest.NewRecorder(), } defer responseRecorder.Close() - setupCtx := func(fn func(http.ResponseWriter)) *m.ReqContext { + setupCtx := func(fn func(http.ResponseWriter)) *models.ReqContext { responseWriter := macaron.NewResponseWriter("GET", responseRecorder) if fn != nil { fn(responseWriter) } - return &m.ReqContext{ - SignedInUser: &m.SignedInUser{}, + return &models.ReqContext{ + SignedInUser: &models.SignedInUser{}, Context: &macaron.Context{ Req: macaron.Request{ Request: httptest.NewRequest("GET", "/render", nil), @@ -545,10 +545,10 @@ func (r *CloseNotifierResponseRecorder) Close() { } // getDatasourceProxiedRequest is a helper for easier setup of tests based on global config and ReqContext. -func getDatasourceProxiedRequest(ctx *m.ReqContext, cfg *setting.Cfg) *http.Request { +func getDatasourceProxiedRequest(ctx *models.ReqContext, cfg *setting.Cfg) *http.Request { plugin := &plugins.DataSourcePlugin{} - ds := &m.DataSource{ + ds := &models.DataSource{ Type: "custom", Url: "http://host/root/", } @@ -586,7 +586,7 @@ func newFakeHTTPClient(fakeBody []byte) httpClient { } type Test struct { - datasource *m.DataSource + datasource *models.DataSource checkReq func(req *http.Request) } @@ -605,7 +605,7 @@ func createAuthTest(dsType string, authType string, authCheck string, useSecureJ base64AthHeader := "Basic dXNlcjpwYXNzd29yZA==" test := &Test{ - datasource: &m.DataSource{ + datasource: &models.DataSource{ Type: dsType, JsonData: simplejson.New(), }, @@ -661,7 +661,7 @@ func createAuthTest(dsType string, authType string, authCheck string, useSecureJ func runDatasourceAuthTest(test *Test) { plugin := &plugins.DataSourcePlugin{} - ctx := &m.ReqContext{} + ctx := &models.ReqContext{} proxy := NewDataSourceProxy(test.datasource, plugin, ctx, "", &setting.Cfg{}) req, err := http.NewRequest(http.MethodGet, "http://grafana.com/sub", nil) diff --git a/pkg/api/pluginproxy/pluginproxy.go b/pkg/api/pluginproxy/pluginproxy.go index 72d783ac8bf..0eec4dc7fd2 100644 --- a/pkg/api/pluginproxy/pluginproxy.go +++ b/pkg/api/pluginproxy/pluginproxy.go @@ -8,7 +8,7 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/infra/log" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/plugins" "github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/util" @@ -23,7 +23,7 @@ type templateData struct { func getHeaders(route *plugins.AppPluginRoute, orgId int64, appID string) (http.Header, error) { result := http.Header{} - query := m.GetPluginSettingByIdQuery{OrgId: orgId, PluginId: appID} + query := models.GetPluginSettingByIdQuery{OrgId: orgId, PluginId: appID} if err := bus.Dispatch(&query); err != nil { return nil, err @@ -39,7 +39,7 @@ func getHeaders(route *plugins.AppPluginRoute, orgId int64, appID string) (http. } func updateURL(route *plugins.AppPluginRoute, orgId int64, appID string) (string, error) { - query := m.GetPluginSettingByIdQuery{OrgId: orgId, PluginId: appID} + query := models.GetPluginSettingByIdQuery{OrgId: orgId, PluginId: appID} if err := bus.Dispatch(&query); err != nil { return "", err } @@ -56,7 +56,7 @@ func updateURL(route *plugins.AppPluginRoute, orgId int64, appID string) (string } // NewApiPluginProxy create a plugin proxy -func NewApiPluginProxy(ctx *m.ReqContext, proxyPath string, route *plugins.AppPluginRoute, appID string, cfg *setting.Cfg) *httputil.ReverseProxy { +func NewApiPluginProxy(ctx *models.ReqContext, proxyPath string, route *plugins.AppPluginRoute, appID string, cfg *setting.Cfg) *httputil.ReverseProxy { targetURL, _ := url.Parse(route.Url) director := func(req *http.Request) { diff --git a/pkg/api/pluginproxy/pluginproxy_test.go b/pkg/api/pluginproxy/pluginproxy_test.go index 343823b00a2..a19745c0574 100644 --- a/pkg/api/pluginproxy/pluginproxy_test.go +++ b/pkg/api/pluginproxy/pluginproxy_test.go @@ -5,7 +5,7 @@ import ( "testing" "github.com/grafana/grafana/pkg/bus" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/plugins" "github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/util" @@ -23,13 +23,13 @@ func TestPluginProxy(t *testing.T) { setting.SecretKey = "password" - bus.AddHandler("test", func(query *m.GetPluginSettingByIdQuery) error { + bus.AddHandler("test", func(query *models.GetPluginSettingByIdQuery) error { key, err := util.Encrypt([]byte("123"), "password") if err != nil { return err } - query.Result = &m.PluginSetting{ + query.Result = &models.PluginSetting{ SecureJsonData: map[string][]byte{ "key": key, }, @@ -47,8 +47,8 @@ func TestPluginProxy(t *testing.T) { Convey("When SendUserHeader config is enabled", t, func() { req := getPluginProxiedRequest( - &m.ReqContext{ - SignedInUser: &m.SignedInUser{ + &models.ReqContext{ + SignedInUser: &models.SignedInUser{ Login: "test_user", }, }, @@ -64,8 +64,8 @@ func TestPluginProxy(t *testing.T) { Convey("When SendUserHeader config is disabled", t, func() { req := getPluginProxiedRequest( - &m.ReqContext{ - SignedInUser: &m.SignedInUser{ + &models.ReqContext{ + SignedInUser: &models.SignedInUser{ Login: "test_user", }, }, @@ -80,8 +80,8 @@ func TestPluginProxy(t *testing.T) { Convey("When SendUserHeader config is enabled but user is anonymous", t, func() { req := getPluginProxiedRequest( - &m.ReqContext{ - SignedInUser: &m.SignedInUser{IsAnonymous: true}, + &models.ReqContext{ + SignedInUser: &models.SignedInUser{IsAnonymous: true}, }, &setting.Cfg{SendUserHeader: true}, nil, @@ -99,8 +99,8 @@ func TestPluginProxy(t *testing.T) { Method: "GET", } - bus.AddHandler("test", func(query *m.GetPluginSettingByIdQuery) error { - query.Result = &m.PluginSetting{ + bus.AddHandler("test", func(query *models.GetPluginSettingByIdQuery) error { + query.Result = &models.PluginSetting{ JsonData: map[string]interface{}{ "dynamicUrl": "https://dynamic.grafana.com", }, @@ -109,8 +109,8 @@ func TestPluginProxy(t *testing.T) { }) req := getPluginProxiedRequest( - &m.ReqContext{ - SignedInUser: &m.SignedInUser{ + &models.ReqContext{ + SignedInUser: &models.SignedInUser{ Login: "test_user", }, }, @@ -133,13 +133,13 @@ func TestPluginProxy(t *testing.T) { } // getPluginProxiedRequest is a helper for easier setup of tests based on global config and ReqContext. -func getPluginProxiedRequest(ctx *m.ReqContext, cfg *setting.Cfg, route *plugins.AppPluginRoute) *http.Request { +func getPluginProxiedRequest(ctx *models.ReqContext, cfg *setting.Cfg, route *plugins.AppPluginRoute) *http.Request { // insert dummy route if none is specified if route == nil { route = &plugins.AppPluginRoute{ Path: "api/v4/", Url: "https://www.google.com", - ReqRole: m.ROLE_EDITOR, + ReqRole: models.ROLE_EDITOR, } } proxy := NewApiPluginProxy(ctx, "", route, "", cfg) diff --git a/pkg/api/pluginproxy/utils.go b/pkg/api/pluginproxy/utils.go index f507a54d376..462f1d96169 100644 --- a/pkg/api/pluginproxy/utils.go +++ b/pkg/api/pluginproxy/utils.go @@ -6,7 +6,7 @@ import ( "net/url" "text/template" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/plugins" ) @@ -28,7 +28,7 @@ func InterpolateString(text string, data templateData) (string, error) { // InterpolateURL accepts template data and return a string with substitutions func InterpolateURL(anURL *url.URL, route *plugins.AppPluginRoute, orgID int64, appID string) (*url.URL, error) { - query := m.GetPluginSettingByIdQuery{OrgId: orgID, PluginId: appID} + query := models.GetPluginSettingByIdQuery{OrgId: orgID, PluginId: appID} result, err := url.Parse(anURL.String()) if query.Result != nil { if len(query.Result.JsonData) > 0 { diff --git a/pkg/api/preferences.go b/pkg/api/preferences.go index 9b451aa2a6e..e47ea0e3b54 100644 --- a/pkg/api/preferences.go +++ b/pkg/api/preferences.go @@ -3,11 +3,11 @@ package api import ( "github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/bus" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" ) // POST /api/preferences/set-home-dash -func SetHomeDashboard(c *m.ReqContext, cmd m.SavePreferencesCommand) Response { +func SetHomeDashboard(c *models.ReqContext, cmd models.SavePreferencesCommand) Response { cmd.UserId = c.UserId cmd.OrgId = c.OrgId @@ -20,12 +20,12 @@ func SetHomeDashboard(c *m.ReqContext, cmd m.SavePreferencesCommand) Response { } // GET /api/user/preferences -func GetUserPreferences(c *m.ReqContext) Response { +func GetUserPreferences(c *models.ReqContext) Response { return getPreferencesFor(c.OrgId, c.UserId, 0) } func getPreferencesFor(orgID, userID, teamID int64) Response { - prefsQuery := m.GetPreferencesQuery{UserId: userID, OrgId: orgID, TeamId: teamID} + prefsQuery := models.GetPreferencesQuery{UserId: userID, OrgId: orgID, TeamId: teamID} if err := bus.Dispatch(&prefsQuery); err != nil { return Error(500, "Failed to get preferences", err) @@ -41,12 +41,12 @@ func getPreferencesFor(orgID, userID, teamID int64) Response { } // PUT /api/user/preferences -func UpdateUserPreferences(c *m.ReqContext, dtoCmd dtos.UpdatePrefsCmd) Response { +func UpdateUserPreferences(c *models.ReqContext, dtoCmd dtos.UpdatePrefsCmd) Response { return updatePreferencesFor(c.OrgId, c.UserId, 0, &dtoCmd) } func updatePreferencesFor(orgID, userID, teamId int64, dtoCmd *dtos.UpdatePrefsCmd) Response { - saveCmd := m.SavePreferencesCommand{ + saveCmd := models.SavePreferencesCommand{ UserId: userID, OrgId: orgID, TeamId: teamId, @@ -63,11 +63,11 @@ func updatePreferencesFor(orgID, userID, teamId int64, dtoCmd *dtos.UpdatePrefsC } // GET /api/org/preferences -func GetOrgPreferences(c *m.ReqContext) Response { +func GetOrgPreferences(c *models.ReqContext) Response { return getPreferencesFor(c.OrgId, 0, 0) } // PUT /api/org/preferences -func UpdateOrgPreferences(c *m.ReqContext, dtoCmd dtos.UpdatePrefsCmd) Response { +func UpdateOrgPreferences(c *models.ReqContext, dtoCmd dtos.UpdatePrefsCmd) Response { return updatePreferencesFor(c.OrgId, 0, 0, &dtoCmd) } diff --git a/pkg/api/quota.go b/pkg/api/quota.go index d469f843930..ad8764f656c 100644 --- a/pkg/api/quota.go +++ b/pkg/api/quota.go @@ -2,15 +2,15 @@ package api import ( "github.com/grafana/grafana/pkg/bus" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/setting" ) -func GetOrgQuotas(c *m.ReqContext) Response { +func GetOrgQuotas(c *models.ReqContext) Response { if !setting.Quota.Enabled { return Error(404, "Quotas not enabled", nil) } - query := m.GetOrgQuotasQuery{OrgId: c.ParamsInt64(":orgId")} + query := models.GetOrgQuotasQuery{OrgId: c.ParamsInt64(":orgId")} if err := bus.Dispatch(&query); err != nil { return Error(500, "Failed to get org quotas", err) @@ -19,7 +19,7 @@ func GetOrgQuotas(c *m.ReqContext) Response { return JSON(200, query.Result) } -func UpdateOrgQuota(c *m.ReqContext, cmd m.UpdateOrgQuotaCmd) Response { +func UpdateOrgQuota(c *models.ReqContext, cmd models.UpdateOrgQuotaCmd) Response { if !setting.Quota.Enabled { return Error(404, "Quotas not enabled", nil) } @@ -36,11 +36,11 @@ func UpdateOrgQuota(c *m.ReqContext, cmd m.UpdateOrgQuotaCmd) Response { return Success("Organization quota updated") } -func GetUserQuotas(c *m.ReqContext) Response { +func GetUserQuotas(c *models.ReqContext) Response { if !setting.Quota.Enabled { return Error(404, "Quotas not enabled", nil) } - query := m.GetUserQuotasQuery{UserId: c.ParamsInt64(":id")} + query := models.GetUserQuotasQuery{UserId: c.ParamsInt64(":id")} if err := bus.Dispatch(&query); err != nil { return Error(500, "Failed to get org quotas", err) @@ -49,7 +49,7 @@ func GetUserQuotas(c *m.ReqContext) Response { return JSON(200, query.Result) } -func UpdateUserQuota(c *m.ReqContext, cmd m.UpdateUserQuotaCmd) Response { +func UpdateUserQuota(c *models.ReqContext, cmd models.UpdateUserQuotaCmd) Response { if !setting.Quota.Enabled { return Error(404, "Quotas not enabled", nil) } diff --git a/pkg/api/render.go b/pkg/api/render.go index a4e2c6ed29c..375f905a561 100644 --- a/pkg/api/render.go +++ b/pkg/api/render.go @@ -8,12 +8,12 @@ import ( "strings" "time" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/rendering" "github.com/grafana/grafana/pkg/util" ) -func (hs *HTTPServer) RenderToPng(c *m.ReqContext) { +func (hs *HTTPServer) RenderToPng(c *models.ReqContext) { queryReader, err := util.NewURLQueryReader(c.Req.URL) if err != nil { c.Handle(400, "Render parameters error", err) diff --git a/pkg/api/search.go b/pkg/api/search.go index 5819bf3ee8a..2bf85a8f5bb 100644 --- a/pkg/api/search.go +++ b/pkg/api/search.go @@ -5,25 +5,25 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/infra/metrics" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/search" ) -func Search(c *m.ReqContext) Response { +func Search(c *models.ReqContext) Response { query := c.Query("query") tags := c.QueryStrings("tag") starred := c.Query("starred") limit := c.QueryInt64("limit") page := c.QueryInt64("page") dashboardType := c.Query("type") - permission := m.PERMISSION_VIEW + permission := models.PERMISSION_VIEW if limit > 5000 { return Error(422, "Limit is above maximum allowed (5000), use page parameter to access hits beyond limit", nil) } if c.Query("permission") == "Edit" { - permission = m.PERMISSION_EDIT + permission = models.PERMISSION_EDIT } dbIDs := make([]int64, 0) diff --git a/pkg/api/signup.go b/pkg/api/signup.go index 5a017655b6e..fb6fe22e5ce 100644 --- a/pkg/api/signup.go +++ b/pkg/api/signup.go @@ -5,13 +5,13 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/events" "github.com/grafana/grafana/pkg/infra/metrics" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/util" ) // GET /api/user/signup/options -func GetSignUpOptions(c *m.ReqContext) Response { +func GetSignUpOptions(c *models.ReqContext) Response { return JSON(200, util.DynMap{ "verifyEmailEnabled": setting.VerifyEmailEnabled, "autoAssignOrg": setting.AutoAssignOrg, @@ -19,20 +19,20 @@ func GetSignUpOptions(c *m.ReqContext) Response { } // POST /api/user/signup -func SignUp(c *m.ReqContext, form dtos.SignUpForm) Response { +func SignUp(c *models.ReqContext, form dtos.SignUpForm) Response { if !setting.AllowUserSignUp { return Error(401, "User signup is disabled", nil) } - existing := m.GetUserByLoginQuery{LoginOrEmail: form.Email} + existing := models.GetUserByLoginQuery{LoginOrEmail: form.Email} if err := bus.Dispatch(&existing); err == nil { return Error(422, "User with same email address already exists", nil) } - cmd := m.CreateTempUserCommand{} + cmd := models.CreateTempUserCommand{} cmd.OrgId = -1 cmd.Email = form.Email - cmd.Status = m.TmpUserSignUpStarted + cmd.Status = models.TmpUserSignUpStarted cmd.InvitedByUserId = c.UserId var err error cmd.Code, err = util.GetRandomString(20) @@ -57,12 +57,12 @@ func SignUp(c *m.ReqContext, form dtos.SignUpForm) Response { return JSON(200, util.DynMap{"status": "SignUpCreated"}) } -func (hs *HTTPServer) SignUpStep2(c *m.ReqContext, form dtos.SignUpStep2Form) Response { +func (hs *HTTPServer) SignUpStep2(c *models.ReqContext, form dtos.SignUpStep2Form) Response { if !setting.AllowUserSignUp { return Error(401, "User signup is disabled", nil) } - createUserCmd := m.CreateUserCommand{ + createUserCmd := models.CreateUserCommand{ Email: form.Email, Login: form.Username, Name: form.Name, @@ -79,7 +79,7 @@ func (hs *HTTPServer) SignUpStep2(c *m.ReqContext, form dtos.SignUpStep2Form) Re } // check if user exists - existing := m.GetUserByLoginQuery{LoginOrEmail: form.Email} + existing := models.GetUserByLoginQuery{LoginOrEmail: form.Email} if err := bus.Dispatch(&existing); err == nil { return Error(401, "User with same email address already exists", nil) } @@ -99,12 +99,12 @@ func (hs *HTTPServer) SignUpStep2(c *m.ReqContext, form dtos.SignUpStep2Form) Re } // mark temp user as completed - if ok, rsp := updateTempUserStatus(form.Code, m.TmpUserCompleted); !ok { + if ok, rsp := updateTempUserStatus(form.Code, models.TmpUserCompleted); !ok { return rsp } // check for pending invites - invitesQuery := m.GetTempUsersQuery{Email: form.Email, Status: m.TmpUserInvitePending} + invitesQuery := models.GetTempUsersQuery{Email: form.Email, Status: models.TmpUserInvitePending} if err := bus.Dispatch(&invitesQuery); err != nil { return Error(500, "Failed to query database for invites", err) } @@ -124,10 +124,10 @@ func (hs *HTTPServer) SignUpStep2(c *m.ReqContext, form dtos.SignUpStep2Form) Re } func verifyUserSignUpEmail(email string, code string) (bool, Response) { - query := m.GetTempUserByCodeQuery{Code: code} + query := models.GetTempUserByCodeQuery{Code: code} if err := bus.Dispatch(&query); err != nil { - if err == m.ErrTempUserNotFound { + if err == models.ErrTempUserNotFound { return false, Error(404, "Invalid email verification code", nil) } return false, Error(500, "Failed to read temp user", err) diff --git a/pkg/api/stars.go b/pkg/api/stars.go index 2c55b95dfbe..3a6640cacf4 100644 --- a/pkg/api/stars.go +++ b/pkg/api/stars.go @@ -2,15 +2,15 @@ package api import ( "github.com/grafana/grafana/pkg/bus" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" ) -func StarDashboard(c *m.ReqContext) Response { +func StarDashboard(c *models.ReqContext) Response { if !c.IsSignedIn { return Error(412, "You need to sign in to star dashboards", nil) } - cmd := m.StarDashboardCommand{UserId: c.UserId, DashboardId: c.ParamsInt64(":id")} + cmd := models.StarDashboardCommand{UserId: c.UserId, DashboardId: c.ParamsInt64(":id")} if cmd.DashboardId <= 0 { return Error(400, "Missing dashboard id", nil) @@ -23,9 +23,9 @@ func StarDashboard(c *m.ReqContext) Response { return Success("Dashboard starred!") } -func UnstarDashboard(c *m.ReqContext) Response { +func UnstarDashboard(c *models.ReqContext) Response { - cmd := m.UnstarDashboardCommand{UserId: c.UserId, DashboardId: c.ParamsInt64(":id")} + cmd := models.UnstarDashboardCommand{UserId: c.UserId, DashboardId: c.ParamsInt64(":id")} if cmd.DashboardId <= 0 { return Error(400, "Missing dashboard id", nil) diff --git a/pkg/api/team.go b/pkg/api/team.go index 7ba9b738b90..7210e7712b9 100644 --- a/pkg/api/team.go +++ b/pkg/api/team.go @@ -3,36 +3,36 @@ package api import ( "github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/bus" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/teamguardian" "github.com/grafana/grafana/pkg/util" ) // POST /api/teams -func (hs *HTTPServer) CreateTeam(c *m.ReqContext, cmd m.CreateTeamCommand) Response { +func (hs *HTTPServer) CreateTeam(c *models.ReqContext, cmd models.CreateTeamCommand) Response { cmd.OrgId = c.OrgId - if c.OrgRole == m.ROLE_VIEWER { + if c.OrgRole == models.ROLE_VIEWER { return Error(403, "Not allowed to create team.", nil) } if err := hs.Bus.Dispatch(&cmd); err != nil { - if err == m.ErrTeamNameTaken { + if err == models.ErrTeamNameTaken { return Error(409, "Team name taken", err) } return Error(500, "Failed to create Team", err) } - if c.OrgRole == m.ROLE_EDITOR && hs.Cfg.EditorsCanAdmin { + if c.OrgRole == models.ROLE_EDITOR && hs.Cfg.EditorsCanAdmin { // if the request is authenticated using API tokens // the SignedInUser is an empty struct therefore // an additional check whether it is an actual user is required if c.SignedInUser.IsRealUser() { - addMemberCmd := m.AddTeamMemberCommand{ + addMemberCmd := models.AddTeamMemberCommand{ UserId: c.SignedInUser.UserId, OrgId: cmd.OrgId, TeamId: cmd.Result.Id, - Permission: m.PERMISSION_ADMIN, + Permission: models.PERMISSION_ADMIN, } if err := hs.Bus.Dispatch(&addMemberCmd); err != nil { @@ -50,7 +50,7 @@ func (hs *HTTPServer) CreateTeam(c *m.ReqContext, cmd m.CreateTeamCommand) Respo } // PUT /api/teams/:teamId -func (hs *HTTPServer) UpdateTeam(c *m.ReqContext, cmd m.UpdateTeamCommand) Response { +func (hs *HTTPServer) UpdateTeam(c *models.ReqContext, cmd models.UpdateTeamCommand) Response { cmd.OrgId = c.OrgId cmd.Id = c.ParamsInt64(":teamId") @@ -59,7 +59,7 @@ func (hs *HTTPServer) UpdateTeam(c *m.ReqContext, cmd m.UpdateTeamCommand) Respo } if err := hs.Bus.Dispatch(&cmd); err != nil { - if err == m.ErrTeamNameTaken { + if err == models.ErrTeamNameTaken { return Error(400, "Team name taken", err) } return Error(500, "Failed to update Team", err) @@ -69,7 +69,7 @@ func (hs *HTTPServer) UpdateTeam(c *m.ReqContext, cmd m.UpdateTeamCommand) Respo } // DELETE /api/teams/:teamId -func (hs *HTTPServer) DeleteTeamByID(c *m.ReqContext) Response { +func (hs *HTTPServer) DeleteTeamByID(c *models.ReqContext) Response { orgId := c.OrgId teamId := c.ParamsInt64(":teamId") user := c.SignedInUser @@ -78,8 +78,8 @@ func (hs *HTTPServer) DeleteTeamByID(c *m.ReqContext) Response { return Error(403, "Not allowed to delete team", err) } - if err := hs.Bus.Dispatch(&m.DeleteTeamCommand{OrgId: orgId, Id: teamId}); err != nil { - if err == m.ErrTeamNotFound { + if err := hs.Bus.Dispatch(&models.DeleteTeamCommand{OrgId: orgId, Id: teamId}); err != nil { + if err == models.ErrTeamNotFound { return Error(404, "Failed to delete Team. ID not found", nil) } return Error(500, "Failed to delete Team", err) @@ -88,7 +88,7 @@ func (hs *HTTPServer) DeleteTeamByID(c *m.ReqContext) Response { } // GET /api/teams/search -func (hs *HTTPServer) SearchTeams(c *m.ReqContext) Response { +func (hs *HTTPServer) SearchTeams(c *models.ReqContext) Response { perPage := c.QueryInt("perpage") if perPage <= 0 { perPage = 1000 @@ -99,11 +99,11 @@ func (hs *HTTPServer) SearchTeams(c *m.ReqContext) Response { } var userIdFilter int64 - if hs.Cfg.EditorsCanAdmin && c.OrgRole != m.ROLE_ADMIN { + if hs.Cfg.EditorsCanAdmin && c.OrgRole != models.ROLE_ADMIN { userIdFilter = c.SignedInUser.UserId } - query := m.SearchTeamsQuery{ + query := models.SearchTeamsQuery{ OrgId: c.OrgId, Query: c.Query("query"), Name: c.Query("name"), @@ -127,11 +127,11 @@ func (hs *HTTPServer) SearchTeams(c *m.ReqContext) Response { } // GET /api/teams/:teamId -func GetTeamByID(c *m.ReqContext) Response { - query := m.GetTeamByIdQuery{OrgId: c.OrgId, Id: c.ParamsInt64(":teamId")} +func GetTeamByID(c *models.ReqContext) Response { + query := models.GetTeamByIdQuery{OrgId: c.OrgId, Id: c.ParamsInt64(":teamId")} if err := bus.Dispatch(&query); err != nil { - if err == m.ErrTeamNotFound { + if err == models.ErrTeamNotFound { return Error(404, "Team not found", err) } @@ -143,7 +143,7 @@ func GetTeamByID(c *m.ReqContext) Response { } // GET /api/teams/:teamId/preferences -func (hs *HTTPServer) GetTeamPreferences(c *m.ReqContext) Response { +func (hs *HTTPServer) GetTeamPreferences(c *models.ReqContext) Response { teamId := c.ParamsInt64(":teamId") orgId := c.OrgId @@ -155,7 +155,7 @@ func (hs *HTTPServer) GetTeamPreferences(c *m.ReqContext) Response { } // PUT /api/teams/:teamId/preferences -func (hs *HTTPServer) UpdateTeamPreferences(c *m.ReqContext, dtoCmd dtos.UpdatePrefsCmd) Response { +func (hs *HTTPServer) UpdateTeamPreferences(c *models.ReqContext, dtoCmd dtos.UpdatePrefsCmd) Response { teamId := c.ParamsInt64(":teamId") orgId := c.OrgId diff --git a/pkg/api/team_members.go b/pkg/api/team_members.go index ed63c72ef91..b07dffadf59 100644 --- a/pkg/api/team_members.go +++ b/pkg/api/team_members.go @@ -3,14 +3,14 @@ package api import ( "github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/bus" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/teamguardian" "github.com/grafana/grafana/pkg/util" ) // GET /api/teams/:teamId/members -func (hs *HTTPServer) GetTeamMembers(c *m.ReqContext) Response { - query := m.GetTeamMembersQuery{OrgId: c.OrgId, TeamId: c.ParamsInt64(":teamId")} +func (hs *HTTPServer) GetTeamMembers(c *models.ReqContext) Response { + query := models.GetTeamMembersQuery{OrgId: c.OrgId, TeamId: c.ParamsInt64(":teamId")} if err := bus.Dispatch(&query); err != nil { return Error(500, "Failed to get Team Members", err) @@ -30,7 +30,7 @@ func (hs *HTTPServer) GetTeamMembers(c *m.ReqContext) Response { } // POST /api/teams/:teamId/members -func (hs *HTTPServer) AddTeamMember(c *m.ReqContext, cmd m.AddTeamMemberCommand) Response { +func (hs *HTTPServer) AddTeamMember(c *models.ReqContext, cmd models.AddTeamMemberCommand) Response { cmd.OrgId = c.OrgId cmd.TeamId = c.ParamsInt64(":teamId") @@ -39,11 +39,11 @@ func (hs *HTTPServer) AddTeamMember(c *m.ReqContext, cmd m.AddTeamMemberCommand) } if err := hs.Bus.Dispatch(&cmd); err != nil { - if err == m.ErrTeamNotFound { + if err == models.ErrTeamNotFound { return Error(404, "Team not found", nil) } - if err == m.ErrTeamMemberAlreadyAdded { + if err == models.ErrTeamMemberAlreadyAdded { return Error(400, "User is already added to this team", nil) } @@ -56,7 +56,7 @@ func (hs *HTTPServer) AddTeamMember(c *m.ReqContext, cmd m.AddTeamMemberCommand) } // PUT /:teamId/members/:userId -func (hs *HTTPServer) UpdateTeamMember(c *m.ReqContext, cmd m.UpdateTeamMemberCommand) Response { +func (hs *HTTPServer) UpdateTeamMember(c *models.ReqContext, cmd models.UpdateTeamMemberCommand) Response { teamId := c.ParamsInt64(":teamId") orgId := c.OrgId @@ -64,7 +64,7 @@ func (hs *HTTPServer) UpdateTeamMember(c *m.ReqContext, cmd m.UpdateTeamMemberCo return Error(403, "Not allowed to update team member", err) } - if c.OrgRole != m.ROLE_ADMIN { + if c.OrgRole != models.ROLE_ADMIN { cmd.ProtectLastAdmin = true } @@ -73,7 +73,7 @@ func (hs *HTTPServer) UpdateTeamMember(c *m.ReqContext, cmd m.UpdateTeamMemberCo cmd.OrgId = orgId if err := hs.Bus.Dispatch(&cmd); err != nil { - if err == m.ErrTeamMemberNotFound { + if err == models.ErrTeamMemberNotFound { return Error(404, "Team member not found.", nil) } return Error(500, "Failed to update team member.", err) @@ -82,7 +82,7 @@ func (hs *HTTPServer) UpdateTeamMember(c *m.ReqContext, cmd m.UpdateTeamMemberCo } // DELETE /api/teams/:teamId/members/:userId -func (hs *HTTPServer) RemoveTeamMember(c *m.ReqContext) Response { +func (hs *HTTPServer) RemoveTeamMember(c *models.ReqContext) Response { orgId := c.OrgId teamId := c.ParamsInt64(":teamId") userId := c.ParamsInt64(":userId") @@ -92,16 +92,16 @@ func (hs *HTTPServer) RemoveTeamMember(c *m.ReqContext) Response { } protectLastAdmin := false - if c.OrgRole != m.ROLE_ADMIN { + if c.OrgRole != models.ROLE_ADMIN { protectLastAdmin = true } - if err := hs.Bus.Dispatch(&m.RemoveTeamMemberCommand{OrgId: orgId, TeamId: teamId, UserId: userId, ProtectLastAdmin: protectLastAdmin}); err != nil { - if err == m.ErrTeamNotFound { + if err := hs.Bus.Dispatch(&models.RemoveTeamMemberCommand{OrgId: orgId, TeamId: teamId, UserId: userId, ProtectLastAdmin: protectLastAdmin}); err != nil { + if err == models.ErrTeamNotFound { return Error(404, "Team not found", nil) } - if err == m.ErrTeamMemberNotFound { + if err == models.ErrTeamMemberNotFound { return Error(404, "Team member not found", nil) } diff --git a/pkg/api/user.go b/pkg/api/user.go index d878d0bb58b..8cedb52034b 100644 --- a/pkg/api/user.go +++ b/pkg/api/user.go @@ -3,32 +3,32 @@ package api import ( "github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/bus" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/util" ) // GET /api/user (current authenticated user) -func GetSignedInUser(c *m.ReqContext) Response { +func GetSignedInUser(c *models.ReqContext) Response { return getUserUserProfile(c.UserId) } // GET /api/users/:id -func GetUserByID(c *m.ReqContext) Response { +func GetUserByID(c *models.ReqContext) Response { return getUserUserProfile(c.ParamsInt64(":id")) } func getUserUserProfile(userID int64) Response { - query := m.GetUserProfileQuery{UserId: userID} + query := models.GetUserProfileQuery{UserId: userID} if err := bus.Dispatch(&query); err != nil { - if err == m.ErrUserNotFound { - return Error(404, m.ErrUserNotFound.Error(), nil) + if err == models.ErrUserNotFound { + return Error(404, models.ErrUserNotFound.Error(), nil) } return Error(500, "Failed to get user", err) } - getAuthQuery := m.GetAuthInfoQuery{UserId: userID} + getAuthQuery := models.GetAuthInfoQuery{UserId: userID} query.Result.AuthLabels = []string{} if err := bus.Dispatch(&getAuthQuery); err == nil { authLabel := GetAuthProviderLabel(getAuthQuery.Result.AuthModule) @@ -42,16 +42,16 @@ func getUserUserProfile(userID int64) Response { } // GET /api/users/lookup -func GetUserByLoginOrEmail(c *m.ReqContext) Response { - query := m.GetUserByLoginQuery{LoginOrEmail: c.Query("loginOrEmail")} +func GetUserByLoginOrEmail(c *models.ReqContext) Response { + query := models.GetUserByLoginQuery{LoginOrEmail: c.Query("loginOrEmail")} if err := bus.Dispatch(&query); err != nil { - if err == m.ErrUserNotFound { - return Error(404, m.ErrUserNotFound.Error(), nil) + if err == models.ErrUserNotFound { + return Error(404, models.ErrUserNotFound.Error(), nil) } return Error(500, "Failed to get user", err) } user := query.Result - result := m.UserProfileDTO{ + result := models.UserProfileDTO{ Id: user.Id, Name: user.Name, Email: user.Email, @@ -66,7 +66,7 @@ func GetUserByLoginOrEmail(c *m.ReqContext) Response { } // POST /api/user -func UpdateSignedInUser(c *m.ReqContext, cmd m.UpdateUserCommand) Response { +func UpdateSignedInUser(c *models.ReqContext, cmd models.UpdateUserCommand) Response { if setting.AuthProxyEnabled { if setting.AuthProxyHeaderProperty == "email" && cmd.Email != c.Email { return Error(400, "Not allowed to change email when auth proxy is using email property", nil) @@ -80,13 +80,13 @@ func UpdateSignedInUser(c *m.ReqContext, cmd m.UpdateUserCommand) Response { } // POST /api/users/:id -func UpdateUser(c *m.ReqContext, cmd m.UpdateUserCommand) Response { +func UpdateUser(c *models.ReqContext, cmd models.UpdateUserCommand) Response { cmd.UserId = c.ParamsInt64(":id") return handleUpdateUser(cmd) } //POST /api/users/:id/using/:orgId -func UpdateUserActiveOrg(c *m.ReqContext) Response { +func UpdateUserActiveOrg(c *models.ReqContext) Response { userID := c.ParamsInt64(":id") orgID := c.ParamsInt64(":orgId") @@ -94,7 +94,7 @@ func UpdateUserActiveOrg(c *m.ReqContext) Response { return Error(401, "Not a valid organization", nil) } - cmd := m.SetUsingOrgCommand{UserId: userID, OrgId: orgID} + cmd := models.SetUsingOrgCommand{UserId: userID, OrgId: orgID} if err := bus.Dispatch(&cmd); err != nil { return Error(500, "Failed to change active organization", err) @@ -103,7 +103,7 @@ func UpdateUserActiveOrg(c *m.ReqContext) Response { return Success("Active organization changed") } -func handleUpdateUser(cmd m.UpdateUserCommand) Response { +func handleUpdateUser(cmd models.UpdateUserCommand) Response { if len(cmd.Login) == 0 { cmd.Login = cmd.Email if len(cmd.Login) == 0 { @@ -119,22 +119,22 @@ func handleUpdateUser(cmd m.UpdateUserCommand) Response { } // GET /api/user/orgs -func GetSignedInUserOrgList(c *m.ReqContext) Response { +func GetSignedInUserOrgList(c *models.ReqContext) Response { return getUserOrgList(c.UserId) } // GET /api/user/teams -func GetSignedInUserTeamList(c *m.ReqContext) Response { +func GetSignedInUserTeamList(c *models.ReqContext) Response { return getUserTeamList(c.OrgId, c.UserId) } // GET /api/users/:id/teams -func GetUserTeams(c *m.ReqContext) Response { +func GetUserTeams(c *models.ReqContext) Response { return getUserTeamList(c.OrgId, c.ParamsInt64(":id")) } func getUserTeamList(orgID int64, userID int64) Response { - query := m.GetTeamsByUserQuery{OrgId: orgID, UserId: userID} + query := models.GetTeamsByUserQuery{OrgId: orgID, UserId: userID} if err := bus.Dispatch(&query); err != nil { return Error(500, "Failed to get user teams", err) @@ -147,12 +147,12 @@ func getUserTeamList(orgID int64, userID int64) Response { } // GET /api/users/:id/orgs -func GetUserOrgList(c *m.ReqContext) Response { +func GetUserOrgList(c *models.ReqContext) Response { return getUserOrgList(c.ParamsInt64(":id")) } func getUserOrgList(userID int64) Response { - query := m.GetUserOrgListQuery{UserId: userID} + query := models.GetUserOrgListQuery{UserId: userID} if err := bus.Dispatch(&query); err != nil { return Error(500, "Failed to get user organizations", err) @@ -162,7 +162,7 @@ func getUserOrgList(userID int64) Response { } func validateUsingOrg(userID int64, orgID int64) bool { - query := m.GetUserOrgListQuery{UserId: userID} + query := models.GetUserOrgListQuery{UserId: userID} if err := bus.Dispatch(&query); err != nil { return false @@ -180,14 +180,14 @@ func validateUsingOrg(userID int64, orgID int64) bool { } // POST /api/user/using/:id -func UserSetUsingOrg(c *m.ReqContext) Response { +func UserSetUsingOrg(c *models.ReqContext) Response { orgID := c.ParamsInt64(":id") if !validateUsingOrg(c.UserId, orgID) { return Error(401, "Not a valid organization", nil) } - cmd := m.SetUsingOrgCommand{UserId: c.UserId, OrgId: orgID} + cmd := models.SetUsingOrgCommand{UserId: c.UserId, OrgId: orgID} if err := bus.Dispatch(&cmd); err != nil { return Error(500, "Failed to change active organization", err) @@ -197,14 +197,14 @@ func UserSetUsingOrg(c *m.ReqContext) Response { } // GET /profile/switch-org/:id -func (hs *HTTPServer) ChangeActiveOrgAndRedirectToHome(c *m.ReqContext) { +func (hs *HTTPServer) ChangeActiveOrgAndRedirectToHome(c *models.ReqContext) { orgID := c.ParamsInt64(":id") if !validateUsingOrg(c.UserId, orgID) { hs.NotFoundHandler(c) } - cmd := m.SetUsingOrgCommand{UserId: c.UserId, OrgId: orgID} + cmd := models.SetUsingOrgCommand{UserId: c.UserId, OrgId: orgID} if err := bus.Dispatch(&cmd); err != nil { hs.NotFoundHandler(c) @@ -213,12 +213,12 @@ func (hs *HTTPServer) ChangeActiveOrgAndRedirectToHome(c *m.ReqContext) { c.Redirect(setting.AppSubUrl + "/") } -func ChangeUserPassword(c *m.ReqContext, cmd m.ChangeUserPasswordCommand) Response { +func ChangeUserPassword(c *models.ReqContext, cmd models.ChangeUserPasswordCommand) Response { if setting.LDAPEnabled || setting.AuthProxyEnabled { return Error(400, "Not allowed to change password when LDAP or Auth Proxy is enabled", nil) } - userQuery := m.GetUserByIdQuery{Id: c.UserId} + userQuery := models.GetUserByIdQuery{Id: c.UserId} if err := bus.Dispatch(&userQuery); err != nil { return Error(500, "Could not read user from database", err) @@ -232,7 +232,7 @@ func ChangeUserPassword(c *m.ReqContext, cmd m.ChangeUserPasswordCommand) Respon return Error(401, "Invalid old password", nil) } - password := m.Password(cmd.NewPassword) + password := models.Password(cmd.NewPassword) if password.IsWeak() { return Error(400, "New password is too short", nil) } @@ -251,7 +251,7 @@ func ChangeUserPassword(c *m.ReqContext, cmd m.ChangeUserPasswordCommand) Respon } // GET /api/users -func SearchUsers(c *m.ReqContext) Response { +func SearchUsers(c *models.ReqContext) Response { query, err := searchUser(c) if err != nil { return Error(500, "Failed to fetch users", err) @@ -261,7 +261,7 @@ func SearchUsers(c *m.ReqContext) Response { } // GET /api/users/search -func SearchUsersWithPaging(c *m.ReqContext) Response { +func SearchUsersWithPaging(c *models.ReqContext) Response { query, err := searchUser(c) if err != nil { return Error(500, "Failed to fetch users", err) @@ -270,7 +270,7 @@ func SearchUsersWithPaging(c *m.ReqContext) Response { return JSON(200, query.Result) } -func searchUser(c *m.ReqContext) (*m.SearchUsersQuery, error) { +func searchUser(c *models.ReqContext) (*models.SearchUsersQuery, error) { perPage := c.QueryInt("perpage") if perPage <= 0 { perPage = 1000 @@ -283,7 +283,7 @@ func searchUser(c *m.ReqContext) (*m.SearchUsersQuery, error) { searchQuery := c.Query("query") - query := &m.SearchUsersQuery{Query: searchQuery, Page: page, Limit: perPage} + query := &models.SearchUsersQuery{Query: searchQuery, Page: page, Limit: perPage} if err := bus.Dispatch(query); err != nil { return nil, err } @@ -304,13 +304,13 @@ func searchUser(c *m.ReqContext) (*m.SearchUsersQuery, error) { return query, nil } -func SetHelpFlag(c *m.ReqContext) Response { +func SetHelpFlag(c *models.ReqContext) Response { flag := c.ParamsInt64(":id") bitmask := &c.HelpFlags1 - bitmask.AddFlag(m.HelpFlags1(flag)) + bitmask.AddFlag(models.HelpFlags1(flag)) - cmd := m.SetUserHelpFlagCommand{ + cmd := models.SetUserHelpFlagCommand{ UserId: c.UserId, HelpFlags1: *bitmask, } @@ -322,10 +322,10 @@ func SetHelpFlag(c *m.ReqContext) Response { return JSON(200, &util.DynMap{"message": "Help flag set", "helpFlags1": cmd.HelpFlags1}) } -func ClearHelpFlags(c *m.ReqContext) Response { - cmd := m.SetUserHelpFlagCommand{ +func ClearHelpFlags(c *models.ReqContext) Response { + cmd := models.SetUserHelpFlagCommand{ UserId: c.UserId, - HelpFlags1: m.HelpFlags1(0), + HelpFlags1: models.HelpFlags1(0), } if err := bus.Dispatch(&cmd); err != nil { diff --git a/pkg/api/user_token_test.go b/pkg/api/user_token_test.go index 6b8ebcf64e2..77b1ee347dd 100644 --- a/pkg/api/user_token_test.go +++ b/pkg/api/user_token_test.go @@ -6,7 +6,7 @@ import ( "time" "github.com/grafana/grafana/pkg/bus" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/auth" . "github.com/smartystreets/goconvey/convey" @@ -15,12 +15,12 @@ import ( func TestUserTokenApiEndpoint(t *testing.T) { Convey("When current user attempts to revoke an auth token for a non-existing user", t, func() { userId := int64(0) - bus.AddHandler("test", func(cmd *m.GetUserByIdQuery) error { + bus.AddHandler("test", func(cmd *models.GetUserByIdQuery) error { userId = cmd.Id - return m.ErrUserNotFound + return models.ErrUserNotFound }) - cmd := m.RevokeAuthTokenCmd{AuthTokenId: 2} + cmd := models.RevokeAuthTokenCmd{AuthTokenId: 2} revokeUserAuthTokenScenario("Should return not found when calling POST on", "/api/user/revoke-auth-token", "/api/user/revoke-auth-token", cmd, 200, func(sc *scenarioContext) { sc.fakeReqWithParams("POST", sc.url, map[string]string{}).exec() @@ -31,9 +31,9 @@ func TestUserTokenApiEndpoint(t *testing.T) { Convey("When current user gets auth tokens for a non-existing user", t, func() { userId := int64(0) - bus.AddHandler("test", func(cmd *m.GetUserByIdQuery) error { + bus.AddHandler("test", func(cmd *models.GetUserByIdQuery) error { userId = cmd.Id - return m.ErrUserNotFound + return models.ErrUserNotFound }) getUserAuthTokensScenario("Should return not found when calling GET on", "/api/user/auth-tokens", "/api/user/auth-tokens", 200, func(sc *scenarioContext) { @@ -44,8 +44,8 @@ func TestUserTokenApiEndpoint(t *testing.T) { }) Convey("When logout an existing user from all devices", t, func() { - bus.AddHandler("test", func(cmd *m.GetUserByIdQuery) error { - cmd.Result = &m.User{Id: 200} + bus.AddHandler("test", func(cmd *models.GetUserByIdQuery) error { + cmd.Result = &models.User{Id: 200} return nil }) @@ -56,8 +56,8 @@ func TestUserTokenApiEndpoint(t *testing.T) { }) Convey("When logout a non-existing user from all devices", t, func() { - bus.AddHandler("test", func(cmd *m.GetUserByIdQuery) error { - return m.ErrUserNotFound + bus.AddHandler("test", func(cmd *models.GetUserByIdQuery) error { + return models.ErrUserNotFound }) logoutUserFromAllDevicesInternalScenario("Should return not found", TestUserID, func(sc *scenarioContext) { @@ -67,17 +67,17 @@ func TestUserTokenApiEndpoint(t *testing.T) { }) Convey("When revoke an auth token for a user", t, func() { - bus.AddHandler("test", func(cmd *m.GetUserByIdQuery) error { - cmd.Result = &m.User{Id: 200} + bus.AddHandler("test", func(cmd *models.GetUserByIdQuery) error { + cmd.Result = &models.User{Id: 200} return nil }) - cmd := m.RevokeAuthTokenCmd{AuthTokenId: 2} - token := &m.UserToken{Id: 1} + cmd := models.RevokeAuthTokenCmd{AuthTokenId: 2} + token := &models.UserToken{Id: 1} revokeUserAuthTokenInternalScenario("Should be successful", cmd, 200, token, func(sc *scenarioContext) { - sc.userAuthTokenService.GetUserTokenProvider = func(ctx context.Context, userId, userTokenId int64) (*m.UserToken, error) { - return &m.UserToken{Id: 2}, nil + sc.userAuthTokenService.GetUserTokenProvider = func(ctx context.Context, userId, userTokenId int64) (*models.UserToken, error) { + return &models.UserToken{Id: 2}, nil } sc.fakeReqWithParams("POST", sc.url, map[string]string{}).exec() So(sc.resp.Code, ShouldEqual, 200) @@ -85,16 +85,16 @@ func TestUserTokenApiEndpoint(t *testing.T) { }) Convey("When revoke the active auth token used by himself", t, func() { - bus.AddHandler("test", func(cmd *m.GetUserByIdQuery) error { - cmd.Result = &m.User{Id: TestUserID} + bus.AddHandler("test", func(cmd *models.GetUserByIdQuery) error { + cmd.Result = &models.User{Id: TestUserID} return nil }) - cmd := m.RevokeAuthTokenCmd{AuthTokenId: 2} - token := &m.UserToken{Id: 2} + cmd := models.RevokeAuthTokenCmd{AuthTokenId: 2} + token := &models.UserToken{Id: 2} revokeUserAuthTokenInternalScenario("Should not be successful", cmd, TestUserID, token, func(sc *scenarioContext) { - sc.userAuthTokenService.GetUserTokenProvider = func(ctx context.Context, userId, userTokenId int64) (*m.UserToken, error) { + sc.userAuthTokenService.GetUserTokenProvider = func(ctx context.Context, userId, userTokenId int64) (*models.UserToken, error) { return token, nil } sc.fakeReqWithParams("POST", sc.url, map[string]string{}).exec() @@ -103,15 +103,15 @@ func TestUserTokenApiEndpoint(t *testing.T) { }) Convey("When gets auth tokens for a user", t, func() { - bus.AddHandler("test", func(cmd *m.GetUserByIdQuery) error { - cmd.Result = &m.User{Id: TestUserID} + bus.AddHandler("test", func(cmd *models.GetUserByIdQuery) error { + cmd.Result = &models.User{Id: TestUserID} return nil }) - currentToken := &m.UserToken{Id: 1} + currentToken := &models.UserToken{Id: 1} getUserAuthTokensInternalScenario("Should be successful", currentToken, func(sc *scenarioContext) { - tokens := []*m.UserToken{ + tokens := []*models.UserToken{ { Id: 1, ClientIp: "127.0.0.1", @@ -127,7 +127,7 @@ func TestUserTokenApiEndpoint(t *testing.T) { SeenAt: 0, }, } - sc.userAuthTokenService.GetUserTokensProvider = func(ctx context.Context, userId int64) ([]*m.UserToken, error) { + sc.userAuthTokenService.GetUserTokensProvider = func(ctx context.Context, userId int64) ([]*models.UserToken, error) { return tokens, nil } sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec() @@ -165,7 +165,7 @@ func TestUserTokenApiEndpoint(t *testing.T) { }) } -func revokeUserAuthTokenScenario(desc string, url string, routePattern string, cmd m.RevokeAuthTokenCmd, userId int64, fn scenarioFunc) { +func revokeUserAuthTokenScenario(desc string, url string, routePattern string, cmd models.RevokeAuthTokenCmd, userId int64, fn scenarioFunc) { Convey(desc+" "+url, func() { defer bus.ClearBusHandlers() @@ -178,11 +178,11 @@ func revokeUserAuthTokenScenario(desc string, url string, routePattern string, c sc := setupScenarioContext(url) sc.userAuthTokenService = fakeAuthTokenService - sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { + sc.defaultHandler = Wrap(func(c *models.ReqContext) Response { sc.context = c sc.context.UserId = userId sc.context.OrgId = TestOrgID - sc.context.OrgRole = m.ROLE_ADMIN + sc.context.OrgRole = models.ROLE_ADMIN return hs.RevokeUserAuthToken(c, cmd) }) @@ -206,11 +206,11 @@ func getUserAuthTokensScenario(desc string, url string, routePattern string, use sc := setupScenarioContext(url) sc.userAuthTokenService = fakeAuthTokenService - sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { + sc.defaultHandler = Wrap(func(c *models.ReqContext) Response { sc.context = c sc.context.UserId = userId sc.context.OrgId = TestOrgID - sc.context.OrgRole = m.ROLE_ADMIN + sc.context.OrgRole = models.ROLE_ADMIN return hs.GetUserAuthTokens(c) }) @@ -231,11 +231,11 @@ func logoutUserFromAllDevicesInternalScenario(desc string, userId int64, fn scen } sc := setupScenarioContext("/") - sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { + sc.defaultHandler = Wrap(func(c *models.ReqContext) Response { sc.context = c sc.context.UserId = TestUserID sc.context.OrgId = TestOrgID - sc.context.OrgRole = m.ROLE_ADMIN + sc.context.OrgRole = models.ROLE_ADMIN return hs.logoutUserFromAllDevicesInternal(context.Background(), userId) }) @@ -246,7 +246,7 @@ func logoutUserFromAllDevicesInternalScenario(desc string, userId int64, fn scen }) } -func revokeUserAuthTokenInternalScenario(desc string, cmd m.RevokeAuthTokenCmd, userId int64, token *m.UserToken, fn scenarioFunc) { +func revokeUserAuthTokenInternalScenario(desc string, cmd models.RevokeAuthTokenCmd, userId int64, token *models.UserToken, fn scenarioFunc) { Convey(desc, func() { defer bus.ClearBusHandlers() @@ -259,11 +259,11 @@ func revokeUserAuthTokenInternalScenario(desc string, cmd m.RevokeAuthTokenCmd, sc := setupScenarioContext("/") sc.userAuthTokenService = fakeAuthTokenService - sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { + sc.defaultHandler = Wrap(func(c *models.ReqContext) Response { sc.context = c sc.context.UserId = TestUserID sc.context.OrgId = TestOrgID - sc.context.OrgRole = m.ROLE_ADMIN + sc.context.OrgRole = models.ROLE_ADMIN sc.context.UserToken = token return hs.revokeUserAuthTokenInternal(c, userId, cmd) @@ -275,7 +275,7 @@ func revokeUserAuthTokenInternalScenario(desc string, cmd m.RevokeAuthTokenCmd, }) } -func getUserAuthTokensInternalScenario(desc string, token *m.UserToken, fn scenarioFunc) { +func getUserAuthTokensInternalScenario(desc string, token *models.UserToken, fn scenarioFunc) { Convey(desc, func() { defer bus.ClearBusHandlers() @@ -288,11 +288,11 @@ func getUserAuthTokensInternalScenario(desc string, token *m.UserToken, fn scena sc := setupScenarioContext("/") sc.userAuthTokenService = fakeAuthTokenService - sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { + sc.defaultHandler = Wrap(func(c *models.ReqContext) Response { sc.context = c sc.context.UserId = TestUserID sc.context.OrgId = TestOrgID - sc.context.OrgRole = m.ROLE_ADMIN + sc.context.OrgRole = models.ROLE_ADMIN sc.context.UserToken = token return hs.getUserAuthTokensInternal(c, TestUserID) diff --git a/pkg/login/brute_force_login_protection.go b/pkg/login/brute_force_login_protection.go index 6bb90d8ca13..2c0cacb99fc 100644 --- a/pkg/login/brute_force_login_protection.go +++ b/pkg/login/brute_force_login_protection.go @@ -4,7 +4,7 @@ import ( "time" "github.com/grafana/grafana/pkg/bus" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/setting" ) @@ -18,7 +18,7 @@ var validateLoginAttempts = func(username string) error { return nil } - loginAttemptCountQuery := m.GetUserLoginAttemptCountQuery{ + loginAttemptCountQuery := models.GetUserLoginAttemptCountQuery{ Username: username, Since: time.Now().Add(-loginAttemptsWindow), } @@ -34,12 +34,12 @@ var validateLoginAttempts = func(username string) error { return nil } -var saveInvalidLoginAttempt = func(query *m.LoginUserQuery) error { +var saveInvalidLoginAttempt = func(query *models.LoginUserQuery) error { if setting.DisableBruteForceLoginProtection { return nil } - loginAttemptCommand := m.CreateLoginAttemptCommand{ + loginAttemptCommand := models.CreateLoginAttemptCommand{ Username: query.Username, IpAddress: query.IpAddress, } diff --git a/pkg/login/brute_force_login_protection_test.go b/pkg/login/brute_force_login_protection_test.go index 38685a2aa2b..f8a09000543 100644 --- a/pkg/login/brute_force_login_protection_test.go +++ b/pkg/login/brute_force_login_protection_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/grafana/grafana/pkg/bus" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/setting" . "github.com/smartystreets/goconvey/convey" ) @@ -43,14 +43,14 @@ func TestLoginAttemptsValidation(t *testing.T) { Convey("When saving invalid login attempt", func() { defer bus.ClearBusHandlers() - createLoginAttemptCmd := &m.CreateLoginAttemptCommand{} + createLoginAttemptCmd := &models.CreateLoginAttemptCommand{} - bus.AddHandler("test", func(cmd *m.CreateLoginAttemptCommand) error { + bus.AddHandler("test", func(cmd *models.CreateLoginAttemptCommand) error { createLoginAttemptCmd = cmd return nil }) - err := saveInvalidLoginAttempt(&m.LoginUserQuery{ + err := saveInvalidLoginAttempt(&models.LoginUserQuery{ Username: "user", Password: "pwd", IpAddress: "192.168.1.1:56433", @@ -97,14 +97,14 @@ func TestLoginAttemptsValidation(t *testing.T) { Convey("When saving invalid login attempt", func() { defer bus.ClearBusHandlers() - createLoginAttemptCmd := (*m.CreateLoginAttemptCommand)(nil) + createLoginAttemptCmd := (*models.CreateLoginAttemptCommand)(nil) - bus.AddHandler("test", func(cmd *m.CreateLoginAttemptCommand) error { + bus.AddHandler("test", func(cmd *models.CreateLoginAttemptCommand) error { createLoginAttemptCmd = cmd return nil }) - err := saveInvalidLoginAttempt(&m.LoginUserQuery{ + err := saveInvalidLoginAttempt(&models.LoginUserQuery{ Username: "user", Password: "pwd", IpAddress: "192.168.1.1:56433", @@ -120,7 +120,7 @@ func TestLoginAttemptsValidation(t *testing.T) { } func withLoginAttempts(loginAttempts int64) { - bus.AddHandler("test", func(query *m.GetUserLoginAttemptCountQuery) error { + bus.AddHandler("test", func(query *models.GetUserLoginAttemptCountQuery) error { query.Result = loginAttempts return nil }) diff --git a/pkg/login/grafana_login.go b/pkg/login/grafana_login.go index e81690a8f28..42f2c788c2b 100644 --- a/pkg/login/grafana_login.go +++ b/pkg/login/grafana_login.go @@ -4,7 +4,7 @@ import ( "crypto/subtle" "github.com/grafana/grafana/pkg/bus" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/util" ) @@ -20,8 +20,8 @@ var validatePassword = func(providedPassword string, userPassword string, userSa return nil } -var loginUsingGrafanaDB = func(query *m.LoginUserQuery) error { - userQuery := m.GetUserByLoginQuery{LoginOrEmail: query.Username} +var loginUsingGrafanaDB = func(query *models.LoginUserQuery) error { + userQuery := models.GetUserByLoginQuery{LoginOrEmail: query.Username} if err := bus.Dispatch(&userQuery); err != nil { return err diff --git a/pkg/login/grafana_login_test.go b/pkg/login/grafana_login_test.go index eddc6e12f5f..6c57499f0df 100644 --- a/pkg/login/grafana_login_test.go +++ b/pkg/login/grafana_login_test.go @@ -6,7 +6,7 @@ import ( . "github.com/smartystreets/goconvey/convey" "github.com/grafana/grafana/pkg/bus" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" ) func TestGrafanaLogin(t *testing.T) { @@ -16,7 +16,7 @@ func TestGrafanaLogin(t *testing.T) { err := loginUsingGrafanaDB(sc.loginUserQuery) Convey("it should result in user not found error", func() { - So(err, ShouldEqual, m.ErrUserNotFound) + So(err, ShouldEqual, models.ErrUserNotFound) }) Convey("it should not call password validation", func() { @@ -84,7 +84,7 @@ func TestGrafanaLogin(t *testing.T) { } type grafanaLoginScenarioContext struct { - loginUserQuery *m.LoginUserQuery + loginUserQuery *models.LoginUserQuery validatePasswordCalled bool } @@ -95,7 +95,7 @@ func grafanaLoginScenario(desc string, fn grafanaLoginScenarioFunc) { origValidatePassword := validatePassword sc := &grafanaLoginScenarioContext{ - loginUserQuery: &m.LoginUserQuery{ + loginUserQuery: &models.LoginUserQuery{ Username: "user", Password: "pwd", IpAddress: "192.168.1.1:56433", @@ -123,10 +123,10 @@ func mockPasswordValidation(valid bool, sc *grafanaLoginScenarioContext) { } } -func (sc *grafanaLoginScenarioContext) getUserByLoginQueryReturns(user *m.User) { - bus.AddHandler("test", func(query *m.GetUserByLoginQuery) error { +func (sc *grafanaLoginScenarioContext) getUserByLoginQueryReturns(user *models.User) { + bus.AddHandler("test", func(query *models.GetUserByLoginQuery) error { if user == nil { - return m.ErrUserNotFound + return models.ErrUserNotFound } query.Result = user @@ -135,7 +135,7 @@ func (sc *grafanaLoginScenarioContext) getUserByLoginQueryReturns(user *m.User) } func (sc *grafanaLoginScenarioContext) withValidCredentials() { - sc.getUserByLoginQueryReturns(&m.User{ + sc.getUserByLoginQueryReturns(&models.User{ Id: 1, Login: sc.loginUserQuery.Username, Password: sc.loginUserQuery.Password, @@ -149,7 +149,7 @@ func (sc *grafanaLoginScenarioContext) withNonExistingUser() { } func (sc *grafanaLoginScenarioContext) withInvalidPassword() { - sc.getUserByLoginQueryReturns(&m.User{ + sc.getUserByLoginQueryReturns(&models.User{ Password: sc.loginUserQuery.Password, Salt: "salt", }) @@ -157,7 +157,7 @@ func (sc *grafanaLoginScenarioContext) withInvalidPassword() { } func (sc *grafanaLoginScenarioContext) withDisabledUser() { - sc.getUserByLoginQueryReturns(&m.User{ + sc.getUserByLoginQueryReturns(&models.User{ IsDisabled: true, }) }