Commit f9962eab by Carl Bergquist Committed by GitHub

chore: avoid aliasing imports in services (#22499)

parent a8531978
......@@ -10,7 +10,7 @@ import (
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/infra/serverlock"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/registry"
"github.com/grafana/grafana/pkg/setting"
)
......@@ -93,7 +93,7 @@ func (srv *CleanUpService) shouldCleanupTempFile(filemtime time.Time, now time.T
}
func (srv *CleanUpService) deleteExpiredSnapshots() {
cmd := m.DeleteExpiredSnapshotsCommand{}
cmd := models.DeleteExpiredSnapshotsCommand{}
if err := bus.Dispatch(&cmd); err != nil {
srv.log.Error("Failed to delete expired snapshots", "error", err.Error())
} else {
......@@ -102,7 +102,7 @@ func (srv *CleanUpService) deleteExpiredSnapshots() {
}
func (srv *CleanUpService) deleteExpiredDashboardVersions() {
cmd := m.DeleteExpiredVersionsCommand{}
cmd := models.DeleteExpiredVersionsCommand{}
if err := bus.Dispatch(&cmd); err != nil {
srv.log.Error("Failed to delete expired dashboard versions", "error", err.Error())
} else {
......@@ -115,7 +115,7 @@ func (srv *CleanUpService) deleteOldLoginAttempts() {
return
}
cmd := m.DeleteOldLoginAttemptsCommand{
cmd := models.DeleteOldLoginAttemptsCommand{
OlderThan: time.Now().Add(time.Minute * -10),
}
if err := bus.Dispatch(&cmd); err != nil {
......
......@@ -6,12 +6,12 @@ import (
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/infra/localcache"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/registry"
)
type CacheService interface {
GetDatasource(datasourceID int64, user *m.SignedInUser, skipCache bool) (*m.DataSource, error)
GetDatasource(datasourceID int64, user *models.SignedInUser, skipCache bool) (*models.DataSource, error)
}
type CacheServiceImpl struct {
......@@ -31,19 +31,19 @@ func (dc *CacheServiceImpl) Init() error {
return nil
}
func (dc *CacheServiceImpl) GetDatasource(datasourceID int64, user *m.SignedInUser, skipCache bool) (*m.DataSource, error) {
func (dc *CacheServiceImpl) GetDatasource(datasourceID int64, user *models.SignedInUser, skipCache bool) (*models.DataSource, error) {
cacheKey := fmt.Sprintf("ds-%d", datasourceID)
if !skipCache {
if cached, found := dc.CacheService.Get(cacheKey); found {
ds := cached.(*m.DataSource)
ds := cached.(*models.DataSource)
if ds.OrgId == user.OrgId {
return ds, nil
}
}
}
query := m.GetDataSourceByIdQuery{Id: datasourceID, OrgId: user.OrgId}
query := models.GetDataSourceByIdQuery{Id: datasourceID, OrgId: user.OrgId}
if err := dc.Bus.Dispatch(&query); err != nil {
return nil, err
}
......
......@@ -5,7 +5,7 @@ import (
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/infra/log"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/setting"
)
......@@ -20,22 +20,22 @@ type DashboardGuardian interface {
CanEdit() (bool, error)
CanView() (bool, error)
CanAdmin() (bool, error)
HasPermission(permission m.PermissionType) (bool, error)
CheckPermissionBeforeUpdate(permission m.PermissionType, updatePermissions []*m.DashboardAcl) (bool, error)
GetAcl() ([]*m.DashboardAclInfoDTO, error)
HasPermission(permission models.PermissionType) (bool, error)
CheckPermissionBeforeUpdate(permission models.PermissionType, updatePermissions []*models.DashboardAcl) (bool, error)
GetAcl() ([]*models.DashboardAclInfoDTO, error)
}
type dashboardGuardianImpl struct {
user *m.SignedInUser
user *models.SignedInUser
dashId int64
orgId int64
acl []*m.DashboardAclInfoDTO
teams []*m.TeamDTO
acl []*models.DashboardAclInfoDTO
teams []*models.TeamDTO
log log.Logger
}
// New factory for creating a new dashboard guardian instance
var New = func(dashId int64, orgId int64, user *m.SignedInUser) DashboardGuardian {
var New = func(dashId int64, orgId int64, user *models.SignedInUser) DashboardGuardian {
return &dashboardGuardianImpl{
user: user,
dashId: dashId,
......@@ -45,27 +45,27 @@ var New = func(dashId int64, orgId int64, user *m.SignedInUser) DashboardGuardia
}
func (g *dashboardGuardianImpl) CanSave() (bool, error) {
return g.HasPermission(m.PERMISSION_EDIT)
return g.HasPermission(models.PERMISSION_EDIT)
}
func (g *dashboardGuardianImpl) CanEdit() (bool, error) {
if setting.ViewersCanEdit {
return g.HasPermission(m.PERMISSION_VIEW)
return g.HasPermission(models.PERMISSION_VIEW)
}
return g.HasPermission(m.PERMISSION_EDIT)
return g.HasPermission(models.PERMISSION_EDIT)
}
func (g *dashboardGuardianImpl) CanView() (bool, error) {
return g.HasPermission(m.PERMISSION_VIEW)
return g.HasPermission(models.PERMISSION_VIEW)
}
func (g *dashboardGuardianImpl) CanAdmin() (bool, error) {
return g.HasPermission(m.PERMISSION_ADMIN)
return g.HasPermission(models.PERMISSION_ADMIN)
}
func (g *dashboardGuardianImpl) HasPermission(permission m.PermissionType) (bool, error) {
if g.user.OrgRole == m.ROLE_ADMIN {
func (g *dashboardGuardianImpl) HasPermission(permission models.PermissionType) (bool, error) {
if g.user.OrgRole == models.ROLE_ADMIN {
return g.logHasPermissionResult(permission, true, nil)
}
......@@ -78,7 +78,7 @@ func (g *dashboardGuardianImpl) HasPermission(permission m.PermissionType) (bool
return g.logHasPermissionResult(permission, result, err)
}
func (g *dashboardGuardianImpl) logHasPermissionResult(permission m.PermissionType, hasPermission bool, err error) (bool, error) {
func (g *dashboardGuardianImpl) logHasPermissionResult(permission models.PermissionType, hasPermission bool, err error) (bool, error) {
if err != nil {
return hasPermission, err
}
......@@ -92,9 +92,9 @@ func (g *dashboardGuardianImpl) logHasPermissionResult(permission m.PermissionTy
return hasPermission, err
}
func (g *dashboardGuardianImpl) checkAcl(permission m.PermissionType, acl []*m.DashboardAclInfoDTO) (bool, error) {
func (g *dashboardGuardianImpl) checkAcl(permission models.PermissionType, acl []*models.DashboardAclInfoDTO) (bool, error) {
orgRole := g.user.OrgRole
teamAclItems := []*m.DashboardAclInfoDTO{}
teamAclItems := []*models.DashboardAclInfoDTO{}
for _, p := range acl {
// user match
......@@ -140,14 +140,14 @@ func (g *dashboardGuardianImpl) checkAcl(permission m.PermissionType, acl []*m.D
return false, nil
}
func (g *dashboardGuardianImpl) CheckPermissionBeforeUpdate(permission m.PermissionType, updatePermissions []*m.DashboardAcl) (bool, error) {
acl := []*m.DashboardAclInfoDTO{}
adminRole := m.ROLE_ADMIN
everyoneWithAdminRole := &m.DashboardAclInfoDTO{DashboardId: g.dashId, UserId: 0, TeamId: 0, Role: &adminRole, Permission: m.PERMISSION_ADMIN}
func (g *dashboardGuardianImpl) CheckPermissionBeforeUpdate(permission models.PermissionType, updatePermissions []*models.DashboardAcl) (bool, error) {
acl := []*models.DashboardAclInfoDTO{}
adminRole := models.ROLE_ADMIN
everyoneWithAdminRole := &models.DashboardAclInfoDTO{DashboardId: g.dashId, UserId: 0, TeamId: 0, Role: &adminRole, Permission: models.PERMISSION_ADMIN}
// validate that duplicate permissions don't exists
for _, p := range updatePermissions {
aclItem := &m.DashboardAclInfoDTO{DashboardId: p.DashboardId, UserId: p.UserId, TeamId: p.TeamId, Role: p.Role, Permission: p.Permission}
aclItem := &models.DashboardAclInfoDTO{DashboardId: p.DashboardId, UserId: p.UserId, TeamId: p.TeamId, Role: p.Role, Permission: p.Permission}
if aclItem.IsDuplicateOf(everyoneWithAdminRole) {
return false, ErrGuardianPermissionExists
}
......@@ -179,7 +179,7 @@ func (g *dashboardGuardianImpl) CheckPermissionBeforeUpdate(permission m.Permiss
}
}
if g.user.OrgRole == m.ROLE_ADMIN {
if g.user.OrgRole == models.ROLE_ADMIN {
return true, nil
}
......@@ -187,12 +187,12 @@ func (g *dashboardGuardianImpl) CheckPermissionBeforeUpdate(permission m.Permiss
}
// GetAcl returns dashboard acl
func (g *dashboardGuardianImpl) GetAcl() ([]*m.DashboardAclInfoDTO, error) {
func (g *dashboardGuardianImpl) GetAcl() ([]*models.DashboardAclInfoDTO, error) {
if g.acl != nil {
return g.acl, nil
}
query := m.GetDashboardAclInfoListQuery{DashboardId: g.dashId, OrgId: g.orgId}
query := models.GetDashboardAclInfoListQuery{DashboardId: g.dashId, OrgId: g.orgId}
if err := bus.Dispatch(&query); err != nil {
return nil, err
}
......@@ -201,12 +201,12 @@ func (g *dashboardGuardianImpl) GetAcl() ([]*m.DashboardAclInfoDTO, error) {
return g.acl, nil
}
func (g *dashboardGuardianImpl) getTeams() ([]*m.TeamDTO, error) {
func (g *dashboardGuardianImpl) getTeams() ([]*models.TeamDTO, error) {
if g.teams != nil {
return g.teams, nil
}
query := m.GetTeamsByUserQuery{OrgId: g.orgId, UserId: g.user.UserId}
query := models.GetTeamsByUserQuery{OrgId: g.orgId, UserId: g.user.UserId}
err := bus.Dispatch(&query)
g.teams = query.Result
......@@ -216,7 +216,7 @@ func (g *dashboardGuardianImpl) getTeams() ([]*m.TeamDTO, error) {
type FakeDashboardGuardian struct {
DashId int64
OrgId int64
User *m.SignedInUser
User *models.SignedInUser
CanSaveValue bool
CanEditValue bool
CanViewValue bool
......@@ -224,7 +224,7 @@ type FakeDashboardGuardian struct {
HasPermissionValue bool
CheckPermissionBeforeUpdateValue bool
CheckPermissionBeforeUpdateError error
GetAclValue []*m.DashboardAclInfoDTO
GetAclValue []*models.DashboardAclInfoDTO
}
func (g *FakeDashboardGuardian) CanSave() (bool, error) {
......@@ -243,20 +243,20 @@ func (g *FakeDashboardGuardian) CanAdmin() (bool, error) {
return g.CanAdminValue, nil
}
func (g *FakeDashboardGuardian) HasPermission(permission m.PermissionType) (bool, error) {
func (g *FakeDashboardGuardian) HasPermission(permission models.PermissionType) (bool, error) {
return g.HasPermissionValue, nil
}
func (g *FakeDashboardGuardian) CheckPermissionBeforeUpdate(permission m.PermissionType, updatePermissions []*m.DashboardAcl) (bool, error) {
func (g *FakeDashboardGuardian) CheckPermissionBeforeUpdate(permission models.PermissionType, updatePermissions []*models.DashboardAcl) (bool, error) {
return g.CheckPermissionBeforeUpdateValue, g.CheckPermissionBeforeUpdateError
}
func (g *FakeDashboardGuardian) GetAcl() ([]*m.DashboardAclInfoDTO, error) {
func (g *FakeDashboardGuardian) GetAcl() ([]*models.DashboardAclInfoDTO, error) {
return g.GetAclValue, nil
}
func MockDashboardGuardian(mock *FakeDashboardGuardian) {
New = func(dashId int64, orgId int64, user *m.SignedInUser) DashboardGuardian {
New = func(dashId int64, orgId int64, user *models.SignedInUser) DashboardGuardian {
mock.OrgId = orgId
mock.DashId = dashId
mock.User = user
......
......@@ -7,7 +7,7 @@ import (
"testing"
"github.com/grafana/grafana/pkg/bus"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/models"
. "github.com/smartystreets/goconvey/convey"
)
......@@ -16,11 +16,11 @@ type scenarioContext struct {
orgRoleScenario string
permissionScenario string
g DashboardGuardian
givenUser *m.SignedInUser
givenUser *models.SignedInUser
givenDashboardID int64
givenPermissions []*m.DashboardAclInfoDTO
givenTeams []*m.TeamDTO
updatePermissions []*m.DashboardAcl
givenPermissions []*models.DashboardAclInfoDTO
givenTeams []*models.TeamDTO
updatePermissions []*models.DashboardAcl
expectedFlags permissionFlags
callerFile string
callerLine int
......@@ -28,8 +28,8 @@ type scenarioContext struct {
type scenarioFunc func(c *scenarioContext)
func orgRoleScenario(desc string, t *testing.T, role m.RoleType, fn scenarioFunc) {
user := &m.SignedInUser{
func orgRoleScenario(desc string, t *testing.T, role models.RoleType, fn scenarioFunc) {
user := &models.SignedInUser{
UserId: userID,
OrgId: orgID,
OrgRole: role,
......@@ -48,8 +48,8 @@ func orgRoleScenario(desc string, t *testing.T, role m.RoleType, fn scenarioFunc
})
}
func apiKeyScenario(desc string, t *testing.T, role m.RoleType, fn scenarioFunc) {
user := &m.SignedInUser{
func apiKeyScenario(desc string, t *testing.T, role models.RoleType, fn scenarioFunc) {
user := &models.SignedInUser{
UserId: 0,
OrgId: orgID,
OrgRole: role,
......@@ -69,10 +69,10 @@ func apiKeyScenario(desc string, t *testing.T, role m.RoleType, fn scenarioFunc)
})
}
func permissionScenario(desc string, dashboardID int64, sc *scenarioContext, permissions []*m.DashboardAclInfoDTO, fn scenarioFunc) {
func permissionScenario(desc string, dashboardID int64, sc *scenarioContext, permissions []*models.DashboardAclInfoDTO, fn scenarioFunc) {
bus.ClearBusHandlers()
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
bus.AddHandler("test", func(query *models.GetDashboardAclInfoListQuery) error {
if query.OrgId != sc.givenUser.OrgId {
sc.reportFailure("Invalid organization id for GetDashboardAclInfoListQuery", sc.givenUser.OrgId, query.OrgId)
}
......@@ -84,15 +84,15 @@ func permissionScenario(desc string, dashboardID int64, sc *scenarioContext, per
return nil
})
teams := []*m.TeamDTO{}
teams := []*models.TeamDTO{}
for _, p := range permissions {
if p.TeamId > 0 {
teams = append(teams, &m.TeamDTO{Id: p.TeamId})
teams = append(teams, &models.TeamDTO{Id: p.TeamId})
}
}
bus.AddHandler("test", func(query *m.GetTeamsByUserQuery) error {
bus.AddHandler("test", func(query *models.GetTeamsByUserQuery) error {
if query.OrgId != sc.givenUser.OrgId {
sc.reportFailure("Invalid organization id for GetTeamsByUserQuery", sc.givenUser.OrgId, query.OrgId)
}
......@@ -236,36 +236,36 @@ func (sc *scenarioContext) reportFailure(desc string, expected interface{}, actu
sc.t.Fatalf(buf.String())
}
func newCustomUserPermission(dashboardID int64, userID int64, permission m.PermissionType) *m.DashboardAcl {
return &m.DashboardAcl{OrgId: orgID, DashboardId: dashboardID, UserId: userID, Permission: permission}
func newCustomUserPermission(dashboardID int64, userID int64, permission models.PermissionType) *models.DashboardAcl {
return &models.DashboardAcl{OrgId: orgID, DashboardId: dashboardID, UserId: userID, Permission: permission}
}
func newDefaultUserPermission(dashboardID int64, permission m.PermissionType) *m.DashboardAcl {
func newDefaultUserPermission(dashboardID int64, permission models.PermissionType) *models.DashboardAcl {
return newCustomUserPermission(dashboardID, userID, permission)
}
func newCustomTeamPermission(dashboardID int64, teamID int64, permission m.PermissionType) *m.DashboardAcl {
return &m.DashboardAcl{OrgId: orgID, DashboardId: dashboardID, TeamId: teamID, Permission: permission}
func newCustomTeamPermission(dashboardID int64, teamID int64, permission models.PermissionType) *models.DashboardAcl {
return &models.DashboardAcl{OrgId: orgID, DashboardId: dashboardID, TeamId: teamID, Permission: permission}
}
func newDefaultTeamPermission(dashboardID int64, permission m.PermissionType) *m.DashboardAcl {
func newDefaultTeamPermission(dashboardID int64, permission models.PermissionType) *models.DashboardAcl {
return newCustomTeamPermission(dashboardID, teamID, permission)
}
func newAdminRolePermission(dashboardID int64, permission m.PermissionType) *m.DashboardAcl {
return &m.DashboardAcl{OrgId: orgID, DashboardId: dashboardID, Role: &adminRole, Permission: permission}
func newAdminRolePermission(dashboardID int64, permission models.PermissionType) *models.DashboardAcl {
return &models.DashboardAcl{OrgId: orgID, DashboardId: dashboardID, Role: &adminRole, Permission: permission}
}
func newEditorRolePermission(dashboardID int64, permission m.PermissionType) *m.DashboardAcl {
return &m.DashboardAcl{OrgId: orgID, DashboardId: dashboardID, Role: &editorRole, Permission: permission}
func newEditorRolePermission(dashboardID int64, permission models.PermissionType) *models.DashboardAcl {
return &models.DashboardAcl{OrgId: orgID, DashboardId: dashboardID, Role: &editorRole, Permission: permission}
}
func newViewerRolePermission(dashboardID int64, permission m.PermissionType) *m.DashboardAcl {
return &m.DashboardAcl{OrgId: orgID, DashboardId: dashboardID, Role: &viewerRole, Permission: permission}
func newViewerRolePermission(dashboardID int64, permission models.PermissionType) *models.DashboardAcl {
return &models.DashboardAcl{OrgId: orgID, DashboardId: dashboardID, Role: &viewerRole, Permission: permission}
}
func toDto(acl *m.DashboardAcl) *m.DashboardAclInfoDTO {
return &m.DashboardAclInfoDTO{
func toDto(acl *models.DashboardAcl) *models.DashboardAclInfoDTO {
return &models.DashboardAclInfoDTO{
OrgId: acl.OrgId,
DashboardId: acl.DashboardId,
UserId: acl.UserId,
......
......@@ -9,7 +9,7 @@ import (
"golang.org/x/xerrors"
"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/util/errutil"
)
......@@ -61,7 +61,7 @@ type GroupToOrgRole struct {
// This pointer specifies if setting was set (for backwards compatibility)
IsGrafanaAdmin *bool `toml:"grafana_admin"`
OrgRole m.RoleType `toml:"org_role"`
OrgRole models.RoleType `toml:"org_role"`
}
// logger for all LDAP stuff
......
......@@ -8,7 +8,7 @@ import (
"github.com/unknwon/com"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/setting"
)
......@@ -49,7 +49,7 @@ func createTimeLimitCode(data string, minutes int, startInf interface{}) (string
}
// verify time limit code
func validateUserEmailCode(user *m.User, code string) (bool, error) {
func validateUserEmailCode(user *models.User, code string) (bool, error) {
if len(code) <= 18 {
return false, nil
}
......@@ -94,7 +94,7 @@ func getLoginForEmailCode(code string) string {
return string(b)
}
func createUserEmailCode(u *m.User, startInf interface{}) (string, error) {
func createUserEmailCode(u *models.User, startInf interface{}) (string, error) {
minutes := setting.EmailCodeValidMinutes
data := com.ToStr(u.Id) + u.Email + u.Login + u.Password + u.Rands
code, err := createTimeLimitCode(data, minutes, startInf)
......
......@@ -3,7 +3,7 @@ package notifications
import (
"testing"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/setting"
. "github.com/smartystreets/goconvey/convey"
)
......@@ -13,7 +13,7 @@ func TestEmailCodes(t *testing.T) {
Convey("When generating code", t, func() {
setting.EmailCodeValidMinutes = 120
user := &m.User{Id: 10, Email: "t@a.com", Login: "asd", Password: "1", Rands: "2"}
user := &models.User{Id: 10, Email: "t@a.com", Login: "asd", Password: "1", Rands: "2"}
code, err := createUserEmailCode(user, nil)
So(err, ShouldBeNil)
......
package notifications
import (
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/setting"
)
......@@ -24,7 +24,7 @@ type Message struct {
AttachedFiles []*AttachedFile
}
func setDefaultTemplateData(data map[string]interface{}, u *m.User) {
func setDefaultTemplateData(data map[string]interface{}, u *models.User) {
data["AppUrl"] = setting.AppUrl
data["BuildVersion"] = setting.BuildVersion
data["BuildStamp"] = setting.BuildStamp
......
......@@ -12,7 +12,7 @@ import (
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/events"
"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/registry"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util"
......@@ -100,7 +100,7 @@ func (ns *NotificationService) Run(ctx context.Context) error {
}
}
func (ns *NotificationService) SendWebhookSync(ctx context.Context, cmd *m.SendWebhookSync) error {
func (ns *NotificationService) SendWebhookSync(ctx context.Context, cmd *models.SendWebhookSync) error {
return ns.sendWebRequestSync(ctx, &Webhook{
Url: cmd.Url,
User: cmd.User,
......@@ -117,8 +117,8 @@ func subjectTemplateFunc(obj map[string]interface{}, value string) string {
return ""
}
func (ns *NotificationService) sendEmailCommandHandlerSync(ctx context.Context, cmd *m.SendEmailCommandSync) error {
message, err := ns.buildEmailMessage(&m.SendEmailCommand{
func (ns *NotificationService) sendEmailCommandHandlerSync(ctx context.Context, cmd *models.SendEmailCommandSync) error {
message, err := ns.buildEmailMessage(&models.SendEmailCommand{
Data: cmd.Data,
Info: cmd.Info,
Template: cmd.Template,
......@@ -136,7 +136,7 @@ func (ns *NotificationService) sendEmailCommandHandlerSync(ctx context.Context,
return err
}
func (ns *NotificationService) sendEmailCommandHandler(cmd *m.SendEmailCommand) error {
func (ns *NotificationService) sendEmailCommandHandler(cmd *models.SendEmailCommand) error {
message, err := ns.buildEmailMessage(cmd)
if err != nil {
......@@ -147,12 +147,12 @@ func (ns *NotificationService) sendEmailCommandHandler(cmd *m.SendEmailCommand)
return nil
}
func (ns *NotificationService) sendResetPasswordEmail(cmd *m.SendResetPasswordEmailCommand) error {
func (ns *NotificationService) sendResetPasswordEmail(cmd *models.SendResetPasswordEmailCommand) error {
code, err := createUserEmailCode(cmd.User, nil)
if err != nil {
return err
}
return ns.sendEmailCommandHandler(&m.SendEmailCommand{
return ns.sendEmailCommandHandler(&models.SendEmailCommand{
To: []string{cmd.User.Email},
Template: tmplResetPassword,
Data: map[string]interface{}{
......@@ -162,13 +162,13 @@ func (ns *NotificationService) sendResetPasswordEmail(cmd *m.SendResetPasswordEm
})
}
func (ns *NotificationService) validateResetPasswordCode(query *m.ValidateResetPasswordCodeQuery) error {
func (ns *NotificationService) validateResetPasswordCode(query *models.ValidateResetPasswordCodeQuery) error {
login := getLoginForEmailCode(query.Code)
if login == "" {
return m.ErrInvalidEmailCode
return models.ErrInvalidEmailCode
}
userQuery := m.GetUserByLoginQuery{LoginOrEmail: login}
userQuery := models.GetUserByLoginQuery{LoginOrEmail: login}
if err := bus.Dispatch(&userQuery); err != nil {
return err
}
......@@ -178,7 +178,7 @@ func (ns *NotificationService) validateResetPasswordCode(query *m.ValidateResetP
return err
}
if !validEmailCode {
return m.ErrInvalidEmailCode
return models.ErrInvalidEmailCode
}
query.Result = userQuery.Result
......@@ -196,7 +196,7 @@ func (ns *NotificationService) signUpStartedHandler(evt *events.SignUpStarted) e
return nil
}
err := ns.sendEmailCommandHandler(&m.SendEmailCommand{
err := ns.sendEmailCommandHandler(&models.SendEmailCommand{
To: []string{evt.Email},
Template: tmplSignUpStarted,
Data: map[string]interface{}{
......@@ -210,7 +210,7 @@ func (ns *NotificationService) signUpStartedHandler(evt *events.SignUpStarted) e
return err
}
emailSentCmd := m.UpdateTempUserWithEmailSentCommand{Code: evt.Code}
emailSentCmd := models.UpdateTempUserWithEmailSentCommand{Code: evt.Code}
return bus.Dispatch(&emailSentCmd)
}
......@@ -219,7 +219,7 @@ func (ns *NotificationService) signUpCompletedHandler(evt *events.SignUpComplete
return nil
}
return ns.sendEmailCommandHandler(&m.SendEmailCommand{
return ns.sendEmailCommandHandler(&models.SendEmailCommand{
To: []string{evt.Email},
Template: tmplWelcomeOnSignUp,
Data: map[string]interface{}{
......
......@@ -4,7 +4,7 @@ import (
"testing"
"github.com/grafana/grafana/pkg/bus"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/setting"
. "github.com/smartystreets/goconvey/convey"
)
......@@ -26,7 +26,7 @@ func TestNotifications(t *testing.T) {
So(err, ShouldBeNil)
Convey("When sending reset email password", func() {
err := ns.sendResetPasswordEmail(&m.SendResetPasswordEmailCommand{User: &m.User{Email: "asd@asd.com"}})
err := ns.sendResetPasswordEmail(&models.SendResetPasswordEmailCommand{User: &models.User{Email: "asd@asd.com"}})
So(err, ShouldBeNil)
sentMsg := <-ns.mailQueue
......
......@@ -5,7 +5,7 @@ import (
"testing"
"github.com/grafana/grafana/pkg/bus"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/setting"
. "github.com/smartystreets/goconvey/convey"
)
......@@ -27,7 +27,7 @@ func TestEmailIntegrationTest(t *testing.T) {
So(err, ShouldBeNil)
Convey("When sending reset email password", func() {
cmd := &m.SendEmailCommand{
cmd := &models.SendEmailCommand{
Data: map[string]interface{}{
"Title": "[CRITICAL] Imaginary timeserie alert",
......
......@@ -8,7 +8,7 @@ import (
"strings"
"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/alerting"
"gopkg.in/yaml.v2"
)
......@@ -147,7 +147,7 @@ func validateNotifications(notifications []*notificationsAsConfig) error {
}
for _, notification := range notifications[i].Notifications {
_, err := alerting.InitNotifier(&m.AlertNotification{
_, err := alerting.InitNotifier(&models.AlertNotification{
Name: notification.Name,
Settings: notification.SettingsToJson(),
Type: notification.Type,
......
......@@ -5,7 +5,7 @@ import (
"testing"
"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/alerting"
"github.com/grafana/grafana/pkg/services/alerting/notifiers"
"github.com/grafana/grafana/pkg/services/sqlstore"
......@@ -120,7 +120,7 @@ func TestNotificationAsConfig(t *testing.T) {
if err != nil {
t.Fatalf("applyChanges return an error %v", err)
}
notificationsQuery := m.GetAllAlertNotificationsQuery{OrgId: 1}
notificationsQuery := models.GetAllAlertNotificationsQuery{OrgId: 1}
err = sqlstore.GetAllAlertNotifications(&notificationsQuery)
So(err, ShouldBeNil)
So(notificationsQuery.Result, ShouldNotBeNil)
......@@ -128,7 +128,7 @@ func TestNotificationAsConfig(t *testing.T) {
})
Convey("One notification in database with same name and uid", func() {
existingNotificationCmd := m.CreateAlertNotificationCommand{
existingNotificationCmd := models.CreateAlertNotificationCommand{
Name: "channel1",
OrgId: 1,
Uid: "notifier1",
......@@ -137,7 +137,7 @@ func TestNotificationAsConfig(t *testing.T) {
err := sqlstore.CreateAlertNotificationCommand(&existingNotificationCmd)
So(err, ShouldBeNil)
So(existingNotificationCmd.Result, ShouldNotBeNil)
notificationsQuery := m.GetAllAlertNotificationsQuery{OrgId: 1}
notificationsQuery := models.GetAllAlertNotificationsQuery{OrgId: 1}
err = sqlstore.GetAllAlertNotifications(&notificationsQuery)
So(err, ShouldBeNil)
So(notificationsQuery.Result, ShouldNotBeNil)
......@@ -171,7 +171,7 @@ func TestNotificationAsConfig(t *testing.T) {
err := dc.applyChanges(doubleNotificationsConfig)
Convey("should both be inserted", func() {
So(err, ShouldBeNil)
notificationsQuery := m.GetAllAlertNotificationsQuery{OrgId: 1}
notificationsQuery := models.GetAllAlertNotificationsQuery{OrgId: 1}
err = sqlstore.GetAllAlertNotifications(&notificationsQuery)
So(err, ShouldBeNil)
So(notificationsQuery.Result, ShouldNotBeNil)
......@@ -185,7 +185,7 @@ func TestNotificationAsConfig(t *testing.T) {
Convey("Two configured notification", func() {
Convey("two other notifications in database", func() {
existingNotificationCmd := m.CreateAlertNotificationCommand{
existingNotificationCmd := models.CreateAlertNotificationCommand{
Name: "channel0",
OrgId: 1,
Uid: "notifier0",
......@@ -193,7 +193,7 @@ func TestNotificationAsConfig(t *testing.T) {
}
err := sqlstore.CreateAlertNotificationCommand(&existingNotificationCmd)
So(err, ShouldBeNil)
existingNotificationCmd = m.CreateAlertNotificationCommand{
existingNotificationCmd = models.CreateAlertNotificationCommand{
Name: "channel3",
OrgId: 1,
Uid: "notifier3",
......@@ -202,7 +202,7 @@ func TestNotificationAsConfig(t *testing.T) {
err = sqlstore.CreateAlertNotificationCommand(&existingNotificationCmd)
So(err, ShouldBeNil)
notificationsQuery := m.GetAllAlertNotificationsQuery{OrgId: 1}
notificationsQuery := models.GetAllAlertNotificationsQuery{OrgId: 1}
err = sqlstore.GetAllAlertNotifications(&notificationsQuery)
So(err, ShouldBeNil)
So(notificationsQuery.Result, ShouldNotBeNil)
......@@ -214,7 +214,7 @@ func TestNotificationAsConfig(t *testing.T) {
if err != nil {
t.Fatalf("applyChanges return an error %v", err)
}
notificationsQuery = m.GetAllAlertNotificationsQuery{OrgId: 1}
notificationsQuery = models.GetAllAlertNotificationsQuery{OrgId: 1}
err = sqlstore.GetAllAlertNotifications(&notificationsQuery)
So(err, ShouldBeNil)
So(notificationsQuery.Result, ShouldNotBeNil)
......@@ -224,16 +224,16 @@ func TestNotificationAsConfig(t *testing.T) {
})
Convey("Can read correct properties with orgName instead of orgId", func() {
existingOrg1 := m.CreateOrgCommand{Name: "Main Org. 1"}
existingOrg1 := models.CreateOrgCommand{Name: "Main Org. 1"}
err := sqlstore.CreateOrg(&existingOrg1)
So(err, ShouldBeNil)
So(existingOrg1.Result, ShouldNotBeNil)
existingOrg2 := m.CreateOrgCommand{Name: "Main Org. 2"}
existingOrg2 := models.CreateOrgCommand{Name: "Main Org. 2"}
err = sqlstore.CreateOrg(&existingOrg2)
So(err, ShouldBeNil)
So(existingOrg2.Result, ShouldNotBeNil)
existingNotificationCmd := m.CreateAlertNotificationCommand{
existingNotificationCmd := models.CreateAlertNotificationCommand{
Name: "default-notification-delete",
OrgId: existingOrg2.Result.Id,
Uid: "notifier2",
......@@ -248,7 +248,7 @@ func TestNotificationAsConfig(t *testing.T) {
t.Fatalf("applyChanges return an error %v", err)
}
notificationsQuery := m.GetAllAlertNotificationsQuery{OrgId: existingOrg2.Result.Id}
notificationsQuery := models.GetAllAlertNotificationsQuery{OrgId: existingOrg2.Result.Id}
err = sqlstore.GetAllAlertNotifications(&notificationsQuery)
So(err, ShouldBeNil)
So(notificationsQuery.Result, ShouldNotBeNil)
......@@ -279,7 +279,7 @@ func TestNotificationAsConfig(t *testing.T) {
if err != nil {
t.Fatalf("applyChanges return an error %v", err)
}
notificationsQuery := m.GetAllAlertNotificationsQuery{OrgId: 1}
notificationsQuery := models.GetAllAlertNotificationsQuery{OrgId: 1}
err = sqlstore.GetAllAlertNotifications(&notificationsQuery)
So(err, ShouldBeNil)
So(notificationsQuery.Result, ShouldBeEmpty)
......
......@@ -2,7 +2,7 @@ package quota
import (
"github.com/grafana/grafana/pkg/bus"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/registry"
"github.com/grafana/grafana/pkg/setting"
)
......@@ -12,14 +12,14 @@ func init() {
}
type QuotaService struct {
AuthTokenService m.UserTokenService `inject:""`
AuthTokenService models.UserTokenService `inject:""`
}
func (qs *QuotaService) Init() error {
return nil
}
func (qs *QuotaService) QuotaReached(c *m.ReqContext, target string) (bool, error) {
func (qs *QuotaService) QuotaReached(c *models.ReqContext, target string) (bool, error) {
if !setting.Quota.Enabled {
return false, nil
}
......@@ -30,7 +30,7 @@ func (qs *QuotaService) QuotaReached(c *m.ReqContext, target string) (bool, erro
return false, nil
}
// get the list of scopes that this target is valid for. Org, User, Global
scopes, err := m.GetQuotaScopes(target)
scopes, err := models.GetQuotaScopes(target)
if err != nil {
return false, err
}
......@@ -59,7 +59,7 @@ func (qs *QuotaService) QuotaReached(c *m.ReqContext, target string) (bool, erro
}
continue
}
query := m.GetGlobalQuotaByTargetQuery{Target: scope.Target}
query := models.GetGlobalQuotaByTargetQuery{Target: scope.Target}
if err := bus.Dispatch(&query); err != nil {
return true, err
}
......@@ -70,7 +70,7 @@ func (qs *QuotaService) QuotaReached(c *m.ReqContext, target string) (bool, erro
if !c.IsSignedIn {
continue
}
query := m.GetOrgQuotaByTargetQuery{OrgId: c.OrgId, Target: scope.Target, Default: scope.DefaultLimit}
query := models.GetOrgQuotaByTargetQuery{OrgId: c.OrgId, Target: scope.Target, Default: scope.DefaultLimit}
if err := bus.Dispatch(&query); err != nil {
return true, err
}
......@@ -88,7 +88,7 @@ func (qs *QuotaService) QuotaReached(c *m.ReqContext, target string) (bool, erro
if !c.IsSignedIn || c.UserId == 0 {
continue
}
query := m.GetUserQuotaByTargetQuery{UserId: c.UserId, Target: scope.Target, Default: scope.DefaultLimit}
query := models.GetUserQuotaByTargetQuery{UserId: c.UserId, Target: scope.Target, Default: scope.DefaultLimit}
if err := bus.Dispatch(&query); err != nil {
return true, err
}
......
......@@ -7,7 +7,7 @@ import (
"time"
"github.com/grafana/grafana/pkg/bus"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/models"
)
// timeNow makes it possible to test usage of time
......@@ -24,8 +24,8 @@ func init() {
bus.AddHandler("sql", PauseAllAlerts)
}
func GetAlertById(query *m.GetAlertByIdQuery) error {
alert := m.Alert{}
func GetAlertById(query *models.GetAlertByIdQuery) error {
alert := models.Alert{}
has, err := x.ID(query.Id).Get(&alert)
if !has {
return fmt.Errorf("could not find alert")
......@@ -38,8 +38,8 @@ func GetAlertById(query *m.GetAlertByIdQuery) error {
return nil
}
func GetAllAlertQueryHandler(query *m.GetAllAlertsQuery) error {
var alerts []*m.Alert
func GetAllAlertQueryHandler(query *models.GetAllAlertsQuery) error {
var alerts []*models.Alert
err := x.SQL("select * from alert").Find(&alerts)
if err != nil {
return err
......@@ -71,7 +71,7 @@ func deleteAlertByIdInternal(alertId int64, reason string, sess *DBSession) erro
return nil
}
func HandleAlertsQuery(query *m.GetAlertsQuery) error {
func HandleAlertsQuery(query *models.GetAlertsQuery) error {
builder := SqlBuilder{}
builder.Write(`SELECT
......@@ -124,8 +124,8 @@ func HandleAlertsQuery(query *m.GetAlertsQuery) error {
builder.Write(")")
}
if query.User.OrgRole != m.ROLE_ADMIN {
builder.writeDashboardPermissionFilter(query.User, m.PERMISSION_VIEW)
if query.User.OrgRole != models.ROLE_ADMIN {
builder.writeDashboardPermissionFilter(query.User, models.PERMISSION_VIEW)
}
builder.Write(" ORDER BY name ASC")
......@@ -134,7 +134,7 @@ func HandleAlertsQuery(query *m.GetAlertsQuery) error {
builder.Write(dialect.Limit(query.Limit))
}
alerts := make([]*m.AlertListItemDTO, 0)
alerts := make([]*models.AlertListItemDTO, 0)
if err := x.SQL(builder.GetSqlString(), builder.params...).Find(&alerts); err != nil {
return err
}
......@@ -150,7 +150,7 @@ func HandleAlertsQuery(query *m.GetAlertsQuery) error {
}
func deleteAlertDefinition(dashboardId int64, sess *DBSession) error {
alerts := make([]*m.Alert, 0)
alerts := make([]*models.Alert, 0)
if err := sess.Where("dashboard_id = ?", dashboardId).Find(&alerts); err != nil {
return err
}
......@@ -166,7 +166,7 @@ func deleteAlertDefinition(dashboardId int64, sess *DBSession) error {
return nil
}
func SaveAlerts(cmd *m.SaveAlertsCommand) error {
func SaveAlerts(cmd *models.SaveAlertsCommand) error {
return inTransaction(func(sess *DBSession) error {
existingAlerts, err := GetAlertsByDashboardId2(cmd.DashboardId, sess)
if err != nil {
......@@ -185,10 +185,10 @@ func SaveAlerts(cmd *m.SaveAlertsCommand) error {
})
}
func updateAlerts(existingAlerts []*m.Alert, cmd *m.SaveAlertsCommand, sess *DBSession) error {
func updateAlerts(existingAlerts []*models.Alert, cmd *models.SaveAlertsCommand, sess *DBSession) error {
for _, alert := range cmd.Alerts {
update := false
var alertToUpdate *m.Alert
var alertToUpdate *models.Alert
for _, k := range existingAlerts {
if alert.PanelId == k.PanelId {
......@@ -215,7 +215,7 @@ func updateAlerts(existingAlerts []*m.Alert, cmd *m.SaveAlertsCommand, sess *DBS
} else {
alert.Updated = timeNow()
alert.Created = timeNow()
alert.State = m.AlertStateUnknown
alert.State = models.AlertStateUnknown
alert.NewStateDate = timeNow()
_, err := sess.Insert(alert)
......@@ -245,7 +245,7 @@ func updateAlerts(existingAlerts []*m.Alert, cmd *m.SaveAlertsCommand, sess *DBS
return nil
}
func deleteMissingAlerts(alerts []*m.Alert, cmd *m.SaveAlertsCommand, sess *DBSession) error {
func deleteMissingAlerts(alerts []*models.Alert, cmd *models.SaveAlertsCommand, sess *DBSession) error {
for _, missingAlert := range alerts {
missing := true
......@@ -268,20 +268,20 @@ func deleteMissingAlerts(alerts []*m.Alert, cmd *m.SaveAlertsCommand, sess *DBSe
return nil
}
func GetAlertsByDashboardId2(dashboardId int64, sess *DBSession) ([]*m.Alert, error) {
alerts := make([]*m.Alert, 0)
func GetAlertsByDashboardId2(dashboardId int64, sess *DBSession) ([]*models.Alert, error) {
alerts := make([]*models.Alert, 0)
err := sess.Where("dashboard_id = ?", dashboardId).Find(&alerts)
if err != nil {
return []*m.Alert{}, err
return []*models.Alert{}, err
}
return alerts, nil
}
func SetAlertState(cmd *m.SetAlertStateCommand) error {
func SetAlertState(cmd *models.SetAlertStateCommand) error {
return inTransaction(func(sess *DBSession) error {
alert := m.Alert{}
alert := models.Alert{}
if has, err := sess.ID(cmd.AlertId).Get(&alert); err != nil {
return err
......@@ -289,12 +289,12 @@ func SetAlertState(cmd *m.SetAlertStateCommand) error {
return fmt.Errorf("Could not find alert")
}
if alert.State == m.AlertStatePaused {
return m.ErrCannotChangeStateOnPausedAlert
if alert.State == models.AlertStatePaused {
return models.ErrCannotChangeStateOnPausedAlert
}
if alert.State == cmd.State {
return m.ErrRequiresNewState
return models.ErrRequiresNewState
}
alert.State = cmd.State
......@@ -318,7 +318,7 @@ func SetAlertState(cmd *m.SetAlertStateCommand) error {
})
}
func PauseAlert(cmd *m.PauseAlertCommand) error {
func PauseAlert(cmd *models.PauseAlertCommand) error {
return inTransaction(func(sess *DBSession) error {
if len(cmd.AlertIds) == 0 {
return fmt.Errorf("command contains no alertids")
......@@ -329,10 +329,10 @@ func PauseAlert(cmd *m.PauseAlertCommand) error {
buffer.WriteString(`UPDATE alert SET state = ?, new_state_date = ?`)
if cmd.Paused {
params = append(params, string(m.AlertStatePaused))
params = append(params, string(models.AlertStatePaused))
params = append(params, timeNow().UTC())
} else {
params = append(params, string(m.AlertStateUnknown))
params = append(params, string(models.AlertStateUnknown))
params = append(params, timeNow().UTC())
}
......@@ -352,13 +352,13 @@ func PauseAlert(cmd *m.PauseAlertCommand) error {
})
}
func PauseAllAlerts(cmd *m.PauseAllAlertCommand) error {
func PauseAllAlerts(cmd *models.PauseAllAlertCommand) error {
return inTransaction(func(sess *DBSession) error {
var newState string
if cmd.Paused {
newState = string(m.AlertStatePaused)
newState = string(models.AlertStatePaused)
} else {
newState = string(m.AlertStateUnknown)
newState = string(models.AlertStateUnknown)
}
res, err := sess.Exec(`UPDATE alert SET state = ?, new_state_date = ?`, newState, timeNow().UTC())
......@@ -370,7 +370,7 @@ func PauseAllAlerts(cmd *m.PauseAllAlertCommand) error {
})
}
func GetAlertStatesForDashboard(query *m.GetAlertStatesForDashboardQuery) error {
func GetAlertStatesForDashboard(query *models.GetAlertStatesForDashboardQuery) error {
var rawSql = `SELECT
id,
dashboard_id,
......@@ -380,7 +380,7 @@ func GetAlertStatesForDashboard(query *m.GetAlertStatesForDashboardQuery) error
FROM alert
WHERE org_id = ? AND dashboard_id = ?`
query.Result = make([]*m.AlertStateInfoDTO, 0)
query.Result = make([]*models.AlertStateInfoDTO, 0)
err := x.SQL(rawSql, query.OrgId, query.DashboardId).Find(&query.Result)
return err
......
......@@ -5,7 +5,7 @@ import (
"time"
"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"
)
......@@ -32,7 +32,7 @@ func TestAlertingDataAccess(t *testing.T) {
testDash := insertTestDashboard("dashboard with alerts", 1, 0, false, "alert")
evalData, _ := simplejson.NewJson([]byte(`{"test": "test"}`))
items := []*m.Alert{
items := []*models.Alert{
{
PanelId: 1,
DashboardId: testDash.Id,
......@@ -45,7 +45,7 @@ func TestAlertingDataAccess(t *testing.T) {
},
}
cmd := m.SaveAlertsCommand{
cmd := models.SaveAlertsCommand{
Alerts: items,
DashboardId: testDash.Id,
OrgId: 1,
......@@ -60,9 +60,9 @@ func TestAlertingDataAccess(t *testing.T) {
Convey("Can set new states", func() {
Convey("new state ok", func() {
cmd := &m.SetAlertStateCommand{
cmd := &models.SetAlertStateCommand{
AlertId: 1,
State: m.AlertStateOK,
State: models.AlertStateOK,
}
err = SetAlertState(cmd)
......@@ -77,9 +77,9 @@ func TestAlertingDataAccess(t *testing.T) {
So(err, ShouldBeNil)
Convey("cannot updated paused alert", func() {
cmd := &m.SetAlertStateCommand{
cmd := &models.SetAlertStateCommand{
AlertId: 1,
State: m.AlertStateOK,
State: models.AlertStateOK,
}
err = SetAlertState(cmd)
......@@ -109,7 +109,7 @@ func TestAlertingDataAccess(t *testing.T) {
})
Convey("Can read properties", func() {
alertQuery := m.GetAlertsQuery{DashboardIDs: []int64{testDash.Id}, PanelId: 1, OrgId: 1, User: &m.SignedInUser{OrgRole: m.ROLE_ADMIN}}
alertQuery := models.GetAlertsQuery{DashboardIDs: []int64{testDash.Id}, PanelId: 1, OrgId: 1, User: &models.SignedInUser{OrgRole: models.ROLE_ADMIN}}
err2 := HandleAlertsQuery(&alertQuery)
alert := alertQuery.Result[0]
......@@ -118,7 +118,7 @@ func TestAlertingDataAccess(t *testing.T) {
So(alert.DashboardId, ShouldEqual, testDash.Id)
So(alert.PanelId, ShouldEqual, 1)
So(alert.Name, ShouldEqual, "Alerting title")
So(alert.State, ShouldEqual, m.AlertStateUnknown)
So(alert.State, ShouldEqual, models.AlertStateUnknown)
So(alert.NewStateDate, ShouldNotBeNil)
So(alert.EvalData, ShouldNotBeNil)
So(alert.EvalData.Get("test").MustString(), ShouldEqual, "test")
......@@ -129,8 +129,8 @@ func TestAlertingDataAccess(t *testing.T) {
})
Convey("Viewer cannot read alerts", func() {
viewerUser := &m.SignedInUser{OrgRole: m.ROLE_VIEWER, OrgId: 1}
alertQuery := m.GetAlertsQuery{DashboardIDs: []int64{testDash.Id}, PanelId: 1, OrgId: 1, User: viewerUser}
viewerUser := &models.SignedInUser{OrgRole: models.ROLE_VIEWER, OrgId: 1}
alertQuery := models.GetAlertsQuery{DashboardIDs: []int64{testDash.Id}, PanelId: 1, OrgId: 1, User: viewerUser}
err2 := HandleAlertsQuery(&alertQuery)
So(err2, ShouldBeNil)
......@@ -141,7 +141,7 @@ func TestAlertingDataAccess(t *testing.T) {
modifiedItems := items
modifiedItems[0].Name = "Name"
modifiedCmd := m.SaveAlertsCommand{
modifiedCmd := models.SaveAlertsCommand{
DashboardId: testDash.Id,
OrgId: 1,
UserId: 1,
......@@ -155,7 +155,7 @@ func TestAlertingDataAccess(t *testing.T) {
})
Convey("Alerts should be updated", func() {
query := m.GetAlertsQuery{DashboardIDs: []int64{testDash.Id}, OrgId: 1, User: &m.SignedInUser{OrgRole: m.ROLE_ADMIN}}
query := models.GetAlertsQuery{DashboardIDs: []int64{testDash.Id}, OrgId: 1, User: &models.SignedInUser{OrgRole: models.ROLE_ADMIN}}
err2 := HandleAlertsQuery(&query)
So(err2, ShouldBeNil)
......@@ -163,7 +163,7 @@ func TestAlertingDataAccess(t *testing.T) {
So(query.Result[0].Name, ShouldEqual, "Name")
Convey("Alert state should not be updated", func() {
So(query.Result[0].State, ShouldEqual, m.AlertStateUnknown)
So(query.Result[0].State, ShouldEqual, models.AlertStateUnknown)
})
})
......@@ -174,7 +174,7 @@ func TestAlertingDataAccess(t *testing.T) {
})
Convey("Multiple alerts per dashboard", func() {
multipleItems := []*m.Alert{
multipleItems := []*models.Alert{
{
DashboardId: testDash.Id,
PanelId: 1,
......@@ -204,7 +204,7 @@ func TestAlertingDataAccess(t *testing.T) {
Convey("Should save 3 dashboards", func() {
So(err, ShouldBeNil)
queryForDashboard := m.GetAlertsQuery{DashboardIDs: []int64{testDash.Id}, OrgId: 1, User: &m.SignedInUser{OrgRole: m.ROLE_ADMIN}}
queryForDashboard := models.GetAlertsQuery{DashboardIDs: []int64{testDash.Id}, OrgId: 1, User: &models.SignedInUser{OrgRole: models.ROLE_ADMIN}}
err2 := HandleAlertsQuery(&queryForDashboard)
So(err2, ShouldBeNil)
......@@ -218,7 +218,7 @@ func TestAlertingDataAccess(t *testing.T) {
err = SaveAlerts(&cmd)
Convey("should delete the missing alert", func() {
query := m.GetAlertsQuery{DashboardIDs: []int64{testDash.Id}, OrgId: 1, User: &m.SignedInUser{OrgRole: m.ROLE_ADMIN}}
query := models.GetAlertsQuery{DashboardIDs: []int64{testDash.Id}, OrgId: 1, User: &models.SignedInUser{OrgRole: models.ROLE_ADMIN}}
err2 := HandleAlertsQuery(&query)
So(err2, ShouldBeNil)
So(len(query.Result), ShouldEqual, 2)
......@@ -227,7 +227,7 @@ func TestAlertingDataAccess(t *testing.T) {
})
Convey("When dashboard is removed", func() {
items := []*m.Alert{
items := []*models.Alert{
{
PanelId: 1,
DashboardId: testDash.Id,
......@@ -236,7 +236,7 @@ func TestAlertingDataAccess(t *testing.T) {
},
}
cmd := m.SaveAlertsCommand{
cmd := models.SaveAlertsCommand{
Alerts: items,
DashboardId: testDash.Id,
OrgId: 1,
......@@ -246,14 +246,14 @@ func TestAlertingDataAccess(t *testing.T) {
err = SaveAlerts(&cmd)
So(err, ShouldBeNil)
err = DeleteDashboard(&m.DeleteDashboardCommand{
err = DeleteDashboard(&models.DeleteDashboardCommand{
OrgId: 1,
Id: testDash.Id,
})
So(err, ShouldBeNil)
Convey("Alerts should be removed", func() {
query := m.GetAlertsQuery{DashboardIDs: []int64{testDash.Id}, OrgId: 1, User: &m.SignedInUser{OrgRole: m.ROLE_ADMIN}}
query := models.GetAlertsQuery{DashboardIDs: []int64{testDash.Id}, OrgId: 1, User: &models.SignedInUser{OrgRole: models.ROLE_ADMIN}}
err2 := HandleAlertsQuery(&query)
So(testDash.Id, ShouldEqual, 1)
......@@ -304,7 +304,7 @@ func TestPausingAlerts(t *testing.T) {
})
}
func pauseAlert(orgId int64, alertId int64, pauseState bool) (int64, error) {
cmd := &m.PauseAlertCommand{
cmd := &models.PauseAlertCommand{
OrgId: orgId,
AlertIds: []int64{alertId},
Paused: pauseState,
......@@ -313,8 +313,8 @@ func pauseAlert(orgId int64, alertId int64, pauseState bool) (int64, error) {
So(err, ShouldBeNil)
return cmd.ResultCount, err
}
func insertTestAlert(title string, message string, orgId int64, dashId int64, settings *simplejson.Json) (*m.Alert, error) {
items := []*m.Alert{
func insertTestAlert(title string, message string, orgId int64, dashId int64, settings *simplejson.Json) (*models.Alert, error) {
items := []*models.Alert{
{
PanelId: 1,
DashboardId: dashId,
......@@ -326,7 +326,7 @@ func insertTestAlert(title string, message string, orgId int64, dashId int64, se
},
}
cmd := m.SaveAlertsCommand{
cmd := models.SaveAlertsCommand{
Alerts: items,
DashboardId: dashId,
OrgId: orgId,
......@@ -337,8 +337,8 @@ func insertTestAlert(title string, message string, orgId int64, dashId int64, se
return cmd.Alerts[0], err
}
func getAlertById(id int64) (*m.Alert, error) {
q := &m.GetAlertByIdQuery{
func getAlertById(id int64) (*models.Alert, error) {
q := &models.GetAlertByIdQuery{
Id: id,
}
err := GetAlertById(q)
......@@ -347,7 +347,7 @@ func getAlertById(id int64) (*m.Alert, error) {
}
func pauseAllAlerts(pauseState bool) error {
cmd := &m.PauseAllAlertCommand{
cmd := &models.PauseAllAlertCommand{
Paused: pauseState,
}
err := PauseAllAlerts(cmd)
......
......@@ -2,7 +2,7 @@ package sqlstore
import (
"github.com/grafana/grafana/pkg/bus"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/models"
)
func init() {
......@@ -10,7 +10,7 @@ func init() {
bus.AddHandler("sql", GetDashboardAclInfoList)
}
func UpdateDashboardAcl(cmd *m.UpdateDashboardAclCommand) error {
func UpdateDashboardAcl(cmd *models.UpdateDashboardAclCommand) error {
return inTransaction(func(sess *DBSession) error {
// delete existing items
_, err := sess.Exec("DELETE FROM dashboard_acl WHERE dashboard_id=?", cmd.DashboardId)
......@@ -20,11 +20,11 @@ func UpdateDashboardAcl(cmd *m.UpdateDashboardAclCommand) error {
for _, item := range cmd.Items {
if item.UserId == 0 && item.TeamId == 0 && (item.Role == nil || !item.Role.IsValid()) {
return m.ErrDashboardAclInfoMissing
return models.ErrDashboardAclInfoMissing
}
if item.DashboardId == 0 {
return m.ErrDashboardPermissionDashboardEmpty
return models.ErrDashboardPermissionDashboardEmpty
}
sess.Nullable("user_id", "team_id")
......@@ -34,7 +34,7 @@ func UpdateDashboardAcl(cmd *m.UpdateDashboardAclCommand) error {
}
// Update dashboard HasAcl flag
dashboard := m.Dashboard{HasAcl: true}
dashboard := models.Dashboard{HasAcl: true}
_, err = sess.Cols("has_acl").Where("id=?", cmd.DashboardId).Update(&dashboard)
return err
})
......@@ -45,7 +45,7 @@ func UpdateDashboardAcl(cmd *m.UpdateDashboardAclCommand) error {
// 1) Permissions for the dashboard
// 2) permissions for its parent folder
// 3) if no specific permissions have been set for the dashboard or its parent folder then get the default permissions
func GetDashboardAclInfoList(query *m.GetDashboardAclInfoListQuery) error {
func GetDashboardAclInfoList(query *models.GetDashboardAclInfoListQuery) error {
var err error
falseStr := dialect.BooleanStr(false)
......@@ -71,7 +71,7 @@ func GetDashboardAclInfoList(query *m.GetDashboardAclInfoListQuery) error {
falseStr + ` AS inherited
FROM dashboard_acl as da
WHERE da.dashboard_id = -1`
query.Result = make([]*m.DashboardAclInfoDTO, 0)
query.Result = make([]*models.DashboardAclInfoDTO, 0)
err = x.SQL(sql).Find(&query.Result)
} else {
......@@ -115,7 +115,7 @@ func GetDashboardAclInfoList(query *m.GetDashboardAclInfoListQuery) error {
ORDER BY da.id ASC
`
query.Result = make([]*m.DashboardAclInfoDTO, 0)
query.Result = make([]*models.DashboardAclInfoDTO, 0)
err = x.SQL(rawSQL, query.OrgId, query.DashboardId).Find(&query.Result)
}
......
......@@ -4,7 +4,7 @@ import (
"time"
"github.com/grafana/grafana/pkg/bus"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/setting"
)
......@@ -19,7 +19,7 @@ func init() {
// DeleteExpiredSnapshots removes snapshots with old expiry dates.
// SnapShotRemoveExpired is deprecated and should be removed in the future.
// Snapshot expiry is decided by the user when they share the snapshot.
func DeleteExpiredSnapshots(cmd *m.DeleteExpiredSnapshotsCommand) error {
func DeleteExpiredSnapshots(cmd *models.DeleteExpiredSnapshotsCommand) error {
return inTransaction(func(sess *DBSession) error {
if !setting.SnapShotRemoveExpired {
sqlog.Warn("[Deprecated] The snapshot_remove_expired setting is outdated. Please remove from your config.")
......@@ -37,7 +37,7 @@ func DeleteExpiredSnapshots(cmd *m.DeleteExpiredSnapshotsCommand) error {
})
}
func CreateDashboardSnapshot(cmd *m.CreateDashboardSnapshotCommand) error {
func CreateDashboardSnapshot(cmd *models.CreateDashboardSnapshotCommand) error {
return inTransaction(func(sess *DBSession) error {
// never
......@@ -46,7 +46,7 @@ func CreateDashboardSnapshot(cmd *m.CreateDashboardSnapshotCommand) error {
expires = time.Now().Add(time.Second * time.Duration(cmd.Expires))
}
snapshot := &m.DashboardSnapshot{
snapshot := &models.DashboardSnapshot{
Name: cmd.Name,
Key: cmd.Key,
DeleteKey: cmd.DeleteKey,
......@@ -68,7 +68,7 @@ func CreateDashboardSnapshot(cmd *m.CreateDashboardSnapshotCommand) error {
})
}
func DeleteDashboardSnapshot(cmd *m.DeleteDashboardSnapshotCommand) error {
func DeleteDashboardSnapshot(cmd *models.DeleteDashboardSnapshotCommand) error {
return inTransaction(func(sess *DBSession) error {
var rawSql = "DELETE FROM dashboard_snapshot WHERE delete_key=?"
_, err := sess.Exec(rawSql, cmd.DeleteKey)
......@@ -76,14 +76,14 @@ func DeleteDashboardSnapshot(cmd *m.DeleteDashboardSnapshotCommand) error {
})
}
func GetDashboardSnapshot(query *m.GetDashboardSnapshotQuery) error {
snapshot := m.DashboardSnapshot{Key: query.Key, DeleteKey: query.DeleteKey}
func GetDashboardSnapshot(query *models.GetDashboardSnapshotQuery) error {
snapshot := models.DashboardSnapshot{Key: query.Key, DeleteKey: query.DeleteKey}
has, err := x.Get(&snapshot)
if err != nil {
return err
} else if !has {
return m.ErrDashboardSnapshotNotFound
return models.ErrDashboardSnapshotNotFound
}
query.Result = &snapshot
......@@ -92,8 +92,8 @@ func GetDashboardSnapshot(query *m.GetDashboardSnapshotQuery) error {
// SearchDashboardSnapshots returns a list of all snapshots for admins
// for other roles, it returns snapshots created by the user
func SearchDashboardSnapshots(query *m.GetDashboardSnapshotsQuery) error {
var snapshots = make(m.DashboardSnapshotsList, 0)
func SearchDashboardSnapshots(query *models.GetDashboardSnapshotsQuery) error {
var snapshots = make(models.DashboardSnapshotsList, 0)
sess := x.Limit(query.Limit)
sess.Table("dashboard_snapshot")
......@@ -103,7 +103,7 @@ func SearchDashboardSnapshots(query *m.GetDashboardSnapshotsQuery) error {
}
// admins can see all snapshots, everyone else can only see their own snapshots
if query.SignedInUser.OrgRole == m.ROLE_ADMIN {
if query.SignedInUser.OrgRole == models.ROLE_ADMIN {
sess.Where("org_id = ?", query.OrgId)
} else if !query.SignedInUser.IsAnonymous {
sess.Where("org_id = ? AND user_id = ?", query.OrgId, query.SignedInUser.UserId)
......
......@@ -7,7 +7,7 @@ import (
. "github.com/smartystreets/goconvey/convey"
"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/setting"
)
......@@ -17,7 +17,7 @@ func TestDashboardSnapshotDBAccess(t *testing.T) {
InitTestDB(t)
Convey("Given saved snapshot", func() {
cmd := m.CreateDashboardSnapshotCommand{
cmd := models.CreateDashboardSnapshotCommand{
Key: "hej",
Dashboard: simplejson.NewFromAny(map[string]interface{}{
"hello": "mupp",
......@@ -29,7 +29,7 @@ func TestDashboardSnapshotDBAccess(t *testing.T) {
So(err, ShouldBeNil)
Convey("Should be able to get snapshot by key", func() {
query := m.GetDashboardSnapshotQuery{Key: "hej"}
query := models.GetDashboardSnapshotQuery{Key: "hej"}
err = GetDashboardSnapshot(&query)
So(err, ShouldBeNil)
......@@ -39,9 +39,9 @@ func TestDashboardSnapshotDBAccess(t *testing.T) {
Convey("And the user has the admin role", func() {
Convey("Should return all the snapshots", func() {
query := m.GetDashboardSnapshotsQuery{
query := models.GetDashboardSnapshotsQuery{
OrgId: 1,
SignedInUser: &m.SignedInUser{OrgRole: m.ROLE_ADMIN},
SignedInUser: &models.SignedInUser{OrgRole: models.ROLE_ADMIN},
}
err := SearchDashboardSnapshots(&query)
So(err, ShouldBeNil)
......@@ -53,9 +53,9 @@ func TestDashboardSnapshotDBAccess(t *testing.T) {
Convey("And the user has the editor role and has created a snapshot", func() {
Convey("Should return all the snapshots", func() {
query := m.GetDashboardSnapshotsQuery{
query := models.GetDashboardSnapshotsQuery{
OrgId: 1,
SignedInUser: &m.SignedInUser{OrgRole: m.ROLE_EDITOR, UserId: 1000},
SignedInUser: &models.SignedInUser{OrgRole: models.ROLE_EDITOR, UserId: 1000},
}
err := SearchDashboardSnapshots(&query)
So(err, ShouldBeNil)
......@@ -67,9 +67,9 @@ func TestDashboardSnapshotDBAccess(t *testing.T) {
Convey("And the user has the editor role and has not created any snapshot", func() {
Convey("Should not return any snapshots", func() {
query := m.GetDashboardSnapshotsQuery{
query := models.GetDashboardSnapshotsQuery{
OrgId: 1,
SignedInUser: &m.SignedInUser{OrgRole: m.ROLE_EDITOR, UserId: 2},
SignedInUser: &models.SignedInUser{OrgRole: models.ROLE_EDITOR, UserId: 2},
}
err := SearchDashboardSnapshots(&query)
So(err, ShouldBeNil)
......@@ -80,7 +80,7 @@ func TestDashboardSnapshotDBAccess(t *testing.T) {
})
Convey("And the user is anonymous", func() {
cmd := m.CreateDashboardSnapshotCommand{
cmd := models.CreateDashboardSnapshotCommand{
Key: "strangesnapshotwithuserid0",
DeleteKey: "adeletekey",
Dashboard: simplejson.NewFromAny(map[string]interface{}{
......@@ -93,9 +93,9 @@ func TestDashboardSnapshotDBAccess(t *testing.T) {
So(err, ShouldBeNil)
Convey("Should not return any snapshots", func() {
query := m.GetDashboardSnapshotsQuery{
query := models.GetDashboardSnapshotsQuery{
OrgId: 1,
SignedInUser: &m.SignedInUser{OrgRole: m.ROLE_EDITOR, IsAnonymous: true, UserId: 0},
SignedInUser: &models.SignedInUser{OrgRole: models.ROLE_EDITOR, IsAnonymous: true, UserId: 0},
}
err := SearchDashboardSnapshots(&query)
So(err, ShouldBeNil)
......@@ -118,12 +118,12 @@ func TestDeleteExpiredSnapshots(t *testing.T) {
createTestSnapshot(sqlstore, "key2", -1200)
createTestSnapshot(sqlstore, "key3", -1200)
err := DeleteExpiredSnapshots(&m.DeleteExpiredSnapshotsCommand{})
err := DeleteExpiredSnapshots(&models.DeleteExpiredSnapshotsCommand{})
So(err, ShouldBeNil)
query := m.GetDashboardSnapshotsQuery{
query := models.GetDashboardSnapshotsQuery{
OrgId: 1,
SignedInUser: &m.SignedInUser{OrgRole: m.ROLE_ADMIN},
SignedInUser: &models.SignedInUser{OrgRole: models.ROLE_ADMIN},
}
err = SearchDashboardSnapshots(&query)
So(err, ShouldBeNil)
......@@ -131,12 +131,12 @@ func TestDeleteExpiredSnapshots(t *testing.T) {
So(len(query.Result), ShouldEqual, 1)
So(query.Result[0].Key, ShouldEqual, notExpiredsnapshot.Key)
err = DeleteExpiredSnapshots(&m.DeleteExpiredSnapshotsCommand{})
err = DeleteExpiredSnapshots(&models.DeleteExpiredSnapshotsCommand{})
So(err, ShouldBeNil)
query = m.GetDashboardSnapshotsQuery{
query = models.GetDashboardSnapshotsQuery{
OrgId: 1,
SignedInUser: &m.SignedInUser{OrgRole: m.ROLE_ADMIN},
SignedInUser: &models.SignedInUser{OrgRole: models.ROLE_ADMIN},
}
err = SearchDashboardSnapshots(&query)
So(err, ShouldBeNil)
......@@ -146,8 +146,8 @@ func TestDeleteExpiredSnapshots(t *testing.T) {
})
}
func createTestSnapshot(sqlstore *SqlStore, key string, expires int64) *m.DashboardSnapshot {
cmd := m.CreateDashboardSnapshotCommand{
func createTestSnapshot(sqlstore *SqlStore, key string, expires int64) *models.DashboardSnapshot {
cmd := models.CreateDashboardSnapshotCommand{
Key: key,
DeleteKey: "delete" + key,
Dashboard: simplejson.NewFromAny(map[string]interface{}{
......
......@@ -4,7 +4,7 @@ import (
"strings"
"github.com/grafana/grafana/pkg/bus"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/setting"
)
......@@ -15,8 +15,8 @@ func init() {
}
// GetDashboardVersion gets the dashboard version for the given dashboard ID and version number.
func GetDashboardVersion(query *m.GetDashboardVersionQuery) error {
version := m.DashboardVersion{}
func GetDashboardVersion(query *models.GetDashboardVersionQuery) error {
version := models.DashboardVersion{}
has, err := x.Where("dashboard_version.dashboard_id=? AND dashboard_version.version=? AND dashboard.org_id=?", query.DashboardId, query.Version, query.OrgId).
Join("LEFT", "dashboard", `dashboard.id = dashboard_version.dashboard_id`).
Get(&version)
......@@ -26,7 +26,7 @@ func GetDashboardVersion(query *m.GetDashboardVersionQuery) error {
}
if !has {
return m.ErrDashboardVersionNotFound
return models.ErrDashboardVersionNotFound
}
version.Data.Set("id", version.DashboardId)
......@@ -35,7 +35,7 @@ func GetDashboardVersion(query *m.GetDashboardVersionQuery) error {
}
// GetDashboardVersions gets all dashboard versions for the given dashboard ID.
func GetDashboardVersions(query *m.GetDashboardVersionsQuery) error {
func GetDashboardVersions(query *models.GetDashboardVersionsQuery) error {
if query.Limit == 0 {
query.Limit = 1000
}
......@@ -62,14 +62,14 @@ func GetDashboardVersions(query *m.GetDashboardVersionsQuery) error {
}
if len(query.Result) < 1 {
return m.ErrNoVersionsForDashboardId
return models.ErrNoVersionsForDashboardId
}
return nil
}
const MAX_VERSIONS_TO_DELETE = 100
func DeleteExpiredVersions(cmd *m.DeleteExpiredVersionsCommand) error {
func DeleteExpiredVersions(cmd *models.DeleteExpiredVersionsCommand) error {
return inTransaction(func(sess *DBSession) error {
versionsToKeep := setting.DashboardVersionsToKeep
if versionsToKeep < 1 {
......
......@@ -7,14 +7,14 @@ import (
. "github.com/smartystreets/goconvey/convey"
"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/setting"
)
func updateTestDashboard(dashboard *m.Dashboard, data map[string]interface{}) {
func updateTestDashboard(dashboard *models.Dashboard, data map[string]interface{}) {
data["id"] = dashboard.Id
saveCmd := m.SaveDashboardCommand{
saveCmd := models.SaveDashboardCommand{
OrgId: dashboard.OrgId,
Overwrite: true,
Dashboard: simplejson.NewFromAny(data),
......@@ -31,7 +31,7 @@ func TestGetDashboardVersion(t *testing.T) {
Convey("Get a Dashboard ID and version ID", func() {
savedDash := insertTestDashboard("test dash 26", 1, 0, false, "diff")
query := m.GetDashboardVersionQuery{
query := models.GetDashboardVersionQuery{
DashboardId: savedDash.Id,
Version: savedDash.Version,
OrgId: 1,
......@@ -42,7 +42,7 @@ func TestGetDashboardVersion(t *testing.T) {
So(savedDash.Id, ShouldEqual, query.DashboardId)
So(savedDash.Version, ShouldEqual, query.Version)
dashCmd := m.GetDashboardQuery{
dashCmd := models.GetDashboardQuery{
OrgId: savedDash.OrgId,
Uid: savedDash.Uid,
}
......@@ -54,7 +54,7 @@ func TestGetDashboardVersion(t *testing.T) {
})
Convey("Attempt to get a version that doesn't exist", func() {
query := m.GetDashboardVersionQuery{
query := models.GetDashboardVersionQuery{
DashboardId: int64(999),
Version: 123,
OrgId: 1,
......@@ -62,7 +62,7 @@ func TestGetDashboardVersion(t *testing.T) {
err := GetDashboardVersion(&query)
So(err, ShouldNotBeNil)
So(err, ShouldEqual, m.ErrDashboardVersionNotFound)
So(err, ShouldEqual, models.ErrDashboardVersionNotFound)
})
})
}
......@@ -73,7 +73,7 @@ func TestGetDashboardVersions(t *testing.T) {
savedDash := insertTestDashboard("test dash 43", 1, 0, false, "diff-all")
Convey("Get all versions for a given Dashboard ID", func() {
query := m.GetDashboardVersionsQuery{DashboardId: savedDash.Id, OrgId: 1}
query := models.GetDashboardVersionsQuery{DashboardId: savedDash.Id, OrgId: 1}
err := GetDashboardVersions(&query)
So(err, ShouldBeNil)
......@@ -81,11 +81,11 @@ func TestGetDashboardVersions(t *testing.T) {
})
Convey("Attempt to get the versions for a non-existent Dashboard ID", func() {
query := m.GetDashboardVersionsQuery{DashboardId: int64(999), OrgId: 1}
query := models.GetDashboardVersionsQuery{DashboardId: int64(999), OrgId: 1}
err := GetDashboardVersions(&query)
So(err, ShouldNotBeNil)
So(err, ShouldEqual, m.ErrNoVersionsForDashboardId)
So(err, ShouldEqual, models.ErrNoVersionsForDashboardId)
So(len(query.Result), ShouldEqual, 0)
})
......@@ -94,7 +94,7 @@ func TestGetDashboardVersions(t *testing.T) {
"tags": "different-tag",
})
query := m.GetDashboardVersionsQuery{DashboardId: savedDash.Id, OrgId: 1}
query := models.GetDashboardVersionsQuery{DashboardId: savedDash.Id, OrgId: 1}
err := GetDashboardVersions(&query)
So(err, ShouldBeNil)
......@@ -118,10 +118,10 @@ func TestDeleteExpiredVersions(t *testing.T) {
}
Convey("Clean up old dashboard versions", func() {
err := DeleteExpiredVersions(&m.DeleteExpiredVersionsCommand{})
err := DeleteExpiredVersions(&models.DeleteExpiredVersionsCommand{})
So(err, ShouldBeNil)
query := m.GetDashboardVersionsQuery{DashboardId: savedDash.Id, OrgId: 1}
query := models.GetDashboardVersionsQuery{DashboardId: savedDash.Id, OrgId: 1}
err = GetDashboardVersions(&query)
So(err, ShouldBeNil)
......@@ -134,10 +134,10 @@ func TestDeleteExpiredVersions(t *testing.T) {
Convey("Don't delete anything if there're no expired versions", func() {
setting.DashboardVersionsToKeep = versionsToWrite
err := DeleteExpiredVersions(&m.DeleteExpiredVersionsCommand{})
err := DeleteExpiredVersions(&models.DeleteExpiredVersionsCommand{})
So(err, ShouldBeNil)
query := m.GetDashboardVersionsQuery{DashboardId: savedDash.Id, OrgId: 1, Limit: versionsToWrite}
query := models.GetDashboardVersionsQuery{DashboardId: savedDash.Id, OrgId: 1, Limit: versionsToWrite}
err = GetDashboardVersions(&query)
So(err, ShouldBeNil)
......@@ -152,10 +152,10 @@ func TestDeleteExpiredVersions(t *testing.T) {
})
}
err := DeleteExpiredVersions(&m.DeleteExpiredVersionsCommand{})
err := DeleteExpiredVersions(&models.DeleteExpiredVersionsCommand{})
So(err, ShouldBeNil)
query := m.GetDashboardVersionsQuery{DashboardId: savedDash.Id, OrgId: 1, Limit: versionsToWriteBigNumber}
query := models.GetDashboardVersionsQuery{DashboardId: savedDash.Id, OrgId: 1, Limit: versionsToWriteBigNumber}
err = GetDashboardVersions(&query)
So(err, ShouldBeNil)
......
......@@ -4,13 +4,13 @@ import (
"time"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/models"
"github.com/go-xorm/xorm"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/components/securejsondata"
"github.com/grafana/grafana/pkg/infra/metrics"
m "github.com/grafana/grafana/pkg/models"
)
func init() {
......@@ -24,10 +24,10 @@ func init() {
bus.AddHandler("sql", GetDataSourceByName)
}
func GetDataSourceById(query *m.GetDataSourceByIdQuery) error {
func GetDataSourceById(query *models.GetDataSourceByIdQuery) error {
metrics.MDBDataSourceQueryByID.Inc()
datasource := m.DataSource{OrgId: query.OrgId, Id: query.Id}
datasource := models.DataSource{OrgId: query.OrgId, Id: query.Id}
has, err := x.Get(&datasource)
if err != nil {
......@@ -35,40 +35,40 @@ func GetDataSourceById(query *m.GetDataSourceByIdQuery) error {
}
if !has {
return m.ErrDataSourceNotFound
return models.ErrDataSourceNotFound
}
query.Result = &datasource
return err
}
func GetDataSourceByName(query *m.GetDataSourceByNameQuery) error {
datasource := m.DataSource{OrgId: query.OrgId, Name: query.Name}
func GetDataSourceByName(query *models.GetDataSourceByNameQuery) error {
datasource := models.DataSource{OrgId: query.OrgId, Name: query.Name}
has, err := x.Get(&datasource)
if !has {
return m.ErrDataSourceNotFound
return models.ErrDataSourceNotFound
}
query.Result = &datasource
return err
}
func GetDataSources(query *m.GetDataSourcesQuery) error {
func GetDataSources(query *models.GetDataSourcesQuery) error {
sess := x.Limit(5000, 0).Where("org_id=?", query.OrgId).Asc("name")
query.Result = make([]*m.DataSource, 0)
query.Result = make([]*models.DataSource, 0)
return sess.Find(&query.Result)
}
func GetAllDataSources(query *m.GetAllDataSourcesQuery) error {
func GetAllDataSources(query *models.GetAllDataSourcesQuery) error {
sess := x.Limit(5000, 0).Asc("name")
query.Result = make([]*m.DataSource, 0)
query.Result = make([]*models.DataSource, 0)
return sess.Find(&query.Result)
}
func DeleteDataSourceById(cmd *m.DeleteDataSourceByIdCommand) error {
func DeleteDataSourceById(cmd *models.DeleteDataSourceByIdCommand) error {
return inTransaction(func(sess *DBSession) error {
var rawSql = "DELETE FROM data_source WHERE id=? and org_id=?"
result, err := sess.Exec(rawSql, cmd.Id, cmd.OrgId)
......@@ -78,7 +78,7 @@ func DeleteDataSourceById(cmd *m.DeleteDataSourceByIdCommand) error {
})
}
func DeleteDataSourceByName(cmd *m.DeleteDataSourceByNameCommand) error {
func DeleteDataSourceByName(cmd *models.DeleteDataSourceByNameCommand) error {
return inTransaction(func(sess *DBSession) error {
var rawSql = "DELETE FROM data_source WHERE name=? and org_id=?"
result, err := sess.Exec(rawSql, cmd.Name, cmd.OrgId)
......@@ -88,20 +88,20 @@ func DeleteDataSourceByName(cmd *m.DeleteDataSourceByNameCommand) error {
})
}
func AddDataSource(cmd *m.AddDataSourceCommand) error {
func AddDataSource(cmd *models.AddDataSourceCommand) error {
return inTransaction(func(sess *DBSession) error {
existing := m.DataSource{OrgId: cmd.OrgId, Name: cmd.Name}
existing := models.DataSource{OrgId: cmd.OrgId, Name: cmd.Name}
has, _ := sess.Get(&existing)
if has {
return m.ErrDataSourceNameExists
return models.ErrDataSourceNameExists
}
if cmd.JsonData == nil {
cmd.JsonData = simplejson.New()
}
ds := &m.DataSource{
ds := &models.DataSource{
OrgId: cmd.OrgId,
Name: cmd.Name,
Type: cmd.Type,
......@@ -135,7 +135,7 @@ func AddDataSource(cmd *m.AddDataSourceCommand) error {
})
}
func updateIsDefaultFlag(ds *m.DataSource, sess *DBSession) error {
func updateIsDefaultFlag(ds *models.DataSource, sess *DBSession) error {
// Handle is default flag
if ds.IsDefault {
rawSql := "UPDATE data_source SET is_default=? WHERE org_id=? AND id <> ?"
......@@ -146,13 +146,13 @@ func updateIsDefaultFlag(ds *m.DataSource, sess *DBSession) error {
return nil
}
func UpdateDataSource(cmd *m.UpdateDataSourceCommand) error {
func UpdateDataSource(cmd *models.UpdateDataSourceCommand) error {
return inTransaction(func(sess *DBSession) error {
if cmd.JsonData == nil {
cmd.JsonData = simplejson.New()
}
ds := &m.DataSource{
ds := &models.DataSource{
Id: cmd.Id,
OrgId: cmd.OrgId,
Name: cmd.Name,
......@@ -200,7 +200,7 @@ func UpdateDataSource(cmd *m.UpdateDataSourceCommand) error {
}
if affected == 0 {
return m.ErrDataSourceUpdatingOldVersion
return models.ErrDataSourceUpdatingOldVersion
}
err = updateIsDefaultFlag(ds, sess)
......
......@@ -2,13 +2,13 @@ package sqlstore
import (
"github.com/grafana/grafana/pkg/bus"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/models"
)
func init() {
bus.AddHandler("sql", GetDBHealthQuery)
}
func GetDBHealthQuery(query *m.GetDBHealthQuery) error {
func GetDBHealthQuery(query *models.GetDBHealthQuery) error {
return x.Ping()
}
......@@ -5,7 +5,7 @@ import (
"time"
"github.com/grafana/grafana/pkg/bus"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/models"
)
var getTimeNow = time.Now
......@@ -16,9 +16,9 @@ func init() {
bus.AddHandler("sql", GetUserLoginAttemptCount)
}
func CreateLoginAttempt(cmd *m.CreateLoginAttemptCommand) error {
func CreateLoginAttempt(cmd *models.CreateLoginAttemptCommand) error {
return inTransaction(func(sess *DBSession) error {
loginAttempt := m.LoginAttempt{
loginAttempt := models.LoginAttempt{
Username: cmd.Username,
IpAddress: cmd.IpAddress,
Created: getTimeNow().Unix(),
......@@ -34,7 +34,7 @@ func CreateLoginAttempt(cmd *m.CreateLoginAttemptCommand) error {
})
}
func DeleteOldLoginAttempts(cmd *m.DeleteOldLoginAttemptsCommand) error {
func DeleteOldLoginAttempts(cmd *models.DeleteOldLoginAttemptsCommand) error {
return inTransaction(func(sess *DBSession) error {
var maxId int64
sql := "SELECT max(id) as id FROM login_attempt WHERE created < ?"
......@@ -66,8 +66,8 @@ func DeleteOldLoginAttempts(cmd *m.DeleteOldLoginAttemptsCommand) error {
})
}
func GetUserLoginAttemptCount(query *m.GetUserLoginAttemptCountQuery) error {
loginAttempt := new(m.LoginAttempt)
func GetUserLoginAttemptCount(query *models.GetUserLoginAttemptCountQuery) error {
loginAttempt := new(models.LoginAttempt)
total, err := x.
Where("username = ?", query.Username).
And("created >= ?", query.Since.Unix()).
......
......@@ -4,7 +4,7 @@ import (
"testing"
"time"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/models"
. "github.com/smartystreets/goconvey/convey"
)
......@@ -20,7 +20,7 @@ func TestLoginAttempts(t *testing.T) {
user := "user"
beginningOfTime := mockTime(time.Date(2017, 10, 22, 8, 0, 0, 0, time.Local))
err := CreateLoginAttempt(&m.CreateLoginAttemptCommand{
err := CreateLoginAttempt(&models.CreateLoginAttemptCommand{
Username: user,
IpAddress: "192.168.0.1",
})
......@@ -28,7 +28,7 @@ func TestLoginAttempts(t *testing.T) {
timePlusOneMinute := mockTime(beginningOfTime.Add(time.Minute * 1))
err = CreateLoginAttempt(&m.CreateLoginAttemptCommand{
err = CreateLoginAttempt(&models.CreateLoginAttemptCommand{
Username: user,
IpAddress: "192.168.0.1",
})
......@@ -36,14 +36,14 @@ func TestLoginAttempts(t *testing.T) {
timePlusTwoMinutes := mockTime(beginningOfTime.Add(time.Minute * 2))
err = CreateLoginAttempt(&m.CreateLoginAttemptCommand{
err = CreateLoginAttempt(&models.CreateLoginAttemptCommand{
Username: user,
IpAddress: "192.168.0.1",
})
So(err, ShouldBeNil)
Convey("Should return a total count of zero login attempts when comparing since beginning of time + 2min and 1s", func() {
query := m.GetUserLoginAttemptCountQuery{
query := models.GetUserLoginAttemptCountQuery{
Username: user,
Since: timePlusTwoMinutes.Add(time.Second * 1),
}
......@@ -53,7 +53,7 @@ func TestLoginAttempts(t *testing.T) {
})
Convey("Should return the total count of login attempts since beginning of time", func() {
query := m.GetUserLoginAttemptCountQuery{
query := models.GetUserLoginAttemptCountQuery{
Username: user,
Since: beginningOfTime,
}
......@@ -63,7 +63,7 @@ func TestLoginAttempts(t *testing.T) {
})
Convey("Should return the total count of login attempts since beginning of time + 1min", func() {
query := m.GetUserLoginAttemptCountQuery{
query := models.GetUserLoginAttemptCountQuery{
Username: user,
Since: timePlusOneMinute,
}
......@@ -73,7 +73,7 @@ func TestLoginAttempts(t *testing.T) {
})
Convey("Should return the total count of login attempts since beginning of time + 2min", func() {
query := m.GetUserLoginAttemptCountQuery{
query := models.GetUserLoginAttemptCountQuery{
Username: user,
Since: timePlusTwoMinutes,
}
......@@ -83,7 +83,7 @@ func TestLoginAttempts(t *testing.T) {
})
Convey("Should return deleted rows older than beginning of time", func() {
cmd := m.DeleteOldLoginAttemptsCommand{
cmd := models.DeleteOldLoginAttemptsCommand{
OlderThan: beginningOfTime,
}
err := DeleteOldLoginAttempts(&cmd)
......@@ -93,7 +93,7 @@ func TestLoginAttempts(t *testing.T) {
})
Convey("Should return deleted rows older than beginning of time + 1min", func() {
cmd := m.DeleteOldLoginAttemptsCommand{
cmd := models.DeleteOldLoginAttemptsCommand{
OlderThan: timePlusOneMinute,
}
err := DeleteOldLoginAttempts(&cmd)
......@@ -103,7 +103,7 @@ func TestLoginAttempts(t *testing.T) {
})
Convey("Should return deleted rows older than beginning of time + 2min", func() {
cmd := m.DeleteOldLoginAttemptsCommand{
cmd := models.DeleteOldLoginAttemptsCommand{
OlderThan: timePlusTwoMinutes,
}
err := DeleteOldLoginAttempts(&cmd)
......@@ -113,7 +113,7 @@ func TestLoginAttempts(t *testing.T) {
})
Convey("Should return deleted rows older than beginning of time + 2min and 1s", func() {
cmd := m.DeleteOldLoginAttemptsCommand{
cmd := models.DeleteOldLoginAttemptsCommand{
OlderThan: timePlusTwoMinutes.Add(time.Second * 1),
}
err := DeleteOldLoginAttempts(&cmd)
......
......@@ -7,7 +7,7 @@ import (
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/events"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/setting"
)
......@@ -23,8 +23,8 @@ func init() {
bus.AddHandler("sql", DeleteOrg)
}
func SearchOrgs(query *m.SearchOrgsQuery) error {
query.Result = make([]*m.OrgDTO, 0)
func SearchOrgs(query *models.SearchOrgsQuery) error {
query.Result = make([]*models.OrgDTO, 0)
sess := x.Table("org")
if query.Query != "" {
sess.Where("name LIKE ?", query.Query+"%")
......@@ -43,30 +43,30 @@ func SearchOrgs(query *m.SearchOrgsQuery) error {
return err
}
func GetOrgById(query *m.GetOrgByIdQuery) error {
var org m.Org
func GetOrgById(query *models.GetOrgByIdQuery) error {
var org models.Org
exists, err := x.Id(query.Id).Get(&org)
if err != nil {
return err
}
if !exists {
return m.ErrOrgNotFound
return models.ErrOrgNotFound
}
query.Result = &org
return nil
}
func GetOrgByName(query *m.GetOrgByNameQuery) error {
var org m.Org
func GetOrgByName(query *models.GetOrgByNameQuery) error {
var org models.Org
exists, err := x.Where("name=?", query.Name).Get(&org)
if err != nil {
return err
}
if !exists {
return m.ErrOrgNotFound
return models.ErrOrgNotFound
}
query.Result = &org
......@@ -75,7 +75,7 @@ func GetOrgByName(query *m.GetOrgByNameQuery) error {
func isOrgNameTaken(name string, existingId int64, sess *DBSession) (bool, error) {
// check if org name is taken
var org m.Org
var org models.Org
exists, err := sess.Where("name=?", name).Get(&org)
if err != nil {
......@@ -89,16 +89,16 @@ func isOrgNameTaken(name string, existingId int64, sess *DBSession) (bool, error
return false, nil
}
func CreateOrg(cmd *m.CreateOrgCommand) error {
func CreateOrg(cmd *models.CreateOrgCommand) error {
return inTransaction(func(sess *DBSession) error {
if isNameTaken, err := isOrgNameTaken(cmd.Name, 0, sess); err != nil {
return err
} else if isNameTaken {
return m.ErrOrgNameTaken
return models.ErrOrgNameTaken
}
org := m.Org{
org := models.Org{
Name: cmd.Name,
Created: time.Now(),
Updated: time.Now(),
......@@ -108,10 +108,10 @@ func CreateOrg(cmd *m.CreateOrgCommand) error {
return err
}
user := m.OrgUser{
user := models.OrgUser{
OrgId: org.Id,
UserId: cmd.UserId,
Role: m.ROLE_ADMIN,
Role: models.ROLE_ADMIN,
Created: time.Now(),
Updated: time.Now(),
}
......@@ -129,16 +129,16 @@ func CreateOrg(cmd *m.CreateOrgCommand) error {
})
}
func UpdateOrg(cmd *m.UpdateOrgCommand) error {
func UpdateOrg(cmd *models.UpdateOrgCommand) error {
return inTransaction(func(sess *DBSession) error {
if isNameTaken, err := isOrgNameTaken(cmd.Name, cmd.OrgId, sess); err != nil {
return err
} else if isNameTaken {
return m.ErrOrgNameTaken
return models.ErrOrgNameTaken
}
org := m.Org{
org := models.Org{
Name: cmd.Name,
Updated: time.Now(),
}
......@@ -150,7 +150,7 @@ func UpdateOrg(cmd *m.UpdateOrgCommand) error {
}
if affectedRows == 0 {
return m.ErrOrgNotFound
return models.ErrOrgNotFound
}
sess.publishAfterCommit(&events.OrgUpdated{
......@@ -163,9 +163,9 @@ func UpdateOrg(cmd *m.UpdateOrgCommand) error {
})
}
func UpdateOrgAddress(cmd *m.UpdateOrgAddressCommand) error {
func UpdateOrgAddress(cmd *models.UpdateOrgAddressCommand) error {
return inTransaction(func(sess *DBSession) error {
org := m.Org{
org := models.Org{
Address1: cmd.Address1,
Address2: cmd.Address2,
City: cmd.City,
......@@ -190,12 +190,12 @@ func UpdateOrgAddress(cmd *m.UpdateOrgAddressCommand) error {
})
}
func DeleteOrg(cmd *m.DeleteOrgCommand) error {
func DeleteOrg(cmd *models.DeleteOrgCommand) error {
return inTransaction(func(sess *DBSession) error {
if res, err := sess.Query("SELECT 1 from org WHERE id=?", cmd.Id); err != nil {
return err
} else if len(res) != 1 {
return m.ErrOrgNotFound
return models.ErrOrgNotFound
}
deletes := []string{
......@@ -221,7 +221,7 @@ func DeleteOrg(cmd *m.DeleteOrgCommand) error {
}
func getOrCreateOrg(sess *DBSession, orgName string) (int64, error) {
var org m.Org
var org models.Org
if setting.AutoAssignOrg {
has, err := sess.Where("id=?", setting.AutoAssignOrgId).Get(&org)
......
......@@ -6,7 +6,7 @@ import (
"time"
"github.com/grafana/grafana/pkg/bus"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/util"
)
......@@ -17,29 +17,29 @@ func init() {
bus.AddHandler("sql", UpdateOrgUser)
}
func AddOrgUser(cmd *m.AddOrgUserCommand) error {
func AddOrgUser(cmd *models.AddOrgUserCommand) error {
return inTransaction(func(sess *DBSession) error {
// check if user exists
var user m.User
var user models.User
if exists, err := sess.ID(cmd.UserId).Get(&user); err != nil {
return err
} else if !exists {
return m.ErrUserNotFound
return models.ErrUserNotFound
}
if res, err := sess.Query("SELECT 1 from org_user WHERE org_id=? and user_id=?", cmd.OrgId, user.Id); err != nil {
return err
} else if len(res) == 1 {
return m.ErrOrgUserAlreadyAdded
return models.ErrOrgUserAlreadyAdded
}
if res, err := sess.Query("SELECT 1 from org WHERE id=?", cmd.OrgId); err != nil {
return err
} else if len(res) != 1 {
return m.ErrOrgNotFound
return models.ErrOrgNotFound
}
entity := m.OrgUser{
entity := models.OrgUser{
OrgId: cmd.OrgId,
UserId: cmd.UserId,
Role: cmd.Role,
......@@ -52,7 +52,7 @@ func AddOrgUser(cmd *m.AddOrgUserCommand) error {
return err
}
var userOrgs []*m.UserOrgDTO
var userOrgs []*models.UserOrgDTO
sess.Table("org_user")
sess.Join("INNER", "org", "org_user.org_id=org.id")
sess.Where("org_user.user_id=? AND org_user.org_id=?", user.Id, user.OrgId)
......@@ -71,16 +71,16 @@ func AddOrgUser(cmd *m.AddOrgUserCommand) error {
})
}
func UpdateOrgUser(cmd *m.UpdateOrgUserCommand) error {
func UpdateOrgUser(cmd *models.UpdateOrgUserCommand) error {
return inTransaction(func(sess *DBSession) error {
var orgUser m.OrgUser
var orgUser models.OrgUser
exists, err := sess.Where("org_id=? AND user_id=?", cmd.OrgId, cmd.UserId).Get(&orgUser)
if err != nil {
return err
}
if !exists {
return m.ErrOrgUserNotFound
return models.ErrOrgUserNotFound
}
orgUser.Role = cmd.Role
......@@ -94,8 +94,8 @@ func UpdateOrgUser(cmd *m.UpdateOrgUserCommand) error {
})
}
func GetOrgUsers(query *m.GetOrgUsersQuery) error {
query.Result = make([]*m.OrgUserDTO, 0)
func GetOrgUsers(query *models.GetOrgUsersQuery) error {
query.Result = make([]*models.OrgUserDTO, 0)
sess := x.Table("org_user")
sess.Join("INNER", x.Dialect().Quote("user"), fmt.Sprintf("org_user.user_id=%s.id", x.Dialect().Quote("user")))
......@@ -142,14 +142,14 @@ func GetOrgUsers(query *m.GetOrgUsersQuery) error {
return nil
}
func RemoveOrgUser(cmd *m.RemoveOrgUserCommand) error {
func RemoveOrgUser(cmd *models.RemoveOrgUserCommand) error {
return inTransaction(func(sess *DBSession) error {
// check if user exists
var user m.User
var user models.User
if exists, err := sess.ID(cmd.UserId).Get(&user); err != nil {
return err
} else if !exists {
return m.ErrUserNotFound
return models.ErrUserNotFound
}
deletes := []string{
......@@ -171,7 +171,7 @@ func RemoveOrgUser(cmd *m.RemoveOrgUserCommand) error {
}
// check user other orgs and update user current org
var userOrgs []*m.UserOrgDTO
var userOrgs []*models.UserOrgDTO
sess.Table("org_user")
sess.Join("INNER", "org", "org_user.org_id=org.id")
sess.Where("org_user.user_id=?", user.Id)
......@@ -199,7 +199,7 @@ func RemoveOrgUser(cmd *m.RemoveOrgUserCommand) error {
}
} else if cmd.ShouldDeleteOrphanedUser {
// no other orgs, delete the full user
if err := deleteUserInTransaction(sess, &m.DeleteUserCommand{UserId: user.Id}); err != nil {
if err := deleteUserInTransaction(sess, &models.DeleteUserCommand{UserId: user.Id}); err != nil {
return err
}
......@@ -218,7 +218,7 @@ func validateOneAdminLeftInOrg(orgId int64, sess *DBSession) error {
}
if len(res) == 0 {
return m.ErrLastOrgAdmin
return models.ErrLastOrgAdmin
}
return err
......
......@@ -2,7 +2,7 @@ package sqlstore
import (
"github.com/grafana/grafana/pkg/bus"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/models"
)
func init() {
......@@ -14,8 +14,8 @@ func init() {
bus.AddHandler("sql", GetPlaylistItem)
}
func CreatePlaylist(cmd *m.CreatePlaylistCommand) error {
playlist := m.Playlist{
func CreatePlaylist(cmd *models.CreatePlaylistCommand) error {
playlist := models.Playlist{
Name: cmd.Name,
Interval: cmd.Interval,
OrgId: cmd.OrgId,
......@@ -26,9 +26,9 @@ func CreatePlaylist(cmd *m.CreatePlaylistCommand) error {
return err
}
playlistItems := make([]m.PlaylistItem, 0)
playlistItems := make([]models.PlaylistItem, 0)
for _, item := range cmd.Items {
playlistItems = append(playlistItems, m.PlaylistItem{
playlistItems = append(playlistItems, models.PlaylistItem{
PlaylistId: playlist.Id,
Type: item.Type,
Value: item.Value,
......@@ -43,21 +43,21 @@ func CreatePlaylist(cmd *m.CreatePlaylistCommand) error {
return err
}
func UpdatePlaylist(cmd *m.UpdatePlaylistCommand) error {
playlist := m.Playlist{
func UpdatePlaylist(cmd *models.UpdatePlaylistCommand) error {
playlist := models.Playlist{
Id: cmd.Id,
OrgId: cmd.OrgId,
Name: cmd.Name,
Interval: cmd.Interval,
}
existingPlaylist := x.Where("id = ? AND org_id = ?", cmd.Id, cmd.OrgId).Find(m.Playlist{})
existingPlaylist := x.Where("id = ? AND org_id = ?", cmd.Id, cmd.OrgId).Find(models.Playlist{})
if existingPlaylist == nil {
return m.ErrPlaylistNotFound
return models.ErrPlaylistNotFound
}
cmd.Result = &m.PlaylistDTO{
cmd.Result = &models.PlaylistDTO{
Id: playlist.Id,
OrgId: playlist.OrgId,
Name: playlist.Name,
......@@ -77,10 +77,10 @@ func UpdatePlaylist(cmd *m.UpdatePlaylistCommand) error {
return err
}
playlistItems := make([]m.PlaylistItem, 0)
playlistItems := make([]models.PlaylistItem, 0)
for index, item := range cmd.Items {
playlistItems = append(playlistItems, m.PlaylistItem{
playlistItems = append(playlistItems, models.PlaylistItem{
PlaylistId: playlist.Id,
Type: item.Type,
Value: item.Value,
......@@ -94,12 +94,12 @@ func UpdatePlaylist(cmd *m.UpdatePlaylistCommand) error {
return err
}
func GetPlaylist(query *m.GetPlaylistByIdQuery) error {
func GetPlaylist(query *models.GetPlaylistByIdQuery) error {
if query.Id == 0 {
return m.ErrCommandValidationFailed
return models.ErrCommandValidationFailed
}
playlist := m.Playlist{}
playlist := models.Playlist{}
_, err := x.ID(query.Id).Get(&playlist)
query.Result = &playlist
......@@ -107,9 +107,9 @@ func GetPlaylist(query *m.GetPlaylistByIdQuery) error {
return err
}
func DeletePlaylist(cmd *m.DeletePlaylistCommand) error {
func DeletePlaylist(cmd *models.DeletePlaylistCommand) error {
if cmd.Id == 0 {
return m.ErrCommandValidationFailed
return models.ErrCommandValidationFailed
}
return inTransaction(func(sess *DBSession) error {
......@@ -127,8 +127,8 @@ func DeletePlaylist(cmd *m.DeletePlaylistCommand) error {
})
}
func SearchPlaylists(query *m.GetPlaylistsQuery) error {
var playlists = make(m.Playlists, 0)
func SearchPlaylists(query *models.GetPlaylistsQuery) error {
var playlists = make(models.Playlists, 0)
sess := x.Limit(query.Limit)
......@@ -143,12 +143,12 @@ func SearchPlaylists(query *m.GetPlaylistsQuery) error {
return err
}
func GetPlaylistItem(query *m.GetPlaylistItemsByIdQuery) error {
func GetPlaylistItem(query *models.GetPlaylistItemsByIdQuery) error {
if query.PlaylistId == 0 {
return m.ErrCommandValidationFailed
return models.ErrCommandValidationFailed
}
var playlistItems = make([]m.PlaylistItem, 0)
var playlistItems = make([]models.PlaylistItem, 0)
err := x.Where("playlist_id=?", query.PlaylistId).Find(&playlistItems)
query.Result = &playlistItems
......
......@@ -5,7 +5,7 @@ import (
. "github.com/smartystreets/goconvey/convey"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/models"
)
func TestPlaylistDataAccess(t *testing.T) {
......@@ -14,26 +14,26 @@ func TestPlaylistDataAccess(t *testing.T) {
InitTestDB(t)
Convey("Can create playlist", func() {
items := []m.PlaylistItemDTO{
items := []models.PlaylistItemDTO{
{Title: "graphite", Value: "graphite", Type: "dashboard_by_tag"},
{Title: "Backend response times", Value: "3", Type: "dashboard_by_id"},
}
cmd := m.CreatePlaylistCommand{Name: "NYC office", Interval: "10m", OrgId: 1, Items: items}
cmd := models.CreatePlaylistCommand{Name: "NYC office", Interval: "10m", OrgId: 1, Items: items}
err := CreatePlaylist(&cmd)
So(err, ShouldBeNil)
Convey("can update playlist", func() {
items := []m.PlaylistItemDTO{
items := []models.PlaylistItemDTO{
{Title: "influxdb", Value: "influxdb", Type: "dashboard_by_tag"},
{Title: "Backend response times", Value: "2", Type: "dashboard_by_id"},
}
query := m.UpdatePlaylistCommand{Name: "NYC office ", OrgId: 1, Id: 1, Interval: "10s", Items: items}
query := models.UpdatePlaylistCommand{Name: "NYC office ", OrgId: 1, Id: 1, Interval: "10s", Items: items}
err = UpdatePlaylist(&query)
So(err, ShouldBeNil)
Convey("can remove playlist", func() {
query := m.DeletePlaylistCommand{Id: 1}
query := models.DeletePlaylistCommand{Id: 1}
err = DeletePlaylist(&query)
So(err, ShouldBeNil)
......
......@@ -4,7 +4,7 @@ import (
"time"
"github.com/grafana/grafana/pkg/bus"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util"
)
......@@ -16,7 +16,7 @@ func init() {
bus.AddHandler("sql", UpdatePluginSettingVersion)
}
func GetPluginSettings(query *m.GetPluginSettingsQuery) error {
func GetPluginSettings(query *models.GetPluginSettingsQuery) error {
sql := `SELECT org_id, plugin_id, enabled, pinned, plugin_version
FROM plugin_setting `
params := make([]interface{}, 0)
......@@ -27,25 +27,25 @@ func GetPluginSettings(query *m.GetPluginSettingsQuery) error {
}
sess := x.SQL(sql, params...)
query.Result = make([]*m.PluginSettingInfoDTO, 0)
query.Result = make([]*models.PluginSettingInfoDTO, 0)
return sess.Find(&query.Result)
}
func GetPluginSettingById(query *m.GetPluginSettingByIdQuery) error {
pluginSetting := m.PluginSetting{OrgId: query.OrgId, PluginId: query.PluginId}
func GetPluginSettingById(query *models.GetPluginSettingByIdQuery) error {
pluginSetting := models.PluginSetting{OrgId: query.OrgId, PluginId: query.PluginId}
has, err := x.Get(&pluginSetting)
if err != nil {
return err
} else if !has {
return m.ErrPluginSettingNotFound
return models.ErrPluginSettingNotFound
}
query.Result = &pluginSetting
return nil
}
func UpdatePluginSetting(cmd *m.UpdatePluginSettingCmd) error {
func UpdatePluginSetting(cmd *models.UpdatePluginSettingCmd) error {
return inTransaction(func(sess *DBSession) error {
var pluginSetting m.PluginSetting
var pluginSetting models.PluginSetting
exists, err := sess.Where("org_id=? and plugin_id=?", cmd.OrgId, cmd.PluginId).Get(&pluginSetting)
if err != nil {
......@@ -54,7 +54,7 @@ func UpdatePluginSetting(cmd *m.UpdatePluginSettingCmd) error {
sess.UseBool("enabled")
sess.UseBool("pinned")
if !exists {
pluginSetting = m.PluginSetting{
pluginSetting = models.PluginSetting{
PluginId: cmd.PluginId,
OrgId: cmd.OrgId,
Enabled: cmd.Enabled,
......@@ -67,7 +67,7 @@ func UpdatePluginSetting(cmd *m.UpdatePluginSettingCmd) error {
}
// add state change event on commit success
sess.events = append(sess.events, &m.PluginStateChangedEvent{
sess.events = append(sess.events, &models.PluginStateChangedEvent{
PluginId: cmd.PluginId,
OrgId: cmd.OrgId,
Enabled: cmd.Enabled,
......@@ -87,7 +87,7 @@ func UpdatePluginSetting(cmd *m.UpdatePluginSettingCmd) error {
// add state change event on commit success
if pluginSetting.Enabled != cmd.Enabled {
sess.events = append(sess.events, &m.PluginStateChangedEvent{
sess.events = append(sess.events, &models.PluginStateChangedEvent{
PluginId: cmd.PluginId,
OrgId: cmd.OrgId,
Enabled: cmd.Enabled,
......@@ -105,7 +105,7 @@ func UpdatePluginSetting(cmd *m.UpdatePluginSettingCmd) error {
})
}
func UpdatePluginSettingVersion(cmd *m.UpdatePluginSettingVersionCmd) error {
func UpdatePluginSettingVersion(cmd *models.UpdatePluginSettingVersionCmd) error {
return inTransaction(func(sess *DBSession) error {
_, err := sess.Exec("UPDATE plugin_setting SET plugin_version=? WHERE org_id=? AND plugin_id=?", cmd.PluginVersion, cmd.OrgId, cmd.PluginId)
......
......@@ -5,7 +5,7 @@ import (
"time"
"github.com/grafana/grafana/pkg/bus"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/setting"
)
......@@ -16,7 +16,7 @@ func init() {
bus.AddHandler("sql", SavePreferences)
}
func GetPreferencesWithDefaults(query *m.GetPreferencesWithDefaultsQuery) error {
func GetPreferencesWithDefaults(query *models.GetPreferencesWithDefaultsQuery) error {
params := make([]interface{}, 0)
filter := ""
if len(query.User.Teams) > 0 {
......@@ -30,7 +30,7 @@ func GetPreferencesWithDefaults(query *m.GetPreferencesWithDefaultsQuery) error
params = append(params, query.User.OrgId)
params = append(params, query.User.UserId)
params = append(params, query.User.OrgId)
prefs := make([]*m.Preferences, 0)
prefs := make([]*models.Preferences, 0)
err := x.Where(filter, params...).
OrderBy("user_id ASC, team_id ASC").
Find(&prefs)
......@@ -39,7 +39,7 @@ func GetPreferencesWithDefaults(query *m.GetPreferencesWithDefaultsQuery) error
return err
}
res := &m.Preferences{
res := &models.Preferences{
Theme: setting.DefaultTheme,
Timezone: "browser",
HomeDashboardId: 0,
......@@ -61,8 +61,8 @@ func GetPreferencesWithDefaults(query *m.GetPreferencesWithDefaultsQuery) error
return nil
}
func GetPreferences(query *m.GetPreferencesQuery) error {
var prefs m.Preferences
func GetPreferences(query *models.GetPreferencesQuery) error {
var prefs models.Preferences
exists, err := x.Where("org_id=? AND user_id=? AND team_id=?", query.OrgId, query.UserId, query.TeamId).Get(&prefs)
if err != nil {
......@@ -72,23 +72,23 @@ func GetPreferences(query *m.GetPreferencesQuery) error {
if exists {
query.Result = &prefs
} else {
query.Result = new(m.Preferences)
query.Result = new(models.Preferences)
}
return nil
}
func SavePreferences(cmd *m.SavePreferencesCommand) error {
func SavePreferences(cmd *models.SavePreferencesCommand) error {
return inTransaction(func(sess *DBSession) error {
var prefs m.Preferences
var prefs models.Preferences
exists, err := sess.Where("org_id=? AND user_id=? AND team_id=?", cmd.OrgId, cmd.UserId, cmd.TeamId).Get(&prefs)
if err != nil {
return err
}
if !exists {
prefs = m.Preferences{
prefs = models.Preferences{
UserId: cmd.UserId,
OrgId: cmd.OrgId,
TeamId: cmd.TeamId,
......
......@@ -5,7 +5,7 @@ import (
"time"
"github.com/grafana/grafana/pkg/bus"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/setting"
)
......@@ -23,8 +23,8 @@ type targetCount struct {
Count int64
}
func GetOrgQuotaByTarget(query *m.GetOrgQuotaByTargetQuery) error {
quota := m.Quota{
func GetOrgQuotaByTarget(query *models.GetOrgQuotaByTargetQuery) error {
quota := models.Quota{
Target: query.Target,
OrgId: query.OrgId,
}
......@@ -42,7 +42,7 @@ func GetOrgQuotaByTarget(query *m.GetOrgQuotaByTargetQuery) error {
return err
}
query.Result = &m.OrgQuotaDTO{
query.Result = &models.OrgQuotaDTO{
Target: query.Target,
Limit: quota.Limit,
OrgId: query.OrgId,
......@@ -52,8 +52,8 @@ func GetOrgQuotaByTarget(query *m.GetOrgQuotaByTargetQuery) error {
return nil
}
func GetOrgQuotas(query *m.GetOrgQuotasQuery) error {
quotas := make([]*m.Quota, 0)
func GetOrgQuotas(query *models.GetOrgQuotasQuery) error {
quotas := make([]*models.Quota, 0)
sess := x.Table("quota")
if err := sess.Where("org_id=? AND user_id=0", query.OrgId).Find(&quotas); err != nil {
return err
......@@ -68,7 +68,7 @@ func GetOrgQuotas(query *m.GetOrgQuotasQuery) error {
for t, v := range defaultQuotas {
if _, ok := seenTargets[t]; !ok {
quotas = append(quotas, &m.Quota{
quotas = append(quotas, &models.Quota{
OrgId: query.OrgId,
Target: t,
Limit: v,
......@@ -76,7 +76,7 @@ func GetOrgQuotas(query *m.GetOrgQuotasQuery) error {
}
}
result := make([]*m.OrgQuotaDTO, len(quotas))
result := make([]*models.OrgQuotaDTO, len(quotas))
for i, q := range quotas {
//get quota used.
rawSql := fmt.Sprintf("SELECT COUNT(*) as count from %s where org_id=?", dialect.Quote(q.Target))
......@@ -84,7 +84,7 @@ func GetOrgQuotas(query *m.GetOrgQuotasQuery) error {
if err := x.SQL(rawSql, q.OrgId).Find(&resp); err != nil {
return err
}
result[i] = &m.OrgQuotaDTO{
result[i] = &models.OrgQuotaDTO{
Target: q.Target,
Limit: q.Limit,
OrgId: q.OrgId,
......@@ -95,10 +95,10 @@ func GetOrgQuotas(query *m.GetOrgQuotasQuery) error {
return nil
}
func UpdateOrgQuota(cmd *m.UpdateOrgQuotaCmd) error {
func UpdateOrgQuota(cmd *models.UpdateOrgQuotaCmd) error {
return inTransaction(func(sess *DBSession) error {
//Check if quota is already defined in the DB
quota := m.Quota{
quota := models.Quota{
Target: cmd.Target,
OrgId: cmd.OrgId,
}
......@@ -125,8 +125,8 @@ func UpdateOrgQuota(cmd *m.UpdateOrgQuotaCmd) error {
})
}
func GetUserQuotaByTarget(query *m.GetUserQuotaByTargetQuery) error {
quota := m.Quota{
func GetUserQuotaByTarget(query *models.GetUserQuotaByTargetQuery) error {
quota := models.Quota{
Target: query.Target,
UserId: query.UserId,
}
......@@ -144,7 +144,7 @@ func GetUserQuotaByTarget(query *m.GetUserQuotaByTargetQuery) error {
return err
}
query.Result = &m.UserQuotaDTO{
query.Result = &models.UserQuotaDTO{
Target: query.Target,
Limit: quota.Limit,
UserId: query.UserId,
......@@ -154,8 +154,8 @@ func GetUserQuotaByTarget(query *m.GetUserQuotaByTargetQuery) error {
return nil
}
func GetUserQuotas(query *m.GetUserQuotasQuery) error {
quotas := make([]*m.Quota, 0)
func GetUserQuotas(query *models.GetUserQuotasQuery) error {
quotas := make([]*models.Quota, 0)
sess := x.Table("quota")
if err := sess.Where("user_id=? AND org_id=0", query.UserId).Find(&quotas); err != nil {
return err
......@@ -170,7 +170,7 @@ func GetUserQuotas(query *m.GetUserQuotasQuery) error {
for t, v := range defaultQuotas {
if _, ok := seenTargets[t]; !ok {
quotas = append(quotas, &m.Quota{
quotas = append(quotas, &models.Quota{
UserId: query.UserId,
Target: t,
Limit: v,
......@@ -178,7 +178,7 @@ func GetUserQuotas(query *m.GetUserQuotasQuery) error {
}
}
result := make([]*m.UserQuotaDTO, len(quotas))
result := make([]*models.UserQuotaDTO, len(quotas))
for i, q := range quotas {
//get quota used.
rawSql := fmt.Sprintf("SELECT COUNT(*) as count from %s where user_id=?", dialect.Quote(q.Target))
......@@ -186,7 +186,7 @@ func GetUserQuotas(query *m.GetUserQuotasQuery) error {
if err := x.SQL(rawSql, q.UserId).Find(&resp); err != nil {
return err
}
result[i] = &m.UserQuotaDTO{
result[i] = &models.UserQuotaDTO{
Target: q.Target,
Limit: q.Limit,
UserId: q.UserId,
......@@ -197,10 +197,10 @@ func GetUserQuotas(query *m.GetUserQuotasQuery) error {
return nil
}
func UpdateUserQuota(cmd *m.UpdateUserQuotaCmd) error {
func UpdateUserQuota(cmd *models.UpdateUserQuotaCmd) error {
return inTransaction(func(sess *DBSession) error {
//Check if quota is already defined in the DB
quota := m.Quota{
quota := models.Quota{
Target: cmd.Target,
UserId: cmd.UserId,
}
......@@ -227,7 +227,7 @@ func UpdateUserQuota(cmd *m.UpdateUserQuotaCmd) error {
})
}
func GetGlobalQuotaByTarget(query *m.GetGlobalQuotaByTargetQuery) error {
func GetGlobalQuotaByTarget(query *models.GetGlobalQuotaByTargetQuery) error {
//get quota used.
rawSql := fmt.Sprintf("SELECT COUNT(*) as count from %s", dialect.Quote(query.Target))
resp := make([]*targetCount, 0)
......@@ -235,7 +235,7 @@ func GetGlobalQuotaByTarget(query *m.GetGlobalQuotaByTargetQuery) error {
return err
}
query.Result = &m.GlobalQuotaDTO{
query.Result = &models.GlobalQuotaDTO{
Target: query.Target,
Limit: query.Default,
Used: resp[0].Count,
......
......@@ -4,7 +4,7 @@ import (
"testing"
"time"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/setting"
. "github.com/smartystreets/goconvey/convey"
)
......@@ -40,7 +40,7 @@ func TestQuotaCommandsAndQueries(t *testing.T) {
// create a new org and add user_id 1 as admin.
// we will then have an org with 1 user. and a user
// with 1 org.
userCmd := m.CreateOrgCommand{
userCmd := models.CreateOrgCommand{
Name: "TestOrg",
UserId: 1,
}
......@@ -50,7 +50,7 @@ func TestQuotaCommandsAndQueries(t *testing.T) {
orgId = userCmd.Result.Id
Convey("Given saved org quota for users", func() {
orgCmd := m.UpdateOrgQuotaCmd{
orgCmd := models.UpdateOrgQuotaCmd{
OrgId: orgId,
Target: "org_user",
Limit: 10,
......@@ -59,35 +59,35 @@ func TestQuotaCommandsAndQueries(t *testing.T) {
So(err, ShouldBeNil)
Convey("Should be able to get saved quota by org id and target", func() {
query := m.GetOrgQuotaByTargetQuery{OrgId: orgId, Target: "org_user", Default: 1}
query := models.GetOrgQuotaByTargetQuery{OrgId: orgId, Target: "org_user", Default: 1}
err = GetOrgQuotaByTarget(&query)
So(err, ShouldBeNil)
So(query.Result.Limit, ShouldEqual, 10)
})
Convey("Should be able to get default quota by org id and target", func() {
query := m.GetOrgQuotaByTargetQuery{OrgId: 123, Target: "org_user", Default: 11}
query := models.GetOrgQuotaByTargetQuery{OrgId: 123, Target: "org_user", Default: 11}
err = GetOrgQuotaByTarget(&query)
So(err, ShouldBeNil)
So(query.Result.Limit, ShouldEqual, 11)
})
Convey("Should be able to get used org quota when rows exist", func() {
query := m.GetOrgQuotaByTargetQuery{OrgId: orgId, Target: "org_user", Default: 11}
query := models.GetOrgQuotaByTargetQuery{OrgId: orgId, Target: "org_user", Default: 11}
err = GetOrgQuotaByTarget(&query)
So(err, ShouldBeNil)
So(query.Result.Used, ShouldEqual, 1)
})
Convey("Should be able to get used org quota when no rows exist", func() {
query := m.GetOrgQuotaByTargetQuery{OrgId: 2, Target: "org_user", Default: 11}
query := models.GetOrgQuotaByTargetQuery{OrgId: 2, Target: "org_user", Default: 11}
err = GetOrgQuotaByTarget(&query)
So(err, ShouldBeNil)
So(query.Result.Used, ShouldEqual, 0)
})
Convey("Should be able to quota list for org", func() {
query := m.GetOrgQuotasQuery{OrgId: orgId}
query := models.GetOrgQuotasQuery{OrgId: orgId}
err = GetOrgQuotas(&query)
So(err, ShouldBeNil)
......@@ -106,7 +106,7 @@ func TestQuotaCommandsAndQueries(t *testing.T) {
})
})
Convey("Given saved user quota for org", func() {
userQuotaCmd := m.UpdateUserQuotaCmd{
userQuotaCmd := models.UpdateUserQuotaCmd{
UserId: userId,
Target: "org_user",
Limit: 10,
......@@ -115,35 +115,35 @@ func TestQuotaCommandsAndQueries(t *testing.T) {
So(err, ShouldBeNil)
Convey("Should be able to get saved quota by user id and target", func() {
query := m.GetUserQuotaByTargetQuery{UserId: userId, Target: "org_user", Default: 1}
query := models.GetUserQuotaByTargetQuery{UserId: userId, Target: "org_user", Default: 1}
err = GetUserQuotaByTarget(&query)
So(err, ShouldBeNil)
So(query.Result.Limit, ShouldEqual, 10)
})
Convey("Should be able to get default quota by user id and target", func() {
query := m.GetUserQuotaByTargetQuery{UserId: 9, Target: "org_user", Default: 11}
query := models.GetUserQuotaByTargetQuery{UserId: 9, Target: "org_user", Default: 11}
err = GetUserQuotaByTarget(&query)
So(err, ShouldBeNil)
So(query.Result.Limit, ShouldEqual, 11)
})
Convey("Should be able to get used user quota when rows exist", func() {
query := m.GetUserQuotaByTargetQuery{UserId: userId, Target: "org_user", Default: 11}
query := models.GetUserQuotaByTargetQuery{UserId: userId, Target: "org_user", Default: 11}
err = GetUserQuotaByTarget(&query)
So(err, ShouldBeNil)
So(query.Result.Used, ShouldEqual, 1)
})
Convey("Should be able to get used user quota when no rows exist", func() {
query := m.GetUserQuotaByTargetQuery{UserId: 2, Target: "org_user", Default: 11}
query := models.GetUserQuotaByTargetQuery{UserId: 2, Target: "org_user", Default: 11}
err = GetUserQuotaByTarget(&query)
So(err, ShouldBeNil)
So(query.Result.Used, ShouldEqual, 0)
})
Convey("Should be able to quota list for user", func() {
query := m.GetUserQuotasQuery{UserId: userId}
query := models.GetUserQuotasQuery{UserId: userId}
err = GetUserQuotas(&query)
So(err, ShouldBeNil)
......@@ -154,7 +154,7 @@ func TestQuotaCommandsAndQueries(t *testing.T) {
})
Convey("Should be able to global user quota", func() {
query := m.GetGlobalQuotaByTargetQuery{Target: "user", Default: 5}
query := models.GetGlobalQuotaByTargetQuery{Target: "user", Default: 5}
err = GetGlobalQuotaByTarget(&query)
So(err, ShouldBeNil)
......@@ -162,7 +162,7 @@ func TestQuotaCommandsAndQueries(t *testing.T) {
So(query.Result.Used, ShouldEqual, 0)
})
Convey("Should be able to global org quota", func() {
query := m.GetGlobalQuotaByTargetQuery{Target: "org", Default: 5}
query := models.GetGlobalQuotaByTargetQuery{Target: "org", Default: 5}
err = GetGlobalQuotaByTarget(&query)
So(err, ShouldBeNil)
......@@ -172,7 +172,7 @@ func TestQuotaCommandsAndQueries(t *testing.T) {
// related: https://github.com/grafana/grafana/issues/14342
Convey("Should org quota updating is successful even if it called multiple time", func() {
orgCmd := m.UpdateOrgQuotaCmd{
orgCmd := models.UpdateOrgQuotaCmd{
OrgId: orgId,
Target: "org_user",
Limit: 5,
......@@ -180,7 +180,7 @@ func TestQuotaCommandsAndQueries(t *testing.T) {
err := UpdateOrgQuota(&orgCmd)
So(err, ShouldBeNil)
query := m.GetOrgQuotaByTargetQuery{OrgId: orgId, Target: "org_user", Default: 1}
query := models.GetOrgQuotaByTargetQuery{OrgId: orgId, Target: "org_user", Default: 1}
err = GetOrgQuotaByTarget(&query)
So(err, ShouldBeNil)
So(query.Result.Limit, ShouldEqual, 5)
......@@ -188,7 +188,7 @@ func TestQuotaCommandsAndQueries(t *testing.T) {
// XXX: resolution of `Updated` column is 1sec, so this makes delay
time.Sleep(1 * time.Second)
orgCmd = m.UpdateOrgQuotaCmd{
orgCmd = models.UpdateOrgQuotaCmd{
OrgId: orgId,
Target: "org_user",
Limit: 10,
......@@ -196,7 +196,7 @@ func TestQuotaCommandsAndQueries(t *testing.T) {
err = UpdateOrgQuota(&orgCmd)
So(err, ShouldBeNil)
query = m.GetOrgQuotaByTargetQuery{OrgId: orgId, Target: "org_user", Default: 1}
query = models.GetOrgQuotaByTargetQuery{OrgId: orgId, Target: "org_user", Default: 1}
err = GetOrgQuotaByTarget(&query)
So(err, ShouldBeNil)
So(query.Result.Limit, ShouldEqual, 10)
......@@ -204,7 +204,7 @@ func TestQuotaCommandsAndQueries(t *testing.T) {
// related: https://github.com/grafana/grafana/issues/14342
Convey("Should user quota updating is successful even if it called multiple time", func() {
userQuotaCmd := m.UpdateUserQuotaCmd{
userQuotaCmd := models.UpdateUserQuotaCmd{
UserId: userId,
Target: "org_user",
Limit: 5,
......@@ -212,7 +212,7 @@ func TestQuotaCommandsAndQueries(t *testing.T) {
err := UpdateUserQuota(&userQuotaCmd)
So(err, ShouldBeNil)
query := m.GetUserQuotaByTargetQuery{UserId: userId, Target: "org_user", Default: 1}
query := models.GetUserQuotaByTargetQuery{UserId: userId, Target: "org_user", Default: 1}
err = GetUserQuotaByTarget(&query)
So(err, ShouldBeNil)
So(query.Result.Limit, ShouldEqual, 5)
......@@ -220,7 +220,7 @@ func TestQuotaCommandsAndQueries(t *testing.T) {
// XXX: resolution of `Updated` column is 1sec, so this makes delay
time.Sleep(1 * time.Second)
userQuotaCmd = m.UpdateUserQuotaCmd{
userQuotaCmd = models.UpdateUserQuotaCmd{
UserId: userId,
Target: "org_user",
Limit: 10,
......@@ -228,7 +228,7 @@ func TestQuotaCommandsAndQueries(t *testing.T) {
err = UpdateUserQuota(&userQuotaCmd)
So(err, ShouldBeNil)
query = m.GetUserQuotaByTargetQuery{UserId: userId, Target: "org_user", Default: 1}
query = models.GetUserQuotaByTargetQuery{UserId: userId, Target: "org_user", Default: 1}
err = GetUserQuotaByTarget(&query)
So(err, ShouldBeNil)
So(query.Result.Limit, ShouldEqual, 10)
......
......@@ -3,7 +3,7 @@ package sqlstore
import (
"strings"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/models"
)
// SearchBuilder is a builder/object mother that builds a dashboard search query
......@@ -13,16 +13,16 @@ type SearchBuilder struct {
isStarred bool
limit int64
page int64
signedInUser *m.SignedInUser
signedInUser *models.SignedInUser
whereDashboardIdsIn []int64
whereTitle string
whereTypeFolder bool
whereTypeDash bool
whereFolderIds []int64
permission m.PermissionType
permission models.PermissionType
}
func NewSearchBuilder(signedInUser *m.SignedInUser, limit int64, page int64, permission m.PermissionType) *SearchBuilder {
func NewSearchBuilder(signedInUser *models.SignedInUser, limit int64, page int64, permission models.PermissionType) *SearchBuilder {
// Default to page 1
if page < 1 {
page = 1
......
......@@ -3,18 +3,18 @@ package sqlstore
import (
"testing"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/models"
. "github.com/smartystreets/goconvey/convey"
)
func TestSearchBuilder(t *testing.T) {
Convey("Testing building a search", t, func() {
signedInUser := &m.SignedInUser{
signedInUser := &models.SignedInUser{
OrgId: 1,
UserId: 1,
}
sb := NewSearchBuilder(signedInUser, 1000, 0, m.PERMISSION_VIEW)
sb := NewSearchBuilder(signedInUser, 1000, 0, models.PERMISSION_VIEW)
Convey("When building a normal search", func() {
sql, params := sb.IsStarred().WithTitle("test").ToSql()
......
......@@ -5,7 +5,7 @@ import (
"time"
"github.com/grafana/grafana/pkg/bus"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/models"
)
func init() {
......@@ -18,7 +18,7 @@ func sqlRandomWalk(m1 string, m2 string, intWalker int64, floatWalker float64, s
now := time.Now().UTC()
step := time.Minute
row := &m.SqlTestData{
row := &models.SqlTestData{
Metric1: m1,
Metric2: m2,
TimeEpoch: timeWalker.Unix(),
......@@ -44,7 +44,7 @@ func sqlRandomWalk(m1 string, m2 string, intWalker int64, floatWalker float64, s
return nil
}
func InsertSqlTestData(cmd *m.InsertSqlTestDataCommand) error {
func InsertSqlTestData(cmd *models.InsertSqlTestDataCommand) error {
return inTransaction(func(sess *DBSession) error {
var err error
......
......@@ -4,7 +4,7 @@ import (
"bytes"
"strings"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/models"
)
type SqlBuilder struct {
......@@ -28,16 +28,16 @@ func (sb *SqlBuilder) AddParams(params ...interface{}) {
sb.params = append(sb.params, params...)
}
func (sb *SqlBuilder) writeDashboardPermissionFilter(user *m.SignedInUser, permission m.PermissionType) {
func (sb *SqlBuilder) writeDashboardPermissionFilter(user *models.SignedInUser, permission models.PermissionType) {
if user.OrgRole == m.ROLE_ADMIN {
if user.OrgRole == models.ROLE_ADMIN {
return
}
okRoles := []interface{}{user.OrgRole}
if user.OrgRole == m.ROLE_EDITOR {
okRoles = append(okRoles, m.ROLE_VIEWER)
if user.OrgRole == models.ROLE_EDITOR {
okRoles = append(okRoles, models.ROLE_VIEWER)
}
falseStr := dialect.BooleanStr(false)
......
......@@ -15,7 +15,7 @@ import (
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/infra/localcache"
"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/registry"
"github.com/grafana/grafana/pkg/services/annotations"
"github.com/grafana/grafana/pkg/services/sqlstore/migrations"
......@@ -109,7 +109,7 @@ func (ss *SqlStore) Init() error {
func (ss *SqlStore) ensureMainOrgAndAdminUser() error {
err := ss.InTransaction(context.Background(), func(ctx context.Context) error {
systemUserCountQuery := m.GetSystemUserCountStatsQuery{}
systemUserCountQuery := models.GetSystemUserCountStatsQuery{}
err := bus.DispatchCtx(ctx, &systemUserCountQuery)
if err != nil {
return fmt.Errorf("Could not determine if admin user exists: %v", err)
......@@ -121,7 +121,7 @@ func (ss *SqlStore) ensureMainOrgAndAdminUser() error {
// ensure admin user
if !ss.Cfg.DisableInitAdminCreation {
cmd := m.CreateUserCommand{}
cmd := models.CreateUserCommand{}
cmd.Login = setting.AdminUser
cmd.Email = setting.AdminUser + "@localhost"
cmd.Password = setting.AdminPassword
......
......@@ -2,7 +2,7 @@ package sqlstore
import (
"github.com/grafana/grafana/pkg/bus"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/models"
)
func init() {
......@@ -12,7 +12,7 @@ func init() {
bus.AddHandler("sql", IsStarredByUser)
}
func IsStarredByUser(query *m.IsStarredByUserQuery) error {
func IsStarredByUser(query *models.IsStarredByUserQuery) error {
rawSql := "SELECT 1 from star where user_id=? and dashboard_id=?"
results, err := x.Query(rawSql, query.UserId, query.DashboardId)
......@@ -29,14 +29,14 @@ func IsStarredByUser(query *m.IsStarredByUserQuery) error {
return nil
}
func StarDashboard(cmd *m.StarDashboardCommand) error {
func StarDashboard(cmd *models.StarDashboardCommand) error {
if cmd.DashboardId == 0 || cmd.UserId == 0 {
return m.ErrCommandValidationFailed
return models.ErrCommandValidationFailed
}
return inTransaction(func(sess *DBSession) error {
entity := m.Star{
entity := models.Star{
UserId: cmd.UserId,
DashboardId: cmd.DashboardId,
}
......@@ -46,9 +46,9 @@ func StarDashboard(cmd *m.StarDashboardCommand) error {
})
}
func UnstarDashboard(cmd *m.UnstarDashboardCommand) error {
func UnstarDashboard(cmd *models.UnstarDashboardCommand) error {
if cmd.DashboardId == 0 || cmd.UserId == 0 {
return m.ErrCommandValidationFailed
return models.ErrCommandValidationFailed
}
return inTransaction(func(sess *DBSession) error {
......@@ -58,8 +58,8 @@ func UnstarDashboard(cmd *m.UnstarDashboardCommand) error {
})
}
func GetUserStars(query *m.GetUserStarsQuery) error {
var stars = make([]m.Star, 0)
func GetUserStars(query *models.GetUserStarsQuery) error {
var stars = make([]models.Star, 0)
err := x.Where("user_id=?", query.UserId).Find(&stars)
query.Result = make(map[int64]bool)
......
......@@ -3,7 +3,7 @@ package sqlstore
import (
"testing"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/models"
. "github.com/smartystreets/goconvey/convey"
)
......@@ -13,7 +13,7 @@ func TestUserStarsDataAccess(t *testing.T) {
InitTestDB(t)
Convey("Given saved star", func() {
cmd := m.StarDashboardCommand{
cmd := models.StarDashboardCommand{
DashboardId: 10,
UserId: 12,
}
......@@ -22,7 +22,7 @@ func TestUserStarsDataAccess(t *testing.T) {
So(err, ShouldBeNil)
Convey("IsStarredByUser should return true when starred", func() {
query := m.IsStarredByUserQuery{UserId: 12, DashboardId: 10}
query := models.IsStarredByUserQuery{UserId: 12, DashboardId: 10}
err := IsStarredByUser(&query)
So(err, ShouldBeNil)
......@@ -30,7 +30,7 @@ func TestUserStarsDataAccess(t *testing.T) {
})
Convey("IsStarredByUser should return false when not starred", func() {
query := m.IsStarredByUserQuery{UserId: 12, DashboardId: 12}
query := models.IsStarredByUserQuery{UserId: 12, DashboardId: 12}
err := IsStarredByUser(&query)
So(err, ShouldBeNil)
......
......@@ -5,7 +5,7 @@ import (
"time"
"github.com/grafana/grafana/pkg/bus"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/models"
)
func init() {
......@@ -19,28 +19,28 @@ func init() {
var activeUserTimeLimit = time.Hour * 24 * 30
func GetAlertNotifiersUsageStats(ctx context.Context, query *m.GetAlertNotifierUsageStatsQuery) error {
func GetAlertNotifiersUsageStats(ctx context.Context, query *models.GetAlertNotifierUsageStatsQuery) error {
var rawSql = `SELECT COUNT(*) as count, type FROM alert_notification GROUP BY type`
query.Result = make([]*m.NotifierUsageStats, 0)
query.Result = make([]*models.NotifierUsageStats, 0)
err := x.SQL(rawSql).Find(&query.Result)
return err
}
func GetDataSourceStats(query *m.GetDataSourceStatsQuery) error {
func GetDataSourceStats(query *models.GetDataSourceStatsQuery) error {
var rawSql = `SELECT COUNT(*) as count, type FROM data_source GROUP BY type`
query.Result = make([]*m.DataSourceStats, 0)
query.Result = make([]*models.DataSourceStats, 0)
err := x.SQL(rawSql).Find(&query.Result)
return err
}
func GetDataSourceAccessStats(query *m.GetDataSourceAccessStatsQuery) error {
func GetDataSourceAccessStats(query *models.GetDataSourceAccessStatsQuery) error {
var rawSql = `SELECT COUNT(*) as count, type, access FROM data_source GROUP BY type, access`
query.Result = make([]*m.DataSourceAccessStats, 0)
query.Result = make([]*models.DataSourceAccessStats, 0)
err := x.SQL(rawSql).Find(&query.Result)
return err
}
func GetSystemStats(query *m.GetSystemStatsQuery) error {
func GetSystemStats(query *models.GetSystemStatsQuery) error {
sb := &SqlBuilder{}
sb.Write("SELECT ")
sb.Write(`(SELECT COUNT(*) FROM ` + dialect.Quote("user") + `) AS users,`)
......@@ -81,7 +81,7 @@ func GetSystemStats(query *m.GetSystemStatsQuery) error {
sb.Write(roleCounterSQL("Editor", "editors")+`,`, activeUserDeadlineDate)
sb.Write(roleCounterSQL("Admin", "admins")+``, activeUserDeadlineDate)
var stats m.SystemStats
var stats models.SystemStats
_, err := x.SQL(sb.GetSqlString(), sb.params...).Get(&stats)
if err != nil {
return err
......@@ -106,7 +106,7 @@ func roleCounterSQL(role, alias string) string {
) as active_` + alias
}
func GetAdminStats(query *m.GetAdminStatsQuery) error {
func GetAdminStats(query *models.GetAdminStatsQuery) error {
activeEndDate := time.Now().Add(-activeUserTimeLimit)
var rawSql = `SELECT
......@@ -158,7 +158,7 @@ func GetAdminStats(query *m.GetAdminStatsQuery) error {
) as active_sessions
`
var stats m.AdminStats
var stats models.AdminStats
_, err := x.SQL(rawSql, activeEndDate, activeEndDate, activeEndDate, activeEndDate, activeEndDate.Unix()).Get(&stats)
if err != nil {
return err
......@@ -168,11 +168,11 @@ func GetAdminStats(query *m.GetAdminStatsQuery) error {
return err
}
func GetSystemUserCountStats(ctx context.Context, query *m.GetSystemUserCountStatsQuery) error {
func GetSystemUserCountStats(ctx context.Context, query *models.GetSystemUserCountStatsQuery) error {
return withDbSession(ctx, func(sess *DBSession) error {
var rawSql = `SELECT COUNT(id) AS Count FROM ` + dialect.Quote("user")
var stats m.SystemUserCountStats
var stats models.SystemUserCountStats
_, err := sess.SQL(rawSql).Get(&stats)
if err != nil {
return err
......
......@@ -4,7 +4,7 @@ import (
"time"
"github.com/grafana/grafana/pkg/bus"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/models"
)
func init() {
......@@ -15,7 +15,7 @@ func init() {
bus.AddHandler("sql", UpdateTempUserWithEmailSent)
}
func UpdateTempUserStatus(cmd *m.UpdateTempUserStatusCommand) error {
func UpdateTempUserStatus(cmd *models.UpdateTempUserStatusCommand) error {
return inTransaction(func(sess *DBSession) error {
var rawSql = "UPDATE temp_user SET status=? WHERE code=?"
_, err := sess.Exec(rawSql, string(cmd.Status), cmd.Code)
......@@ -23,11 +23,11 @@ func UpdateTempUserStatus(cmd *m.UpdateTempUserStatusCommand) error {
})
}
func CreateTempUser(cmd *m.CreateTempUserCommand) error {
func CreateTempUser(cmd *models.CreateTempUserCommand) error {
return inTransaction(func(sess *DBSession) error {
// create user
user := &m.TempUser{
user := &models.TempUser{
Email: cmd.Email,
Name: cmd.Name,
OrgId: cmd.OrgId,
......@@ -50,9 +50,9 @@ func CreateTempUser(cmd *m.CreateTempUserCommand) error {
})
}
func UpdateTempUserWithEmailSent(cmd *m.UpdateTempUserWithEmailSentCommand) error {
func UpdateTempUserWithEmailSent(cmd *models.UpdateTempUserWithEmailSentCommand) error {
return inTransaction(func(sess *DBSession) error {
user := &m.TempUser{
user := &models.TempUser{
EmailSent: true,
EmailSentOn: time.Now(),
}
......@@ -63,7 +63,7 @@ func UpdateTempUserWithEmailSent(cmd *m.UpdateTempUserWithEmailSentCommand) erro
})
}
func GetTempUsersQuery(query *m.GetTempUsersQuery) error {
func GetTempUsersQuery(query *models.GetTempUsersQuery) error {
rawSql := `SELECT
tu.id as id,
tu.org_id as org_id,
......@@ -95,13 +95,13 @@ func GetTempUsersQuery(query *m.GetTempUsersQuery) error {
rawSql += " ORDER BY tu.created desc"
query.Result = make([]*m.TempUserDTO, 0)
query.Result = make([]*models.TempUserDTO, 0)
sess := x.SQL(rawSql, params...)
err := sess.Find(&query.Result)
return err
}
func GetTempUserByCode(query *m.GetTempUserByCodeQuery) error {
func GetTempUserByCode(query *models.GetTempUserByCodeQuery) error {
var rawSql = `SELECT
tu.id as id,
tu.org_id as org_id,
......@@ -120,14 +120,14 @@ func GetTempUserByCode(query *m.GetTempUserByCodeQuery) error {
LEFT OUTER JOIN ` + dialect.Quote("user") + ` as u on u.id = tu.invited_by_user_id
WHERE tu.code=?`
var tempUser m.TempUserDTO
var tempUser models.TempUserDTO
sess := x.SQL(rawSql, query.Code)
has, err := sess.Get(&tempUser)
if err != nil {
return err
} else if !has {
return m.ErrTempUserNotFound
return models.ErrTempUserNotFound
}
query.Result = &tempUser
......
......@@ -3,9 +3,8 @@ package sqlstore
import (
"testing"
"github.com/grafana/grafana/pkg/models"
. "github.com/smartystreets/goconvey/convey"
m "github.com/grafana/grafana/pkg/models"
)
func TestTempUserCommandsAndQueries(t *testing.T) {
......@@ -14,18 +13,18 @@ func TestTempUserCommandsAndQueries(t *testing.T) {
InitTestDB(t)
Convey("Given saved api key", func() {
cmd := m.CreateTempUserCommand{
cmd := models.CreateTempUserCommand{
OrgId: 2256,
Name: "hello",
Code: "asd",
Email: "e@as.co",
Status: m.TmpUserInvitePending,
Status: models.TmpUserInvitePending,
}
err := CreateTempUser(&cmd)
So(err, ShouldBeNil)
Convey("Should be able to get temp users by org id", func() {
query := m.GetTempUsersQuery{OrgId: 2256, Status: m.TmpUserInvitePending}
query := models.GetTempUsersQuery{OrgId: 2256, Status: models.TmpUserInvitePending}
err = GetTempUsersQuery(&query)
So(err, ShouldBeNil)
......@@ -33,7 +32,7 @@ func TestTempUserCommandsAndQueries(t *testing.T) {
})
Convey("Should be able to get temp users by email", func() {
query := m.GetTempUsersQuery{Email: "e@as.co", Status: m.TmpUserInvitePending}
query := models.GetTempUsersQuery{Email: "e@as.co", Status: models.TmpUserInvitePending}
err = GetTempUsersQuery(&query)
So(err, ShouldBeNil)
......@@ -41,7 +40,7 @@ func TestTempUserCommandsAndQueries(t *testing.T) {
})
Convey("Should be able to get temp users by code", func() {
query := m.GetTempUserByCodeQuery{Code: "asd"}
query := models.GetTempUserByCodeQuery{Code: "asd"}
err = GetTempUserByCode(&query)
So(err, ShouldBeNil)
......@@ -49,24 +48,23 @@ func TestTempUserCommandsAndQueries(t *testing.T) {
})
Convey("Should be able update status", func() {
cmd2 := m.UpdateTempUserStatusCommand{Code: "asd", Status: m.TmpUserRevoked}
cmd2 := models.UpdateTempUserStatusCommand{Code: "asd", Status: models.TmpUserRevoked}
err := UpdateTempUserStatus(&cmd2)
So(err, ShouldBeNil)
})
Convey("Should be able update email sent and email sent on", func() {
cmd3 := m.UpdateTempUserWithEmailSentCommand{Code: cmd.Result.Code}
cmd3 := models.UpdateTempUserWithEmailSentCommand{Code: cmd.Result.Code}
err := UpdateTempUserWithEmailSent(&cmd3)
So(err, ShouldBeNil)
query := m.GetTempUsersQuery{OrgId: 2256, Status: m.TmpUserInvitePending}
query := models.GetTempUsersQuery{OrgId: 2256, Status: models.TmpUserInvitePending}
err = GetTempUsersQuery(&query)
So(err, ShouldBeNil)
So(query.Result[0].EmailSent, ShouldBeTrue)
So(query.Result[0].EmailSentOn, ShouldHappenOnOrAfter, (query.Result[0].Created))
})
})
})
}
......@@ -6,10 +6,9 @@ import (
"testing"
"time"
"github.com/grafana/grafana/pkg/models"
. "github.com/smartystreets/goconvey/convey"
"golang.org/x/oauth2"
m "github.com/grafana/grafana/pkg/models"
)
//nolint:goconst
......@@ -18,9 +17,9 @@ func TestUserAuth(t *testing.T) {
Convey("Given 5 users", t, func() {
var err error
var cmd *m.CreateUserCommand
var cmd *models.CreateUserCommand
for i := 0; i < 5; i++ {
cmd = &m.CreateUserCommand{
cmd = &models.CreateUserCommand{
Email: fmt.Sprint("user", i, "@test.com"),
Name: fmt.Sprint("user", i),
Login: fmt.Sprint("loginuser", i),
......@@ -44,7 +43,7 @@ func TestUserAuth(t *testing.T) {
// By Login
login := "loginuser0"
query := &m.GetUserByAuthInfoQuery{Login: login}
query := &models.GetUserByAuthInfoQuery{Login: login}
err = GetUserByAuthInfo(query)
So(err, ShouldBeNil)
......@@ -53,7 +52,7 @@ func TestUserAuth(t *testing.T) {
// By ID
id := query.Result.Id
query = &m.GetUserByAuthInfoQuery{UserId: id}
query = &models.GetUserByAuthInfoQuery{UserId: id}
err = GetUserByAuthInfo(query)
So(err, ShouldBeNil)
......@@ -62,7 +61,7 @@ func TestUserAuth(t *testing.T) {
// By Email
email := "user1@test.com"
query = &m.GetUserByAuthInfoQuery{Email: email}
query = &models.GetUserByAuthInfoQuery{Email: email}
err = GetUserByAuthInfo(query)
So(err, ShouldBeNil)
......@@ -71,19 +70,19 @@ func TestUserAuth(t *testing.T) {
// Don't find nonexistent user
email = "nonexistent@test.com"
query = &m.GetUserByAuthInfoQuery{Email: email}
query = &models.GetUserByAuthInfoQuery{Email: email}
err = GetUserByAuthInfo(query)
So(err, ShouldEqual, m.ErrUserNotFound)
So(err, ShouldEqual, models.ErrUserNotFound)
So(query.Result, ShouldBeNil)
})
Convey("Can set & locate by AuthModule and AuthId", func() {
// get nonexistent user_auth entry
query := &m.GetUserByAuthInfoQuery{AuthModule: "test", AuthId: "test"}
query := &models.GetUserByAuthInfoQuery{AuthModule: "test", AuthId: "test"}
err = GetUserByAuthInfo(query)
So(err, ShouldEqual, m.ErrUserNotFound)
So(err, ShouldEqual, models.ErrUserNotFound)
So(query.Result, ShouldBeNil)
// create user_auth entry
......@@ -96,7 +95,7 @@ func TestUserAuth(t *testing.T) {
So(query.Result.Login, ShouldEqual, login)
// get via user_auth
query = &m.GetUserByAuthInfoQuery{AuthModule: "test", AuthId: "test"}
query = &models.GetUserByAuthInfoQuery{AuthModule: "test", AuthId: "test"}
err = GetUserByAuthInfo(query)
So(err, ShouldBeNil)
......@@ -112,7 +111,7 @@ func TestUserAuth(t *testing.T) {
So(query.Result.Login, ShouldEqual, "loginuser1")
// get via user_auth
query = &m.GetUserByAuthInfoQuery{AuthModule: "test", AuthId: "test"}
query = &models.GetUserByAuthInfoQuery{AuthModule: "test", AuthId: "test"}
err = GetUserByAuthInfo(query)
So(err, ShouldBeNil)
......@@ -123,10 +122,10 @@ func TestUserAuth(t *testing.T) {
So(err, ShouldBeNil)
// get via user_auth for deleted user
query = &m.GetUserByAuthInfoQuery{AuthModule: "test", AuthId: "test"}
query = &models.GetUserByAuthInfoQuery{AuthModule: "test", AuthId: "test"}
err = GetUserByAuthInfo(query)
So(err, ShouldEqual, m.ErrUserNotFound)
So(err, ShouldEqual, models.ErrUserNotFound)
So(query.Result, ShouldBeNil)
})
......@@ -142,13 +141,13 @@ func TestUserAuth(t *testing.T) {
login := "loginuser0"
// Calling GetUserByAuthInfoQuery on an existing user will populate an entry in the user_auth table
query := &m.GetUserByAuthInfoQuery{Login: login, AuthModule: "test", AuthId: "test"}
query := &models.GetUserByAuthInfoQuery{Login: login, AuthModule: "test", AuthId: "test"}
err = GetUserByAuthInfo(query)
So(err, ShouldBeNil)
So(query.Result.Login, ShouldEqual, login)
cmd := &m.UpdateAuthInfoCommand{
cmd := &models.UpdateAuthInfoCommand{
UserId: query.Result.Id,
AuthId: query.AuthId,
AuthModule: query.AuthModule,
......@@ -158,7 +157,7 @@ func TestUserAuth(t *testing.T) {
So(err, ShouldBeNil)
getAuthQuery := &m.GetAuthInfoQuery{
getAuthQuery := &models.GetAuthInfoQuery{
UserId: query.Result.Id,
}
......@@ -178,7 +177,7 @@ func TestUserAuth(t *testing.T) {
// Calling GetUserByAuthInfoQuery on an existing user will populate an entry in the user_auth table
// Make the first log-in during the past
getTime = func() time.Time { return time.Now().AddDate(0, 0, -2) }
query := &m.GetUserByAuthInfoQuery{Login: login, AuthModule: "test1", AuthId: "test1"}
query := &models.GetUserByAuthInfoQuery{Login: login, AuthModule: "test1", AuthId: "test1"}
err = GetUserByAuthInfo(query)
getTime = time.Now
......@@ -188,7 +187,7 @@ func TestUserAuth(t *testing.T) {
// Add a second auth module for this user
// Have this module's last log-in be more recent
getTime = func() time.Time { return time.Now().AddDate(0, 0, -1) }
query = &m.GetUserByAuthInfoQuery{Login: login, AuthModule: "test2", AuthId: "test2"}
query = &models.GetUserByAuthInfoQuery{Login: login, AuthModule: "test2", AuthId: "test2"}
err = GetUserByAuthInfo(query)
getTime = time.Now
......@@ -196,7 +195,7 @@ func TestUserAuth(t *testing.T) {
So(query.Result.Login, ShouldEqual, login)
// Get the latest entry by not supply an authmodule or authid
getAuthQuery := &m.GetAuthInfoQuery{
getAuthQuery := &models.GetAuthInfoQuery{
UserId: query.Result.Id,
}
......@@ -206,13 +205,13 @@ func TestUserAuth(t *testing.T) {
So(getAuthQuery.Result.AuthModule, ShouldEqual, "test2")
// "log in" again with the first auth module
updateAuthCmd := &m.UpdateAuthInfoCommand{UserId: query.Result.Id, AuthModule: "test1", AuthId: "test1"}
updateAuthCmd := &models.UpdateAuthInfoCommand{UserId: query.Result.Id, AuthModule: "test1", AuthId: "test1"}
err = UpdateAuthInfo(updateAuthCmd)
So(err, ShouldBeNil)
// Get the latest entry by not supply an authmodule or authid
getAuthQuery = &m.GetAuthInfoQuery{
getAuthQuery = &models.GetAuthInfoQuery{
UserId: query.Result.Id,
}
......
......@@ -2,19 +2,19 @@ package teamguardian
import (
"github.com/grafana/grafana/pkg/bus"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/models"
)
func CanAdmin(bus bus.Bus, orgId int64, teamId int64, user *m.SignedInUser) error {
if user.OrgRole == m.ROLE_ADMIN {
func CanAdmin(bus bus.Bus, orgId int64, teamId int64, user *models.SignedInUser) error {
if user.OrgRole == models.ROLE_ADMIN {
return nil
}
if user.OrgId != orgId {
return m.ErrNotAllowedToUpdateTeamInDifferentOrg
return models.ErrNotAllowedToUpdateTeamInDifferentOrg
}
cmd := m.GetTeamMembersQuery{
cmd := models.GetTeamMembersQuery{
OrgId: orgId,
TeamId: teamId,
UserId: user.UserId,
......@@ -25,10 +25,10 @@ func CanAdmin(bus bus.Bus, orgId int64, teamId int64, user *m.SignedInUser) erro
}
for _, member := range cmd.Result {
if member.UserId == user.UserId && member.Permission == m.PERMISSION_ADMIN {
if member.UserId == user.UserId && member.Permission == models.PERMISSION_ADMIN {
return nil
}
}
return m.ErrNotAllowedToUpdateTeam
return models.ErrNotAllowedToUpdateTeam
}
package teamguardian
import (
"testing"
"github.com/grafana/grafana/pkg/bus"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/models"
. "github.com/smartystreets/goconvey/convey"
"testing"
)
func TestUpdateTeam(t *testing.T) {
Convey("Updating a team", t, func() {
bus.ClearBusHandlers()
admin := m.SignedInUser{
admin := models.SignedInUser{
UserId: 1,
OrgId: 1,
OrgRole: m.ROLE_ADMIN,
OrgRole: models.ROLE_ADMIN,
}
editor := m.SignedInUser{
editor := models.SignedInUser{
UserId: 2,
OrgId: 1,
OrgRole: m.ROLE_EDITOR,
OrgRole: models.ROLE_EDITOR,
}
testTeam := m.Team{
testTeam := models.Team{
Id: 1,
OrgId: 1,
}
Convey("Given an editor and a team he isn't a member of", func() {
Convey("Should not be able to update the team", func() {
bus.AddHandler("test", func(cmd *m.GetTeamMembersQuery) error {
cmd.Result = []*m.TeamMemberDTO{}
bus.AddHandler("test", func(cmd *models.GetTeamMembersQuery) error {
cmd.Result = []*models.TeamMemberDTO{}
return nil
})
err := CanAdmin(bus.GetBus(), testTeam.OrgId, testTeam.Id, &editor)
So(err, ShouldEqual, m.ErrNotAllowedToUpdateTeam)
So(err, ShouldEqual, models.ErrNotAllowedToUpdateTeam)
})
})
Convey("Given an editor and a team he is an admin in", func() {
Convey("Should be able to update the team", func() {
bus.AddHandler("test", func(cmd *m.GetTeamMembersQuery) error {
cmd.Result = []*m.TeamMemberDTO{{
bus.AddHandler("test", func(cmd *models.GetTeamMembersQuery) error {
cmd.Result = []*models.TeamMemberDTO{{
OrgId: testTeam.OrgId,
TeamId: testTeam.Id,
UserId: editor.UserId,
Permission: m.PERMISSION_ADMIN,
Permission: models.PERMISSION_ADMIN,
}}
return nil
})
......@@ -56,24 +57,24 @@ func TestUpdateTeam(t *testing.T) {
})
Convey("Given an editor and a team in another org", func() {
testTeamOtherOrg := m.Team{
testTeamOtherOrg := models.Team{
Id: 1,
OrgId: 2,
}
Convey("Shouldn't be able to update the team", func() {
bus.AddHandler("test", func(cmd *m.GetTeamMembersQuery) error {
cmd.Result = []*m.TeamMemberDTO{{
bus.AddHandler("test", func(cmd *models.GetTeamMembersQuery) error {
cmd.Result = []*models.TeamMemberDTO{{
OrgId: testTeamOtherOrg.OrgId,
TeamId: testTeamOtherOrg.Id,
UserId: editor.UserId,
Permission: m.PERMISSION_ADMIN,
Permission: models.PERMISSION_ADMIN,
}}
return nil
})
err := CanAdmin(bus.GetBus(), testTeamOtherOrg.OrgId, testTeamOtherOrg.Id, &editor)
So(err, ShouldEqual, m.ErrNotAllowedToUpdateTeamInDifferentOrg)
So(err, ShouldEqual, models.ErrNotAllowedToUpdateTeamInDifferentOrg)
})
})
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment