Chore: Avoid aliasing importing models in api package (#22492)

This commit is contained in:
Carl Bergquist
2020-03-04 12:57:20 +01:00
committed by GitHub
parent fcaff011b1
commit 3fdd2648b1
53 changed files with 910 additions and 912 deletions

View File

@@ -5,11 +5,11 @@ import (
"strings" "strings"
"github.com/grafana/grafana/pkg/bus" "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/setting"
) )
func AdminGetSettings(c *m.ReqContext) { func AdminGetSettings(c *models.ReqContext) {
settings := make(map[string]interface{}) settings := make(map[string]interface{})
for _, section := range setting.Raw.Sections() { for _, section := range setting.Raw.Sections() {
@@ -38,9 +38,9 @@ func AdminGetSettings(c *m.ReqContext) {
c.JSON(200, settings) 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 { if err := bus.Dispatch(&statsQuery); err != nil {
c.JsonApiErr(500, "Failed to get admin stats from database", err) c.JsonApiErr(500, "Failed to get admin stats from database", err)

View File

@@ -6,22 +6,22 @@ import (
"github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/components/simplejson" "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/grafana/grafana/pkg/services/auth"
. "github.com/smartystreets/goconvey/convey" . "github.com/smartystreets/goconvey/convey"
) )
func TestAdminApiEndpoint(t *testing.T) { 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() { Convey("Given a server admin attempts to remove themself as an admin", t, func() {
updateCmd := dtos.AdminUpdateUserPermissionsForm{ updateCmd := dtos.AdminUpdateUserPermissionsForm{
IsGrafanaAdmin: false, IsGrafanaAdmin: false,
} }
bus.AddHandler("test", func(cmd *m.UpdateUserPermissionsCommand) error { bus.AddHandler("test", func(cmd *models.UpdateUserPermissionsCommand) error {
return m.ErrLastGrafanaAdmin return models.ErrLastGrafanaAdmin
}) })
putAdminScenario("When calling PUT on", "/api/admin/users/1/permissions", "/api/admin/users/:id/permissions", role, updateCmd, func(sc *scenarioContext) { 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() { Convey("When a server admin attempts to logout himself from all devices", t, func() {
bus.AddHandler("test", func(cmd *m.GetUserByIdQuery) error { bus.AddHandler("test", func(cmd *models.GetUserByIdQuery) error {
cmd.Result = &m.User{Id: TestUserID} cmd.Result = &models.User{Id: TestUserID}
return nil 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() { Convey("When a server admin attempts to logout a non-existing user from all devices", t, func() {
userId := int64(0) userId := int64(0)
bus.AddHandler("test", func(cmd *m.GetUserByIdQuery) error { bus.AddHandler("test", func(cmd *models.GetUserByIdQuery) error {
userId = cmd.Id 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) { 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() { Convey("When a server admin attempts to revoke an auth token for a non-existing user", t, func() {
userId := int64(0) userId := int64(0)
bus.AddHandler("test", func(cmd *m.GetUserByIdQuery) error { bus.AddHandler("test", func(cmd *models.GetUserByIdQuery) error {
userId = cmd.Id 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) { 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() 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() { Convey("When a server admin gets auth tokens for a non-existing user", t, func() {
userId := int64(0) userId := int64(0)
bus.AddHandler("test", func(cmd *m.GetUserByIdQuery) error { bus.AddHandler("test", func(cmd *models.GetUserByIdQuery) error {
userId = cmd.Id 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) { 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() { Convey("When a server admin attempts to enable/disable a nonexistent user", t, func() {
var userId int64 var userId int64
isDisabled := false isDisabled := false
bus.AddHandler("test", func(cmd *m.GetAuthInfoQuery) error { bus.AddHandler("test", func(cmd *models.GetAuthInfoQuery) error {
return m.ErrUserNotFound return models.ErrUserNotFound
}) })
bus.AddHandler("test", func(cmd *m.DisableUserCommand) error { bus.AddHandler("test", func(cmd *models.DisableUserCommand) error {
userId = cmd.UserId userId = cmd.UserId
isDisabled = cmd.IsDisabled 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) { 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() { Convey("When a server admin attempts to disable/enable external user", t, func() {
userId := int64(0) userId := int64(0)
bus.AddHandler("test", func(cmd *m.GetAuthInfoQuery) error { bus.AddHandler("test", func(cmd *models.GetAuthInfoQuery) error {
userId = cmd.UserId userId = cmd.UserId
return nil return nil
}) })
@@ -158,9 +158,9 @@ func TestAdminApiEndpoint(t *testing.T) {
Convey("When a server admin attempts to delete a nonexistent user", t, func() { Convey("When a server admin attempts to delete a nonexistent user", t, func() {
var userId int64 var userId int64
bus.AddHandler("test", func(cmd *m.DeleteUserCommand) error { bus.AddHandler("test", func(cmd *models.DeleteUserCommand) error {
userId = cmd.UserId 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) { 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() { Convey(desc+" "+url, func() {
defer bus.ClearBusHandlers() defer bus.ClearBusHandlers()
sc := setupScenarioContext(url) sc := setupScenarioContext(url)
sc.defaultHandler = Wrap(func(c *m.ReqContext) { sc.defaultHandler = Wrap(func(c *models.ReqContext) {
sc.context = c sc.context = c
sc.context.UserId = TestUserID sc.context.UserId = TestUserID
sc.context.OrgId = TestOrgID sc.context.OrgId = TestOrgID
@@ -207,11 +207,11 @@ func adminLogoutUserScenario(desc string, url string, routePattern string, fn sc
} }
sc := setupScenarioContext(url) sc := setupScenarioContext(url)
sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { sc.defaultHandler = Wrap(func(c *models.ReqContext) Response {
sc.context = c sc.context = c
sc.context.UserId = TestUserID sc.context.UserId = TestUserID
sc.context.OrgId = TestOrgID sc.context.OrgId = TestOrgID
sc.context.OrgRole = m.ROLE_ADMIN sc.context.OrgRole = models.ROLE_ADMIN
return hs.AdminLogoutUser(c) 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() { Convey(desc+" "+url, func() {
defer bus.ClearBusHandlers() defer bus.ClearBusHandlers()
@@ -235,11 +235,11 @@ func adminRevokeUserAuthTokenScenario(desc string, url string, routePattern stri
sc := setupScenarioContext(url) sc := setupScenarioContext(url)
sc.userAuthTokenService = fakeAuthTokenService sc.userAuthTokenService = fakeAuthTokenService
sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { sc.defaultHandler = Wrap(func(c *models.ReqContext) Response {
sc.context = c sc.context = c
sc.context.UserId = TestUserID sc.context.UserId = TestUserID
sc.context.OrgId = TestOrgID sc.context.OrgId = TestOrgID
sc.context.OrgRole = m.ROLE_ADMIN sc.context.OrgRole = models.ROLE_ADMIN
return hs.AdminRevokeUserAuthToken(c, cmd) return hs.AdminRevokeUserAuthToken(c, cmd)
}) })
@@ -263,11 +263,11 @@ func adminGetUserAuthTokensScenario(desc string, url string, routePattern string
sc := setupScenarioContext(url) sc := setupScenarioContext(url)
sc.userAuthTokenService = fakeAuthTokenService sc.userAuthTokenService = fakeAuthTokenService
sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { sc.defaultHandler = Wrap(func(c *models.ReqContext) Response {
sc.context = c sc.context = c
sc.context.UserId = TestUserID sc.context.UserId = TestUserID
sc.context.OrgId = TestOrgID sc.context.OrgId = TestOrgID
sc.context.OrgRole = m.ROLE_ADMIN sc.context.OrgRole = models.ROLE_ADMIN
return hs.AdminGetUserAuthTokens(c) return hs.AdminGetUserAuthTokens(c)
}) })
@@ -290,7 +290,7 @@ func adminDisableUserScenario(desc string, action string, url string, routePatte
} }
sc := setupScenarioContext(url) sc := setupScenarioContext(url)
sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { sc.defaultHandler = Wrap(func(c *models.ReqContext) Response {
sc.context = c sc.context = c
sc.context.UserId = TestUserID sc.context.UserId = TestUserID
@@ -312,7 +312,7 @@ func adminDeleteUserScenario(desc string, url string, routePattern string, fn sc
defer bus.ClearBusHandlers() defer bus.ClearBusHandlers()
sc := setupScenarioContext(url) sc := setupScenarioContext(url)
sc.defaultHandler = Wrap(func(c *m.ReqContext) { sc.defaultHandler = Wrap(func(c *models.ReqContext) {
sc.context = c sc.context = c
sc.context.UserId = TestUserID sc.context.UserId = TestUserID

View File

@@ -4,13 +4,13 @@ import (
"strings" "strings"
"github.com/grafana/grafana/pkg/api/dtos" "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/annotations"
"github.com/grafana/grafana/pkg/services/guardian" "github.com/grafana/grafana/pkg/services/guardian"
"github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/util"
) )
func GetAnnotations(c *m.ReqContext) Response { func GetAnnotations(c *models.ReqContext) Response {
query := &annotations.ItemQuery{ query := &annotations.ItemQuery{
From: c.QueryInt64("from"), From: c.QueryInt64("from"),
@@ -50,7 +50,7 @@ func (e *CreateAnnotationError) Error() string {
return e.message 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 { if canSave, err := canSaveByDashboardID(c, cmd.DashboardId); err != nil || !canSave {
return dashboardGuardianResponse(err) return dashboardGuardianResponse(err)
} }
@@ -94,7 +94,7 @@ func formatGraphiteAnnotation(what string, data string) string {
return text return text
} }
func PostGraphiteAnnotation(c *m.ReqContext, cmd dtos.PostGraphiteAnnotationsCmd) Response { func PostGraphiteAnnotation(c *models.ReqContext, cmd dtos.PostGraphiteAnnotationsCmd) Response {
repo := annotations.GetRepository() repo := annotations.GetRepository()
if cmd.What == "" { 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") annotationID := c.ParamsInt64(":annotationId")
repo := annotations.GetRepository() repo := annotations.GetRepository()
@@ -171,7 +171,7 @@ func UpdateAnnotation(c *m.ReqContext, cmd dtos.UpdateAnnotationsCmd) Response {
return Success("Annotation updated") 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") annotationID := c.ParamsInt64(":annotationId")
repo := annotations.GetRepository() repo := annotations.GetRepository()
@@ -219,7 +219,7 @@ func PatchAnnotation(c *m.ReqContext, cmd dtos.PatchAnnotationsCmd) Response {
return Success("Annotation patched") 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() repo := annotations.GetRepository()
err := repo.Delete(&annotations.DeleteParams{ err := repo.Delete(&annotations.DeleteParams{
@@ -236,7 +236,7 @@ func DeleteAnnotations(c *m.ReqContext, cmd dtos.DeleteAnnotationsCmd) Response
return Success("Annotations deleted") return Success("Annotations deleted")
} }
func DeleteAnnotationByID(c *m.ReqContext) Response { func DeleteAnnotationByID(c *models.ReqContext) Response {
repo := annotations.GetRepository() repo := annotations.GetRepository()
annotationID := c.ParamsInt64(":annotationId") annotationID := c.ParamsInt64(":annotationId")
@@ -256,8 +256,8 @@ func DeleteAnnotationByID(c *m.ReqContext) Response {
return Success("Annotation deleted") return Success("Annotation deleted")
} }
func canSaveByDashboardID(c *m.ReqContext, dashboardID int64) (bool, error) { func canSaveByDashboardID(c *models.ReqContext, dashboardID int64) (bool, error) {
if dashboardID == 0 && !c.SignedInUser.HasRole(m.ROLE_EDITOR) { if dashboardID == 0 && !c.SignedInUser.HasRole(models.ROLE_EDITOR) {
return false, nil return false, nil
} }
@@ -271,7 +271,7 @@ func canSaveByDashboardID(c *m.ReqContext, dashboardID int64) (bool, error) {
return true, nil 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}) items, err := repo.Find(&annotations.ItemQuery{AnnotationId: annotationID, OrgId: c.OrgId})
if err != nil || len(items) == 0 { if err != nil || len(items) == 0 {

View File

@@ -5,7 +5,7 @@ import (
"github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/bus" "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/grafana/grafana/pkg/services/annotations"
. "github.com/smartystreets/goconvey/convey" . "github.com/smartystreets/goconvey/convey"
@@ -32,7 +32,7 @@ func TestAnnotationsApiEndpoint(t *testing.T) {
} }
Convey("When user is an Org Viewer", func() { 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() { Convey("Should not be allowed to save an annotation", func() {
postAnnotationScenario("When calling POST on", "/api/annotations", "/api/annotations", role, cmd, func(sc *scenarioContext) { postAnnotationScenario("When calling POST on", "/api/annotations", "/api/annotations", role, cmd, func(sc *scenarioContext) {
sc.fakeReqWithParams("POST", sc.url, map[string]string{}).exec() 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() { 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() { Convey("Should be able to save an annotation", func() {
postAnnotationScenario("When calling POST on", "/api/annotations", "/api/annotations", role, cmd, func(sc *scenarioContext) { postAnnotationScenario("When calling POST on", "/api/annotations", "/api/annotations", role, cmd, func(sc *scenarioContext) {
sc.fakeReqWithParams("POST", sc.url, map[string]string{}).exec() sc.fakeReqWithParams("POST", sc.url, map[string]string{}).exec()
@@ -112,26 +112,26 @@ func TestAnnotationsApiEndpoint(t *testing.T) {
PanelId: 1, PanelId: 1,
} }
viewerRole := m.ROLE_VIEWER viewerRole := models.ROLE_VIEWER
editorRole := m.ROLE_EDITOR editorRole := models.ROLE_EDITOR
aclMockResp := []*m.DashboardAclInfoDTO{ aclMockResp := []*models.DashboardAclInfoDTO{
{Role: &viewerRole, Permission: m.PERMISSION_VIEW}, {Role: &viewerRole, Permission: models.PERMISSION_VIEW},
{Role: &editorRole, Permission: m.PERMISSION_EDIT}, {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 query.Result = aclMockResp
return nil return nil
}) })
bus.AddHandler("test", func(query *m.GetTeamsByUserQuery) error { bus.AddHandler("test", func(query *models.GetTeamsByUserQuery) error {
query.Result = []*m.TeamDTO{} query.Result = []*models.TeamDTO{}
return nil return nil
}) })
Convey("When user is an Org Viewer", func() { 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() { Convey("Should not be allowed to save an annotation", func() {
postAnnotationScenario("When calling POST on", "/api/annotations", "/api/annotations", role, cmd, func(sc *scenarioContext) { postAnnotationScenario("When calling POST on", "/api/annotations", "/api/annotations", role, cmd, func(sc *scenarioContext) {
sc.fakeReqWithParams("POST", sc.url, map[string]string{}).exec() 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() { 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() { Convey("Should be able to save an annotation", func() {
postAnnotationScenario("When calling POST on", "/api/annotations", "/api/annotations", role, cmd, func(sc *scenarioContext) { postAnnotationScenario("When calling POST on", "/api/annotations", "/api/annotations", role, cmd, func(sc *scenarioContext) {
sc.fakeReqWithParams("POST", sc.url, map[string]string{}).exec() 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() { Convey("When user is an Admin", func() {
role := m.ROLE_ADMIN role := models.ROLE_ADMIN
Convey("Should be able to do anything", func() { Convey("Should be able to do anything", func() {
postAnnotationScenario("When calling POST on", "/api/annotations", "/api/annotations", role, cmd, func(sc *scenarioContext) { postAnnotationScenario("When calling POST on", "/api/annotations", "/api/annotations", role, cmd, func(sc *scenarioContext) {
sc.fakeReqWithParams("POST", sc.url, map[string]string{}).exec() sc.fakeReqWithParams("POST", sc.url, map[string]string{}).exec()
@@ -229,12 +229,12 @@ func (repo *fakeAnnotationsRepo) Find(query *annotations.ItemQuery) ([]*annotati
var fakeAnnoRepo *fakeAnnotationsRepo 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() { Convey(desc+" "+url, func() {
defer bus.ClearBusHandlers() defer bus.ClearBusHandlers()
sc := setupScenarioContext(url) sc := setupScenarioContext(url)
sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { sc.defaultHandler = Wrap(func(c *models.ReqContext) Response {
sc.context = c sc.context = c
sc.context.UserId = TestUserID sc.context.UserId = TestUserID
sc.context.OrgId = TestOrgID 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() { Convey(desc+" "+url, func() {
defer bus.ClearBusHandlers() defer bus.ClearBusHandlers()
sc := setupScenarioContext(url) sc := setupScenarioContext(url)
sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { sc.defaultHandler = Wrap(func(c *models.ReqContext) Response {
sc.context = c sc.context = c
sc.context.UserId = TestUserID sc.context.UserId = TestUserID
sc.context.OrgId = TestOrgID 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() { Convey(desc+" "+url, func() {
defer bus.ClearBusHandlers() defer bus.ClearBusHandlers()
sc := setupScenarioContext(url) sc := setupScenarioContext(url)
sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { sc.defaultHandler = Wrap(func(c *models.ReqContext) Response {
sc.context = c sc.context = c
sc.context.UserId = TestUserID sc.context.UserId = TestUserID
sc.context.OrgId = TestOrgID 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() { Convey(desc+" "+url, func() {
defer bus.ClearBusHandlers() defer bus.ClearBusHandlers()
sc := setupScenarioContext(url) sc := setupScenarioContext(url)
sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { sc.defaultHandler = Wrap(func(c *models.ReqContext) Response {
sc.context = c sc.context = c
sc.context.UserId = TestUserID sc.context.UserId = TestUserID
sc.context.OrgId = TestOrgID sc.context.OrgId = TestOrgID

View File

@@ -9,7 +9,7 @@ import (
"github.com/grafana/grafana/pkg/api/pluginproxy" "github.com/grafana/grafana/pkg/api/pluginproxy"
"github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/middleware" "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/plugins"
"github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/util"
macaron "gopkg.in/macaron.v1" macaron "gopkg.in/macaron.v1"
@@ -40,10 +40,10 @@ func (hs *HTTPServer) initAppPluginRoutes(r *macaron.Macaron) {
})) }))
if route.ReqRole != "" { if route.ReqRole != "" {
if route.ReqRole == m.ROLE_ADMIN { if route.ReqRole == models.ROLE_ADMIN {
handlers = append(handlers, middleware.RoleAuth(m.ROLE_ADMIN)) handlers = append(handlers, middleware.RoleAuth(models.ROLE_ADMIN))
} else if route.ReqRole == m.ROLE_EDITOR { } else if route.ReqRole == models.ROLE_EDITOR {
handlers = append(handlers, middleware.RoleAuth(m.ROLE_EDITOR, m.ROLE_ADMIN)) handlers = append(handlers, middleware.RoleAuth(models.ROLE_EDITOR, models.ROLE_ADMIN))
} }
} }
handlers = append(handlers, AppPluginRoute(route, plugin.Id, hs)) 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 { func AppPluginRoute(route *plugins.AppPluginRoute, appID string, hs *HTTPServer) macaron.Handler {
return func(c *m.ReqContext) { return func(c *models.ReqContext) {
path := c.Params("*") path := c.Params("*")
proxy := pluginproxy.NewApiPluginProxy(c, path, route, appID, hs.Cfg) proxy := pluginproxy.NewApiPluginProxy(c, path, route, appID, hs.Cfg)

View File

@@ -4,7 +4,7 @@ import (
"encoding/json" "encoding/json"
"net/http" "net/http"
m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
"gopkg.in/macaron.v1" "gopkg.in/macaron.v1"
) )
@@ -19,7 +19,7 @@ var (
) )
type Response interface { type Response interface {
WriteTo(ctx *m.ReqContext) WriteTo(ctx *models.ReqContext)
} }
type NormalResponse struct { type NormalResponse struct {
@@ -32,7 +32,7 @@ type NormalResponse struct {
func Wrap(action interface{}) macaron.Handler { func Wrap(action interface{}) macaron.Handler {
return func(c *m.ReqContext) { return func(c *models.ReqContext) {
var res Response var res Response
val, err := c.Invoke(action) val, err := c.Invoke(action)
if err == nil && val != nil && len(val) > 0 { 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 { if r.err != nil {
ctx.Logger.Error(r.errMessage, "error", r.err, "remote_addr", ctx.RemoteAddr()) ctx.Logger.Error(r.errMessage, "error", r.err, "remote_addr", ctx.RemoteAddr())
@@ -143,7 +143,7 @@ type RedirectResponse struct {
location string location string
} }
func (r *RedirectResponse) WriteTo(ctx *m.ReqContext) { func (r *RedirectResponse) WriteTo(ctx *models.ReqContext) {
ctx.Redirect(r.location) ctx.Redirect(r.location)
} }

View File

@@ -7,22 +7,22 @@ import (
"github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/middleware" "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/grafana/grafana/pkg/services/auth"
. "github.com/smartystreets/goconvey/convey" . "github.com/smartystreets/goconvey/convey"
"gopkg.in/macaron.v1" "gopkg.in/macaron.v1"
) )
func loggedInUserScenario(desc string, url string, fn scenarioFunc) { 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() { Convey(desc+" "+url, func() {
defer bus.ClearBusHandlers() defer bus.ClearBusHandlers()
sc := setupScenarioContext(url) sc := setupScenarioContext(url)
sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { sc.defaultHandler = Wrap(func(c *models.ReqContext) Response {
sc.context = c sc.context = c
sc.context.UserId = TestUserID sc.context.UserId = TestUserID
sc.context.OrgId = TestOrgID sc.context.OrgId = TestOrgID
@@ -50,7 +50,7 @@ func anonymousUserScenario(desc string, method string, url string, routePattern
defer bus.ClearBusHandlers() defer bus.ClearBusHandlers()
sc := setupScenarioContext(url) sc := setupScenarioContext(url)
sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { sc.defaultHandler = Wrap(func(c *models.ReqContext) Response {
sc.context = c sc.context = c
if sc.handlerFunc != nil { if sc.handlerFunc != nil {
return sc.handlerFunc(sc.context) return sc.handlerFunc(sc.context)
@@ -115,7 +115,7 @@ func (sc *scenarioContext) fakeReqNoAssertionsWithCookie(method, url string, coo
type scenarioContext struct { type scenarioContext struct {
m *macaron.Macaron m *macaron.Macaron
context *m.ReqContext context *models.ReqContext
resp *httptest.ResponseRecorder resp *httptest.ResponseRecorder
handlerFunc handlerFunc handlerFunc handlerFunc
defaultHandler macaron.Handler defaultHandler macaron.Handler
@@ -129,7 +129,7 @@ func (sc *scenarioContext) exec() {
} }
type scenarioFunc func(c *scenarioContext) type scenarioFunc func(c *scenarioContext)
type handlerFunc func(c *m.ReqContext) Response type handlerFunc func(c *models.ReqContext) Response
func setupScenarioContext(url string) *scenarioContext { func setupScenarioContext(url string) *scenarioContext {
sc := &scenarioContext{ sc := &scenarioContext{

View File

@@ -7,6 +7,7 @@ import (
"path" "path"
"path/filepath" "path/filepath"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/alerting" "github.com/grafana/grafana/pkg/services/alerting"
"github.com/grafana/grafana/pkg/services/dashboards" "github.com/grafana/grafana/pkg/services/dashboards"
@@ -16,7 +17,6 @@ import (
"github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/infra/metrics" "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/plugins"
"github.com/grafana/grafana/pkg/services/guardian" "github.com/grafana/grafana/pkg/services/guardian"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
@@ -27,12 +27,12 @@ const (
anonString = "Anonymous" anonString = "Anonymous"
) )
func isDashboardStarredByUser(c *m.ReqContext, dashID int64) (bool, error) { func isDashboardStarredByUser(c *models.ReqContext, dashID int64) (bool, error) {
if !c.IsSignedIn { if !c.IsSignedIn {
return false, nil 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 { if err := bus.Dispatch(&query); err != nil {
return false, err return false, err
} }
@@ -48,7 +48,7 @@ func dashboardGuardianResponse(err error) Response {
return Error(403, "Access denied to this dashboard", nil) 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")) dash, rsp := getDashboardHelper(c.OrgId, c.Params(":slug"), 0, c.Params(":uid"))
if rsp != nil { if rsp != nil {
return rsp return rsp
@@ -80,7 +80,7 @@ func (hs *HTTPServer) GetDashboard(c *m.ReqContext) Response {
meta := dtos.DashboardMeta{ meta := dtos.DashboardMeta{
IsStarred: isStarred, IsStarred: isStarred,
Slug: dash.Slug, Slug: dash.Slug,
Type: m.DashTypeDB, Type: models.DashTypeDB,
CanStar: c.IsSignedIn, CanStar: c.IsSignedIn,
CanSave: canSave, CanSave: canSave,
CanEdit: canEdit, CanEdit: canEdit,
@@ -99,7 +99,7 @@ func (hs *HTTPServer) GetDashboard(c *m.ReqContext) Response {
// lookup folder title // lookup folder title
if dash.FolderId > 0 { 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 { if err := bus.Dispatch(&query); err != nil {
return Error(500, "Dashboard folder could not be read", err) 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 { func getUserLogin(userID int64) string {
query := m.GetUserByIdQuery{Id: userID} query := models.GetUserByIdQuery{Id: userID}
err := bus.Dispatch(&query) err := bus.Dispatch(&query)
if err != nil { if err != nil {
return anonString return anonString
@@ -150,13 +150,13 @@ func getUserLogin(userID int64) string {
return query.Result.Login return query.Result.Login
} }
func getDashboardHelper(orgID int64, slug string, id int64, uid string) (*m.Dashboard, Response) { func getDashboardHelper(orgID int64, slug string, id int64, uid string) (*models.Dashboard, Response) {
var query m.GetDashboardQuery var query models.GetDashboardQuery
if len(uid) > 0 { if len(uid) > 0 {
query = m.GetDashboardQuery{Uid: uid, Id: id, OrgId: orgID} query = models.GetDashboardQuery{Uid: uid, Id: id, OrgId: orgID}
} else { } 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 { 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 return query.Result, nil
} }
func DeleteDashboardBySlug(c *m.ReqContext) Response { func DeleteDashboardBySlug(c *models.ReqContext) Response {
query := m.GetDashboardsBySlugQuery{OrgId: c.OrgId, Slug: c.Params(":slug")} query := models.GetDashboardsBySlugQuery{OrgId: c.OrgId, Slug: c.Params(":slug")}
if err := bus.Dispatch(&query); err != nil { if err := bus.Dispatch(&query); err != nil {
return Error(500, "Failed to retrieve dashboards by slug", err) return Error(500, "Failed to retrieve dashboards by slug", err)
} }
if len(query.Result) > 1 { 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) return deleteDashboard(c)
} }
func DeleteDashboardByUID(c *m.ReqContext) Response { func DeleteDashboardByUID(c *models.ReqContext) Response {
return deleteDashboard(c) 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")) dash, rsp := getDashboardHelper(c.OrgId, c.Params(":slug"), 0, c.Params(":uid"))
if rsp != nil { if rsp != nil {
return rsp return rsp
@@ -196,7 +196,7 @@ func deleteDashboard(c *m.ReqContext) Response {
} }
err := dashboards.NewService().DeleteDashboard(dash.Id, c.OrgId) 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) return Error(400, "Dashboard cannot be deleted because it was provisioned", err)
} else if err != nil { } else if err != nil {
return Error(500, "Failed to delete dashboard", err) 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.OrgId = c.OrgId
cmd.UserId = c.UserId cmd.UserId = c.UserId
@@ -268,22 +268,22 @@ func (hs *HTTPServer) PostDashboard(c *m.ReqContext, cmd m.SaveDashboardCommand)
} }
func dashboardSaveErrorToApiResponse(err error) Response { func dashboardSaveErrorToApiResponse(err error) Response {
if err == m.ErrDashboardTitleEmpty || if err == models.ErrDashboardTitleEmpty ||
err == m.ErrDashboardWithSameNameAsFolder || err == models.ErrDashboardWithSameNameAsFolder ||
err == m.ErrDashboardFolderWithSameNameAsDashboard || err == models.ErrDashboardFolderWithSameNameAsDashboard ||
err == m.ErrDashboardTypeMismatch || err == models.ErrDashboardTypeMismatch ||
err == m.ErrDashboardInvalidUid || err == models.ErrDashboardInvalidUid ||
err == m.ErrDashboardUidToLong || err == models.ErrDashboardUidToLong ||
err == m.ErrDashboardWithSameUIDExists || err == models.ErrDashboardWithSameUIDExists ||
err == m.ErrFolderNotFound || err == models.ErrFolderNotFound ||
err == m.ErrDashboardFolderCannotHaveParent || err == models.ErrDashboardFolderCannotHaveParent ||
err == m.ErrDashboardFolderNameExists || err == models.ErrDashboardFolderNameExists ||
err == m.ErrDashboardRefreshIntervalTooShort || err == models.ErrDashboardRefreshIntervalTooShort ||
err == m.ErrDashboardCannotSaveProvisionedDashboard { err == models.ErrDashboardCannotSaveProvisionedDashboard {
return Error(400, err.Error(), nil) return Error(400, err.Error(), nil)
} }
if err == m.ErrDashboardUpdateAccessDenied { if err == models.ErrDashboardUpdateAccessDenied {
return Error(403, err.Error(), err) return Error(403, err.Error(), err)
} }
@@ -291,15 +291,15 @@ func dashboardSaveErrorToApiResponse(err error) Response {
return Error(422, validationErr.Error(), nil) 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()}) 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()}) 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 + "." message := "The dashboard belongs to plugin " + pluginErr.PluginId + "."
// look up plugin name // look up plugin name
if pluginDef, exist := plugins.Plugins[pluginErr.PluginId]; exist { 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}) 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 JSON(404, util.DynMap{"status": "not-found", "message": err.Error()})
} }
return Error(500, "Failed to save dashboard", err) return Error(500, "Failed to save dashboard", err)
} }
func GetHomeDashboard(c *m.ReqContext) Response { func GetHomeDashboard(c *models.ReqContext) Response {
prefsQuery := m.GetPreferencesWithDefaultsQuery{User: c.SignedInUser} prefsQuery := models.GetPreferencesWithDefaultsQuery{User: c.SignedInUser}
if err := bus.Dispatch(&prefsQuery); err != nil { if err := bus.Dispatch(&prefsQuery); err != nil {
return Error(500, "Failed to get preferences", err) return Error(500, "Failed to get preferences", err)
} }
if prefsQuery.Result.HomeDashboardId != 0 { if prefsQuery.Result.HomeDashboardId != 0 {
slugQuery := m.GetDashboardRefByIdQuery{Id: prefsQuery.Result.HomeDashboardId} slugQuery := models.GetDashboardRefByIdQuery{Id: prefsQuery.Result.HomeDashboardId}
err := bus.Dispatch(&slugQuery) err := bus.Dispatch(&slugQuery)
if err == nil { 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} dashRedirect := dtos.DashboardRedirect{RedirectUri: url}
return JSON(200, &dashRedirect) return JSON(200, &dashRedirect)
} }
@@ -341,7 +341,7 @@ func GetHomeDashboard(c *m.ReqContext) Response {
dash := dtos.DashboardFullWithMeta{} dash := dtos.DashboardFullWithMeta{}
dash.Meta.IsHome = true 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" dash.Meta.FolderTitle = "General"
jsonParser := json.NewDecoder(file) jsonParser := json.NewDecoder(file)
@@ -349,7 +349,7 @@ func GetHomeDashboard(c *m.ReqContext) Response {
return Error(500, "Failed to load home dashboard", err) 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) addGettingStartedPanelToHomeDashboard(dash.Dashboard)
} }
@@ -375,7 +375,7 @@ func addGettingStartedPanelToHomeDashboard(dash *simplejson.Json) {
} }
// GetDashboardVersions returns all dashboard versions as JSON // GetDashboardVersions returns all dashboard versions as JSON
func GetDashboardVersions(c *m.ReqContext) Response { func GetDashboardVersions(c *models.ReqContext) Response {
dashID := c.ParamsInt64(":dashboardId") dashID := c.ParamsInt64(":dashboardId")
guardian := guardian.New(dashID, c.OrgId, c.SignedInUser) guardian := guardian.New(dashID, c.OrgId, c.SignedInUser)
@@ -383,7 +383,7 @@ func GetDashboardVersions(c *m.ReqContext) Response {
return dashboardGuardianResponse(err) return dashboardGuardianResponse(err)
} }
query := m.GetDashboardVersionsQuery{ query := models.GetDashboardVersionsQuery{
OrgId: c.OrgId, OrgId: c.OrgId,
DashboardId: dashID, DashboardId: dashID,
Limit: c.QueryInt("limit"), Limit: c.QueryInt("limit"),
@@ -414,7 +414,7 @@ func GetDashboardVersions(c *m.ReqContext) Response {
} }
// GetDashboardVersion returns the dashboard version with the given ID. // 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") dashID := c.ParamsInt64(":dashboardId")
guardian := guardian.New(dashID, c.OrgId, c.SignedInUser) guardian := guardian.New(dashID, c.OrgId, c.SignedInUser)
@@ -422,7 +422,7 @@ func GetDashboardVersion(c *m.ReqContext) Response {
return dashboardGuardianResponse(err) return dashboardGuardianResponse(err)
} }
query := m.GetDashboardVersionQuery{ query := models.GetDashboardVersionQuery{
OrgId: c.OrgId, OrgId: c.OrgId,
DashboardId: dashID, DashboardId: dashID,
Version: c.ParamsInt(":id"), Version: c.ParamsInt(":id"),
@@ -437,7 +437,7 @@ func GetDashboardVersion(c *m.ReqContext) Response {
creator = getUserLogin(query.Result.CreatedBy) creator = getUserLogin(query.Result.CreatedBy)
} }
dashVersionMeta := &m.DashboardVersionMeta{ dashVersionMeta := &models.DashboardVersionMeta{
Id: query.Result.Id, Id: query.Result.Id,
DashboardId: query.Result.DashboardId, DashboardId: query.Result.DashboardId,
Data: query.Result.Data, Data: query.Result.Data,
@@ -453,7 +453,7 @@ func GetDashboardVersion(c *m.ReqContext) Response {
} }
// POST /api/dashboards/calculate-diff performs diffs on two dashboards // 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) guardianBase := guardian.New(apiOptions.Base.DashboardId, c.OrgId, c.SignedInUser)
if canSave, err := guardianBase.CanSave(); err != nil || !canSave { 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) result, err := dashdiffs.CalculateDiff(&options)
if err != nil { if err != nil {
if err == m.ErrDashboardVersionNotFound { if err == models.ErrDashboardVersionNotFound {
return Error(404, "Dashboard version not found", err) return Error(404, "Dashboard version not found", err)
} }
return Error(500, "Unable to compute diff", 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. // 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"), "") dash, rsp := getDashboardHelper(c.OrgId, "", c.ParamsInt64(":dashboardId"), "")
if rsp != nil { if rsp != nil {
return rsp return rsp
@@ -509,14 +509,14 @@ func (hs *HTTPServer) RestoreDashboardVersion(c *m.ReqContext, apiCmd dtos.Resto
return dashboardGuardianResponse(err) 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 { if err := bus.Dispatch(&versionQuery); err != nil {
return Error(404, "Dashboard version not found", nil) return Error(404, "Dashboard version not found", nil)
} }
version := versionQuery.Result version := versionQuery.Result
saveCmd := m.SaveDashboardCommand{} saveCmd := models.SaveDashboardCommand{}
saveCmd.RestoredFrom = version.Version saveCmd.RestoredFrom = version.Version
saveCmd.OrgId = c.OrgId saveCmd.OrgId = c.OrgId
saveCmd.UserId = c.UserId saveCmd.UserId = c.UserId
@@ -529,8 +529,8 @@ func (hs *HTTPServer) RestoreDashboardVersion(c *m.ReqContext, apiCmd dtos.Resto
return hs.PostDashboard(c, saveCmd) return hs.PostDashboard(c, saveCmd)
} }
func GetDashboardTags(c *m.ReqContext) { func GetDashboardTags(c *models.ReqContext) {
query := m.GetDashboardTagsQuery{OrgId: c.OrgId} query := models.GetDashboardTagsQuery{OrgId: c.OrgId}
err := bus.Dispatch(&query) err := bus.Dispatch(&query)
if err != nil { if err != nil {
c.JsonApiErr(500, "Failed to get tags from database", err) c.JsonApiErr(500, "Failed to get tags from database", err)

View File

@@ -5,11 +5,11 @@ import (
"github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/bus" "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" "github.com/grafana/grafana/pkg/services/guardian"
) )
func GetDashboardPermissionList(c *m.ReqContext) Response { func GetDashboardPermissionList(c *models.ReqContext) Response {
dashID := c.ParamsInt64(":dashboardId") dashID := c.ParamsInt64(":dashboardId")
_, rsp := getDashboardHelper(c.OrgId, "", dashID, "") _, rsp := getDashboardHelper(c.OrgId, "", dashID, "")
@@ -35,14 +35,14 @@ func GetDashboardPermissionList(c *m.ReqContext) Response {
perm.TeamAvatarUrl = dtos.GetGravatarUrlWithDefault(perm.TeamEmail, perm.Team) perm.TeamAvatarUrl = dtos.GetGravatarUrlWithDefault(perm.TeamEmail, perm.Team)
} }
if perm.Slug != "" { 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) 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") dashID := c.ParamsInt64(":dashboardId")
_, rsp := getDashboardHelper(c.OrgId, "", dashID, "") _, rsp := getDashboardHelper(c.OrgId, "", dashID, "")
@@ -55,11 +55,11 @@ func UpdateDashboardPermissions(c *m.ReqContext, apiCmd dtos.UpdateDashboardAclC
return dashboardGuardianResponse(err) return dashboardGuardianResponse(err)
} }
cmd := m.UpdateDashboardAclCommand{} cmd := models.UpdateDashboardAclCommand{}
cmd.DashboardId = dashID cmd.DashboardId = dashID
for _, item := range apiCmd.Items { for _, item := range apiCmd.Items {
cmd.Items = append(cmd.Items, &m.DashboardAcl{ cmd.Items = append(cmd.Items, &models.DashboardAcl{
OrgId: c.OrgId, OrgId: c.OrgId,
DashboardId: dashID, DashboardId: dashID,
UserId: item.UserId, 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 != nil {
if err == guardian.ErrGuardianPermissionExists || if err == guardian.ErrGuardianPermissionExists ||
err == guardian.ErrGuardianOverride { err == guardian.ErrGuardianOverride {
@@ -85,7 +85,7 @@ func UpdateDashboardPermissions(c *m.ReqContext, apiCmd dtos.UpdateDashboardAclC
} }
if err := bus.Dispatch(&cmd); err != nil { 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(409, err.Error(), err)
} }
return Error(500, "Failed to create permission", err) return Error(500, "Failed to create permission", err)

View File

@@ -6,7 +6,7 @@ import (
"github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/components/simplejson" "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/grafana/grafana/pkg/services/guardian"
. "github.com/smartystreets/goconvey/convey" . "github.com/smartystreets/goconvey/convey"
@@ -15,18 +15,18 @@ import (
func TestDashboardPermissionApiEndpoint(t *testing.T) { func TestDashboardPermissionApiEndpoint(t *testing.T) {
Convey("Dashboard permissions test", t, func() { Convey("Dashboard permissions test", t, func() {
Convey("Given dashboard not exists", func() { Convey("Given dashboard not exists", func() {
bus.AddHandler("test", func(query *m.GetDashboardQuery) error { bus.AddHandler("test", func(query *models.GetDashboardQuery) error {
return m.ErrDashboardNotFound 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) callGetDashboardPermissions(sc)
So(sc.resp.Code, ShouldEqual, 404) So(sc.resp.Code, ShouldEqual, 404)
}) })
cmd := dtos.UpdateDashboardAclCommand{ cmd := dtos.UpdateDashboardAclCommand{
Items: []dtos.DashboardAclUpdateItem{ 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 origNewGuardian := guardian.New
guardian.MockDashboardGuardian(&guardian.FakeDashboardGuardian{CanAdminValue: false}) guardian.MockDashboardGuardian(&guardian.FakeDashboardGuardian{CanAdminValue: false})
getDashboardQueryResult := m.NewDashboard("Dash") getDashboardQueryResult := models.NewDashboard("Dash")
bus.AddHandler("test", func(query *m.GetDashboardQuery) error { bus.AddHandler("test", func(query *models.GetDashboardQuery) error {
query.Result = getDashboardQueryResult query.Result = getDashboardQueryResult
return nil 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) callGetDashboardPermissions(sc)
So(sc.resp.Code, ShouldEqual, 403) So(sc.resp.Code, ShouldEqual, 403)
}) })
cmd := dtos.UpdateDashboardAclCommand{ cmd := dtos.UpdateDashboardAclCommand{
Items: []dtos.DashboardAclUpdateItem{ 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{ guardian.MockDashboardGuardian(&guardian.FakeDashboardGuardian{
CanAdminValue: true, CanAdminValue: true,
CheckPermissionBeforeUpdateValue: true, CheckPermissionBeforeUpdateValue: true,
GetAclValue: []*m.DashboardAclInfoDTO{ GetAclValue: []*models.DashboardAclInfoDTO{
{OrgId: 1, DashboardId: 1, UserId: 2, Permission: m.PERMISSION_VIEW}, {OrgId: 1, DashboardId: 1, UserId: 2, Permission: models.PERMISSION_VIEW},
{OrgId: 1, DashboardId: 1, UserId: 3, Permission: m.PERMISSION_EDIT}, {OrgId: 1, DashboardId: 1, UserId: 3, Permission: models.PERMISSION_EDIT},
{OrgId: 1, DashboardId: 1, UserId: 4, Permission: m.PERMISSION_ADMIN}, {OrgId: 1, DashboardId: 1, UserId: 4, Permission: models.PERMISSION_ADMIN},
{OrgId: 1, DashboardId: 1, TeamId: 1, Permission: m.PERMISSION_VIEW}, {OrgId: 1, DashboardId: 1, TeamId: 1, Permission: models.PERMISSION_VIEW},
{OrgId: 1, DashboardId: 1, TeamId: 2, Permission: m.PERMISSION_ADMIN}, {OrgId: 1, DashboardId: 1, TeamId: 2, Permission: models.PERMISSION_ADMIN},
}, },
}) })
getDashboardQueryResult := m.NewDashboard("Dash") getDashboardQueryResult := models.NewDashboard("Dash")
bus.AddHandler("test", func(query *m.GetDashboardQuery) error { bus.AddHandler("test", func(query *models.GetDashboardQuery) error {
query.Result = getDashboardQueryResult query.Result = getDashboardQueryResult
return nil 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) callGetDashboardPermissions(sc)
So(sc.resp.Code, ShouldEqual, 200) So(sc.resp.Code, ShouldEqual, 200)
respJSON, err := simplejson.NewJson(sc.resp.Body.Bytes()) respJSON, err := simplejson.NewJson(sc.resp.Body.Bytes())
So(err, ShouldBeNil) So(err, ShouldBeNil)
So(len(respJSON.MustArray()), ShouldEqual, 5) So(len(respJSON.MustArray()), ShouldEqual, 5)
So(respJSON.GetIndex(0).Get("userId").MustInt(), ShouldEqual, 2) 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{ cmd := dtos.UpdateDashboardAclCommand{
Items: []dtos.DashboardAclUpdateItem{ 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, CheckPermissionBeforeUpdateError: guardian.ErrGuardianPermissionExists,
}) })
getDashboardQueryResult := m.NewDashboard("Dash") getDashboardQueryResult := models.NewDashboard("Dash")
bus.AddHandler("test", func(query *m.GetDashboardQuery) error { bus.AddHandler("test", func(query *models.GetDashboardQuery) error {
query.Result = getDashboardQueryResult query.Result = getDashboardQueryResult
return nil return nil
}) })
cmd := dtos.UpdateDashboardAclCommand{ cmd := dtos.UpdateDashboardAclCommand{
Items: []dtos.DashboardAclUpdateItem{ 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}, CheckPermissionBeforeUpdateError: guardian.ErrGuardianOverride},
) )
getDashboardQueryResult := m.NewDashboard("Dash") getDashboardQueryResult := models.NewDashboard("Dash")
bus.AddHandler("test", func(query *m.GetDashboardQuery) error { bus.AddHandler("test", func(query *models.GetDashboardQuery) error {
query.Result = getDashboardQueryResult query.Result = getDashboardQueryResult
return nil return nil
}) })
cmd := dtos.UpdateDashboardAclCommand{ cmd := dtos.UpdateDashboardAclCommand{
Items: []dtos.DashboardAclUpdateItem{ 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) { func callUpdateDashboardPermissions(sc *scenarioContext) {
bus.AddHandler("test", func(cmd *m.UpdateDashboardAclCommand) error { bus.AddHandler("test", func(cmd *models.UpdateDashboardAclCommand) error {
return nil return nil
}) })
@@ -194,7 +194,7 @@ func updateDashboardPermissionScenario(desc string, url string, routePattern str
sc := setupScenarioContext(url) sc := setupScenarioContext(url)
sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { sc.defaultHandler = Wrap(func(c *models.ReqContext) Response {
sc.context = c sc.context = c
sc.context.OrgId = TestOrgID sc.context.OrgId = TestOrgID
sc.context.UserId = TestUserID sc.context.UserId = TestUserID

View File

@@ -11,7 +11,7 @@ import (
"github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/infra/metrics" "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/services/guardian"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/util"
@@ -22,7 +22,7 @@ var client = &http.Client{
Transport: &http.Transport{Proxy: http.ProxyFromEnvironment}, Transport: &http.Transport{Proxy: http.ProxyFromEnvironment},
} }
func GetSharingOptions(c *m.ReqContext) { func GetSharingOptions(c *models.ReqContext) {
c.JSON(200, util.DynMap{ c.JSON(200, util.DynMap{
"externalSnapshotURL": setting.ExternalSnapshotUrl, "externalSnapshotURL": setting.ExternalSnapshotUrl,
"externalSnapshotName": setting.ExternalSnapshotName, "externalSnapshotName": setting.ExternalSnapshotName,
@@ -37,7 +37,7 @@ type CreateExternalSnapshotResponse struct {
DeleteUrl string `json:"deleteUrl"` DeleteUrl string `json:"deleteUrl"`
} }
func createExternalDashboardSnapshot(cmd m.CreateDashboardSnapshotCommand) (*CreateExternalSnapshotResponse, error) { func createExternalDashboardSnapshot(cmd models.CreateDashboardSnapshotCommand) (*CreateExternalSnapshotResponse, error) {
var createSnapshotResponse CreateExternalSnapshotResponse var createSnapshotResponse CreateExternalSnapshotResponse
message := map[string]interface{}{ message := map[string]interface{}{
"name": cmd.Name, "name": cmd.Name,
@@ -68,7 +68,7 @@ func createExternalDashboardSnapshot(cmd m.CreateDashboardSnapshotCommand) (*Cre
} }
// POST /api/snapshots // POST /api/snapshots
func CreateDashboardSnapshot(c *m.ReqContext, cmd m.CreateDashboardSnapshotCommand) { func CreateDashboardSnapshot(c *models.ReqContext, cmd models.CreateDashboardSnapshotCommand) {
if cmd.Name == "" { if cmd.Name == "" {
cmd.Name = "Unnamed snapshot" cmd.Name = "Unnamed snapshot"
} }
@@ -136,9 +136,9 @@ func CreateDashboardSnapshot(c *m.ReqContext, cmd m.CreateDashboardSnapshotComma
} }
// GET /api/snapshots/:key // GET /api/snapshots/:key
func GetDashboardSnapshot(c *m.ReqContext) { func GetDashboardSnapshot(c *models.ReqContext) {
key := c.Params(":key") key := c.Params(":key")
query := &m.GetDashboardSnapshotQuery{Key: key} query := &models.GetDashboardSnapshotQuery{Key: key}
err := bus.Dispatch(query) err := bus.Dispatch(query)
if err != nil { if err != nil {
@@ -157,7 +157,7 @@ func GetDashboardSnapshot(c *m.ReqContext) {
dto := dtos.DashboardFullWithMeta{ dto := dtos.DashboardFullWithMeta{
Dashboard: snapshot.Dashboard, Dashboard: snapshot.Dashboard,
Meta: dtos.DashboardMeta{ Meta: dtos.DashboardMeta{
Type: m.DashTypeSnapshot, Type: models.DashTypeSnapshot,
IsSnapshot: true, IsSnapshot: true,
Created: snapshot.Created, Created: snapshot.Created,
Expires: snapshot.Expires, Expires: snapshot.Expires,
@@ -198,10 +198,10 @@ func deleteExternalDashboardSnapshot(externalUrl string) error {
} }
// GET /api/snapshots-delete/:deleteKey // GET /api/snapshots-delete/:deleteKey
func DeleteDashboardSnapshotByDeleteKey(c *m.ReqContext) Response { func DeleteDashboardSnapshotByDeleteKey(c *models.ReqContext) Response {
key := c.Params(":deleteKey") key := c.Params(":deleteKey")
query := &m.GetDashboardSnapshotQuery{DeleteKey: key} query := &models.GetDashboardSnapshotQuery{DeleteKey: key}
err := bus.Dispatch(query) err := bus.Dispatch(query)
if err != nil { 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 { if err := bus.Dispatch(cmd); err != nil {
return Error(500, "Failed to delete dashboard snapshot", err) return Error(500, "Failed to delete dashboard snapshot", err)
@@ -225,10 +225,10 @@ func DeleteDashboardSnapshotByDeleteKey(c *m.ReqContext) Response {
} }
// DELETE /api/snapshots/:key // DELETE /api/snapshots/:key
func DeleteDashboardSnapshot(c *m.ReqContext) Response { func DeleteDashboardSnapshot(c *models.ReqContext) Response {
key := c.Params(":key") key := c.Params(":key")
query := &m.GetDashboardSnapshotQuery{Key: key} query := &models.GetDashboardSnapshotQuery{Key: key}
err := bus.Dispatch(query) err := bus.Dispatch(query)
if err != nil { 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 { if err := bus.Dispatch(cmd); err != nil {
return Error(500, "Failed to delete dashboard snapshot", err) return Error(500, "Failed to delete dashboard snapshot", err)
@@ -268,7 +268,7 @@ func DeleteDashboardSnapshot(c *m.ReqContext) Response {
} }
// GET /api/dashboard/snapshots // GET /api/dashboard/snapshots
func SearchDashboardSnapshots(c *m.ReqContext) Response { func SearchDashboardSnapshots(c *models.ReqContext) Response {
query := c.Query("query") query := c.Query("query")
limit := c.QueryInt("limit") limit := c.QueryInt("limit")
@@ -276,7 +276,7 @@ func SearchDashboardSnapshots(c *m.ReqContext) Response {
limit = 1000 limit = 1000
} }
searchQuery := m.GetDashboardSnapshotsQuery{ searchQuery := models.GetDashboardSnapshotsQuery{
Name: query, Name: query,
Limit: limit, Limit: limit,
OrgId: c.OrgId, OrgId: c.OrgId,
@@ -288,9 +288,9 @@ func SearchDashboardSnapshots(c *m.ReqContext) Response {
return Error(500, "Search failed", err) 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 { for i, snapshot := range searchQuery.Result {
dtos[i] = &m.DashboardSnapshotDTO{ dtos[i] = &models.DashboardSnapshotDTO{
Id: snapshot.Id, Id: snapshot.Id,
Name: snapshot.Name, Name: snapshot.Name,
Key: snapshot.Key, Key: snapshot.Key,

View File

@@ -9,7 +9,7 @@ import (
"github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/components/simplejson" "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" . "github.com/smartystreets/goconvey/convey"
) )
@@ -19,7 +19,7 @@ func TestDashboardSnapshotApiEndpoint(t *testing.T) {
var externalRequest *http.Request var externalRequest *http.Request
jsonModel, _ := simplejson.NewJson([]byte(`{"id":100}`)) jsonModel, _ := simplejson.NewJson([]byte(`{"id":100}`))
mockSnapshotResult := &m.DashboardSnapshot{ mockSnapshotResult := &models.DashboardSnapshot{
Id: 1, Id: 1,
Key: "12345", Key: "12345",
DeleteKey: "54321", DeleteKey: "54321",
@@ -29,25 +29,25 @@ func TestDashboardSnapshotApiEndpoint(t *testing.T) {
External: true, External: true,
} }
bus.AddHandler("test", func(query *m.GetDashboardSnapshotQuery) error { bus.AddHandler("test", func(query *models.GetDashboardSnapshotQuery) error {
query.Result = mockSnapshotResult query.Result = mockSnapshotResult
return nil return nil
}) })
bus.AddHandler("test", func(cmd *m.DeleteDashboardSnapshotCommand) error { bus.AddHandler("test", func(cmd *models.DeleteDashboardSnapshotCommand) error {
return nil return nil
}) })
viewerRole := m.ROLE_VIEWER viewerRole := models.ROLE_VIEWER
editorRole := m.ROLE_EDITOR editorRole := models.ROLE_EDITOR
aclMockResp := []*m.DashboardAclInfoDTO{} aclMockResp := []*models.DashboardAclInfoDTO{}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error { bus.AddHandler("test", func(query *models.GetDashboardAclInfoListQuery) error {
query.Result = aclMockResp query.Result = aclMockResp
return nil return nil
}) })
teamResp := []*m.TeamDTO{} teamResp := []*models.TeamDTO{}
bus.AddHandler("test", func(query *m.GetTeamsByUserQuery) error { bus.AddHandler("test", func(query *models.GetTeamsByUserQuery) error {
query.Result = teamResp query.Result = teamResp
return nil 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("When user has editor role and is not in the ACL", func() {
Convey("Should not be able to delete snapshot", 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) { ts := setupRemoteServer(func(rw http.ResponseWriter, req *http.Request) {
externalRequest = req externalRequest = req
}) })
@@ -101,13 +101,13 @@ func TestDashboardSnapshotApiEndpoint(t *testing.T) {
}) })
Convey("When user is editor and dashboard has default ACL", func() { Convey("When user is editor and dashboard has default ACL", func() {
aclMockResp = []*m.DashboardAclInfoDTO{ aclMockResp = []*models.DashboardAclInfoDTO{
{Role: &viewerRole, Permission: m.PERMISSION_VIEW}, {Role: &viewerRole, Permission: models.PERMISSION_VIEW},
{Role: &editorRole, Permission: m.PERMISSION_EDIT}, {Role: &editorRole, Permission: models.PERMISSION_EDIT},
} }
Convey("Should be able to delete a snapshot", func() { 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) { ts := setupRemoteServer(func(rw http.ResponseWriter, req *http.Request) {
rw.WriteHeader(200) rw.WriteHeader(200)
externalRequest = req externalRequest = req
@@ -129,12 +129,12 @@ func TestDashboardSnapshotApiEndpoint(t *testing.T) {
}) })
Convey("When user is editor and is the creator of the snapshot", func() { Convey("When user is editor and is the creator of the snapshot", func() {
aclMockResp = []*m.DashboardAclInfoDTO{} aclMockResp = []*models.DashboardAclInfoDTO{}
mockSnapshotResult.UserId = TestUserID mockSnapshotResult.UserId = TestUserID
mockSnapshotResult.External = false mockSnapshotResult.External = false
Convey("Should be able to delete a snapshot", func() { 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.handlerFunc = DeleteDashboardSnapshot
sc.fakeReqWithParams("DELETE", sc.url, map[string]string{"key": "12345"}).exec() 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() { Convey("When deleting an external snapshot", func() {
aclMockResp = []*m.DashboardAclInfoDTO{} aclMockResp = []*models.DashboardAclInfoDTO{}
mockSnapshotResult.UserId = TestUserID mockSnapshotResult.UserId = TestUserID
Convey("Should gracefully delete local snapshot when remote snapshot has already been removed", func() { Convey("Should gracefully delete local snapshot when remote snapshot has already been removed", func() {
var writeErr error 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) { ts := setupRemoteServer(func(rw http.ResponseWriter, req *http.Request) {
_, writeErr = rw.Write([]byte(`{"message":"Failed to get dashboard snapshot"}`)) _, writeErr = rw.Write([]byte(`{"message":"Failed to get dashboard snapshot"}`))
rw.WriteHeader(500) 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() { 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 var writeErr error
ts := setupRemoteServer(func(rw http.ResponseWriter, req *http.Request) { ts := setupRemoteServer(func(rw http.ResponseWriter, req *http.Request) {
rw.WriteHeader(500) 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() { 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) { ts := setupRemoteServer(func(rw http.ResponseWriter, req *http.Request) {
rw.WriteHeader(404) rw.WriteHeader(404)
}) })

View File

@@ -8,7 +8,7 @@ import (
"github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/components/simplejson" "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/alerting"
"github.com/grafana/grafana/pkg/services/dashboards" "github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/provisioning" "github.com/grafana/grafana/pkg/services/provisioning"
@@ -25,45 +25,45 @@ import (
func TestDashboardApiEndpoint(t *testing.T) { func TestDashboardApiEndpoint(t *testing.T) {
Convey("Given a dashboard with a parent folder which does not have an acl", t, func() { 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.Id = 1
fakeDash.FolderId = 1 fakeDash.FolderId = 1
fakeDash.HasAcl = false fakeDash.HasAcl = false
bus.AddHandler("test", func(query *m.GetDashboardsBySlugQuery) error { bus.AddHandler("test", func(query *models.GetDashboardsBySlugQuery) error {
dashboards := []*m.Dashboard{fakeDash} dashboards := []*models.Dashboard{fakeDash}
query.Result = dashboards query.Result = dashboards
return nil 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 query.Result = fakeDash
getDashboardQueries = append(getDashboardQueries, query) getDashboardQueries = append(getDashboardQueries, query)
return nil return nil
}) })
bus.AddHandler("test", func(query *m.GetProvisionedDashboardDataByIdQuery) error { bus.AddHandler("test", func(query *models.GetProvisionedDashboardDataByIdQuery) error {
query.Result = nil query.Result = nil
return nil return nil
}) })
viewerRole := m.ROLE_VIEWER viewerRole := models.ROLE_VIEWER
editorRole := m.ROLE_EDITOR editorRole := models.ROLE_EDITOR
aclMockResp := []*m.DashboardAclInfoDTO{ aclMockResp := []*models.DashboardAclInfoDTO{
{Role: &viewerRole, Permission: m.PERMISSION_VIEW}, {Role: &viewerRole, Permission: models.PERMISSION_VIEW},
{Role: &editorRole, Permission: m.PERMISSION_EDIT}, {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 query.Result = aclMockResp
return nil return nil
}) })
bus.AddHandler("test", func(query *m.GetTeamsByUserQuery) error { bus.AddHandler("test", func(query *models.GetTeamsByUserQuery) error {
query.Result = []*m.TeamDTO{} query.Result = []*models.TeamDTO{}
return nil return nil
}) })
@@ -72,7 +72,7 @@ func TestDashboardApiEndpoint(t *testing.T) {
// 2. user is an org editor // 2. user is an org editor
Convey("When user is an Org Viewer", func() { 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) { loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc) dash := GetDashboardShouldReturn200(sc)
@@ -132,7 +132,7 @@ func TestDashboardApiEndpoint(t *testing.T) {
}) })
Convey("When user is an Org Editor", func() { 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) { loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc) 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() { 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.Id = 1
fakeDash.FolderId = 1 fakeDash.FolderId = 1
fakeDash.HasAcl = true fakeDash.HasAcl = true
setting.ViewersCanEdit = false setting.ViewersCanEdit = false
bus.AddHandler("test", func(query *m.GetProvisionedDashboardDataByIdQuery) error { bus.AddHandler("test", func(query *models.GetProvisionedDashboardDataByIdQuery) error {
query.Result = nil query.Result = nil
return nil return nil
}) })
bus.AddHandler("test", func(query *m.GetDashboardsBySlugQuery) error { bus.AddHandler("test", func(query *models.GetDashboardsBySlugQuery) error {
dashboards := []*m.Dashboard{fakeDash} dashboards := []*models.Dashboard{fakeDash}
query.Result = dashboards query.Result = dashboards
return nil return nil
}) })
aclMockResp := []*m.DashboardAclInfoDTO{ aclMockResp := []*models.DashboardAclInfoDTO{
{ {
DashboardId: 1, DashboardId: 1,
Permission: m.PERMISSION_EDIT, Permission: models.PERMISSION_EDIT,
UserId: 200, UserId: 200,
}, },
} }
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error { bus.AddHandler("test", func(query *models.GetDashboardAclInfoListQuery) error {
query.Result = aclMockResp query.Result = aclMockResp
return nil 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 query.Result = fakeDash
getDashboardQueries = append(getDashboardQueries, query) getDashboardQueries = append(getDashboardQueries, query)
return nil return nil
}) })
bus.AddHandler("test", func(query *m.GetTeamsByUserQuery) error { bus.AddHandler("test", func(query *models.GetTeamsByUserQuery) error {
query.Result = []*m.TeamDTO{} query.Result = []*models.TeamDTO{}
return nil return nil
}) })
@@ -249,7 +249,7 @@ func TestDashboardApiEndpoint(t *testing.T) {
// 6. user is an org editor AND has been granted a view permission // 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() { 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) { loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
sc.handlerFunc = hs.GetDashboard 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() { 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) { loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
sc.handlerFunc = hs.GetDashboard 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() { Convey("When user is an Org Viewer but has an edit permission", func() {
role := m.ROLE_VIEWER role := models.ROLE_VIEWER
mockResult := []*m.DashboardAclInfoDTO{ mockResult := []*models.DashboardAclInfoDTO{
{OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_EDIT}, {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 query.Result = mockResult
return nil return nil
}) })
@@ -434,14 +434,14 @@ func TestDashboardApiEndpoint(t *testing.T) {
}) })
Convey("When user is an Org Viewer and viewers can edit", func() { Convey("When user is an Org Viewer and viewers can edit", func() {
role := m.ROLE_VIEWER role := models.ROLE_VIEWER
setting.ViewersCanEdit = true setting.ViewersCanEdit = true
mockResult := []*m.DashboardAclInfoDTO{ mockResult := []*models.DashboardAclInfoDTO{
{OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_VIEW}, {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 query.Result = mockResult
return nil return nil
}) })
@@ -494,13 +494,13 @@ func TestDashboardApiEndpoint(t *testing.T) {
}) })
Convey("When user is an Org Viewer but has an admin permission", func() { Convey("When user is an Org Viewer but has an admin permission", func() {
role := m.ROLE_VIEWER role := models.ROLE_VIEWER
mockResult := []*m.DashboardAclInfoDTO{ mockResult := []*models.DashboardAclInfoDTO{
{OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_ADMIN}, {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 query.Result = mockResult
return nil return nil
}) })
@@ -563,13 +563,13 @@ func TestDashboardApiEndpoint(t *testing.T) {
}) })
Convey("When user is an Org Editor but has a view permission", func() { Convey("When user is an Org Editor but has a view permission", func() {
role := m.ROLE_EDITOR role := models.ROLE_EDITOR
mockResult := []*m.DashboardAclInfoDTO{ mockResult := []*models.DashboardAclInfoDTO{
{OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_VIEW}, {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 query.Result = mockResult
return nil return nil
}) })
@@ -631,28 +631,28 @@ func TestDashboardApiEndpoint(t *testing.T) {
}) })
Convey("Given two dashboards with the same title in different folders", t, func() { 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.Id = 2
dashOne.FolderId = 1 dashOne.FolderId = 1
dashOne.HasAcl = false dashOne.HasAcl = false
dashTwo := m.NewDashboard("dash") dashTwo := models.NewDashboard("dash")
dashTwo.Id = 4 dashTwo.Id = 4
dashTwo.FolderId = 3 dashTwo.FolderId = 3
dashTwo.HasAcl = false dashTwo.HasAcl = false
bus.AddHandler("test", func(query *m.GetProvisionedDashboardDataByIdQuery) error { bus.AddHandler("test", func(query *models.GetProvisionedDashboardDataByIdQuery) error {
query.Result = nil query.Result = nil
return nil return nil
}) })
bus.AddHandler("test", func(query *m.GetDashboardsBySlugQuery) error { bus.AddHandler("test", func(query *models.GetDashboardsBySlugQuery) error {
dashboards := []*m.Dashboard{dashOne, dashTwo} dashboards := []*models.Dashboard{dashOne, dashTwo}
query.Result = dashboards query.Result = dashboards
return nil 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) { loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboardBySlug(sc) CallDeleteDashboardBySlug(sc)
@@ -661,7 +661,7 @@ func TestDashboardApiEndpoint(t *testing.T) {
So(sc.resp.Code, ShouldEqual, 412) So(sc.resp.Code, ShouldEqual, 412)
result := sc.ToJSON() result := sc.ToJSON()
So(result.Get("status").MustString(), ShouldEqual, "multiple-slugs-exists") 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 // This tests that a valid request returns correct response
Convey("Given a correct request for creating a dashboard", func() { Convey("Given a correct request for creating a dashboard", func() {
cmd := m.SaveDashboardCommand{ cmd := models.SaveDashboardCommand{
OrgId: 1, OrgId: 1,
UserId: 5, UserId: 5,
Dashboard: simplejson.NewFromAny(map[string]interface{}{ Dashboard: simplejson.NewFromAny(map[string]interface{}{
@@ -684,7 +684,7 @@ func TestDashboardApiEndpoint(t *testing.T) {
} }
mock := &dashboards.FakeDashboardService{ mock := &dashboards.FakeDashboardService{
SaveDashboardResult: &m.Dashboard{ SaveDashboardResult: &models.Dashboard{
Id: 2, Id: 2,
Uid: "uid", Uid: "uid",
Title: "Dash", Title: "Dash",
@@ -724,27 +724,27 @@ func TestDashboardApiEndpoint(t *testing.T) {
SaveError error SaveError error
ExpectedStatusCode int ExpectedStatusCode int
}{ }{
{SaveError: m.ErrDashboardNotFound, ExpectedStatusCode: 404}, {SaveError: models.ErrDashboardNotFound, ExpectedStatusCode: 404},
{SaveError: m.ErrFolderNotFound, ExpectedStatusCode: 400}, {SaveError: models.ErrFolderNotFound, ExpectedStatusCode: 400},
{SaveError: m.ErrDashboardWithSameUIDExists, ExpectedStatusCode: 400}, {SaveError: models.ErrDashboardWithSameUIDExists, ExpectedStatusCode: 400},
{SaveError: m.ErrDashboardWithSameNameInFolderExists, ExpectedStatusCode: 412}, {SaveError: models.ErrDashboardWithSameNameInFolderExists, ExpectedStatusCode: 412},
{SaveError: m.ErrDashboardVersionMismatch, ExpectedStatusCode: 412}, {SaveError: models.ErrDashboardVersionMismatch, ExpectedStatusCode: 412},
{SaveError: m.ErrDashboardTitleEmpty, ExpectedStatusCode: 400}, {SaveError: models.ErrDashboardTitleEmpty, ExpectedStatusCode: 400},
{SaveError: m.ErrDashboardFolderCannotHaveParent, ExpectedStatusCode: 400}, {SaveError: models.ErrDashboardFolderCannotHaveParent, ExpectedStatusCode: 400},
{SaveError: alerting.ValidationError{Reason: "Mu"}, ExpectedStatusCode: 422}, {SaveError: alerting.ValidationError{Reason: "Mu"}, ExpectedStatusCode: 422},
{SaveError: m.ErrDashboardFailedGenerateUniqueUid, ExpectedStatusCode: 500}, {SaveError: models.ErrDashboardFailedGenerateUniqueUid, ExpectedStatusCode: 500},
{SaveError: m.ErrDashboardTypeMismatch, ExpectedStatusCode: 400}, {SaveError: models.ErrDashboardTypeMismatch, ExpectedStatusCode: 400},
{SaveError: m.ErrDashboardFolderWithSameNameAsDashboard, ExpectedStatusCode: 400}, {SaveError: models.ErrDashboardFolderWithSameNameAsDashboard, ExpectedStatusCode: 400},
{SaveError: m.ErrDashboardWithSameNameAsFolder, ExpectedStatusCode: 400}, {SaveError: models.ErrDashboardWithSameNameAsFolder, ExpectedStatusCode: 400},
{SaveError: m.ErrDashboardFolderNameExists, ExpectedStatusCode: 400}, {SaveError: models.ErrDashboardFolderNameExists, ExpectedStatusCode: 400},
{SaveError: m.ErrDashboardUpdateAccessDenied, ExpectedStatusCode: 403}, {SaveError: models.ErrDashboardUpdateAccessDenied, ExpectedStatusCode: 403},
{SaveError: m.ErrDashboardInvalidUid, ExpectedStatusCode: 400}, {SaveError: models.ErrDashboardInvalidUid, ExpectedStatusCode: 400},
{SaveError: m.ErrDashboardUidToLong, ExpectedStatusCode: 400}, {SaveError: models.ErrDashboardUidToLong, ExpectedStatusCode: 400},
{SaveError: m.ErrDashboardCannotSaveProvisionedDashboard, ExpectedStatusCode: 400}, {SaveError: models.ErrDashboardCannotSaveProvisionedDashboard, ExpectedStatusCode: 400},
{SaveError: m.UpdatePluginDashboardError{PluginId: "plug"}, ExpectedStatusCode: 412}, {SaveError: models.UpdatePluginDashboardError{PluginId: "plug"}, ExpectedStatusCode: 412},
} }
cmd := m.SaveDashboardCommand{ cmd := models.SaveDashboardCommand{
OrgId: 1, OrgId: 1,
Dashboard: simplejson.NewFromAny(map[string]interface{}{ Dashboard: simplejson.NewFromAny(map[string]interface{}{
"title": "", "title": "",
@@ -765,19 +765,19 @@ func TestDashboardApiEndpoint(t *testing.T) {
}) })
Convey("Given two dashboards being compared", t, func() { Convey("Given two dashboards being compared", t, func() {
mockResult := []*m.DashboardAclInfoDTO{} mockResult := []*models.DashboardAclInfoDTO{}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error { bus.AddHandler("test", func(query *models.GetDashboardAclInfoListQuery) error {
query.Result = mockResult query.Result = mockResult
return nil return nil
}) })
bus.AddHandler("test", func(query *m.GetProvisionedDashboardDataByIdQuery) error { bus.AddHandler("test", func(query *models.GetProvisionedDashboardDataByIdQuery) error {
query.Result = nil query.Result = nil
return nil return nil
}) })
bus.AddHandler("test", func(query *m.GetDashboardVersionQuery) error { bus.AddHandler("test", func(query *models.GetDashboardVersionQuery) error {
query.Result = &m.DashboardVersion{ query.Result = &models.DashboardVersion{
Data: simplejson.NewFromAny(map[string]interface{}{ Data: simplejson.NewFromAny(map[string]interface{}{
"title": "Dash" + string(query.DashboardId), "title": "Dash" + string(query.DashboardId),
}), }),
@@ -798,7 +798,7 @@ func TestDashboardApiEndpoint(t *testing.T) {
} }
Convey("when user does not have permission", func() { 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) { postDiffScenario("When calling POST on", "/api/dashboards/calculate-diff", "/api/dashboards/calculate-diff", cmd, role, func(sc *scenarioContext) {
CallPostDashboard(sc) CallPostDashboard(sc)
@@ -807,7 +807,7 @@ func TestDashboardApiEndpoint(t *testing.T) {
}) })
Convey("when user does have permission", func() { 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) { postDiffScenario("When calling POST on", "/api/dashboards/calculate-diff", "/api/dashboards/calculate-diff", cmd, role, func(sc *scenarioContext) {
CallPostDashboard(sc) CallPostDashboard(sc)
@@ -817,18 +817,18 @@ func TestDashboardApiEndpoint(t *testing.T) {
}) })
Convey("Given dashboard in folder being restored should restore to folder", t, func() { 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.Id = 2
fakeDash.FolderId = 1 fakeDash.FolderId = 1
fakeDash.HasAcl = false fakeDash.HasAcl = false
bus.AddHandler("test", func(query *m.GetDashboardQuery) error { bus.AddHandler("test", func(query *models.GetDashboardQuery) error {
query.Result = fakeDash query.Result = fakeDash
return nil return nil
}) })
bus.AddHandler("test", func(query *m.GetDashboardVersionQuery) error { bus.AddHandler("test", func(query *models.GetDashboardVersionQuery) error {
query.Result = &m.DashboardVersion{ query.Result = &models.DashboardVersion{
DashboardId: 2, DashboardId: 2,
Version: 1, Version: 1,
Data: fakeDash.Data, Data: fakeDash.Data,
@@ -837,7 +837,7 @@ func TestDashboardApiEndpoint(t *testing.T) {
}) })
mock := &dashboards.FakeDashboardService{ mock := &dashboards.FakeDashboardService{
SaveDashboardResult: &m.Dashboard{ SaveDashboardResult: &models.Dashboard{
Id: 2, Id: 2,
Uid: "uid", Uid: "uid",
Title: "Dash", 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() { 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.Id = 2
fakeDash.HasAcl = false fakeDash.HasAcl = false
bus.AddHandler("test", func(query *m.GetDashboardQuery) error { bus.AddHandler("test", func(query *models.GetDashboardQuery) error {
query.Result = fakeDash query.Result = fakeDash
return nil return nil
}) })
bus.AddHandler("test", func(query *m.GetDashboardVersionQuery) error { bus.AddHandler("test", func(query *models.GetDashboardVersionQuery) error {
query.Result = &m.DashboardVersion{ query.Result = &models.DashboardVersion{
DashboardId: 2, DashboardId: 2,
Version: 1, Version: 1,
Data: fakeDash.Data, Data: fakeDash.Data,
@@ -880,7 +880,7 @@ func TestDashboardApiEndpoint(t *testing.T) {
}) })
mock := &dashboards.FakeDashboardService{ mock := &dashboards.FakeDashboardService{
SaveDashboardResult: &m.Dashboard{ SaveDashboardResult: &models.Dashboard{
Id: 2, Id: 2,
Uid: "uid", Uid: "uid",
Title: "Dash", Title: "Dash",
@@ -905,48 +905,48 @@ func TestDashboardApiEndpoint(t *testing.T) {
Convey("Given provisioned dashboard", t, func() { Convey("Given provisioned dashboard", t, func() {
bus.AddHandler("test", func(query *m.GetDashboardsBySlugQuery) error { bus.AddHandler("test", func(query *models.GetDashboardsBySlugQuery) error {
query.Result = []*m.Dashboard{{}} query.Result = []*models.Dashboard{{}}
return nil return nil
}) })
bus.AddHandler("test", func(query *m.GetDashboardQuery) error { bus.AddHandler("test", func(query *models.GetDashboardQuery) error {
query.Result = &m.Dashboard{Id: 1, Data: &simplejson.Json{}} query.Result = &models.Dashboard{Id: 1, Data: &simplejson.Json{}}
return nil return nil
}) })
bus.AddHandler("test", func(query *m.GetProvisionedDashboardDataByIdQuery) error { bus.AddHandler("test", func(query *models.GetProvisionedDashboardDataByIdQuery) error {
query.Result = &m.DashboardProvisioning{ExternalId: "/tmp/grafana/dashboards/test/dashboard1.json"} query.Result = &models.DashboardProvisioning{ExternalId: "/tmp/grafana/dashboards/test/dashboard1.json"}
return nil return nil
}) })
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error { bus.AddHandler("test", func(query *models.GetDashboardAclInfoListQuery) error {
query.Result = []*m.DashboardAclInfoDTO{ query.Result = []*models.DashboardAclInfoDTO{
{OrgId: TestOrgID, DashboardId: 1, UserId: TestUserID, Permission: m.PERMISSION_EDIT}, {OrgId: TestOrgID, DashboardId: 1, UserId: TestUserID, Permission: models.PERMISSION_EDIT},
} }
return nil 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) CallDeleteDashboardBySlug(sc)
Convey("Should result in 400", func() { Convey("Should result in 400", func() {
So(sc.resp.Code, ShouldEqual, 400) So(sc.resp.Code, ShouldEqual, 400)
result := sc.ToJSON() 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) CallDeleteDashboardByUID(sc)
Convey("Should result in 400", func() { Convey("Should result in 400", func() {
So(sc.resp.Code, ShouldEqual, 400) So(sc.resp.Code, ShouldEqual, 400)
result := sc.ToJSON() 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 := provisioning.NewProvisioningServiceMock()
mock.GetDashboardProvisionerResolvedPathFunc = func(name string) string { mock.GetDashboardProvisionerResolvedPathFunc = func(name string) string {
return "/tmp/grafana/dashboards" 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 := provisioning.NewProvisioningServiceMock()
mock.GetDashboardProvisionerResolvedPathFunc = func(name string) string { mock.GetDashboardProvisionerResolvedPathFunc = func(name string) string {
return "/tmp/grafana/dashboards" return "/tmp/grafana/dashboards"
@@ -1018,8 +1018,8 @@ func CallGetDashboard(sc *scenarioContext, hs *HTTPServer) {
} }
func CallGetDashboardVersion(sc *scenarioContext) { func CallGetDashboardVersion(sc *scenarioContext) {
bus.AddHandler("test", func(query *m.GetDashboardVersionQuery) error { bus.AddHandler("test", func(query *models.GetDashboardVersionQuery) error {
query.Result = &m.DashboardVersion{} query.Result = &models.DashboardVersion{}
return nil return nil
}) })
@@ -1028,8 +1028,8 @@ func CallGetDashboardVersion(sc *scenarioContext) {
} }
func CallGetDashboardVersions(sc *scenarioContext) { func CallGetDashboardVersions(sc *scenarioContext) {
bus.AddHandler("test", func(query *m.GetDashboardVersionsQuery) error { bus.AddHandler("test", func(query *models.GetDashboardVersionsQuery) error {
query.Result = []*m.DashboardVersionDTO{} query.Result = []*models.DashboardVersionDTO{}
return nil return nil
}) })
@@ -1038,7 +1038,7 @@ func CallGetDashboardVersions(sc *scenarioContext) {
} }
func CallDeleteDashboardBySlug(sc *scenarioContext) { func CallDeleteDashboardBySlug(sc *scenarioContext) {
bus.AddHandler("test", func(cmd *m.DeleteDashboardCommand) error { bus.AddHandler("test", func(cmd *models.DeleteDashboardCommand) error {
return nil return nil
}) })
@@ -1047,7 +1047,7 @@ func CallDeleteDashboardBySlug(sc *scenarioContext) {
} }
func CallDeleteDashboardByUID(sc *scenarioContext) { func CallDeleteDashboardByUID(sc *scenarioContext) {
bus.AddHandler("test", func(cmd *m.DeleteDashboardCommand) error { bus.AddHandler("test", func(cmd *models.DeleteDashboardCommand) error {
return nil return nil
}) })
@@ -1073,7 +1073,7 @@ func (m mockDashboardProvisioningService) DeleteProvisionedDashboard(dashboardId
panic("implement me") 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() { Convey(desc+" "+url, func() {
defer bus.ClearBusHandlers() defer bus.ClearBusHandlers()
@@ -1084,9 +1084,9 @@ func postDashboardScenario(desc string, url string, routePattern string, mock *d
} }
sc := setupScenarioContext(url) sc := setupScenarioContext(url)
sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { sc.defaultHandler = Wrap(func(c *models.ReqContext) Response {
sc.context = c 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) 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() { Convey(desc+" "+url, func() {
defer bus.ClearBusHandlers() defer bus.ClearBusHandlers()
sc := setupScenarioContext(url) sc := setupScenarioContext(url)
sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { sc.defaultHandler = Wrap(func(c *models.ReqContext) Response {
sc.context = c sc.context = c
sc.context.SignedInUser = &m.SignedInUser{ sc.context.SignedInUser = &models.SignedInUser{
OrgId: TestOrgID, OrgId: TestOrgID,
UserId: TestUserID, UserId: TestUserID,
} }
@@ -1143,13 +1143,13 @@ func restoreDashboardVersionScenario(desc string, url string, routePattern strin
} }
sc := setupScenarioContext(url) sc := setupScenarioContext(url)
sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { sc.defaultHandler = Wrap(func(c *models.ReqContext) Response {
sc.context = c sc.context = c
sc.context.SignedInUser = &m.SignedInUser{ sc.context.SignedInUser = &models.SignedInUser{
OrgId: TestOrgID, OrgId: TestOrgID,
UserId: TestUserID, UserId: TestUserID,
} }
sc.context.OrgRole = m.ROLE_ADMIN sc.context.OrgRole = models.ROLE_ADMIN
return hs.RestoreDashboardVersion(c, cmd) return hs.RestoreDashboardVersion(c, cmd)
}) })
@@ -1183,20 +1183,20 @@ func (sc *scenarioContext) ToJSON() *simplejson.Json {
type mockDashboardProvisioningService struct { 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") panic("implement me")
} }
func (m mockDashboardProvisioningService) SaveFolderForProvisionedDashboards(*dashboards.SaveDashboardDTO) (*m.Dashboard, error) { func (m mockDashboardProvisioningService) SaveFolderForProvisionedDashboards(*dashboards.SaveDashboardDTO) (*models.Dashboard, error) {
panic("implement me") panic("implement me")
} }
func (m mockDashboardProvisioningService) GetProvisionedDashboardData(name string) ([]*m.DashboardProvisioning, error) { func (m mockDashboardProvisioningService) GetProvisionedDashboardData(name string) ([]*models.DashboardProvisioning, error) {
panic("implement me") panic("implement me")
} }
func (mock mockDashboardProvisioningService) GetProvisionedDashboardDataByDashboardId(dashboardId int64) (*m.DashboardProvisioning, error) { func (mock mockDashboardProvisioningService) GetProvisionedDashboardDataByDashboardId(dashboardId int64) (*models.DashboardProvisioning, error) {
return &m.DashboardProvisioning{}, nil return &models.DashboardProvisioning{}, nil
} }
func (m mockDashboardProvisioningService) UnprovisionDashboard(dashboardId int64) error { func (m mockDashboardProvisioningService) UnprovisionDashboard(dashboardId int64) error {

View File

@@ -3,17 +3,18 @@ package api
import ( import (
"github.com/grafana/grafana/pkg/api/pluginproxy" "github.com/grafana/grafana/pkg/api/pluginproxy"
"github.com/grafana/grafana/pkg/infra/metrics" "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" "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) c.TimeRequest(metrics.MDataSourceProxyReqTimer)
dsId := c.ParamsInt64(":id") dsID := c.ParamsInt64(":id")
ds, err := hs.DatasourceCache.GetDatasource(dsId, c.SignedInUser, c.SkipCache) ds, err := hs.DatasourceCache.GetDatasource(dsID, c.SignedInUser, c.SkipCache)
if err != nil { if err != nil {
if err == m.ErrDataSourceAccessDenied { if err == models.ErrDataSourceAccessDenied {
c.JsonApiErr(403, "Access denied to datasource", err) c.JsonApiErr(403, "Access denied to datasource", err)
return return
} }

View File

@@ -5,14 +5,14 @@ import (
"github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/bus" "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"
"github.com/grafana/grafana/pkg/plugins/backendplugin" "github.com/grafana/grafana/pkg/plugins/backendplugin"
"github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/util"
) )
func GetDataSources(c *m.ReqContext) Response { func GetDataSources(c *models.ReqContext) Response {
query := m.GetDataSourcesQuery{OrgId: c.OrgId} query := models.GetDataSourcesQuery{OrgId: c.OrgId}
if err := bus.Dispatch(&query); err != nil { if err := bus.Dispatch(&query); err != nil {
return Error(500, "Failed to query datasources", err) return Error(500, "Failed to query datasources", err)
@@ -50,14 +50,14 @@ func GetDataSources(c *m.ReqContext) Response {
return JSON(200, &result) return JSON(200, &result)
} }
func GetDataSourceById(c *m.ReqContext) Response { func GetDataSourceById(c *models.ReqContext) Response {
query := m.GetDataSourceByIdQuery{ query := models.GetDataSourceByIdQuery{
Id: c.ParamsInt64(":id"), Id: c.ParamsInt64(":id"),
OrgId: c.OrgId, OrgId: c.OrgId,
} }
if err := bus.Dispatch(&query); err != nil { 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(404, "Data source not found", nil)
} }
return Error(500, "Failed to query datasources", err) return Error(500, "Failed to query datasources", err)
@@ -69,7 +69,7 @@ func GetDataSourceById(c *m.ReqContext) Response {
return JSON(200, &dtos) return JSON(200, &dtos)
} }
func DeleteDataSourceById(c *m.ReqContext) Response { func DeleteDataSourceById(c *models.ReqContext) Response {
id := c.ParamsInt64(":id") id := c.ParamsInt64(":id")
if id <= 0 { if id <= 0 {
@@ -85,7 +85,7 @@ func DeleteDataSourceById(c *m.ReqContext) Response {
return Error(403, "Cannot delete read-only data source", nil) 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) err = bus.Dispatch(cmd)
if err != nil { if err != nil {
@@ -95,16 +95,16 @@ func DeleteDataSourceById(c *m.ReqContext) Response {
return Success("Data source deleted") return Success("Data source deleted")
} }
func DeleteDataSourceByName(c *m.ReqContext) Response { func DeleteDataSourceByName(c *models.ReqContext) Response {
name := c.Params(":name") name := c.Params(":name")
if name == "" { if name == "" {
return Error(400, "Missing valid datasource name", nil) 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 := bus.Dispatch(getCmd); err != nil {
if err == m.ErrDataSourceNotFound { if err == models.ErrDataSourceNotFound {
return Error(404, "Data source not found", nil) return Error(404, "Data source not found", nil)
} }
return Error(500, "Failed to delete datasource", err) 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) 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) err := bus.Dispatch(cmd)
if err != nil { if err != nil {
return Error(500, "Failed to delete datasource", err) return Error(500, "Failed to delete datasource", err)
@@ -123,11 +123,11 @@ func DeleteDataSourceByName(c *m.ReqContext) Response {
return Success("Data source deleted") 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 cmd.OrgId = c.OrgId
if err := bus.Dispatch(&cmd); err != nil { if err := bus.Dispatch(&cmd); err != nil {
if err == m.ErrDataSourceNameExists { if err == models.ErrDataSourceNameExists {
return Error(409, err.Error(), err) 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.OrgId = c.OrgId
cmd.Id = c.ParamsInt64(":id") cmd.Id = c.ParamsInt64(":id")
@@ -154,19 +154,19 @@ func UpdateDataSource(c *m.ReqContext, cmd m.UpdateDataSourceCommand) Response {
err = bus.Dispatch(&cmd) err = bus.Dispatch(&cmd)
if err != nil { 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. Reload new version and try again", err)
} }
return Error(500, "Failed to update datasource", err) return Error(500, "Failed to update datasource", err)
} }
query := m.GetDataSourceByIdQuery{ query := models.GetDataSourceByIdQuery{
Id: cmd.Id, Id: cmd.Id,
OrgId: c.OrgId, OrgId: c.OrgId,
} }
if err := bus.Dispatch(&query); err != nil { 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(404, "Data source not found", nil)
} }
return Error(500, "Failed to query datasources", err) 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 { if len(cmd.SecureJsonData) == 0 {
return nil return nil
} }
@@ -193,7 +193,7 @@ func fillWithSecureJSONData(cmd *m.UpdateDataSourceCommand) error {
} }
if ds.ReadOnly { if ds.ReadOnly {
return m.ErrDatasourceIsReadOnly return models.ErrDatasourceIsReadOnly
} }
secureJSONData := ds.SecureJsonData.Decrypt() secureJSONData := ds.SecureJsonData.Decrypt()
@@ -207,8 +207,8 @@ func fillWithSecureJSONData(cmd *m.UpdateDataSourceCommand) error {
return nil return nil
} }
func getRawDataSourceById(id int64, orgID int64) (*m.DataSource, error) { func getRawDataSourceById(id int64, orgID int64) (*models.DataSource, error) {
query := m.GetDataSourceByIdQuery{ query := models.GetDataSourceByIdQuery{
Id: id, Id: id,
OrgId: orgID, OrgId: orgID,
} }
@@ -221,11 +221,11 @@ func getRawDataSourceById(id int64, orgID int64) (*m.DataSource, error) {
} }
// Get /api/datasources/name/:name // Get /api/datasources/name/:name
func GetDataSourceByName(c *m.ReqContext) Response { func GetDataSourceByName(c *models.ReqContext) Response {
query := m.GetDataSourceByNameQuery{Name: c.Params(":name"), OrgId: c.OrgId} query := models.GetDataSourceByNameQuery{Name: c.Params(":name"), OrgId: c.OrgId}
if err := bus.Dispatch(&query); err != nil { 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(404, "Data source not found", nil)
} }
return Error(500, "Failed to query datasources", err) return Error(500, "Failed to query datasources", err)
@@ -236,11 +236,11 @@ func GetDataSourceByName(c *m.ReqContext) Response {
} }
// Get /api/datasources/id/:name // Get /api/datasources/id/:name
func GetDataSourceIdByName(c *m.ReqContext) Response { func GetDataSourceIdByName(c *models.ReqContext) Response {
query := m.GetDataSourceByNameQuery{Name: c.Params(":name"), OrgId: c.OrgId} query := models.GetDataSourceByNameQuery{Name: c.Params(":name"), OrgId: c.OrgId}
if err := bus.Dispatch(&query); err != nil { 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(404, "Data source not found", nil)
} }
return Error(500, "Failed to query datasources", err) return Error(500, "Failed to query datasources", err)
@@ -255,11 +255,11 @@ func GetDataSourceIdByName(c *m.ReqContext) Response {
} }
// /api/datasources/:id/resources/* // /api/datasources/:id/resources/*
func (hs *HTTPServer) CallDatasourceResource(c *m.ReqContext) { func (hs *HTTPServer) CallDatasourceResource(c *models.ReqContext) {
datasourceID := c.ParamsInt64(":id") datasourceID := c.ParamsInt64(":id")
ds, err := hs.DatasourceCache.GetDatasource(datasourceID, c.SignedInUser, c.SkipCache) ds, err := hs.DatasourceCache.GetDatasource(datasourceID, c.SignedInUser, c.SkipCache)
if err != nil { if err != nil {
if err == m.ErrDataSourceAccessDenied { if err == models.ErrDataSourceAccessDenied {
c.JsonApiErr(403, "Access denied to datasource", err) c.JsonApiErr(403, "Access denied to datasource", err)
return return
} }
@@ -294,7 +294,7 @@ func (hs *HTTPServer) CallDatasourceResource(c *m.ReqContext) {
hs.BackendPluginManager.CallResource(config, c, c.Params("*")) hs.BackendPluginManager.CallResource(config, c, c.Params("*"))
} }
func convertModelToDtos(ds *m.DataSource) dtos.DataSource { func convertModelToDtos(ds *models.DataSource) dtos.DataSource {
dto := dtos.DataSource{ dto := dtos.DataSource{
Id: ds.Id, Id: ds.Id,
OrgId: ds.OrgId, OrgId: ds.OrgId,

View File

@@ -1,8 +1,6 @@
package dtos package dtos
import ( import "github.com/grafana/grafana/pkg/models"
m "github.com/grafana/grafana/pkg/models"
)
type UpdateDashboardAclCommand struct { type UpdateDashboardAclCommand struct {
Items []DashboardAclUpdateItem `json:"items"` Items []DashboardAclUpdateItem `json:"items"`
@@ -11,6 +9,6 @@ type UpdateDashboardAclCommand struct {
type DashboardAclUpdateItem struct { type DashboardAclUpdateItem struct {
UserId int64 `json:"userId"` UserId int64 `json:"userId"`
TeamId int64 `json:"teamId"` TeamId int64 `json:"teamId"`
Role *m.RoleType `json:"role,omitempty"` Role *models.RoleType `json:"role,omitempty"`
Permission m.PermissionType `json:"permission"` Permission models.PermissionType `json:"permission"`
} }

View File

@@ -4,7 +4,7 @@ import (
"strings" "strings"
"github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/components/simplejson"
m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
) )
type DataSource struct { type DataSource struct {
@@ -13,7 +13,7 @@ type DataSource struct {
Name string `json:"name"` Name string `json:"name"`
Type string `json:"type"` Type string `json:"type"`
TypeLogoUrl string `json:"typeLogoUrl"` TypeLogoUrl string `json:"typeLogoUrl"`
Access m.DsAccess `json:"access"` Access models.DsAccess `json:"access"`
Url string `json:"url"` Url string `json:"url"`
Password string `json:"password"` Password string `json:"password"`
User string `json:"user"` User string `json:"user"`
@@ -35,7 +35,7 @@ type DataSourceListItemDTO struct {
Name string `json:"name"` Name string `json:"name"`
Type string `json:"type"` Type string `json:"type"`
TypeLogoUrl string `json:"typeLogoUrl"` TypeLogoUrl string `json:"typeLogoUrl"`
Access m.DsAccess `json:"access"` Access models.DsAccess `json:"access"`
Url string `json:"url"` Url string `json:"url"`
Password string `json:"password"` Password string `json:"password"`
User string `json:"user"` User string `json:"user"`

View File

@@ -8,7 +8,7 @@ import (
"github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/infra/log" "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" "github.com/grafana/grafana/pkg/setting"
) )
@@ -32,12 +32,12 @@ type CurrentUser struct {
OrgCount int `json:"orgCount"` OrgCount int `json:"orgCount"`
OrgId int64 `json:"orgId"` OrgId int64 `json:"orgId"`
OrgName string `json:"orgName"` OrgName string `json:"orgName"`
OrgRole m.RoleType `json:"orgRole"` OrgRole models.RoleType `json:"orgRole"`
IsGrafanaAdmin bool `json:"isGrafanaAdmin"` IsGrafanaAdmin bool `json:"isGrafanaAdmin"`
GravatarUrl string `json:"gravatarUrl"` GravatarUrl string `json:"gravatarUrl"`
Timezone string `json:"timezone"` Timezone string `json:"timezone"`
Locale string `json:"locale"` Locale string `json:"locale"`
HelpFlags1 m.HelpFlags1 `json:"helpFlags1"` HelpFlags1 models.HelpFlags1 `json:"helpFlags1"`
HasEditPermissionInFolders bool `json:"hasEditPermissionInFolders"` HasEditPermissionInFolders bool `json:"hasEditPermissionInFolders"`
} }

View File

@@ -4,13 +4,13 @@ import (
"fmt" "fmt"
"github.com/grafana/grafana/pkg/api/dtos" "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/dashboards"
"github.com/grafana/grafana/pkg/services/guardian" "github.com/grafana/grafana/pkg/services/guardian"
"github.com/grafana/grafana/pkg/util" "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) s := dashboards.NewFolderService(c.OrgId, c.SignedInUser)
folders, err := s.GetFolders(c.QueryInt64("limit")) folders, err := s.GetFolders(c.QueryInt64("limit"))
@@ -31,7 +31,7 @@ func GetFolders(c *m.ReqContext) Response {
return JSON(200, result) return JSON(200, result)
} }
func GetFolderByUID(c *m.ReqContext) Response { func GetFolderByUID(c *models.ReqContext) Response {
s := dashboards.NewFolderService(c.OrgId, c.SignedInUser) s := dashboards.NewFolderService(c.OrgId, c.SignedInUser)
folder, err := s.GetFolderByUID(c.Params(":uid")) folder, err := s.GetFolderByUID(c.Params(":uid"))
@@ -43,7 +43,7 @@ func GetFolderByUID(c *m.ReqContext) Response {
return JSON(200, toFolderDto(g, folder)) 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) s := dashboards.NewFolderService(c.OrgId, c.SignedInUser)
folder, err := s.GetFolderByID(c.ParamsInt64(":id")) folder, err := s.GetFolderByID(c.ParamsInt64(":id"))
if err != nil { if err != nil {
@@ -54,7 +54,7 @@ func GetFolderByID(c *m.ReqContext) Response {
return JSON(200, toFolderDto(g, folder)) 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) s := dashboards.NewFolderService(c.OrgId, c.SignedInUser)
err := s.CreateFolder(&cmd) err := s.CreateFolder(&cmd)
if err != nil { 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)) 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) s := dashboards.NewFolderService(c.OrgId, c.SignedInUser)
err := s.UpdateFolder(c.Params(":uid"), &cmd) err := s.UpdateFolder(c.Params(":uid"), &cmd)
if err != nil { if err != nil {
@@ -82,7 +82,7 @@ func UpdateFolder(c *m.ReqContext, cmd m.UpdateFolderCommand) Response {
return JSON(200, toFolderDto(g, cmd.Result)) 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) s := dashboards.NewFolderService(c.OrgId, c.SignedInUser)
f, err := s.DeleteFolder(c.Params(":uid")) f, err := s.DeleteFolder(c.Params(":uid"))
if err != nil { 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() canEdit, _ := g.CanEdit()
canSave, _ := g.CanSave() canSave, _ := g.CanSave()
canAdmin, _ := g.CanAdmin() canAdmin, _ := g.CanAdmin()
@@ -127,25 +127,25 @@ func toFolderDto(g guardian.DashboardGuardian, folder *m.Folder) dtos.Folder {
} }
func toFolderError(err error) Response { func toFolderError(err error) Response {
if err == m.ErrFolderTitleEmpty || if err == models.ErrFolderTitleEmpty ||
err == m.ErrFolderSameNameExists || err == models.ErrFolderSameNameExists ||
err == m.ErrFolderWithSameUIDExists || err == models.ErrFolderWithSameUIDExists ||
err == m.ErrDashboardTypeMismatch || err == models.ErrDashboardTypeMismatch ||
err == m.ErrDashboardInvalidUid || err == models.ErrDashboardInvalidUid ||
err == m.ErrDashboardUidToLong { err == models.ErrDashboardUidToLong {
return Error(400, err.Error(), nil) return Error(400, err.Error(), nil)
} }
if err == m.ErrFolderAccessDenied { if err == models.ErrFolderAccessDenied {
return Error(403, "Access denied", err) return Error(403, "Access denied", err)
} }
if err == m.ErrFolderNotFound { if err == models.ErrFolderNotFound {
return JSON(404, util.DynMap{"status": "not-found", "message": m.ErrFolderNotFound.Error()}) return JSON(404, util.DynMap{"status": "not-found", "message": models.ErrFolderNotFound.Error()})
} }
if err == m.ErrFolderVersionMismatch { if err == models.ErrFolderVersionMismatch {
return JSON(412, util.DynMap{"status": "version-mismatch", "message": m.ErrFolderVersionMismatch.Error()}) return JSON(412, util.DynMap{"status": "version-mismatch", "message": models.ErrFolderVersionMismatch.Error()})
} }
return Error(500, "Folder API error", err) return Error(500, "Folder API error", err)

View File

@@ -5,12 +5,12 @@ import (
"github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/bus" "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/dashboards"
"github.com/grafana/grafana/pkg/services/guardian" "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) s := dashboards.NewFolderService(c.OrgId, c.SignedInUser)
folder, err := s.GetFolderByUID(c.Params(":uid")) 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) g := guardian.New(folder.Id, c.OrgId, c.SignedInUser)
if canAdmin, err := g.CanAdmin(); err != nil || !canAdmin { if canAdmin, err := g.CanAdmin(); err != nil || !canAdmin {
return toFolderError(m.ErrFolderAccessDenied) return toFolderError(models.ErrFolderAccessDenied)
} }
acl, err := g.GetAcl() acl, err := g.GetAcl()
@@ -40,14 +40,14 @@ func GetFolderPermissionList(c *m.ReqContext) Response {
} }
if perm.Slug != "" { 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) 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) s := dashboards.NewFolderService(c.OrgId, c.SignedInUser)
folder, err := s.GetFolderByUID(c.Params(":uid")) folder, err := s.GetFolderByUID(c.Params(":uid"))
@@ -62,14 +62,14 @@ func UpdateFolderPermissions(c *m.ReqContext, apiCmd dtos.UpdateDashboardAclComm
} }
if !canAdmin { if !canAdmin {
return toFolderError(m.ErrFolderAccessDenied) return toFolderError(models.ErrFolderAccessDenied)
} }
cmd := m.UpdateDashboardAclCommand{} cmd := models.UpdateDashboardAclCommand{}
cmd.DashboardId = folder.Id cmd.DashboardId = folder.Id
for _, item := range apiCmd.Items { for _, item := range apiCmd.Items {
cmd.Items = append(cmd.Items, &m.DashboardAcl{ cmd.Items = append(cmd.Items, &models.DashboardAcl{
OrgId: c.OrgId, OrgId: c.OrgId,
DashboardId: folder.Id, DashboardId: folder.Id,
UserId: item.UserId, 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 != nil {
if err == guardian.ErrGuardianPermissionExists || if err == guardian.ErrGuardianPermissionExists ||
err == guardian.ErrGuardianOverride { err == guardian.ErrGuardianOverride {
@@ -95,14 +95,14 @@ func UpdateFolderPermissions(c *m.ReqContext, apiCmd dtos.UpdateDashboardAclComm
} }
if err := bus.Dispatch(&cmd); err != nil { if err := bus.Dispatch(&cmd); err != nil {
if err == m.ErrDashboardAclInfoMissing { if err == models.ErrDashboardAclInfoMissing {
err = m.ErrFolderAclInfoMissing err = models.ErrFolderAclInfoMissing
} }
if err == m.ErrDashboardPermissionDashboardEmpty { if err == models.ErrDashboardPermissionDashboardEmpty {
err = m.ErrFolderPermissionFolderEmpty err = models.ErrFolderPermissionFolderEmpty
} }
if err == m.ErrFolderAclInfoMissing || err == m.ErrFolderPermissionFolderEmpty { if err == models.ErrFolderAclInfoMissing || err == models.ErrFolderPermissionFolderEmpty {
return Error(409, err.Error(), err) return Error(409, err.Error(), err)
} }

View File

@@ -6,7 +6,7 @@ import (
"github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/components/simplejson" "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/dashboards"
"github.com/grafana/grafana/pkg/services/guardian" "github.com/grafana/grafana/pkg/services/guardian"
@@ -17,20 +17,20 @@ func TestFolderPermissionApiEndpoint(t *testing.T) {
Convey("Folder permissions test", t, func() { Convey("Folder permissions test", t, func() {
Convey("Given folder not exists", func() { Convey("Given folder not exists", func() {
mock := &fakeFolderService{ mock := &fakeFolderService{
GetFolderByUIDError: m.ErrFolderNotFound, GetFolderByUIDError: models.ErrFolderNotFound,
} }
origNewFolderService := dashboards.NewFolderService origNewFolderService := dashboards.NewFolderService
mockFolderService(mock) 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) callGetFolderPermissions(sc)
So(sc.resp.Code, ShouldEqual, 404) So(sc.resp.Code, ShouldEqual, 404)
}) })
cmd := dtos.UpdateDashboardAclCommand{ cmd := dtos.UpdateDashboardAclCommand{
Items: []dtos.DashboardAclUpdateItem{ 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}) guardian.MockDashboardGuardian(&guardian.FakeDashboardGuardian{CanAdminValue: false})
mock := &fakeFolderService{ mock := &fakeFolderService{
GetFolderByUIDResult: &m.Folder{ GetFolderByUIDResult: &models.Folder{
Id: 1, Id: 1,
Uid: "uid", Uid: "uid",
Title: "Folder", Title: "Folder",
@@ -59,14 +59,14 @@ func TestFolderPermissionApiEndpoint(t *testing.T) {
origNewFolderService := dashboards.NewFolderService origNewFolderService := dashboards.NewFolderService
mockFolderService(mock) 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) callGetFolderPermissions(sc)
So(sc.resp.Code, ShouldEqual, 403) So(sc.resp.Code, ShouldEqual, 403)
}) })
cmd := dtos.UpdateDashboardAclCommand{ cmd := dtos.UpdateDashboardAclCommand{
Items: []dtos.DashboardAclUpdateItem{ 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{ guardian.MockDashboardGuardian(&guardian.FakeDashboardGuardian{
CanAdminValue: true, CanAdminValue: true,
CheckPermissionBeforeUpdateValue: true, CheckPermissionBeforeUpdateValue: true,
GetAclValue: []*m.DashboardAclInfoDTO{ GetAclValue: []*models.DashboardAclInfoDTO{
{OrgId: 1, DashboardId: 1, UserId: 2, Permission: m.PERMISSION_VIEW}, {OrgId: 1, DashboardId: 1, UserId: 2, Permission: models.PERMISSION_VIEW},
{OrgId: 1, DashboardId: 1, UserId: 3, Permission: m.PERMISSION_EDIT}, {OrgId: 1, DashboardId: 1, UserId: 3, Permission: models.PERMISSION_EDIT},
{OrgId: 1, DashboardId: 1, UserId: 4, Permission: m.PERMISSION_ADMIN}, {OrgId: 1, DashboardId: 1, UserId: 4, Permission: models.PERMISSION_ADMIN},
{OrgId: 1, DashboardId: 1, TeamId: 1, Permission: m.PERMISSION_VIEW}, {OrgId: 1, DashboardId: 1, TeamId: 1, Permission: models.PERMISSION_VIEW},
{OrgId: 1, DashboardId: 1, TeamId: 2, Permission: m.PERMISSION_ADMIN}, {OrgId: 1, DashboardId: 1, TeamId: 2, Permission: models.PERMISSION_ADMIN},
}, },
}) })
mock := &fakeFolderService{ mock := &fakeFolderService{
GetFolderByUIDResult: &m.Folder{ GetFolderByUIDResult: &models.Folder{
Id: 1, Id: 1,
Uid: "uid", Uid: "uid",
Title: "Folder", Title: "Folder",
@@ -106,19 +106,19 @@ func TestFolderPermissionApiEndpoint(t *testing.T) {
origNewFolderService := dashboards.NewFolderService origNewFolderService := dashboards.NewFolderService
mockFolderService(mock) 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) callGetFolderPermissions(sc)
So(sc.resp.Code, ShouldEqual, 200) So(sc.resp.Code, ShouldEqual, 200)
respJSON, err := simplejson.NewJson(sc.resp.Body.Bytes()) respJSON, err := simplejson.NewJson(sc.resp.Body.Bytes())
So(err, ShouldBeNil) So(err, ShouldBeNil)
So(len(respJSON.MustArray()), ShouldEqual, 5) So(len(respJSON.MustArray()), ShouldEqual, 5)
So(respJSON.GetIndex(0).Get("userId").MustInt(), ShouldEqual, 2) 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{ cmd := dtos.UpdateDashboardAclCommand{
Items: []dtos.DashboardAclUpdateItem{ 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{ mock := &fakeFolderService{
GetFolderByUIDResult: &m.Folder{ GetFolderByUIDResult: &models.Folder{
Id: 1, Id: 1,
Uid: "uid", Uid: "uid",
Title: "Folder", Title: "Folder",
@@ -154,7 +154,7 @@ func TestFolderPermissionApiEndpoint(t *testing.T) {
cmd := dtos.UpdateDashboardAclCommand{ cmd := dtos.UpdateDashboardAclCommand{
Items: []dtos.DashboardAclUpdateItem{ 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{ mock := &fakeFolderService{
GetFolderByUIDResult: &m.Folder{ GetFolderByUIDResult: &models.Folder{
Id: 1, Id: 1,
Uid: "uid", Uid: "uid",
Title: "Folder", Title: "Folder",
@@ -190,7 +190,7 @@ func TestFolderPermissionApiEndpoint(t *testing.T) {
cmd := dtos.UpdateDashboardAclCommand{ cmd := dtos.UpdateDashboardAclCommand{
Items: []dtos.DashboardAclUpdateItem{ 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) { func callUpdateFolderPermissions(sc *scenarioContext) {
bus.AddHandler("test", func(cmd *m.UpdateDashboardAclCommand) error { bus.AddHandler("test", func(cmd *models.UpdateDashboardAclCommand) error {
return nil return nil
}) })
@@ -226,7 +226,7 @@ func updateFolderPermissionScenario(desc string, url string, routePattern string
sc := setupScenarioContext(url) sc := setupScenarioContext(url)
sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { sc.defaultHandler = Wrap(func(c *models.ReqContext) Response {
sc.context = c sc.context = c
sc.context.OrgId = TestOrgID sc.context.OrgId = TestOrgID
sc.context.UserId = TestUserID sc.context.UserId = TestUserID

View File

@@ -7,7 +7,7 @@ import (
"github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/bus" "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/dashboards"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
@@ -17,13 +17,13 @@ import (
func TestFoldersApiEndpoint(t *testing.T) { func TestFoldersApiEndpoint(t *testing.T) {
Convey("Create/update folder response tests", t, func() { Convey("Create/update folder response tests", t, func() {
Convey("Given a correct request for creating a folder", func() { Convey("Given a correct request for creating a folder", func() {
cmd := m.CreateFolderCommand{ cmd := models.CreateFolderCommand{
Uid: "uid", Uid: "uid",
Title: "Folder", Title: "Folder",
} }
mock := &fakeFolderService{ 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) { 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 Error error
ExpectedStatusCode int ExpectedStatusCode int
}{ }{
{Error: m.ErrFolderWithSameUIDExists, ExpectedStatusCode: 400}, {Error: models.ErrFolderWithSameUIDExists, ExpectedStatusCode: 400},
{Error: m.ErrFolderTitleEmpty, ExpectedStatusCode: 400}, {Error: models.ErrFolderTitleEmpty, ExpectedStatusCode: 400},
{Error: m.ErrFolderSameNameExists, ExpectedStatusCode: 400}, {Error: models.ErrFolderSameNameExists, ExpectedStatusCode: 400},
{Error: m.ErrDashboardInvalidUid, ExpectedStatusCode: 400}, {Error: models.ErrDashboardInvalidUid, ExpectedStatusCode: 400},
{Error: m.ErrDashboardUidToLong, ExpectedStatusCode: 400}, {Error: models.ErrDashboardUidToLong, ExpectedStatusCode: 400},
{Error: m.ErrFolderAccessDenied, ExpectedStatusCode: 403}, {Error: models.ErrFolderAccessDenied, ExpectedStatusCode: 403},
{Error: m.ErrFolderNotFound, ExpectedStatusCode: 404}, {Error: models.ErrFolderNotFound, ExpectedStatusCode: 404},
{Error: m.ErrFolderVersionMismatch, ExpectedStatusCode: 412}, {Error: models.ErrFolderVersionMismatch, ExpectedStatusCode: 412},
{Error: m.ErrFolderFailedGenerateUniqueUid, ExpectedStatusCode: 500}, {Error: models.ErrFolderFailedGenerateUniqueUid, ExpectedStatusCode: 500},
} }
cmd := m.CreateFolderCommand{ cmd := models.CreateFolderCommand{
Uid: "uid", Uid: "uid",
Title: "Folder", Title: "Folder",
} }
@@ -76,12 +76,12 @@ func TestFoldersApiEndpoint(t *testing.T) {
}) })
Convey("Given a correct request for updating a folder", func() { Convey("Given a correct request for updating a folder", func() {
cmd := m.UpdateFolderCommand{ cmd := models.UpdateFolderCommand{
Title: "Folder upd", Title: "Folder upd",
} }
mock := &fakeFolderService{ 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) { 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 Error error
ExpectedStatusCode int ExpectedStatusCode int
}{ }{
{Error: m.ErrFolderWithSameUIDExists, ExpectedStatusCode: 400}, {Error: models.ErrFolderWithSameUIDExists, ExpectedStatusCode: 400},
{Error: m.ErrFolderTitleEmpty, ExpectedStatusCode: 400}, {Error: models.ErrFolderTitleEmpty, ExpectedStatusCode: 400},
{Error: m.ErrFolderSameNameExists, ExpectedStatusCode: 400}, {Error: models.ErrFolderSameNameExists, ExpectedStatusCode: 400},
{Error: m.ErrDashboardInvalidUid, ExpectedStatusCode: 400}, {Error: models.ErrDashboardInvalidUid, ExpectedStatusCode: 400},
{Error: m.ErrDashboardUidToLong, ExpectedStatusCode: 400}, {Error: models.ErrDashboardUidToLong, ExpectedStatusCode: 400},
{Error: m.ErrFolderAccessDenied, ExpectedStatusCode: 403}, {Error: models.ErrFolderAccessDenied, ExpectedStatusCode: 403},
{Error: m.ErrFolderNotFound, ExpectedStatusCode: 404}, {Error: models.ErrFolderNotFound, ExpectedStatusCode: 404},
{Error: m.ErrFolderVersionMismatch, ExpectedStatusCode: 412}, {Error: models.ErrFolderVersionMismatch, ExpectedStatusCode: 412},
{Error: m.ErrFolderFailedGenerateUniqueUid, ExpectedStatusCode: 500}, {Error: models.ErrFolderFailedGenerateUniqueUid, ExpectedStatusCode: 500},
} }
cmd := m.UpdateFolderCommand{ cmd := models.UpdateFolderCommand{
Title: "Folder upd", Title: "Folder upd",
} }
@@ -138,7 +138,7 @@ func callCreateFolder(sc *scenarioContext) {
sc.fakeReqWithParams("POST", sc.url, map[string]string{}).exec() 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() { Convey(desc+" "+url, func() {
defer bus.ClearBusHandlers() defer bus.ClearBusHandlers()
@@ -148,9 +148,9 @@ func createFolderScenario(desc string, url string, routePattern string, mock *fa
} }
sc := setupScenarioContext(url) sc := setupScenarioContext(url)
sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { sc.defaultHandler = Wrap(func(c *models.ReqContext) Response {
sc.context = c 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) return hs.CreateFolder(c, cmd)
}) })
@@ -172,14 +172,14 @@ func callUpdateFolder(sc *scenarioContext) {
sc.fakeReqWithParams("PUT", sc.url, map[string]string{}).exec() 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() { Convey(desc+" "+url, func() {
defer bus.ClearBusHandlers() defer bus.ClearBusHandlers()
sc := setupScenarioContext(url) sc := setupScenarioContext(url)
sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { sc.defaultHandler = Wrap(func(c *models.ReqContext) Response {
sc.context = c 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) return UpdateFolder(c, cmd)
}) })
@@ -198,50 +198,50 @@ func updateFolderScenario(desc string, url string, routePattern string, mock *fa
} }
type fakeFolderService struct { type fakeFolderService struct {
GetFoldersResult []*m.Folder GetFoldersResult []*models.Folder
GetFoldersError error GetFoldersError error
GetFolderByUIDResult *m.Folder GetFolderByUIDResult *models.Folder
GetFolderByUIDError error GetFolderByUIDError error
GetFolderByIDResult *m.Folder GetFolderByIDResult *models.Folder
GetFolderByIDError error GetFolderByIDError error
CreateFolderResult *m.Folder CreateFolderResult *models.Folder
CreateFolderError error CreateFolderError error
UpdateFolderResult *m.Folder UpdateFolderResult *models.Folder
UpdateFolderError error UpdateFolderError error
DeleteFolderResult *m.Folder DeleteFolderResult *models.Folder
DeleteFolderError error DeleteFolderError error
DeletedFolderUids []string 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 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 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 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 cmd.Result = s.CreateFolderResult
return s.CreateFolderError 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 cmd.Result = s.UpdateFolderResult
return s.UpdateFolderError 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) s.DeletedFolderUids = append(s.DeletedFolderUids, uid)
return s.DeleteFolderResult, s.DeleteFolderError return s.DeleteFolderResult, s.DeleteFolderError
} }
func mockFolderService(mock *fakeFolderService) { 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 return mock
} }
} }

View File

@@ -3,6 +3,7 @@ package api
import ( import (
"strconv" "strconv"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/rendering" "github.com/grafana/grafana/pkg/services/rendering"
"github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/components/simplejson"
@@ -10,24 +11,23 @@ import (
"github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/infra/log" "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/plugins"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
) )
// getFrontendSettingsMap returns a json object with all the settings needed for front end initialisation. // 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) { func (hs *HTTPServer) getFrontendSettingsMap(c *models.ReqContext) (map[string]interface{}, error) {
orgDataSources := make([]*m.DataSource, 0) orgDataSources := make([]*models.DataSource, 0)
if c.OrgId != 0 { if c.OrgId != 0 {
query := m.GetDataSourcesQuery{OrgId: c.OrgId} query := models.GetDataSourcesQuery{OrgId: c.OrgId}
err := bus.Dispatch(&query) err := bus.Dispatch(&query)
if err != nil { if err != nil {
return nil, err return nil, err
} }
dsFilterQuery := m.DatasourcesPermissionFilterQuery{ dsFilterQuery := models.DatasourcesPermissionFilterQuery{
User: c.SignedInUser, User: c.SignedInUser,
Datasources: query.Result, Datasources: query.Result,
} }
@@ -62,7 +62,7 @@ func (hs *HTTPServer) getFrontendSettingsMap(c *m.ReqContext) (map[string]interf
for _, ds := range orgDataSources { for _, ds := range orgDataSources {
url := ds.Url 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) 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 dsMap["jsonData"] = jsonData
if ds.Access == m.DS_ACCESS_DIRECT { if ds.Access == models.DS_ACCESS_DIRECT {
if ds.BasicAuth { if ds.BasicAuth {
dsMap["basicAuth"] = util.GetBasicAuthHeader(ds.BasicAuthUser, ds.DecryptedBasicAuthPassword()) 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 dsMap["withCredentials"] = ds.WithCredentials
} }
if ds.Type == m.DS_INFLUXDB_08 { if ds.Type == models.DS_INFLUXDB_08 {
dsMap["username"] = ds.User dsMap["username"] = ds.User
dsMap["password"] = ds.DecryptedPassword() dsMap["password"] = ds.DecryptedPassword()
dsMap["url"] = url + "/db/" + ds.Database dsMap["url"] = url + "/db/" + ds.Database
} }
if ds.Type == m.DS_INFLUXDB { if ds.Type == models.DS_INFLUXDB {
dsMap["username"] = ds.User dsMap["username"] = ds.User
dsMap["password"] = ds.DecryptedPassword() dsMap["password"] = ds.DecryptedPassword()
dsMap["url"] = url 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 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 // add unproxied server URL for link to Prometheus web UI
jsonData.Set("directUrl", ds.Url) jsonData.Set("directUrl", ds.Url)
} }
@@ -247,7 +247,7 @@ func getPanelSort(id string) int {
return sort return sort
} }
func (hs *HTTPServer) GetFrontendSettings(c *m.ReqContext) { func (hs *HTTPServer) GetFrontendSettings(c *models.ReqContext) {
settings, err := hs.getFrontendSettingsMap(c) settings, err := hs.getFrontendSettingsMap(c)
if err != nil { if err != nil {
c.JsonApiErr(400, "Failed to get frontend settings", err) c.JsonApiErr(400, "Failed to get frontend settings", err)

View File

@@ -7,7 +7,7 @@ import (
"net/url" "net/url"
"time" "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/setting"
"github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/util"
) )
@@ -40,7 +40,7 @@ func ReverseProxyGnetReq(proxyPath string) *httputil.ReverseProxy {
return &httputil.ReverseProxy{Director: director} return &httputil.ReverseProxy{Director: director}
} }
func ProxyGnetRequest(c *m.ReqContext) { func ProxyGnetRequest(c *models.ReqContext) {
proxyPath := c.Params("*") proxyPath := c.Params("*")
proxy := ReverseProxyGnetReq(proxyPath) proxy := ReverseProxyGnetReq(proxyPath)
proxy.Transport = grafanaComProxyTransport proxy.Transport = grafanaComProxyTransport

View File

@@ -7,7 +7,7 @@ import (
"github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/bus" "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"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
) )
@@ -18,13 +18,13 @@ const (
darkName = "dark" 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) settings, err := hs.getFrontendSettingsMap(c)
if err != nil { if err != nil {
return nil, err return nil, err
} }
prefsQuery := m.GetPreferencesWithDefaultsQuery{User: c.SignedInUser} prefsQuery := models.GetPreferencesWithDefaultsQuery{User: c.SignedInUser}
if err := bus.Dispatch(&prefsQuery); err != nil { if err := bus.Dispatch(&prefsQuery); err != nil {
return nil, err return nil, err
} }
@@ -49,7 +49,7 @@ func (hs *HTTPServer) setIndexViewData(c *m.ReqContext) (*dtos.IndexViewData, er
settings["appSubUrl"] = "" settings["appSubUrl"] = ""
} }
hasEditPermissionInFoldersQuery := m.HasEditPermissionInFoldersQuery{SignedInUser: c.SignedInUser} hasEditPermissionInFoldersQuery := models.HasEditPermissionInFoldersQuery{SignedInUser: c.SignedInUser}
if err := bus.Dispatch(&hasEditPermissionInFoldersQuery); err != nil { if err := bus.Dispatch(&hasEditPermissionInFoldersQuery); err != nil {
return nil, err 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"}, {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"}) 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, 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{ data.NavTree = append(data.NavTree, &dtos.NavLink{
Text: "Explore", Text: "Explore",
Id: "explore", Id: "explore",
@@ -192,7 +192,7 @@ func (hs *HTTPServer) setIndexViewData(c *m.ReqContext) (*dtos.IndexViewData, er
data.NavTree = append(data.NavTree, profileNode) 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{ alertChildNavs := []*dtos.NavLink{
{Text: "Alert Rules", Id: "alert-list", Url: setting.AppSubUrl + "/alerting/list", Icon: "gicon gicon-alert-rules"}, {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"}, {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{Divider: true})
appLink.Children = append(appLink.Children, &dtos.NavLink{Text: "Plugin Config", Icon: "gicon gicon-cog", Url: setting.AppSubUrl + "/plugins/" + plugin.Id + "/"}) 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{} configNodes := []*dtos.NavLink{}
if c.OrgRole == m.ROLE_ADMIN { if c.OrgRole == models.ROLE_ADMIN {
configNodes = append(configNodes, &dtos.NavLink{ configNodes = append(configNodes, &dtos.NavLink{
Text: "Data Sources", Text: "Data Sources",
Icon: "gicon gicon-datasources", 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{ configNodes = append(configNodes, &dtos.NavLink{
Text: "Teams", Text: "Teams",
Id: "teams", Id: "teams",
@@ -305,7 +305,7 @@ func (hs *HTTPServer) setIndexViewData(c *m.ReqContext) (*dtos.IndexViewData, er
Url: setting.AppSubUrl + "/plugins", Url: setting.AppSubUrl + "/plugins",
}) })
if c.OrgRole == m.ROLE_ADMIN { if c.OrgRole == models.ROLE_ADMIN {
configNodes = append(configNodes, &dtos.NavLink{ configNodes = append(configNodes, &dtos.NavLink{
Text: "Preferences", Text: "Preferences",
Id: "org-settings", Id: "org-settings",
@@ -377,7 +377,7 @@ func (hs *HTTPServer) setIndexViewData(c *m.ReqContext) (*dtos.IndexViewData, er
return &data, nil return &data, nil
} }
func (hs *HTTPServer) Index(c *m.ReqContext) { func (hs *HTTPServer) Index(c *models.ReqContext) {
data, err := hs.setIndexViewData(c) data, err := hs.setIndexViewData(c)
if err != nil { if err != nil {
c.Handle(500, "Failed to get settings", err) c.Handle(500, "Failed to get settings", err)
@@ -386,7 +386,7 @@ func (hs *HTTPServer) Index(c *m.ReqContext) {
c.HTML(200, "index", data) c.HTML(200, "index", data)
} }
func (hs *HTTPServer) NotFoundHandler(c *m.ReqContext) { func (hs *HTTPServer) NotFoundHandler(c *models.ReqContext) {
if c.IsApiRequest() { if c.IsApiRequest() {
c.JsonApiErr(404, "Not found", nil) c.JsonApiErr(404, "Not found", nil)
return return

View File

@@ -7,7 +7,7 @@ import (
"github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/log"
m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
) )
type StreamManager struct { type StreamManager struct {
@@ -51,11 +51,11 @@ func (sm *StreamManager) Serve(w http.ResponseWriter, r *http.Request) {
c.readPump() c.readPump()
} }
func (s *StreamManager) GetStreamList() m.StreamList { func (s *StreamManager) GetStreamList() models.StreamList {
list := make(m.StreamList, 0) list := make(models.StreamList, 0)
for _, stream := range s.streams { for _, stream := range s.streams {
list = append(list, &m.StreamInfo{ list = append(list, &models.StreamInfo{
Name: stream.name, Name: stream.name,
}) })
} }
@@ -63,7 +63,7 @@ func (s *StreamManager) GetStreamList() m.StreamList {
return list return list
} }
func (s *StreamManager) Push(packet *m.StreamPacket) { func (s *StreamManager) Push(packet *models.StreamPacket) {
stream, exist := s.streams[packet.Stream] stream, exist := s.streams[packet.Stream]
if !exist { 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() messageBytes, _ := simplejson.NewFromAny(packet).Encode()

View File

@@ -21,7 +21,7 @@ import (
"github.com/grafana/grafana/pkg/login" "github.com/grafana/grafana/pkg/login"
"github.com/grafana/grafana/pkg/login/social" "github.com/grafana/grafana/pkg/login/social"
"github.com/grafana/grafana/pkg/middleware" "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" "github.com/grafana/grafana/pkg/setting"
) )
@@ -39,7 +39,7 @@ func GenStateString() (string, error) {
return base64.URLEncoding.EncodeToString(rnd), nil return base64.URLEncoding.EncodeToString(rnd), nil
} }
func (hs *HTTPServer) OAuthLogin(ctx *m.ReqContext) { func (hs *HTTPServer) OAuthLogin(ctx *models.ReqContext) {
if setting.OAuthService == nil { if setting.OAuthService == nil {
ctx.Handle(404, "OAuth not enabled", nil) ctx.Handle(404, "OAuth not enabled", nil)
return return
@@ -172,19 +172,19 @@ func (hs *HTTPServer) OAuthLogin(ctx *m.ReqContext) {
return return
} }
extUser := &m.ExternalUserInfo{ extUser := &models.ExternalUserInfo{
AuthModule: "oauth_" + name, AuthModule: "oauth_" + name,
OAuthToken: token, OAuthToken: token,
AuthId: userInfo.Id, AuthId: userInfo.Id,
Name: userInfo.Name, Name: userInfo.Name,
Login: userInfo.Login, Login: userInfo.Login,
Email: userInfo.Email, Email: userInfo.Email,
OrgRoles: map[int64]m.RoleType{}, OrgRoles: map[int64]models.RoleType{},
Groups: userInfo.Groups, Groups: userInfo.Groups,
} }
if userInfo.Role != "" { if userInfo.Role != "" {
rt := m.RoleType(userInfo.Role) rt := models.RoleType(userInfo.Role)
if rt.IsValid() { if rt.IsValid() {
var orgID int64 var orgID int64
if setting.AutoAssignOrg && setting.AutoAssignOrgId > 0 { if setting.AutoAssignOrg && setting.AutoAssignOrgId > 0 {
@@ -197,7 +197,7 @@ func (hs *HTTPServer) OAuthLogin(ctx *m.ReqContext) {
} }
// add/update user in grafana // add/update user in grafana
cmd := &m.UpsertUserCommand{ cmd := &models.UpsertUserCommand{
ReqContext: ctx, ReqContext: ctx,
ExternalUser: extUser, ExternalUser: extUser,
SignupAllowed: connect.IsSignupAllowed(), SignupAllowed: connect.IsSignupAllowed(),
@@ -236,7 +236,7 @@ func hashStatecode(code, seed string) string {
return hex.EncodeToString(hashBytes[:]) 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...) ctx.Logger.Error(err.Error(), v...)
if err := hs.trySetEncryptedCookie(ctx, LoginErrorCookieName, err.Error(), 60); err != nil { if err := hs.trySetEncryptedCookie(ctx, LoginErrorCookieName, err.Error(), 60); err != nil {
oauthLogger.Error("Failed to set encrypted cookie", "err", err) oauthLogger.Error("Failed to set encrypted cookie", "err", err)

View File

@@ -4,20 +4,20 @@ import (
"context" "context"
"sort" "sort"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/plugins" "github.com/grafana/grafana/pkg/plugins"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/components/simplejson" "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"
"github.com/grafana/grafana/pkg/tsdb/testdatasource" "github.com/grafana/grafana/pkg/tsdb/testdatasource"
"github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/util"
) )
// POST /api/ds/query DataSource query w/ expressions // 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() { if !setting.IsExpressionsEnabled() {
return Error(404, "Expressions feature toggle is not enabled", nil) 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 expr := false
var ds *m.DataSource var ds *models.DataSource
for i, query := range reqDto.Queries { for i, query := range reqDto.Queries {
name, err := query.Get("datasource").String() name, err := query.Get("datasource").String()
if err != nil { if err != nil {
@@ -50,12 +50,13 @@ func (hs *HTTPServer) QueryMetricsV2(c *m.ReqContext, reqDto dtos.MetricRequest)
if i == 0 && !expr { if i == 0 && !expr {
ds, err = hs.DatasourceCache.GetDatasource(datasourceID, c.SignedInUser, c.SkipCache) ds, err = hs.DatasourceCache.GetDatasource(datasourceID, c.SignedInUser, c.SkipCache)
if err != nil { if err != nil {
if err == m.ErrDataSourceAccessDenied { if err == models.ErrDataSourceAccessDenied {
return Error(403, "Access denied to datasource", err) return Error(403, "Access denied to datasource", err)
} }
return Error(500, "Unable to load datasource meta data", err) return Error(500, "Unable to load datasource meta data", err)
} }
} }
request.Queries = append(request.Queries, &tsdb.Query{ request.Queries = append(request.Queries, &tsdb.Query{
RefId: query.Get("refId").MustString("A"), RefId: query.Get("refId").MustString("A"),
MaxDataPoints: query.Get("maxDataPoints").MustInt64(100), MaxDataPoints: query.Get("maxDataPoints").MustInt64(100),
@@ -63,7 +64,6 @@ func (hs *HTTPServer) QueryMetricsV2(c *m.ReqContext, reqDto dtos.MetricRequest)
Model: query, Model: query,
DataSource: ds, DataSource: ds,
}) })
} }
var resp *tsdb.Response var resp *tsdb.Response
@@ -93,7 +93,7 @@ func (hs *HTTPServer) QueryMetricsV2(c *m.ReqContext, reqDto dtos.MetricRequest)
} }
// POST /api/tsdb/query // 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) timeRange := tsdb.NewTimeRange(reqDto.From, reqDto.To)
if len(reqDto.Queries) == 0 { 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) ds, err := hs.DatasourceCache.GetDatasource(datasourceId, c.SignedInUser, c.SkipCache)
if err != nil { if err != nil {
if err == m.ErrDataSourceAccessDenied { if err == models.ErrDataSourceAccessDenied {
return Error(403, "Access denied to datasource", err) return Error(403, "Access denied to datasource", err)
} }
return Error(500, "Unable to load datasource meta data", 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 // GET /api/tsdb/testdata/scenarios
func GetTestDataScenarios(c *m.ReqContext) Response { func GetTestDataScenarios(c *models.ReqContext) Response {
result := make([]interface{}, 0) result := make([]interface{}, 0)
scenarioIds := make([]string, 0) scenarioIds := make([]string, 0)
@@ -166,15 +166,15 @@ func GetTestDataScenarios(c *m.ReqContext) Response {
} }
// Generates a index out of range error // Generates a index out of range error
func GenerateError(c *m.ReqContext) Response { func GenerateError(c *models.ReqContext) Response {
var array []string var array []string
// nolint: govet // nolint: govet
return JSON(200, array[20]) return JSON(200, array[20])
} }
// GET /api/tsdb/testdata/gensql // GET /api/tsdb/testdata/gensql
func GenerateSQLTestData(c *m.ReqContext) Response { func GenerateSQLTestData(c *models.ReqContext) Response {
if err := bus.Dispatch(&m.InsertSqlTestDataCommand{}); err != nil { if err := bus.Dispatch(&models.InsertSqlTestDataCommand{}); err != nil {
return Error(500, "Failed to insert test data", err) 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 // GET /api/tsdb/testdata/random-walk
func GetTestDataRandomWalk(c *m.ReqContext) Response { func GetTestDataRandomWalk(c *models.ReqContext) Response {
from := c.Query("from") from := c.Query("from")
to := c.Query("to") to := c.Query("to")
intervalMs := c.QueryInt64("intervalMs") intervalMs := c.QueryInt64("intervalMs")
@@ -190,7 +190,7 @@ func GetTestDataRandomWalk(c *m.ReqContext) Response {
timeRange := tsdb.NewTimeRange(from, to) timeRange := tsdb.NewTimeRange(from, to)
request := &tsdb.TsdbQuery{TimeRange: timeRange} request := &tsdb.TsdbQuery{TimeRange: timeRange}
dsInfo := &m.DataSource{Type: "testdata"} dsInfo := &models.DataSource{Type: "testdata"}
request.Queries = append(request.Queries, &tsdb.Query{ request.Queries = append(request.Queries, &tsdb.Query{
RefId: "A", RefId: "A",
IntervalMs: intervalMs, IntervalMs: intervalMs,

View File

@@ -4,36 +4,36 @@ import (
"github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/infra/metrics" "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/setting"
"github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/util"
) )
// GET /api/org // GET /api/org
func GetOrgCurrent(c *m.ReqContext) Response { func GetOrgCurrent(c *models.ReqContext) Response {
return getOrgHelper(c.OrgId) return getOrgHelper(c.OrgId)
} }
// GET /api/orgs/:orgId // GET /api/orgs/:orgId
func GetOrgByID(c *m.ReqContext) Response { func GetOrgByID(c *models.ReqContext) Response {
return getOrgHelper(c.ParamsInt64(":orgId")) return getOrgHelper(c.ParamsInt64(":orgId"))
} }
// Get /api/orgs/name/:name // Get /api/orgs/name/:name
func GetOrgByName(c *m.ReqContext) Response { func GetOrgByName(c *models.ReqContext) Response {
query := m.GetOrgByNameQuery{Name: c.Params(":name")} query := models.GetOrgByNameQuery{Name: c.Params(":name")}
if err := bus.Dispatch(&query); err != nil { if err := bus.Dispatch(&query); err != nil {
if err == m.ErrOrgNotFound { if err == models.ErrOrgNotFound {
return Error(404, "Organization not found", err) return Error(404, "Organization not found", err)
} }
return Error(500, "Failed to get organization", err) return Error(500, "Failed to get organization", err)
} }
org := query.Result org := query.Result
result := m.OrgDetailsDTO{ result := models.OrgDetailsDTO{
Id: org.Id, Id: org.Id,
Name: org.Name, Name: org.Name,
Address: m.Address{ Address: models.Address{
Address1: org.Address1, Address1: org.Address1,
Address2: org.Address2, Address2: org.Address2,
City: org.City, City: org.City,
@@ -47,10 +47,10 @@ func GetOrgByName(c *m.ReqContext) Response {
} }
func getOrgHelper(orgID int64) 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 := bus.Dispatch(&query); err != nil {
if err == m.ErrOrgNotFound { if err == models.ErrOrgNotFound {
return Error(404, "Organization not found", err) return Error(404, "Organization not found", err)
} }
@@ -58,10 +58,10 @@ func getOrgHelper(orgID int64) Response {
} }
org := query.Result org := query.Result
result := m.OrgDetailsDTO{ result := models.OrgDetailsDTO{
Id: org.Id, Id: org.Id,
Name: org.Name, Name: org.Name,
Address: m.Address{ Address: models.Address{
Address1: org.Address1, Address1: org.Address1,
Address2: org.Address2, Address2: org.Address2,
City: org.City, City: org.City,
@@ -75,14 +75,14 @@ func getOrgHelper(orgID int64) Response {
} }
// POST /api/orgs // 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) { if !c.IsSignedIn || (!setting.AllowUserOrgCreate && !c.IsGrafanaAdmin) {
return Error(403, "Access denied", nil) return Error(403, "Access denied", nil)
} }
cmd.UserId = c.UserId cmd.UserId = c.UserId
if err := bus.Dispatch(&cmd); err != nil { if err := bus.Dispatch(&cmd); err != nil {
if err == m.ErrOrgNameTaken { if err == models.ErrOrgNameTaken {
return Error(409, "Organization name taken", err) return Error(409, "Organization name taken", err)
} }
return Error(500, "Failed to create organization", 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 // 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) return updateOrgHelper(form, c.OrgId)
} }
// PUT /api/orgs/: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")) return updateOrgHelper(form, c.ParamsInt64(":orgId"))
} }
func updateOrgHelper(form dtos.UpdateOrgForm, orgID int64) Response { 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 := bus.Dispatch(&cmd); err != nil {
if err == m.ErrOrgNameTaken { if err == models.ErrOrgNameTaken {
return Error(400, "Organization name taken", err) return Error(400, "Organization name taken", err)
} }
return Error(500, "Failed to update organization", 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 // 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) return updateOrgAddressHelper(form, c.OrgId)
} }
// PUT /api/orgs/:orgId/address // 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")) return updateOrgAddressHelper(form, c.ParamsInt64(":orgId"))
} }
func updateOrgAddressHelper(form dtos.UpdateOrgAddressForm, orgID int64) Response { func updateOrgAddressHelper(form dtos.UpdateOrgAddressForm, orgID int64) Response {
cmd := m.UpdateOrgAddressCommand{ cmd := models.UpdateOrgAddressCommand{
OrgId: orgID, OrgId: orgID,
Address: m.Address{ Address: models.Address{
Address1: form.Address1, Address1: form.Address1,
Address2: form.Address2, Address2: form.Address2,
City: form.City, City: form.City,
@@ -149,9 +149,9 @@ func updateOrgAddressHelper(form dtos.UpdateOrgAddressForm, orgID int64) Respons
} }
// GET /api/orgs/:orgId // GET /api/orgs/:orgId
func DeleteOrgByID(c *m.ReqContext) Response { func DeleteOrgByID(c *models.ReqContext) Response {
if err := bus.Dispatch(&m.DeleteOrgCommand{Id: c.ParamsInt64(":orgId")}); err != nil { if err := bus.Dispatch(&models.DeleteOrgCommand{Id: c.ParamsInt64(":orgId")}); err != nil {
if err == m.ErrOrgNotFound { if err == models.ErrOrgNotFound {
return Error(404, "Failed to delete organization. ID not found", nil) return Error(404, "Failed to delete organization. ID not found", nil)
} }
return Error(500, "Failed to update organization", err) return Error(500, "Failed to update organization", err)
@@ -159,8 +159,8 @@ func DeleteOrgByID(c *m.ReqContext) Response {
return Success("Organization deleted") return Success("Organization deleted")
} }
func SearchOrgs(c *m.ReqContext) Response { func SearchOrgs(c *models.ReqContext) Response {
query := m.SearchOrgsQuery{ query := models.SearchOrgsQuery{
Query: c.Query("query"), Query: c.Query("query"),
Name: c.Query("name"), Name: c.Query("name"),
Page: 0, Page: 0,

View File

@@ -7,13 +7,13 @@ import (
"github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/events" "github.com/grafana/grafana/pkg/events"
"github.com/grafana/grafana/pkg/infra/metrics" "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/setting"
"github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/util"
) )
func GetPendingOrgInvites(c *m.ReqContext) Response { func GetPendingOrgInvites(c *models.ReqContext) Response {
query := m.GetTempUsersQuery{OrgId: c.OrgId, Status: m.TmpUserInvitePending} query := models.GetTempUsersQuery{OrgId: c.OrgId, Status: models.TmpUserInvitePending}
if err := bus.Dispatch(&query); err != nil { if err := bus.Dispatch(&query); err != nil {
return Error(500, "Failed to get invites from db", err) 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) 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() { if !inviteDto.Role.IsValid() {
return Error(400, "Invalid role specified", nil) return Error(400, "Invalid role specified", nil)
} }
// first try get existing user // 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 := 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) return Error(500, "Failed to query db for existing user check", err)
} }
} else { } else {
@@ -45,11 +45,11 @@ func AddOrgInvite(c *m.ReqContext, inviteDto dtos.AddInviteForm) Response {
return Error(400, "Cannot invite when login is disabled.", nil) return Error(400, "Cannot invite when login is disabled.", nil)
} }
cmd := m.CreateTempUserCommand{} cmd := models.CreateTempUserCommand{}
cmd.OrgId = c.OrgId cmd.OrgId = c.OrgId
cmd.Email = inviteDto.LoginOrEmail cmd.Email = inviteDto.LoginOrEmail
cmd.Name = inviteDto.Name cmd.Name = inviteDto.Name
cmd.Status = m.TmpUserInvitePending cmd.Status = models.TmpUserInvitePending
cmd.InvitedByUserId = c.UserId cmd.InvitedByUserId = c.UserId
var err error var err error
cmd.Code, err = util.GetRandomString(30) cmd.Code, err = util.GetRandomString(30)
@@ -65,7 +65,7 @@ func AddOrgInvite(c *m.ReqContext, inviteDto dtos.AddInviteForm) Response {
// send invite email // send invite email
if inviteDto.SendEmail && util.IsEmail(inviteDto.LoginOrEmail) { if inviteDto.SendEmail && util.IsEmail(inviteDto.LoginOrEmail) {
emailCmd := m.SendEmailCommand{ emailCmd := models.SendEmailCommand{
To: []string{inviteDto.LoginOrEmail}, To: []string{inviteDto.LoginOrEmail},
Template: "new_user_invite.html", Template: "new_user_invite.html",
Data: map[string]interface{}{ 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 := bus.Dispatch(&emailCmd); err != nil {
if err == m.ErrSmtpNotEnabled { if err == models.ErrSmtpNotEnabled {
return Error(412, err.Error(), err) return Error(412, err.Error(), err)
} }
return Error(500, "Failed to send email invite", 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 { if err := bus.Dispatch(&emailSentCmd); err != nil {
return Error(500, "Failed to update invite with email sent info", err) 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)) 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 // 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 := 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(412, fmt.Sprintf("User %s is already added to organization", inviteDto.LoginOrEmail), err)
} }
return Error(500, "Error while trying to create org user", err) return Error(500, "Error while trying to create org user", err)
} }
if inviteDto.SendEmail && util.IsEmail(user.Email) { if inviteDto.SendEmail && util.IsEmail(user.Email) {
emailCmd := m.SendEmailCommand{ emailCmd := models.SendEmailCommand{
To: []string{user.Email}, To: []string{user.Email},
Template: "invited_to_org.html", Template: "invited_to_org.html",
Data: map[string]interface{}{ 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)) return Success(fmt.Sprintf("Existing Grafana user %s added to org %s", user.NameOrFallback(), c.OrgName))
} }
func RevokeInvite(c *m.ReqContext) Response { func RevokeInvite(c *models.ReqContext) Response {
if ok, rsp := updateTempUserStatus(c.Params(":code"), m.TmpUserRevoked); !ok { if ok, rsp := updateTempUserStatus(c.Params(":code"), models.TmpUserRevoked); !ok {
return rsp return rsp
} }
@@ -135,17 +135,17 @@ func RevokeInvite(c *m.ReqContext) Response {
// GetInviteInfoByCode gets a pending user invite corresponding to a certain code. // GetInviteInfoByCode gets a pending user invite corresponding to a certain code.
// A response containing an InviteInfo object is returned if the invite is found. // A response containing an InviteInfo object is returned if the invite is found.
// If a (pending) invite is not found, 404 is returned. // If a (pending) invite is not found, 404 is returned.
func GetInviteInfoByCode(c *m.ReqContext) Response { func GetInviteInfoByCode(c *models.ReqContext) Response {
query := m.GetTempUserByCodeQuery{Code: c.Params(":code")} query := models.GetTempUserByCodeQuery{Code: c.Params(":code")}
if err := bus.Dispatch(&query); err != nil { if err := bus.Dispatch(&query); err != nil {
if err == m.ErrTempUserNotFound { if err == models.ErrTempUserNotFound {
return Error(404, "Invite not found", nil) return Error(404, "Invite not found", nil)
} }
return Error(500, "Failed to get invite", err) return Error(500, "Failed to get invite", err)
} }
invite := query.Result invite := query.Result
if invite.Status != m.TmpUserInvitePending { if invite.Status != models.TmpUserInvitePending {
return Error(404, "Invite not found", nil) 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 { func (hs *HTTPServer) CompleteInvite(c *models.ReqContext, completeInvite dtos.CompleteInviteForm) Response {
query := m.GetTempUserByCodeQuery{Code: completeInvite.InviteCode} query := models.GetTempUserByCodeQuery{Code: completeInvite.InviteCode}
if err := bus.Dispatch(&query); err != nil { if err := bus.Dispatch(&query); err != nil {
if err == m.ErrTempUserNotFound { if err == models.ErrTempUserNotFound {
return Error(404, "Invite not found", nil) return Error(404, "Invite not found", nil)
} }
return Error(500, "Failed to get invite", err) return Error(500, "Failed to get invite", err)
} }
invite := query.Result 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) return Error(412, fmt.Sprintf("Invite cannot be used in status %s", invite.Status), nil)
} }
cmd := m.CreateUserCommand{ cmd := models.CreateUserCommand{
Email: completeInvite.Email, Email: completeInvite.Email,
Name: completeInvite.Name, Name: completeInvite.Name,
Login: completeInvite.Username, Login: completeInvite.Username,
@@ -205,9 +205,9 @@ func (hs *HTTPServer) CompleteInvite(c *m.ReqContext, completeInvite dtos.Comple
return Success("User created and logged in") 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 // 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 { if err := bus.Dispatch(&updateTmpUserCmd); err != nil {
return false, Error(500, "Failed to update invite status", err) 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 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 // 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 := 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) return false, Error(500, "Error while trying to create org user", err)
} }
} }
// update temp user status // 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 return false, rsp
} }
if setActive { if setActive {
// set org to active // 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) return false, Error(500, "Failed to set org as active", err)
} }
} }

View File

@@ -3,12 +3,12 @@ package api
import ( import (
"github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/bus" "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/setting"
"github.com/grafana/grafana/pkg/util" "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 { if setting.LDAPEnabled || setting.AuthProxyEnabled {
return Error(401, "Not allowed to reset password when LDAP or Auth Proxy is enabled", nil) 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) 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 { if err := bus.Dispatch(&userQuery); err != nil {
c.Logger.Info("Requested password reset for user that was not found", "user", userQuery.LoginOrEmail) c.Logger.Info("Requested password reset for user that was not found", "user", userQuery.LoginOrEmail)
return Error(200, "Email sent", err) 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 { if err := bus.Dispatch(&emailCmd); err != nil {
return Error(500, "Failed to send email", err) return Error(500, "Failed to send email", err)
} }
@@ -31,11 +31,11 @@ func SendResetPasswordEmail(c *m.ReqContext, form dtos.SendResetPasswordEmailFor
return Success("Email sent") return Success("Email sent")
} }
func ResetPassword(c *m.ReqContext, form dtos.ResetUserPasswordForm) Response { func ResetPassword(c *models.ReqContext, form dtos.ResetUserPasswordForm) Response {
query := m.ValidateResetPasswordCodeQuery{Code: form.Code} query := models.ValidateResetPasswordCodeQuery{Code: form.Code}
if err := bus.Dispatch(&query); err != nil { 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(400, "Invalid or expired reset password code", nil)
} }
return Error(500, "Unknown error validating email code", err) 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) return Error(400, "Passwords do not match", nil)
} }
cmd := m.ChangeUserPasswordCommand{} cmd := models.ChangeUserPasswordCommand{}
cmd.UserId = query.Result.Id cmd.UserId = query.Result.Id
var err error var err error
cmd.NewPassword, err = util.EncodePassword(form.NewPassword, query.Result.Salt) cmd.NewPassword, err = util.EncodePassword(form.NewPassword, query.Result.Salt)

View File

@@ -4,13 +4,12 @@ import (
"net/http" "net/http"
"github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/bus"
_ "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/models"
m "github.com/grafana/grafana/pkg/models"
) )
func ValidateOrgPlaylist(c *m.ReqContext) { func ValidateOrgPlaylist(c *models.ReqContext) {
id := c.ParamsInt64(":id") id := c.ParamsInt64(":id")
query := m.GetPlaylistByIdQuery{Id: id} query := models.GetPlaylistByIdQuery{Id: id}
err := bus.Dispatch(&query) err := bus.Dispatch(&query)
if err != nil { 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") query := c.Query("query")
limit := c.QueryInt("limit") limit := c.QueryInt("limit")
@@ -49,7 +48,7 @@ func SearchPlaylists(c *m.ReqContext) Response {
limit = 1000 limit = 1000
} }
searchQuery := m.GetPlaylistsQuery{ searchQuery := models.GetPlaylistsQuery{
Name: query, Name: query,
Limit: limit, Limit: limit,
OrgId: c.OrgId, OrgId: c.OrgId,
@@ -63,9 +62,9 @@ func SearchPlaylists(c *m.ReqContext) Response {
return JSON(200, searchQuery.Result) return JSON(200, searchQuery.Result)
} }
func GetPlaylist(c *m.ReqContext) Response { func GetPlaylist(c *models.ReqContext) Response {
id := c.ParamsInt64(":id") id := c.ParamsInt64(":id")
cmd := m.GetPlaylistByIdQuery{Id: id} cmd := models.GetPlaylistByIdQuery{Id: id}
if err := bus.Dispatch(&cmd); err != nil { if err := bus.Dispatch(&cmd); err != nil {
return Error(500, "Playlist not found", err) return Error(500, "Playlist not found", err)
@@ -73,7 +72,7 @@ func GetPlaylist(c *m.ReqContext) Response {
playlistDTOs, _ := LoadPlaylistItemDTOs(id) playlistDTOs, _ := LoadPlaylistItemDTOs(id)
dto := &m.PlaylistDTO{ dto := &models.PlaylistDTO{
Id: cmd.Result.Id, Id: cmd.Result.Id,
Name: cmd.Result.Name, Name: cmd.Result.Name,
Interval: cmd.Result.Interval, Interval: cmd.Result.Interval,
@@ -84,17 +83,17 @@ func GetPlaylist(c *m.ReqContext) Response {
return JSON(200, dto) return JSON(200, dto)
} }
func LoadPlaylistItemDTOs(id int64) ([]m.PlaylistItemDTO, error) { func LoadPlaylistItemDTOs(id int64) ([]models.PlaylistItemDTO, error) {
playlistitems, err := LoadPlaylistItems(id) playlistitems, err := LoadPlaylistItems(id)
if err != nil { if err != nil {
return nil, err return nil, err
} }
playlistDTOs := make([]m.PlaylistItemDTO, 0) playlistDTOs := make([]models.PlaylistItemDTO, 0)
for _, item := range playlistitems { for _, item := range playlistitems {
playlistDTOs = append(playlistDTOs, m.PlaylistItemDTO{ playlistDTOs = append(playlistDTOs, models.PlaylistItemDTO{
Id: item.Id, Id: item.Id,
PlaylistId: item.PlaylistId, PlaylistId: item.PlaylistId,
Type: item.Type, Type: item.Type,
@@ -107,8 +106,8 @@ func LoadPlaylistItemDTOs(id int64) ([]m.PlaylistItemDTO, error) {
return playlistDTOs, nil return playlistDTOs, nil
} }
func LoadPlaylistItems(id int64) ([]m.PlaylistItem, error) { func LoadPlaylistItems(id int64) ([]models.PlaylistItem, error) {
itemQuery := m.GetPlaylistItemsByIdQuery{PlaylistId: id} itemQuery := models.GetPlaylistItemsByIdQuery{PlaylistId: id}
if err := bus.Dispatch(&itemQuery); err != nil { if err := bus.Dispatch(&itemQuery); err != nil {
return nil, err return nil, err
} }
@@ -116,7 +115,7 @@ func LoadPlaylistItems(id int64) ([]m.PlaylistItem, error) {
return *itemQuery.Result, nil return *itemQuery.Result, nil
} }
func GetPlaylistItems(c *m.ReqContext) Response { func GetPlaylistItems(c *models.ReqContext) Response {
id := c.ParamsInt64(":id") id := c.ParamsInt64(":id")
playlistDTOs, err := LoadPlaylistItemDTOs(id) playlistDTOs, err := LoadPlaylistItemDTOs(id)
@@ -128,7 +127,7 @@ func GetPlaylistItems(c *m.ReqContext) Response {
return JSON(200, playlistDTOs) return JSON(200, playlistDTOs)
} }
func GetPlaylistDashboards(c *m.ReqContext) Response { func GetPlaylistDashboards(c *models.ReqContext) Response {
playlistID := c.ParamsInt64(":id") playlistID := c.ParamsInt64(":id")
playlists, err := LoadPlaylistDashboards(c.OrgId, c.SignedInUser, playlistID) playlists, err := LoadPlaylistDashboards(c.OrgId, c.SignedInUser, playlistID)
@@ -139,10 +138,10 @@ func GetPlaylistDashboards(c *m.ReqContext) Response {
return JSON(200, playlists) return JSON(200, playlists)
} }
func DeletePlaylist(c *m.ReqContext) Response { func DeletePlaylist(c *models.ReqContext) Response {
id := c.ParamsInt64(":id") 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 { if err := bus.Dispatch(&cmd); err != nil {
return Error(500, "Failed to delete playlist", err) return Error(500, "Failed to delete playlist", err)
} }
@@ -150,7 +149,7 @@ func DeletePlaylist(c *m.ReqContext) Response {
return JSON(200, "") 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 cmd.OrgId = c.OrgId
if err := bus.Dispatch(&cmd); err != nil { 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) 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.OrgId = c.OrgId
cmd.Id = c.ParamsInt64(":id") cmd.Id = c.ParamsInt64(":id")

View File

@@ -7,7 +7,7 @@ import (
"github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/bus"
_ "github.com/grafana/grafana/pkg/infra/log" _ "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" "github.com/grafana/grafana/pkg/services/search"
) )
@@ -15,7 +15,7 @@ func populateDashboardsByID(dashboardByIDs []int64, dashboardIDOrder map[int64]i
result := make(dtos.PlaylistDashboardsSlice, 0) result := make(dtos.PlaylistDashboardsSlice, 0)
if len(dashboardByIDs) > 0 { if len(dashboardByIDs) > 0 {
dashboardQuery := m.GetDashboardsQuery{DashboardIds: dashboardByIDs} dashboardQuery := models.GetDashboardsQuery{DashboardIds: dashboardByIDs}
if err := bus.Dispatch(&dashboardQuery); err != nil { if err := bus.Dispatch(&dashboardQuery); err != nil {
return result, err return result, err
} }
@@ -26,7 +26,7 @@ func populateDashboardsByID(dashboardByIDs []int64, dashboardIDOrder map[int64]i
Slug: item.Slug, Slug: item.Slug,
Title: item.Title, Title: item.Title,
Uri: "db/" + item.Slug, Uri: "db/" + item.Slug,
Url: m.GetDashboardUrl(item.Uid, item.Slug), Url: models.GetDashboardUrl(item.Uid, item.Slug),
Order: dashboardIDOrder[item.Id], Order: dashboardIDOrder[item.Id],
}) })
} }
@@ -35,7 +35,7 @@ func populateDashboardsByID(dashboardByIDs []int64, dashboardIDOrder map[int64]i
return result, nil 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) result := make(dtos.PlaylistDashboardsSlice, 0)
for _, tag := range dashboardByTag { for _, tag := range dashboardByTag {
@@ -65,7 +65,7 @@ func populateDashboardsByTag(orgID int64, signedInUser *m.SignedInUser, dashboar
return result 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) playlistItems, _ := LoadPlaylistItems(playlistID)
dashboardByIDs := make([]int64, 0) dashboardByIDs := make([]int64, 0)

View File

@@ -7,14 +7,14 @@ import (
"net/url" "net/url"
"strings" "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/plugins"
"github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/util"
"golang.org/x/oauth2/google" "golang.org/x/oauth2/google"
) )
//ApplyRoute should use the plugin route data to set auth headers and custom headers //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) proxyPath = strings.TrimPrefix(proxyPath, route.Path)
data := templateData{ data := templateData{

View File

@@ -19,7 +19,7 @@ import (
"github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/bus"
glog "github.com/grafana/grafana/pkg/infra/log" glog "github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/login/social" "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/plugins"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/util"
@@ -32,8 +32,8 @@ var (
) )
type DataSourceProxy struct { type DataSourceProxy struct {
ds *m.DataSource ds *models.DataSource
ctx *m.ReqContext ctx *models.ReqContext
targetUrl *url.URL targetUrl *url.URL
proxyPath string proxyPath string
route *plugins.AppPluginRoute route *plugins.AppPluginRoute
@@ -70,7 +70,7 @@ func (lw *logWrapper) Write(p []byte) (n int, err error) {
} }
// NewDataSourceProxy creates a new Datasource proxy // 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) targetURL, _ := url.Parse(ds.Url)
return &DataSourceProxy{ return &DataSourceProxy{
@@ -154,12 +154,12 @@ func (proxy *DataSourceProxy) getDirector() func(req *http.Request) {
reqQueryVals := req.URL.Query() 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) req.URL.Path = util.JoinURLFragments(proxy.targetUrl.Path, "db/"+proxy.ds.Database+"/"+proxy.proxyPath)
reqQueryVals.Add("u", proxy.ds.User) reqQueryVals.Add("u", proxy.ds.User)
reqQueryVals.Add("p", proxy.ds.DecryptedPassword()) reqQueryVals.Add("p", proxy.ds.DecryptedPassword())
req.URL.RawQuery = reqQueryVals.Encode() 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.Path = util.JoinURLFragments(proxy.targetUrl.Path, proxy.proxyPath)
req.URL.RawQuery = reqQueryVals.Encode() req.URL.RawQuery = reqQueryVals.Encode()
if !proxy.ds.BasicAuth { if !proxy.ds.BasicAuth {
@@ -216,7 +216,7 @@ func (proxy *DataSourceProxy) validateRequest() error {
return errors.New("Target url is not a valid target") 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" { if proxy.ctx.Req.Request.Method == "DELETE" {
return errors.New("Deletes not allowed on proxied Prometheus datasource") 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" { if proxy.ctx.Req.Request.Method == "DELETE" {
return errors.New("Deletes not allowed on proxied Elasticsearch datasource") return errors.New("Deletes not allowed on proxied Elasticsearch datasource")
} }
@@ -288,7 +288,7 @@ func (proxy *DataSourceProxy) logRequest() {
"body", body) "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 host != "" && len(setting.DataProxyWhiteList) > 0 {
if _, exists := setting.DataProxyWhiteList[host]; !exists { if _, exists := setting.DataProxyWhiteList[host]; !exists {
c.JsonApiErr(403, "Data proxy hostname and ip are not included in whitelist", nil) 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 return true
} }
func addOAuthPassThruAuth(c *m.ReqContext, req *http.Request) { func addOAuthPassThruAuth(c *models.ReqContext, req *http.Request) {
authInfoQuery := &m.GetAuthInfoQuery{UserId: c.UserId} authInfoQuery := &models.GetAuthInfoQuery{UserId: c.UserId}
if err := bus.Dispatch(authInfoQuery); err != nil { if err := bus.Dispatch(authInfoQuery); err != nil {
logger.Error("Error feching oauth information for user", "error", err) logger.Error("Error feching oauth information for user", "error", err)
return 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 the tokens are not the same, update the entry in the DB
if token.AccessToken != authInfoQuery.Result.OAuthAccessToken { if token.AccessToken != authInfoQuery.Result.OAuthAccessToken {
updateAuthCommand := &m.UpdateAuthInfoCommand{ updateAuthCommand := &models.UpdateAuthInfoCommand{
UserId: authInfoQuery.Result.UserId, UserId: authInfoQuery.Result.UserId,
AuthModule: authInfoQuery.Result.AuthModule, AuthModule: authInfoQuery.Result.AuthModule,
AuthId: authInfoQuery.Result.AuthId, AuthId: authInfoQuery.Result.AuthId,

View File

@@ -11,6 +11,7 @@ import (
"time" "time"
"github.com/grafana/grafana/pkg/components/securejsondata" "github.com/grafana/grafana/pkg/components/securejsondata"
"github.com/grafana/grafana/pkg/models"
"golang.org/x/oauth2" "golang.org/x/oauth2"
macaron "gopkg.in/macaron.v1" macaron "gopkg.in/macaron.v1"
@@ -18,7 +19,6 @@ import (
"github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/login/social" "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/plugins"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/util"
@@ -34,7 +34,7 @@ func TestDSRouteRule(t *testing.T) {
{ {
Path: "api/v4/", Path: "api/v4/",
Url: "https://www.google.com", Url: "https://www.google.com",
ReqRole: m.ROLE_EDITOR, ReqRole: models.ROLE_EDITOR,
Headers: []plugins.AppPluginRouteHeader{ Headers: []plugins.AppPluginRouteHeader{
{Name: "x-header", Content: "my secret {{.SecureJsonData.key}}"}, {Name: "x-header", Content: "my secret {{.SecureJsonData.key}}"},
}, },
@@ -42,7 +42,7 @@ func TestDSRouteRule(t *testing.T) {
{ {
Path: "api/admin", Path: "api/admin",
Url: "https://www.google.com", Url: "https://www.google.com",
ReqRole: m.ROLE_ADMIN, ReqRole: models.ROLE_ADMIN,
Headers: []plugins.AppPluginRouteHeader{ Headers: []plugins.AppPluginRouteHeader{
{Name: "x-header", Content: "my secret {{.SecureJsonData.key}}"}, {Name: "x-header", Content: "my secret {{.SecureJsonData.key}}"},
}, },
@@ -67,7 +67,7 @@ func TestDSRouteRule(t *testing.T) {
setting.SecretKey = "password" //nolint:goconst setting.SecretKey = "password" //nolint:goconst
key, _ := util.Encrypt([]byte("123"), "password") key, _ := util.Encrypt([]byte("123"), "password")
ds := &m.DataSource{ ds := &models.DataSource{
JsonData: simplejson.NewFromAny(map[string]interface{}{ JsonData: simplejson.NewFromAny(map[string]interface{}{
"clientId": "asd", "clientId": "asd",
"dynamicUrl": "https://dynamic.grafana.com", "dynamicUrl": "https://dynamic.grafana.com",
@@ -78,11 +78,11 @@ func TestDSRouteRule(t *testing.T) {
} }
req, _ := http.NewRequest("GET", "http://localhost/asd", nil) req, _ := http.NewRequest("GET", "http://localhost/asd", nil)
ctx := &m.ReqContext{ ctx := &models.ReqContext{
Context: &macaron.Context{ Context: &macaron.Context{
Req: macaron.Request{Request: req}, 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() { 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() { 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{}) proxy := NewDataSourceProxy(ds, plugin, ctx, "api/admin", &setting.Cfg{})
err := proxy.validateRequest() err := proxy.validateRequest()
So(err, ShouldBeNil) So(err, ShouldBeNil)
@@ -164,7 +164,7 @@ func TestDSRouteRule(t *testing.T) {
setting.SecretKey = "password" setting.SecretKey = "password"
key, _ := util.Encrypt([]byte("123"), "password") key, _ := util.Encrypt([]byte("123"), "password")
ds := &m.DataSource{ ds := &models.DataSource{
JsonData: simplejson.NewFromAny(map[string]interface{}{ JsonData: simplejson.NewFromAny(map[string]interface{}{
"clientId": "asd", "clientId": "asd",
"tenantId": "mytenantId", "tenantId": "mytenantId",
@@ -175,11 +175,11 @@ func TestDSRouteRule(t *testing.T) {
} }
req, _ := http.NewRequest("GET", "http://localhost/asd", nil) req, _ := http.NewRequest("GET", "http://localhost/asd", nil)
ctx := &m.ReqContext{ ctx := &models.ReqContext{
Context: &macaron.Context{ Context: &macaron.Context{
Req: macaron.Request{Request: req}, 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() { Convey("When creating and caching access tokens", func() {
@@ -238,8 +238,8 @@ func TestDSRouteRule(t *testing.T) {
Convey("When proxying graphite", func() { Convey("When proxying graphite", func() {
setting.BuildVersion = "5.3.0" setting.BuildVersion = "5.3.0"
plugin := &plugins.DataSourcePlugin{} plugin := &plugins.DataSourcePlugin{}
ds := &m.DataSource{Url: "htttp://graphite:8080", Type: m.DS_GRAPHITE} ds := &models.DataSource{Url: "htttp://graphite:8080", Type: models.DS_GRAPHITE}
ctx := &m.ReqContext{} ctx := &models.ReqContext{}
proxy := NewDataSourceProxy(ds, plugin, ctx, "/render", &setting.Cfg{}) proxy := NewDataSourceProxy(ds, plugin, ctx, "/render", &setting.Cfg{})
req, err := http.NewRequest(http.MethodGet, "http://grafana.com/sub", nil) 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() { Convey("When proxying InfluxDB", func() {
plugin := &plugins.DataSourcePlugin{} plugin := &plugins.DataSourcePlugin{}
ds := &m.DataSource{ ds := &models.DataSource{
Type: m.DS_INFLUXDB_08, Type: models.DS_INFLUXDB_08,
Url: "http://influxdb:8083", Url: "http://influxdb:8083",
Database: "site", Database: "site",
User: "user", User: "user",
Password: "password", Password: "password",
} }
ctx := &m.ReqContext{} ctx := &models.ReqContext{}
proxy := NewDataSourceProxy(ds, plugin, ctx, "", &setting.Cfg{}) proxy := NewDataSourceProxy(ds, plugin, ctx, "", &setting.Cfg{})
req, err := http.NewRequest(http.MethodGet, "http://grafana.com/sub", nil) 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": []}`)) json, _ := simplejson.NewJson([]byte(`{"keepCookies": []}`))
ds := &m.DataSource{ ds := &models.DataSource{
Type: m.DS_GRAPHITE, Type: models.DS_GRAPHITE,
Url: "http://graphite:8086", Url: "http://graphite:8086",
JsonData: json, JsonData: json,
} }
ctx := &m.ReqContext{} ctx := &models.ReqContext{}
proxy := NewDataSourceProxy(ds, plugin, ctx, "", &setting.Cfg{}) proxy := NewDataSourceProxy(ds, plugin, ctx, "", &setting.Cfg{})
requestURL, _ := url.Parse("http://grafana.com/sub") requestURL, _ := url.Parse("http://grafana.com/sub")
@@ -309,13 +309,13 @@ func TestDSRouteRule(t *testing.T) {
json, _ := simplejson.NewJson([]byte(`{"keepCookies": ["JSESSION_ID"]}`)) json, _ := simplejson.NewJson([]byte(`{"keepCookies": ["JSESSION_ID"]}`))
ds := &m.DataSource{ ds := &models.DataSource{
Type: m.DS_GRAPHITE, Type: models.DS_GRAPHITE,
Url: "http://graphite:8086", Url: "http://graphite:8086",
JsonData: json, JsonData: json,
} }
ctx := &m.ReqContext{} ctx := &models.ReqContext{}
proxy := NewDataSourceProxy(ds, plugin, ctx, "", &setting.Cfg{}) proxy := NewDataSourceProxy(ds, plugin, ctx, "", &setting.Cfg{})
requestURL, _ := url.Parse("http://grafana.com/sub") requestURL, _ := url.Parse("http://grafana.com/sub")
@@ -332,11 +332,11 @@ func TestDSRouteRule(t *testing.T) {
Convey("When proxying a custom datasource", func() { Convey("When proxying a custom datasource", func() {
plugin := &plugins.DataSourcePlugin{} plugin := &plugins.DataSourcePlugin{}
ds := &m.DataSource{ ds := &models.DataSource{
Type: "custom-datasource", Type: "custom-datasource",
Url: "http://host/root/", Url: "http://host/root/",
} }
ctx := &m.ReqContext{} ctx := &models.ReqContext{}
proxy := NewDataSourceProxy(ds, plugin, ctx, "/path/to/folder/", &setting.Cfg{}) proxy := NewDataSourceProxy(ds, plugin, ctx, "/path/to/folder/", &setting.Cfg{})
req, err := http.NewRequest(http.MethodGet, "http://grafana.com/sub", nil) req, err := http.NewRequest(http.MethodGet, "http://grafana.com/sub", nil)
req.Header.Add("Origin", "grafana.com") req.Header.Add("Origin", "grafana.com")
@@ -364,8 +364,8 @@ func TestDSRouteRule(t *testing.T) {
}, },
} }
bus.AddHandler("test", func(query *m.GetAuthInfoQuery) error { bus.AddHandler("test", func(query *models.GetAuthInfoQuery) error {
query.Result = &m.UserAuth{ query.Result = &models.UserAuth{
Id: 1, Id: 1,
UserId: 1, UserId: 1,
AuthModule: "generic_oauth", AuthModule: "generic_oauth",
@@ -378,7 +378,7 @@ func TestDSRouteRule(t *testing.T) {
}) })
plugin := &plugins.DataSourcePlugin{} plugin := &plugins.DataSourcePlugin{}
ds := &m.DataSource{ ds := &models.DataSource{
Type: "custom-datasource", Type: "custom-datasource",
Url: "http://host/root/", Url: "http://host/root/",
JsonData: simplejson.NewFromAny(map[string]interface{}{ JsonData: simplejson.NewFromAny(map[string]interface{}{
@@ -387,8 +387,8 @@ func TestDSRouteRule(t *testing.T) {
} }
req, _ := http.NewRequest("GET", "http://localhost/asd", nil) req, _ := http.NewRequest("GET", "http://localhost/asd", nil)
ctx := &m.ReqContext{ ctx := &models.ReqContext{
SignedInUser: &m.SignedInUser{UserId: 1}, SignedInUser: &models.SignedInUser{UserId: 1},
Context: &macaron.Context{ Context: &macaron.Context{
Req: macaron.Request{Request: req}, Req: macaron.Request{Request: req},
}, },
@@ -407,8 +407,8 @@ func TestDSRouteRule(t *testing.T) {
Convey("When SendUserHeader config is enabled", func() { Convey("When SendUserHeader config is enabled", func() {
req := getDatasourceProxiedRequest( req := getDatasourceProxiedRequest(
&m.ReqContext{ &models.ReqContext{
SignedInUser: &m.SignedInUser{ SignedInUser: &models.SignedInUser{
Login: "test_user", Login: "test_user",
}, },
}, },
@@ -421,8 +421,8 @@ func TestDSRouteRule(t *testing.T) {
Convey("When SendUserHeader config is disabled", func() { Convey("When SendUserHeader config is disabled", func() {
req := getDatasourceProxiedRequest( req := getDatasourceProxiedRequest(
&m.ReqContext{ &models.ReqContext{
SignedInUser: &m.SignedInUser{ SignedInUser: &models.SignedInUser{
Login: "test_user", Login: "test_user",
}, },
}, },
@@ -436,8 +436,8 @@ func TestDSRouteRule(t *testing.T) {
Convey("When SendUserHeader config is enabled but user is anonymous", func() { Convey("When SendUserHeader config is enabled but user is anonymous", func() {
req := getDatasourceProxiedRequest( req := getDatasourceProxiedRequest(
&m.ReqContext{ &models.ReqContext{
SignedInUser: &m.SignedInUser{IsAnonymous: true}, SignedInUser: &models.SignedInUser{IsAnonymous: true},
}, },
&setting.Cfg{SendUserHeader: true}, &setting.Cfg{SendUserHeader: true},
) )
@@ -449,21 +449,21 @@ func TestDSRouteRule(t *testing.T) {
Convey("When proxying data source proxy should handle authentication", func() { Convey("When proxying data source proxy should handle authentication", func() {
tests := []*Test{ tests := []*Test{
createAuthTest(m.DS_INFLUXDB_08, AUTHTYPE_PASSWORD, AUTHCHECK_QUERY, false), createAuthTest(models.DS_INFLUXDB_08, AUTHTYPE_PASSWORD, AUTHCHECK_QUERY, false),
createAuthTest(m.DS_INFLUXDB_08, AUTHTYPE_PASSWORD, AUTHCHECK_QUERY, true), createAuthTest(models.DS_INFLUXDB_08, AUTHTYPE_PASSWORD, AUTHCHECK_QUERY, true),
createAuthTest(m.DS_INFLUXDB, AUTHTYPE_PASSWORD, AUTHCHECK_HEADER, true), createAuthTest(models.DS_INFLUXDB, AUTHTYPE_PASSWORD, AUTHCHECK_HEADER, true),
createAuthTest(m.DS_INFLUXDB, AUTHTYPE_PASSWORD, AUTHCHECK_HEADER, false), createAuthTest(models.DS_INFLUXDB, AUTHTYPE_PASSWORD, AUTHCHECK_HEADER, false),
createAuthTest(m.DS_INFLUXDB, AUTHTYPE_BASIC, AUTHCHECK_HEADER, true), createAuthTest(models.DS_INFLUXDB, AUTHTYPE_BASIC, AUTHCHECK_HEADER, true),
createAuthTest(m.DS_INFLUXDB, AUTHTYPE_BASIC, AUTHCHECK_HEADER, false), 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 // 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 // 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. // do not go through proxy but through TSDB API which is not tested here.
createAuthTest(m.DS_ES, AUTHTYPE_BASIC, AUTHCHECK_HEADER, false), createAuthTest(models.DS_ES, AUTHTYPE_BASIC, AUTHCHECK_HEADER, false),
createAuthTest(m.DS_ES, AUTHTYPE_BASIC, AUTHCHECK_HEADER, true), createAuthTest(models.DS_ES, AUTHTYPE_BASIC, AUTHCHECK_HEADER, true),
} }
for _, test := range tests { for _, test := range tests {
m.ClearDSDecryptionCache() models.ClearDSDecryptionCache()
runDatasourceAuthTest(test) runDatasourceAuthTest(test)
} }
}) })
@@ -478,21 +478,21 @@ func TestDSRouteRule(t *testing.T) {
defer backend.Close() defer backend.Close()
plugin := &plugins.DataSourcePlugin{} 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 := &CloseNotifierResponseRecorder{
ResponseRecorder: httptest.NewRecorder(), ResponseRecorder: httptest.NewRecorder(),
} }
defer responseRecorder.Close() defer responseRecorder.Close()
setupCtx := func(fn func(http.ResponseWriter)) *m.ReqContext { setupCtx := func(fn func(http.ResponseWriter)) *models.ReqContext {
responseWriter := macaron.NewResponseWriter("GET", responseRecorder) responseWriter := macaron.NewResponseWriter("GET", responseRecorder)
if fn != nil { if fn != nil {
fn(responseWriter) fn(responseWriter)
} }
return &m.ReqContext{ return &models.ReqContext{
SignedInUser: &m.SignedInUser{}, SignedInUser: &models.SignedInUser{},
Context: &macaron.Context{ Context: &macaron.Context{
Req: macaron.Request{ Req: macaron.Request{
Request: httptest.NewRequest("GET", "/render", nil), 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. // 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{} plugin := &plugins.DataSourcePlugin{}
ds := &m.DataSource{ ds := &models.DataSource{
Type: "custom", Type: "custom",
Url: "http://host/root/", Url: "http://host/root/",
} }
@@ -586,7 +586,7 @@ func newFakeHTTPClient(fakeBody []byte) httpClient {
} }
type Test struct { type Test struct {
datasource *m.DataSource datasource *models.DataSource
checkReq func(req *http.Request) checkReq func(req *http.Request)
} }
@@ -605,7 +605,7 @@ func createAuthTest(dsType string, authType string, authCheck string, useSecureJ
base64AthHeader := "Basic dXNlcjpwYXNzd29yZA==" base64AthHeader := "Basic dXNlcjpwYXNzd29yZA=="
test := &Test{ test := &Test{
datasource: &m.DataSource{ datasource: &models.DataSource{
Type: dsType, Type: dsType,
JsonData: simplejson.New(), JsonData: simplejson.New(),
}, },
@@ -661,7 +661,7 @@ func createAuthTest(dsType string, authType string, authCheck string, useSecureJ
func runDatasourceAuthTest(test *Test) { func runDatasourceAuthTest(test *Test) {
plugin := &plugins.DataSourcePlugin{} plugin := &plugins.DataSourcePlugin{}
ctx := &m.ReqContext{} ctx := &models.ReqContext{}
proxy := NewDataSourceProxy(test.datasource, plugin, ctx, "", &setting.Cfg{}) proxy := NewDataSourceProxy(test.datasource, plugin, ctx, "", &setting.Cfg{})
req, err := http.NewRequest(http.MethodGet, "http://grafana.com/sub", nil) req, err := http.NewRequest(http.MethodGet, "http://grafana.com/sub", nil)

View File

@@ -8,7 +8,7 @@ import (
"github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/infra/log" "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/plugins"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util" "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) { func getHeaders(route *plugins.AppPluginRoute, orgId int64, appID string) (http.Header, error) {
result := http.Header{} result := http.Header{}
query := m.GetPluginSettingByIdQuery{OrgId: orgId, PluginId: appID} query := models.GetPluginSettingByIdQuery{OrgId: orgId, PluginId: appID}
if err := bus.Dispatch(&query); err != nil { if err := bus.Dispatch(&query); err != nil {
return nil, err 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) { 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 { if err := bus.Dispatch(&query); err != nil {
return "", err return "", err
} }
@@ -56,7 +56,7 @@ func updateURL(route *plugins.AppPluginRoute, orgId int64, appID string) (string
} }
// NewApiPluginProxy create a plugin proxy // 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) targetURL, _ := url.Parse(route.Url)
director := func(req *http.Request) { director := func(req *http.Request) {

View File

@@ -5,7 +5,7 @@ import (
"testing" "testing"
"github.com/grafana/grafana/pkg/bus" "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"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/util"
@@ -23,13 +23,13 @@ func TestPluginProxy(t *testing.T) {
setting.SecretKey = "password" 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") key, err := util.Encrypt([]byte("123"), "password")
if err != nil { if err != nil {
return err return err
} }
query.Result = &m.PluginSetting{ query.Result = &models.PluginSetting{
SecureJsonData: map[string][]byte{ SecureJsonData: map[string][]byte{
"key": key, "key": key,
}, },
@@ -47,8 +47,8 @@ func TestPluginProxy(t *testing.T) {
Convey("When SendUserHeader config is enabled", t, func() { Convey("When SendUserHeader config is enabled", t, func() {
req := getPluginProxiedRequest( req := getPluginProxiedRequest(
&m.ReqContext{ &models.ReqContext{
SignedInUser: &m.SignedInUser{ SignedInUser: &models.SignedInUser{
Login: "test_user", Login: "test_user",
}, },
}, },
@@ -64,8 +64,8 @@ func TestPluginProxy(t *testing.T) {
Convey("When SendUserHeader config is disabled", t, func() { Convey("When SendUserHeader config is disabled", t, func() {
req := getPluginProxiedRequest( req := getPluginProxiedRequest(
&m.ReqContext{ &models.ReqContext{
SignedInUser: &m.SignedInUser{ SignedInUser: &models.SignedInUser{
Login: "test_user", Login: "test_user",
}, },
}, },
@@ -80,8 +80,8 @@ func TestPluginProxy(t *testing.T) {
Convey("When SendUserHeader config is enabled but user is anonymous", t, func() { Convey("When SendUserHeader config is enabled but user is anonymous", t, func() {
req := getPluginProxiedRequest( req := getPluginProxiedRequest(
&m.ReqContext{ &models.ReqContext{
SignedInUser: &m.SignedInUser{IsAnonymous: true}, SignedInUser: &models.SignedInUser{IsAnonymous: true},
}, },
&setting.Cfg{SendUserHeader: true}, &setting.Cfg{SendUserHeader: true},
nil, nil,
@@ -99,8 +99,8 @@ func TestPluginProxy(t *testing.T) {
Method: "GET", Method: "GET",
} }
bus.AddHandler("test", func(query *m.GetPluginSettingByIdQuery) error { bus.AddHandler("test", func(query *models.GetPluginSettingByIdQuery) error {
query.Result = &m.PluginSetting{ query.Result = &models.PluginSetting{
JsonData: map[string]interface{}{ JsonData: map[string]interface{}{
"dynamicUrl": "https://dynamic.grafana.com", "dynamicUrl": "https://dynamic.grafana.com",
}, },
@@ -109,8 +109,8 @@ func TestPluginProxy(t *testing.T) {
}) })
req := getPluginProxiedRequest( req := getPluginProxiedRequest(
&m.ReqContext{ &models.ReqContext{
SignedInUser: &m.SignedInUser{ SignedInUser: &models.SignedInUser{
Login: "test_user", 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. // 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 // insert dummy route if none is specified
if route == nil { if route == nil {
route = &plugins.AppPluginRoute{ route = &plugins.AppPluginRoute{
Path: "api/v4/", Path: "api/v4/",
Url: "https://www.google.com", Url: "https://www.google.com",
ReqRole: m.ROLE_EDITOR, ReqRole: models.ROLE_EDITOR,
} }
} }
proxy := NewApiPluginProxy(ctx, "", route, "", cfg) proxy := NewApiPluginProxy(ctx, "", route, "", cfg)

View File

@@ -6,7 +6,7 @@ import (
"net/url" "net/url"
"text/template" "text/template"
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"
) )
@@ -28,7 +28,7 @@ func InterpolateString(text string, data templateData) (string, error) {
// InterpolateURL accepts template data and return a string with substitutions // 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) { 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()) result, err := url.Parse(anURL.String())
if query.Result != nil { if query.Result != nil {
if len(query.Result.JsonData) > 0 { if len(query.Result.JsonData) > 0 {

View File

@@ -3,11 +3,11 @@ package api
import ( import (
"github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/bus" "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 // 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.UserId = c.UserId
cmd.OrgId = c.OrgId cmd.OrgId = c.OrgId
@@ -20,12 +20,12 @@ func SetHomeDashboard(c *m.ReqContext, cmd m.SavePreferencesCommand) Response {
} }
// GET /api/user/preferences // GET /api/user/preferences
func GetUserPreferences(c *m.ReqContext) Response { func GetUserPreferences(c *models.ReqContext) Response {
return getPreferencesFor(c.OrgId, c.UserId, 0) return getPreferencesFor(c.OrgId, c.UserId, 0)
} }
func getPreferencesFor(orgID, userID, teamID int64) Response { 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 { if err := bus.Dispatch(&prefsQuery); err != nil {
return Error(500, "Failed to get preferences", err) return Error(500, "Failed to get preferences", err)
@@ -41,12 +41,12 @@ func getPreferencesFor(orgID, userID, teamID int64) Response {
} }
// PUT /api/user/preferences // 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) return updatePreferencesFor(c.OrgId, c.UserId, 0, &dtoCmd)
} }
func updatePreferencesFor(orgID, userID, teamId int64, dtoCmd *dtos.UpdatePrefsCmd) Response { func updatePreferencesFor(orgID, userID, teamId int64, dtoCmd *dtos.UpdatePrefsCmd) Response {
saveCmd := m.SavePreferencesCommand{ saveCmd := models.SavePreferencesCommand{
UserId: userID, UserId: userID,
OrgId: orgID, OrgId: orgID,
TeamId: teamId, TeamId: teamId,
@@ -63,11 +63,11 @@ func updatePreferencesFor(orgID, userID, teamId int64, dtoCmd *dtos.UpdatePrefsC
} }
// GET /api/org/preferences // GET /api/org/preferences
func GetOrgPreferences(c *m.ReqContext) Response { func GetOrgPreferences(c *models.ReqContext) Response {
return getPreferencesFor(c.OrgId, 0, 0) return getPreferencesFor(c.OrgId, 0, 0)
} }
// PUT /api/org/preferences // 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) return updatePreferencesFor(c.OrgId, 0, 0, &dtoCmd)
} }

View File

@@ -2,15 +2,15 @@ package api
import ( import (
"github.com/grafana/grafana/pkg/bus" "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/setting"
) )
func GetOrgQuotas(c *m.ReqContext) Response { func GetOrgQuotas(c *models.ReqContext) Response {
if !setting.Quota.Enabled { if !setting.Quota.Enabled {
return Error(404, "Quotas not enabled", nil) 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 { if err := bus.Dispatch(&query); err != nil {
return Error(500, "Failed to get org quotas", err) return Error(500, "Failed to get org quotas", err)
@@ -19,7 +19,7 @@ func GetOrgQuotas(c *m.ReqContext) Response {
return JSON(200, query.Result) 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 { if !setting.Quota.Enabled {
return Error(404, "Quotas not enabled", nil) 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") return Success("Organization quota updated")
} }
func GetUserQuotas(c *m.ReqContext) Response { func GetUserQuotas(c *models.ReqContext) Response {
if !setting.Quota.Enabled { if !setting.Quota.Enabled {
return Error(404, "Quotas not enabled", nil) 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 { if err := bus.Dispatch(&query); err != nil {
return Error(500, "Failed to get org quotas", err) return Error(500, "Failed to get org quotas", err)
@@ -49,7 +49,7 @@ func GetUserQuotas(c *m.ReqContext) Response {
return JSON(200, query.Result) 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 { if !setting.Quota.Enabled {
return Error(404, "Quotas not enabled", nil) return Error(404, "Quotas not enabled", nil)
} }

View File

@@ -8,12 +8,12 @@ import (
"strings" "strings"
"time" "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/services/rendering"
"github.com/grafana/grafana/pkg/util" "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) queryReader, err := util.NewURLQueryReader(c.Req.URL)
if err != nil { if err != nil {
c.Handle(400, "Render parameters error", err) c.Handle(400, "Render parameters error", err)

View File

@@ -5,25 +5,25 @@ import (
"github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/infra/metrics" "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" "github.com/grafana/grafana/pkg/services/search"
) )
func Search(c *m.ReqContext) Response { func Search(c *models.ReqContext) Response {
query := c.Query("query") query := c.Query("query")
tags := c.QueryStrings("tag") tags := c.QueryStrings("tag")
starred := c.Query("starred") starred := c.Query("starred")
limit := c.QueryInt64("limit") limit := c.QueryInt64("limit")
page := c.QueryInt64("page") page := c.QueryInt64("page")
dashboardType := c.Query("type") dashboardType := c.Query("type")
permission := m.PERMISSION_VIEW permission := models.PERMISSION_VIEW
if limit > 5000 { if limit > 5000 {
return Error(422, "Limit is above maximum allowed (5000), use page parameter to access hits beyond limit", nil) return Error(422, "Limit is above maximum allowed (5000), use page parameter to access hits beyond limit", nil)
} }
if c.Query("permission") == "Edit" { if c.Query("permission") == "Edit" {
permission = m.PERMISSION_EDIT permission = models.PERMISSION_EDIT
} }
dbIDs := make([]int64, 0) dbIDs := make([]int64, 0)

View File

@@ -5,13 +5,13 @@ import (
"github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/events" "github.com/grafana/grafana/pkg/events"
"github.com/grafana/grafana/pkg/infra/metrics" "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/setting"
"github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/util"
) )
// GET /api/user/signup/options // GET /api/user/signup/options
func GetSignUpOptions(c *m.ReqContext) Response { func GetSignUpOptions(c *models.ReqContext) Response {
return JSON(200, util.DynMap{ return JSON(200, util.DynMap{
"verifyEmailEnabled": setting.VerifyEmailEnabled, "verifyEmailEnabled": setting.VerifyEmailEnabled,
"autoAssignOrg": setting.AutoAssignOrg, "autoAssignOrg": setting.AutoAssignOrg,
@@ -19,20 +19,20 @@ func GetSignUpOptions(c *m.ReqContext) Response {
} }
// POST /api/user/signup // 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 { if !setting.AllowUserSignUp {
return Error(401, "User signup is disabled", nil) 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 { if err := bus.Dispatch(&existing); err == nil {
return Error(422, "User with same email address already exists", nil) return Error(422, "User with same email address already exists", nil)
} }
cmd := m.CreateTempUserCommand{} cmd := models.CreateTempUserCommand{}
cmd.OrgId = -1 cmd.OrgId = -1
cmd.Email = form.Email cmd.Email = form.Email
cmd.Status = m.TmpUserSignUpStarted cmd.Status = models.TmpUserSignUpStarted
cmd.InvitedByUserId = c.UserId cmd.InvitedByUserId = c.UserId
var err error var err error
cmd.Code, err = util.GetRandomString(20) 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"}) 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 { if !setting.AllowUserSignUp {
return Error(401, "User signup is disabled", nil) return Error(401, "User signup is disabled", nil)
} }
createUserCmd := m.CreateUserCommand{ createUserCmd := models.CreateUserCommand{
Email: form.Email, Email: form.Email,
Login: form.Username, Login: form.Username,
Name: form.Name, Name: form.Name,
@@ -79,7 +79,7 @@ func (hs *HTTPServer) SignUpStep2(c *m.ReqContext, form dtos.SignUpStep2Form) Re
} }
// check if user exists // check if user exists
existing := m.GetUserByLoginQuery{LoginOrEmail: form.Email} existing := models.GetUserByLoginQuery{LoginOrEmail: form.Email}
if err := bus.Dispatch(&existing); err == nil { if err := bus.Dispatch(&existing); err == nil {
return Error(401, "User with same email address already exists", 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 // 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 return rsp
} }
// check for pending invites // 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 { if err := bus.Dispatch(&invitesQuery); err != nil {
return Error(500, "Failed to query database for invites", err) 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) { 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 := 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(404, "Invalid email verification code", nil)
} }
return false, Error(500, "Failed to read temp user", err) return false, Error(500, "Failed to read temp user", err)

View File

@@ -2,15 +2,15 @@ package api
import ( import (
"github.com/grafana/grafana/pkg/bus" "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 { if !c.IsSignedIn {
return Error(412, "You need to sign in to star dashboards", nil) 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 { if cmd.DashboardId <= 0 {
return Error(400, "Missing dashboard id", nil) return Error(400, "Missing dashboard id", nil)
@@ -23,9 +23,9 @@ func StarDashboard(c *m.ReqContext) Response {
return Success("Dashboard starred!") 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 { if cmd.DashboardId <= 0 {
return Error(400, "Missing dashboard id", nil) return Error(400, "Missing dashboard id", nil)

View File

@@ -3,36 +3,36 @@ package api
import ( import (
"github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/bus" "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/services/teamguardian"
"github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/util"
) )
// POST /api/teams // 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 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) return Error(403, "Not allowed to create team.", nil)
} }
if err := hs.Bus.Dispatch(&cmd); err != 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(409, "Team name taken", err)
} }
return Error(500, "Failed to create Team", 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 // if the request is authenticated using API tokens
// the SignedInUser is an empty struct therefore // the SignedInUser is an empty struct therefore
// an additional check whether it is an actual user is required // an additional check whether it is an actual user is required
if c.SignedInUser.IsRealUser() { if c.SignedInUser.IsRealUser() {
addMemberCmd := m.AddTeamMemberCommand{ addMemberCmd := models.AddTeamMemberCommand{
UserId: c.SignedInUser.UserId, UserId: c.SignedInUser.UserId,
OrgId: cmd.OrgId, OrgId: cmd.OrgId,
TeamId: cmd.Result.Id, TeamId: cmd.Result.Id,
Permission: m.PERMISSION_ADMIN, Permission: models.PERMISSION_ADMIN,
} }
if err := hs.Bus.Dispatch(&addMemberCmd); err != nil { 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 // 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.OrgId = c.OrgId
cmd.Id = c.ParamsInt64(":teamId") 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 := hs.Bus.Dispatch(&cmd); err != nil {
if err == m.ErrTeamNameTaken { if err == models.ErrTeamNameTaken {
return Error(400, "Team name taken", err) return Error(400, "Team name taken", err)
} }
return Error(500, "Failed to update Team", 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 // DELETE /api/teams/:teamId
func (hs *HTTPServer) DeleteTeamByID(c *m.ReqContext) Response { func (hs *HTTPServer) DeleteTeamByID(c *models.ReqContext) Response {
orgId := c.OrgId orgId := c.OrgId
teamId := c.ParamsInt64(":teamId") teamId := c.ParamsInt64(":teamId")
user := c.SignedInUser user := c.SignedInUser
@@ -78,8 +78,8 @@ func (hs *HTTPServer) DeleteTeamByID(c *m.ReqContext) Response {
return Error(403, "Not allowed to delete team", err) return Error(403, "Not allowed to delete team", err)
} }
if err := hs.Bus.Dispatch(&m.DeleteTeamCommand{OrgId: orgId, Id: teamId}); err != nil { if err := hs.Bus.Dispatch(&models.DeleteTeamCommand{OrgId: orgId, Id: teamId}); err != nil {
if err == m.ErrTeamNotFound { if err == models.ErrTeamNotFound {
return Error(404, "Failed to delete Team. ID not found", nil) return Error(404, "Failed to delete Team. ID not found", nil)
} }
return Error(500, "Failed to delete Team", err) return Error(500, "Failed to delete Team", err)
@@ -88,7 +88,7 @@ func (hs *HTTPServer) DeleteTeamByID(c *m.ReqContext) Response {
} }
// GET /api/teams/search // GET /api/teams/search
func (hs *HTTPServer) SearchTeams(c *m.ReqContext) Response { func (hs *HTTPServer) SearchTeams(c *models.ReqContext) Response {
perPage := c.QueryInt("perpage") perPage := c.QueryInt("perpage")
if perPage <= 0 { if perPage <= 0 {
perPage = 1000 perPage = 1000
@@ -99,11 +99,11 @@ func (hs *HTTPServer) SearchTeams(c *m.ReqContext) Response {
} }
var userIdFilter int64 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 userIdFilter = c.SignedInUser.UserId
} }
query := m.SearchTeamsQuery{ query := models.SearchTeamsQuery{
OrgId: c.OrgId, OrgId: c.OrgId,
Query: c.Query("query"), Query: c.Query("query"),
Name: c.Query("name"), Name: c.Query("name"),
@@ -127,11 +127,11 @@ func (hs *HTTPServer) SearchTeams(c *m.ReqContext) Response {
} }
// GET /api/teams/:teamId // GET /api/teams/:teamId
func GetTeamByID(c *m.ReqContext) Response { func GetTeamByID(c *models.ReqContext) Response {
query := m.GetTeamByIdQuery{OrgId: c.OrgId, Id: c.ParamsInt64(":teamId")} query := models.GetTeamByIdQuery{OrgId: c.OrgId, Id: c.ParamsInt64(":teamId")}
if err := bus.Dispatch(&query); err != nil { if err := bus.Dispatch(&query); err != nil {
if err == m.ErrTeamNotFound { if err == models.ErrTeamNotFound {
return Error(404, "Team not found", err) return Error(404, "Team not found", err)
} }
@@ -143,7 +143,7 @@ func GetTeamByID(c *m.ReqContext) Response {
} }
// GET /api/teams/:teamId/preferences // 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") teamId := c.ParamsInt64(":teamId")
orgId := c.OrgId orgId := c.OrgId
@@ -155,7 +155,7 @@ func (hs *HTTPServer) GetTeamPreferences(c *m.ReqContext) Response {
} }
// PUT /api/teams/:teamId/preferences // 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") teamId := c.ParamsInt64(":teamId")
orgId := c.OrgId orgId := c.OrgId

View File

@@ -3,14 +3,14 @@ package api
import ( import (
"github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/bus" "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/services/teamguardian"
"github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/util"
) )
// GET /api/teams/:teamId/members // GET /api/teams/:teamId/members
func (hs *HTTPServer) GetTeamMembers(c *m.ReqContext) Response { func (hs *HTTPServer) GetTeamMembers(c *models.ReqContext) Response {
query := m.GetTeamMembersQuery{OrgId: c.OrgId, TeamId: c.ParamsInt64(":teamId")} query := models.GetTeamMembersQuery{OrgId: c.OrgId, TeamId: c.ParamsInt64(":teamId")}
if err := bus.Dispatch(&query); err != nil { if err := bus.Dispatch(&query); err != nil {
return Error(500, "Failed to get Team Members", err) 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 // 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.OrgId = c.OrgId
cmd.TeamId = c.ParamsInt64(":teamId") 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 := hs.Bus.Dispatch(&cmd); err != nil {
if err == m.ErrTeamNotFound { if err == models.ErrTeamNotFound {
return Error(404, "Team not found", nil) 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) 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 // 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") teamId := c.ParamsInt64(":teamId")
orgId := c.OrgId 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) 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 cmd.ProtectLastAdmin = true
} }
@@ -73,7 +73,7 @@ func (hs *HTTPServer) UpdateTeamMember(c *m.ReqContext, cmd m.UpdateTeamMemberCo
cmd.OrgId = orgId cmd.OrgId = orgId
if err := hs.Bus.Dispatch(&cmd); err != nil { 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(404, "Team member not found.", nil)
} }
return Error(500, "Failed to update team member.", err) 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 // 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 orgId := c.OrgId
teamId := c.ParamsInt64(":teamId") teamId := c.ParamsInt64(":teamId")
userId := c.ParamsInt64(":userId") userId := c.ParamsInt64(":userId")
@@ -92,16 +92,16 @@ func (hs *HTTPServer) RemoveTeamMember(c *m.ReqContext) Response {
} }
protectLastAdmin := false protectLastAdmin := false
if c.OrgRole != m.ROLE_ADMIN { if c.OrgRole != models.ROLE_ADMIN {
protectLastAdmin = true protectLastAdmin = true
} }
if err := hs.Bus.Dispatch(&m.RemoveTeamMemberCommand{OrgId: orgId, TeamId: teamId, UserId: userId, ProtectLastAdmin: protectLastAdmin}); err != nil { if err := hs.Bus.Dispatch(&models.RemoveTeamMemberCommand{OrgId: orgId, TeamId: teamId, UserId: userId, ProtectLastAdmin: protectLastAdmin}); err != nil {
if err == m.ErrTeamNotFound { if err == models.ErrTeamNotFound {
return Error(404, "Team not found", nil) return Error(404, "Team not found", nil)
} }
if err == m.ErrTeamMemberNotFound { if err == models.ErrTeamMemberNotFound {
return Error(404, "Team member not found", nil) return Error(404, "Team member not found", nil)
} }

View File

@@ -3,32 +3,32 @@ package api
import ( import (
"github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/bus" "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/setting"
"github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/util"
) )
// GET /api/user (current authenticated user) // GET /api/user (current authenticated user)
func GetSignedInUser(c *m.ReqContext) Response { func GetSignedInUser(c *models.ReqContext) Response {
return getUserUserProfile(c.UserId) return getUserUserProfile(c.UserId)
} }
// GET /api/users/:id // GET /api/users/:id
func GetUserByID(c *m.ReqContext) Response { func GetUserByID(c *models.ReqContext) Response {
return getUserUserProfile(c.ParamsInt64(":id")) return getUserUserProfile(c.ParamsInt64(":id"))
} }
func getUserUserProfile(userID int64) Response { func getUserUserProfile(userID int64) Response {
query := m.GetUserProfileQuery{UserId: userID} query := models.GetUserProfileQuery{UserId: userID}
if err := bus.Dispatch(&query); err != nil { if err := bus.Dispatch(&query); err != nil {
if err == m.ErrUserNotFound { if err == models.ErrUserNotFound {
return Error(404, m.ErrUserNotFound.Error(), nil) return Error(404, models.ErrUserNotFound.Error(), nil)
} }
return Error(500, "Failed to get user", err) return Error(500, "Failed to get user", err)
} }
getAuthQuery := m.GetAuthInfoQuery{UserId: userID} getAuthQuery := models.GetAuthInfoQuery{UserId: userID}
query.Result.AuthLabels = []string{} query.Result.AuthLabels = []string{}
if err := bus.Dispatch(&getAuthQuery); err == nil { if err := bus.Dispatch(&getAuthQuery); err == nil {
authLabel := GetAuthProviderLabel(getAuthQuery.Result.AuthModule) authLabel := GetAuthProviderLabel(getAuthQuery.Result.AuthModule)
@@ -42,16 +42,16 @@ func getUserUserProfile(userID int64) Response {
} }
// GET /api/users/lookup // GET /api/users/lookup
func GetUserByLoginOrEmail(c *m.ReqContext) Response { func GetUserByLoginOrEmail(c *models.ReqContext) Response {
query := m.GetUserByLoginQuery{LoginOrEmail: c.Query("loginOrEmail")} query := models.GetUserByLoginQuery{LoginOrEmail: c.Query("loginOrEmail")}
if err := bus.Dispatch(&query); err != nil { if err := bus.Dispatch(&query); err != nil {
if err == m.ErrUserNotFound { if err == models.ErrUserNotFound {
return Error(404, m.ErrUserNotFound.Error(), nil) return Error(404, models.ErrUserNotFound.Error(), nil)
} }
return Error(500, "Failed to get user", err) return Error(500, "Failed to get user", err)
} }
user := query.Result user := query.Result
result := m.UserProfileDTO{ result := models.UserProfileDTO{
Id: user.Id, Id: user.Id,
Name: user.Name, Name: user.Name,
Email: user.Email, Email: user.Email,
@@ -66,7 +66,7 @@ func GetUserByLoginOrEmail(c *m.ReqContext) Response {
} }
// POST /api/user // 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.AuthProxyEnabled {
if setting.AuthProxyHeaderProperty == "email" && cmd.Email != c.Email { if setting.AuthProxyHeaderProperty == "email" && cmd.Email != c.Email {
return Error(400, "Not allowed to change email when auth proxy is using email property", nil) 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 // 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") cmd.UserId = c.ParamsInt64(":id")
return handleUpdateUser(cmd) return handleUpdateUser(cmd)
} }
//POST /api/users/:id/using/:orgId //POST /api/users/:id/using/:orgId
func UpdateUserActiveOrg(c *m.ReqContext) Response { func UpdateUserActiveOrg(c *models.ReqContext) Response {
userID := c.ParamsInt64(":id") userID := c.ParamsInt64(":id")
orgID := c.ParamsInt64(":orgId") orgID := c.ParamsInt64(":orgId")
@@ -94,7 +94,7 @@ func UpdateUserActiveOrg(c *m.ReqContext) Response {
return Error(401, "Not a valid organization", nil) 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 { if err := bus.Dispatch(&cmd); err != nil {
return Error(500, "Failed to change active organization", err) return Error(500, "Failed to change active organization", err)
@@ -103,7 +103,7 @@ func UpdateUserActiveOrg(c *m.ReqContext) Response {
return Success("Active organization changed") return Success("Active organization changed")
} }
func handleUpdateUser(cmd m.UpdateUserCommand) Response { func handleUpdateUser(cmd models.UpdateUserCommand) Response {
if len(cmd.Login) == 0 { if len(cmd.Login) == 0 {
cmd.Login = cmd.Email cmd.Login = cmd.Email
if len(cmd.Login) == 0 { if len(cmd.Login) == 0 {
@@ -119,22 +119,22 @@ func handleUpdateUser(cmd m.UpdateUserCommand) Response {
} }
// GET /api/user/orgs // GET /api/user/orgs
func GetSignedInUserOrgList(c *m.ReqContext) Response { func GetSignedInUserOrgList(c *models.ReqContext) Response {
return getUserOrgList(c.UserId) return getUserOrgList(c.UserId)
} }
// GET /api/user/teams // GET /api/user/teams
func GetSignedInUserTeamList(c *m.ReqContext) Response { func GetSignedInUserTeamList(c *models.ReqContext) Response {
return getUserTeamList(c.OrgId, c.UserId) return getUserTeamList(c.OrgId, c.UserId)
} }
// GET /api/users/:id/teams // GET /api/users/:id/teams
func GetUserTeams(c *m.ReqContext) Response { func GetUserTeams(c *models.ReqContext) Response {
return getUserTeamList(c.OrgId, c.ParamsInt64(":id")) return getUserTeamList(c.OrgId, c.ParamsInt64(":id"))
} }
func getUserTeamList(orgID int64, userID int64) Response { 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 { if err := bus.Dispatch(&query); err != nil {
return Error(500, "Failed to get user teams", err) 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 // GET /api/users/:id/orgs
func GetUserOrgList(c *m.ReqContext) Response { func GetUserOrgList(c *models.ReqContext) Response {
return getUserOrgList(c.ParamsInt64(":id")) return getUserOrgList(c.ParamsInt64(":id"))
} }
func getUserOrgList(userID int64) Response { func getUserOrgList(userID int64) Response {
query := m.GetUserOrgListQuery{UserId: userID} query := models.GetUserOrgListQuery{UserId: userID}
if err := bus.Dispatch(&query); err != nil { if err := bus.Dispatch(&query); err != nil {
return Error(500, "Failed to get user organizations", err) 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 { func validateUsingOrg(userID int64, orgID int64) bool {
query := m.GetUserOrgListQuery{UserId: userID} query := models.GetUserOrgListQuery{UserId: userID}
if err := bus.Dispatch(&query); err != nil { if err := bus.Dispatch(&query); err != nil {
return false return false
@@ -180,14 +180,14 @@ func validateUsingOrg(userID int64, orgID int64) bool {
} }
// POST /api/user/using/:id // POST /api/user/using/:id
func UserSetUsingOrg(c *m.ReqContext) Response { func UserSetUsingOrg(c *models.ReqContext) Response {
orgID := c.ParamsInt64(":id") orgID := c.ParamsInt64(":id")
if !validateUsingOrg(c.UserId, orgID) { if !validateUsingOrg(c.UserId, orgID) {
return Error(401, "Not a valid organization", nil) 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 { if err := bus.Dispatch(&cmd); err != nil {
return Error(500, "Failed to change active organization", err) return Error(500, "Failed to change active organization", err)
@@ -197,14 +197,14 @@ func UserSetUsingOrg(c *m.ReqContext) Response {
} }
// GET /profile/switch-org/:id // GET /profile/switch-org/:id
func (hs *HTTPServer) ChangeActiveOrgAndRedirectToHome(c *m.ReqContext) { func (hs *HTTPServer) ChangeActiveOrgAndRedirectToHome(c *models.ReqContext) {
orgID := c.ParamsInt64(":id") orgID := c.ParamsInt64(":id")
if !validateUsingOrg(c.UserId, orgID) { if !validateUsingOrg(c.UserId, orgID) {
hs.NotFoundHandler(c) 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 { if err := bus.Dispatch(&cmd); err != nil {
hs.NotFoundHandler(c) hs.NotFoundHandler(c)
@@ -213,12 +213,12 @@ func (hs *HTTPServer) ChangeActiveOrgAndRedirectToHome(c *m.ReqContext) {
c.Redirect(setting.AppSubUrl + "/") 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 { if setting.LDAPEnabled || setting.AuthProxyEnabled {
return Error(400, "Not allowed to change password when LDAP or Auth Proxy is enabled", nil) 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 { if err := bus.Dispatch(&userQuery); err != nil {
return Error(500, "Could not read user from database", err) 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) return Error(401, "Invalid old password", nil)
} }
password := m.Password(cmd.NewPassword) password := models.Password(cmd.NewPassword)
if password.IsWeak() { if password.IsWeak() {
return Error(400, "New password is too short", nil) 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 // GET /api/users
func SearchUsers(c *m.ReqContext) Response { func SearchUsers(c *models.ReqContext) Response {
query, err := searchUser(c) query, err := searchUser(c)
if err != nil { if err != nil {
return Error(500, "Failed to fetch users", err) return Error(500, "Failed to fetch users", err)
@@ -261,7 +261,7 @@ func SearchUsers(c *m.ReqContext) Response {
} }
// GET /api/users/search // GET /api/users/search
func SearchUsersWithPaging(c *m.ReqContext) Response { func SearchUsersWithPaging(c *models.ReqContext) Response {
query, err := searchUser(c) query, err := searchUser(c)
if err != nil { if err != nil {
return Error(500, "Failed to fetch users", err) return Error(500, "Failed to fetch users", err)
@@ -270,7 +270,7 @@ func SearchUsersWithPaging(c *m.ReqContext) Response {
return JSON(200, query.Result) 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") perPage := c.QueryInt("perpage")
if perPage <= 0 { if perPage <= 0 {
perPage = 1000 perPage = 1000
@@ -283,7 +283,7 @@ func searchUser(c *m.ReqContext) (*m.SearchUsersQuery, error) {
searchQuery := c.Query("query") 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 { if err := bus.Dispatch(query); err != nil {
return nil, err return nil, err
} }
@@ -304,13 +304,13 @@ func searchUser(c *m.ReqContext) (*m.SearchUsersQuery, error) {
return query, nil return query, nil
} }
func SetHelpFlag(c *m.ReqContext) Response { func SetHelpFlag(c *models.ReqContext) Response {
flag := c.ParamsInt64(":id") flag := c.ParamsInt64(":id")
bitmask := &c.HelpFlags1 bitmask := &c.HelpFlags1
bitmask.AddFlag(m.HelpFlags1(flag)) bitmask.AddFlag(models.HelpFlags1(flag))
cmd := m.SetUserHelpFlagCommand{ cmd := models.SetUserHelpFlagCommand{
UserId: c.UserId, UserId: c.UserId,
HelpFlags1: *bitmask, HelpFlags1: *bitmask,
} }
@@ -322,10 +322,10 @@ func SetHelpFlag(c *m.ReqContext) Response {
return JSON(200, &util.DynMap{"message": "Help flag set", "helpFlags1": cmd.HelpFlags1}) return JSON(200, &util.DynMap{"message": "Help flag set", "helpFlags1": cmd.HelpFlags1})
} }
func ClearHelpFlags(c *m.ReqContext) Response { func ClearHelpFlags(c *models.ReqContext) Response {
cmd := m.SetUserHelpFlagCommand{ cmd := models.SetUserHelpFlagCommand{
UserId: c.UserId, UserId: c.UserId,
HelpFlags1: m.HelpFlags1(0), HelpFlags1: models.HelpFlags1(0),
} }
if err := bus.Dispatch(&cmd); err != nil { if err := bus.Dispatch(&cmd); err != nil {

View File

@@ -6,7 +6,7 @@ import (
"time" "time"
"github.com/grafana/grafana/pkg/bus" "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/grafana/grafana/pkg/services/auth"
. "github.com/smartystreets/goconvey/convey" . "github.com/smartystreets/goconvey/convey"
@@ -15,12 +15,12 @@ import (
func TestUserTokenApiEndpoint(t *testing.T) { func TestUserTokenApiEndpoint(t *testing.T) {
Convey("When current user attempts to revoke an auth token for a non-existing user", t, func() { Convey("When current user attempts to revoke an auth token for a non-existing user", t, func() {
userId := int64(0) userId := int64(0)
bus.AddHandler("test", func(cmd *m.GetUserByIdQuery) error { bus.AddHandler("test", func(cmd *models.GetUserByIdQuery) error {
userId = cmd.Id 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) { 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() 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() { Convey("When current user gets auth tokens for a non-existing user", t, func() {
userId := int64(0) userId := int64(0)
bus.AddHandler("test", func(cmd *m.GetUserByIdQuery) error { bus.AddHandler("test", func(cmd *models.GetUserByIdQuery) error {
userId = cmd.Id 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) { 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() { Convey("When logout an existing user from all devices", t, func() {
bus.AddHandler("test", func(cmd *m.GetUserByIdQuery) error { bus.AddHandler("test", func(cmd *models.GetUserByIdQuery) error {
cmd.Result = &m.User{Id: 200} cmd.Result = &models.User{Id: 200}
return nil return nil
}) })
@@ -56,8 +56,8 @@ func TestUserTokenApiEndpoint(t *testing.T) {
}) })
Convey("When logout a non-existing user from all devices", t, func() { Convey("When logout a non-existing user from all devices", t, func() {
bus.AddHandler("test", func(cmd *m.GetUserByIdQuery) error { bus.AddHandler("test", func(cmd *models.GetUserByIdQuery) error {
return m.ErrUserNotFound return models.ErrUserNotFound
}) })
logoutUserFromAllDevicesInternalScenario("Should return not found", TestUserID, func(sc *scenarioContext) { 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() { Convey("When revoke an auth token for a user", t, func() {
bus.AddHandler("test", func(cmd *m.GetUserByIdQuery) error { bus.AddHandler("test", func(cmd *models.GetUserByIdQuery) error {
cmd.Result = &m.User{Id: 200} cmd.Result = &models.User{Id: 200}
return nil return nil
}) })
cmd := m.RevokeAuthTokenCmd{AuthTokenId: 2} cmd := models.RevokeAuthTokenCmd{AuthTokenId: 2}
token := &m.UserToken{Id: 1} token := &models.UserToken{Id: 1}
revokeUserAuthTokenInternalScenario("Should be successful", cmd, 200, token, func(sc *scenarioContext) { revokeUserAuthTokenInternalScenario("Should be successful", cmd, 200, 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 &m.UserToken{Id: 2}, nil return &models.UserToken{Id: 2}, nil
} }
sc.fakeReqWithParams("POST", sc.url, map[string]string{}).exec() sc.fakeReqWithParams("POST", sc.url, map[string]string{}).exec()
So(sc.resp.Code, ShouldEqual, 200) 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() { Convey("When revoke the active auth token used by himself", t, func() {
bus.AddHandler("test", func(cmd *m.GetUserByIdQuery) error { bus.AddHandler("test", func(cmd *models.GetUserByIdQuery) error {
cmd.Result = &m.User{Id: TestUserID} cmd.Result = &models.User{Id: TestUserID}
return nil return nil
}) })
cmd := m.RevokeAuthTokenCmd{AuthTokenId: 2} cmd := models.RevokeAuthTokenCmd{AuthTokenId: 2}
token := &m.UserToken{Id: 2} token := &models.UserToken{Id: 2}
revokeUserAuthTokenInternalScenario("Should not be successful", cmd, TestUserID, token, func(sc *scenarioContext) { 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 return token, nil
} }
sc.fakeReqWithParams("POST", sc.url, map[string]string{}).exec() 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() { Convey("When gets auth tokens for a user", t, func() {
bus.AddHandler("test", func(cmd *m.GetUserByIdQuery) error { bus.AddHandler("test", func(cmd *models.GetUserByIdQuery) error {
cmd.Result = &m.User{Id: TestUserID} cmd.Result = &models.User{Id: TestUserID}
return nil return nil
}) })
currentToken := &m.UserToken{Id: 1} currentToken := &models.UserToken{Id: 1}
getUserAuthTokensInternalScenario("Should be successful", currentToken, func(sc *scenarioContext) { getUserAuthTokensInternalScenario("Should be successful", currentToken, func(sc *scenarioContext) {
tokens := []*m.UserToken{ tokens := []*models.UserToken{
{ {
Id: 1, Id: 1,
ClientIp: "127.0.0.1", ClientIp: "127.0.0.1",
@@ -127,7 +127,7 @@ func TestUserTokenApiEndpoint(t *testing.T) {
SeenAt: 0, 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 return tokens, nil
} }
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec() 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() { Convey(desc+" "+url, func() {
defer bus.ClearBusHandlers() defer bus.ClearBusHandlers()
@@ -178,11 +178,11 @@ func revokeUserAuthTokenScenario(desc string, url string, routePattern string, c
sc := setupScenarioContext(url) sc := setupScenarioContext(url)
sc.userAuthTokenService = fakeAuthTokenService sc.userAuthTokenService = fakeAuthTokenService
sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { sc.defaultHandler = Wrap(func(c *models.ReqContext) Response {
sc.context = c sc.context = c
sc.context.UserId = userId sc.context.UserId = userId
sc.context.OrgId = TestOrgID sc.context.OrgId = TestOrgID
sc.context.OrgRole = m.ROLE_ADMIN sc.context.OrgRole = models.ROLE_ADMIN
return hs.RevokeUserAuthToken(c, cmd) return hs.RevokeUserAuthToken(c, cmd)
}) })
@@ -206,11 +206,11 @@ func getUserAuthTokensScenario(desc string, url string, routePattern string, use
sc := setupScenarioContext(url) sc := setupScenarioContext(url)
sc.userAuthTokenService = fakeAuthTokenService sc.userAuthTokenService = fakeAuthTokenService
sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { sc.defaultHandler = Wrap(func(c *models.ReqContext) Response {
sc.context = c sc.context = c
sc.context.UserId = userId sc.context.UserId = userId
sc.context.OrgId = TestOrgID sc.context.OrgId = TestOrgID
sc.context.OrgRole = m.ROLE_ADMIN sc.context.OrgRole = models.ROLE_ADMIN
return hs.GetUserAuthTokens(c) return hs.GetUserAuthTokens(c)
}) })
@@ -231,11 +231,11 @@ func logoutUserFromAllDevicesInternalScenario(desc string, userId int64, fn scen
} }
sc := setupScenarioContext("/") sc := setupScenarioContext("/")
sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { sc.defaultHandler = Wrap(func(c *models.ReqContext) Response {
sc.context = c sc.context = c
sc.context.UserId = TestUserID sc.context.UserId = TestUserID
sc.context.OrgId = TestOrgID sc.context.OrgId = TestOrgID
sc.context.OrgRole = m.ROLE_ADMIN sc.context.OrgRole = models.ROLE_ADMIN
return hs.logoutUserFromAllDevicesInternal(context.Background(), userId) 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() { Convey(desc, func() {
defer bus.ClearBusHandlers() defer bus.ClearBusHandlers()
@@ -259,11 +259,11 @@ func revokeUserAuthTokenInternalScenario(desc string, cmd m.RevokeAuthTokenCmd,
sc := setupScenarioContext("/") sc := setupScenarioContext("/")
sc.userAuthTokenService = fakeAuthTokenService sc.userAuthTokenService = fakeAuthTokenService
sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { sc.defaultHandler = Wrap(func(c *models.ReqContext) Response {
sc.context = c sc.context = c
sc.context.UserId = TestUserID sc.context.UserId = TestUserID
sc.context.OrgId = TestOrgID sc.context.OrgId = TestOrgID
sc.context.OrgRole = m.ROLE_ADMIN sc.context.OrgRole = models.ROLE_ADMIN
sc.context.UserToken = token sc.context.UserToken = token
return hs.revokeUserAuthTokenInternal(c, userId, cmd) 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() { Convey(desc, func() {
defer bus.ClearBusHandlers() defer bus.ClearBusHandlers()
@@ -288,11 +288,11 @@ func getUserAuthTokensInternalScenario(desc string, token *m.UserToken, fn scena
sc := setupScenarioContext("/") sc := setupScenarioContext("/")
sc.userAuthTokenService = fakeAuthTokenService sc.userAuthTokenService = fakeAuthTokenService
sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { sc.defaultHandler = Wrap(func(c *models.ReqContext) Response {
sc.context = c sc.context = c
sc.context.UserId = TestUserID sc.context.UserId = TestUserID
sc.context.OrgId = TestOrgID sc.context.OrgId = TestOrgID
sc.context.OrgRole = m.ROLE_ADMIN sc.context.OrgRole = models.ROLE_ADMIN
sc.context.UserToken = token sc.context.UserToken = token
return hs.getUserAuthTokensInternal(c, TestUserID) return hs.getUserAuthTokensInternal(c, TestUserID)

View File

@@ -4,7 +4,7 @@ import (
"time" "time"
"github.com/grafana/grafana/pkg/bus" "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/setting"
) )
@@ -18,7 +18,7 @@ var validateLoginAttempts = func(username string) error {
return nil return nil
} }
loginAttemptCountQuery := m.GetUserLoginAttemptCountQuery{ loginAttemptCountQuery := models.GetUserLoginAttemptCountQuery{
Username: username, Username: username,
Since: time.Now().Add(-loginAttemptsWindow), Since: time.Now().Add(-loginAttemptsWindow),
} }
@@ -34,12 +34,12 @@ var validateLoginAttempts = func(username string) error {
return nil return nil
} }
var saveInvalidLoginAttempt = func(query *m.LoginUserQuery) error { var saveInvalidLoginAttempt = func(query *models.LoginUserQuery) error {
if setting.DisableBruteForceLoginProtection { if setting.DisableBruteForceLoginProtection {
return nil return nil
} }
loginAttemptCommand := m.CreateLoginAttemptCommand{ loginAttemptCommand := models.CreateLoginAttemptCommand{
Username: query.Username, Username: query.Username,
IpAddress: query.IpAddress, IpAddress: query.IpAddress,
} }

View File

@@ -4,7 +4,7 @@ import (
"testing" "testing"
"github.com/grafana/grafana/pkg/bus" "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/setting"
. "github.com/smartystreets/goconvey/convey" . "github.com/smartystreets/goconvey/convey"
) )
@@ -43,14 +43,14 @@ func TestLoginAttemptsValidation(t *testing.T) {
Convey("When saving invalid login attempt", func() { Convey("When saving invalid login attempt", func() {
defer bus.ClearBusHandlers() 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 createLoginAttemptCmd = cmd
return nil return nil
}) })
err := saveInvalidLoginAttempt(&m.LoginUserQuery{ err := saveInvalidLoginAttempt(&models.LoginUserQuery{
Username: "user", Username: "user",
Password: "pwd", Password: "pwd",
IpAddress: "192.168.1.1:56433", IpAddress: "192.168.1.1:56433",
@@ -97,14 +97,14 @@ func TestLoginAttemptsValidation(t *testing.T) {
Convey("When saving invalid login attempt", func() { Convey("When saving invalid login attempt", func() {
defer bus.ClearBusHandlers() 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 createLoginAttemptCmd = cmd
return nil return nil
}) })
err := saveInvalidLoginAttempt(&m.LoginUserQuery{ err := saveInvalidLoginAttempt(&models.LoginUserQuery{
Username: "user", Username: "user",
Password: "pwd", Password: "pwd",
IpAddress: "192.168.1.1:56433", IpAddress: "192.168.1.1:56433",
@@ -120,7 +120,7 @@ func TestLoginAttemptsValidation(t *testing.T) {
} }
func withLoginAttempts(loginAttempts int64) { func withLoginAttempts(loginAttempts int64) {
bus.AddHandler("test", func(query *m.GetUserLoginAttemptCountQuery) error { bus.AddHandler("test", func(query *models.GetUserLoginAttemptCountQuery) error {
query.Result = loginAttempts query.Result = loginAttempts
return nil return nil
}) })

View File

@@ -4,7 +4,7 @@ import (
"crypto/subtle" "crypto/subtle"
"github.com/grafana/grafana/pkg/bus" "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" "github.com/grafana/grafana/pkg/util"
) )
@@ -20,8 +20,8 @@ var validatePassword = func(providedPassword string, userPassword string, userSa
return nil return nil
} }
var loginUsingGrafanaDB = func(query *m.LoginUserQuery) error { var loginUsingGrafanaDB = func(query *models.LoginUserQuery) error {
userQuery := m.GetUserByLoginQuery{LoginOrEmail: query.Username} userQuery := models.GetUserByLoginQuery{LoginOrEmail: query.Username}
if err := bus.Dispatch(&userQuery); err != nil { if err := bus.Dispatch(&userQuery); err != nil {
return err return err

View File

@@ -6,7 +6,7 @@ import (
. "github.com/smartystreets/goconvey/convey" . "github.com/smartystreets/goconvey/convey"
"github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/bus"
m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
) )
func TestGrafanaLogin(t *testing.T) { func TestGrafanaLogin(t *testing.T) {
@@ -16,7 +16,7 @@ func TestGrafanaLogin(t *testing.T) {
err := loginUsingGrafanaDB(sc.loginUserQuery) err := loginUsingGrafanaDB(sc.loginUserQuery)
Convey("it should result in user not found error", func() { 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() { Convey("it should not call password validation", func() {
@@ -84,7 +84,7 @@ func TestGrafanaLogin(t *testing.T) {
} }
type grafanaLoginScenarioContext struct { type grafanaLoginScenarioContext struct {
loginUserQuery *m.LoginUserQuery loginUserQuery *models.LoginUserQuery
validatePasswordCalled bool validatePasswordCalled bool
} }
@@ -95,7 +95,7 @@ func grafanaLoginScenario(desc string, fn grafanaLoginScenarioFunc) {
origValidatePassword := validatePassword origValidatePassword := validatePassword
sc := &grafanaLoginScenarioContext{ sc := &grafanaLoginScenarioContext{
loginUserQuery: &m.LoginUserQuery{ loginUserQuery: &models.LoginUserQuery{
Username: "user", Username: "user",
Password: "pwd", Password: "pwd",
IpAddress: "192.168.1.1:56433", IpAddress: "192.168.1.1:56433",
@@ -123,10 +123,10 @@ func mockPasswordValidation(valid bool, sc *grafanaLoginScenarioContext) {
} }
} }
func (sc *grafanaLoginScenarioContext) getUserByLoginQueryReturns(user *m.User) { func (sc *grafanaLoginScenarioContext) getUserByLoginQueryReturns(user *models.User) {
bus.AddHandler("test", func(query *m.GetUserByLoginQuery) error { bus.AddHandler("test", func(query *models.GetUserByLoginQuery) error {
if user == nil { if user == nil {
return m.ErrUserNotFound return models.ErrUserNotFound
} }
query.Result = user query.Result = user
@@ -135,7 +135,7 @@ func (sc *grafanaLoginScenarioContext) getUserByLoginQueryReturns(user *m.User)
} }
func (sc *grafanaLoginScenarioContext) withValidCredentials() { func (sc *grafanaLoginScenarioContext) withValidCredentials() {
sc.getUserByLoginQueryReturns(&m.User{ sc.getUserByLoginQueryReturns(&models.User{
Id: 1, Id: 1,
Login: sc.loginUserQuery.Username, Login: sc.loginUserQuery.Username,
Password: sc.loginUserQuery.Password, Password: sc.loginUserQuery.Password,
@@ -149,7 +149,7 @@ func (sc *grafanaLoginScenarioContext) withNonExistingUser() {
} }
func (sc *grafanaLoginScenarioContext) withInvalidPassword() { func (sc *grafanaLoginScenarioContext) withInvalidPassword() {
sc.getUserByLoginQueryReturns(&m.User{ sc.getUserByLoginQueryReturns(&models.User{
Password: sc.loginUserQuery.Password, Password: sc.loginUserQuery.Password,
Salt: "salt", Salt: "salt",
}) })
@@ -157,7 +157,7 @@ func (sc *grafanaLoginScenarioContext) withInvalidPassword() {
} }
func (sc *grafanaLoginScenarioContext) withDisabledUser() { func (sc *grafanaLoginScenarioContext) withDisabledUser() {
sc.getUserByLoginQueryReturns(&m.User{ sc.getUserByLoginQueryReturns(&models.User{
IsDisabled: true, IsDisabled: true,
}) })
} }