mirror of
https://github.com/grafana/grafana.git
synced 2026-08-11 13:44:59 -05:00
public dashboards: finalize db schema & v1 feature complete (#50467)
This PR completes public dashboards v1 functionality and simplifies public dashboard conventions. It exists as a large PR so that we are not making constant changes to the database schema. models.PublicDashboardConfig model replaced with models.PublicDashboard directly dashboard_public_config table renamed to dashboard_public models.Dashboard.IsPublic removed from the dashboard and replaced with models.PublicDashboard.isEnabled Routing now uses a uuid v4 as an access token for viewing a public dashboard anonymously, PublicDashboard.Uid only used as database identifier Frontend utilizes uuid for auth'd operations and access token for anonymous access Default to time range defined on dashboard when viewing public dashboard Add audit fields to public dashboard Co-authored-by: Owen Smallwood <owen.smallwood@grafana.com>, Ezequiel Victorero <ezequiel.victorero@grafana.com>, Jesse Weaver <jesse.weaver@grafana.com>
This commit is contained in:
co-authored by
Owen Smallwood <owen.smallwood@grafana.com>, Ezequiel Victorero <ezequiel.victorero@grafana.com>, Jesse Weaver <jesse.weaver@grafana.com>
parent
773c269084
commit
d076bedb5e
+3
-7
@@ -89,11 +89,6 @@ func (hs *HTTPServer) registerRoutes() {
|
||||
r.Get("/a/:id/*", reqSignedIn, hs.Index) // App Root Page
|
||||
r.Get("/a/:id", reqSignedIn, hs.Index)
|
||||
|
||||
//pubdash
|
||||
if hs.Features.IsEnabled(featuremgmt.FlagPublicDashboards) {
|
||||
r.Get("/public-dashboards/:uid", middleware.SetPublicDashboardFlag(), hs.Index)
|
||||
}
|
||||
|
||||
r.Get("/d/:uid/:slug", reqSignedIn, redirectFromLegacyPanelEditURL, hs.Index)
|
||||
r.Get("/d/:uid", reqSignedIn, redirectFromLegacyPanelEditURL, hs.Index)
|
||||
r.Get("/dashboard/script/*", reqSignedIn, hs.Index)
|
||||
@@ -612,8 +607,9 @@ func (hs *HTTPServer) registerRoutes() {
|
||||
|
||||
// Public API
|
||||
if hs.Features.IsEnabled(featuremgmt.FlagPublicDashboards) {
|
||||
r.Get("/api/public/dashboards/:uid", routing.Wrap(hs.GetPublicDashboard))
|
||||
r.Post("/api/public/dashboards/:uid/panels/:panelId/query", routing.Wrap(hs.QueryPublicDashboard))
|
||||
r.Get("/public-dashboards/:accessToken", middleware.SetPublicDashboardFlag(), hs.Index)
|
||||
r.Get("/api/public/dashboards/:accessToken", routing.Wrap(hs.GetPublicDashboard))
|
||||
r.Post("/api/public/dashboards/:accessToken/panels/:panelId/query", routing.Wrap(hs.QueryPublicDashboard))
|
||||
}
|
||||
|
||||
// Frontend logs
|
||||
|
||||
@@ -139,7 +139,6 @@ func (hs *HTTPServer) GetDashboard(c *models.ReqContext) response.Response {
|
||||
Url: dash.GetUrl(),
|
||||
FolderTitle: "General",
|
||||
AnnotationsPermissions: annotationPermissions,
|
||||
IsPublic: dash.IsPublic,
|
||||
}
|
||||
|
||||
// lookup folder title
|
||||
|
||||
+57
-26
@@ -2,40 +2,42 @@ package api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/grafana/grafana/pkg/api/dtos"
|
||||
"github.com/grafana/grafana/pkg/api/response"
|
||||
"github.com/grafana/grafana/pkg/models"
|
||||
"github.com/grafana/grafana/pkg/services/dashboards"
|
||||
"github.com/grafana/grafana/pkg/services/datasources"
|
||||
"github.com/grafana/grafana/pkg/web"
|
||||
)
|
||||
|
||||
// gets public dashboard
|
||||
func (hs *HTTPServer) GetPublicDashboard(c *models.ReqContext) response.Response {
|
||||
publicDashboardUid := web.Params(c.Req)[":uid"]
|
||||
accessToken := web.Params(c.Req)[":accessToken"]
|
||||
|
||||
dash, err := hs.dashboardService.GetPublicDashboard(c.Req.Context(), publicDashboardUid)
|
||||
dash, err := hs.dashboardService.GetPublicDashboard(c.Req.Context(), accessToken)
|
||||
if err != nil {
|
||||
return handleDashboardErr(http.StatusInternalServerError, "Failed to get public dashboard", err)
|
||||
}
|
||||
|
||||
meta := dtos.DashboardMeta{
|
||||
Slug: dash.Slug,
|
||||
Type: models.DashTypeDB,
|
||||
CanStar: false,
|
||||
CanSave: false,
|
||||
CanEdit: false,
|
||||
CanAdmin: false,
|
||||
CanDelete: false,
|
||||
Created: dash.Created,
|
||||
Updated: dash.Updated,
|
||||
Version: dash.Version,
|
||||
IsFolder: false,
|
||||
FolderId: dash.FolderId,
|
||||
IsPublic: dash.IsPublic,
|
||||
PublicDashboardUid: publicDashboardUid,
|
||||
Slug: dash.Slug,
|
||||
Type: models.DashTypeDB,
|
||||
CanStar: false,
|
||||
CanSave: false,
|
||||
CanEdit: false,
|
||||
CanAdmin: false,
|
||||
CanDelete: false,
|
||||
Created: dash.Created,
|
||||
Updated: dash.Updated,
|
||||
Version: dash.Version,
|
||||
IsFolder: false,
|
||||
FolderId: dash.FolderId,
|
||||
PublicDashboardAccessToken: accessToken,
|
||||
}
|
||||
|
||||
dto := dtos.DashboardFullWithMeta{Meta: meta, Dashboard: dash.Data}
|
||||
@@ -54,43 +56,72 @@ func (hs *HTTPServer) GetPublicDashboardConfig(c *models.ReqContext) response.Re
|
||||
|
||||
// sets public dashboard configuration for dashboard
|
||||
func (hs *HTTPServer) SavePublicDashboardConfig(c *models.ReqContext) response.Response {
|
||||
pdc := &models.PublicDashboardConfig{}
|
||||
if err := web.Bind(c.Req, pdc); err != nil {
|
||||
pubdash := &models.PublicDashboard{}
|
||||
if err := web.Bind(c.Req, pubdash); err != nil {
|
||||
return response.Error(http.StatusBadRequest, "bad request data", err)
|
||||
}
|
||||
|
||||
// Always set the org id to the current auth session orgId
|
||||
pubdash.OrgId = c.OrgId
|
||||
|
||||
dto := dashboards.SavePublicDashboardConfigDTO{
|
||||
OrgId: c.OrgId,
|
||||
DashboardUid: web.Params(c.Req)[":uid"],
|
||||
PublicDashboardConfig: pdc,
|
||||
OrgId: c.OrgId,
|
||||
DashboardUid: web.Params(c.Req)[":uid"],
|
||||
UserId: c.UserId,
|
||||
PublicDashboard: pubdash,
|
||||
}
|
||||
|
||||
pdc, err := hs.dashboardService.SavePublicDashboardConfig(c.Req.Context(), &dto)
|
||||
pubdash, err := hs.dashboardService.SavePublicDashboardConfig(c.Req.Context(), &dto)
|
||||
if err != nil {
|
||||
return handleDashboardErr(http.StatusInternalServerError, "Failed to save public dashboard configuration", err)
|
||||
}
|
||||
|
||||
return response.JSON(http.StatusOK, pdc)
|
||||
return response.JSON(http.StatusOK, pubdash)
|
||||
}
|
||||
|
||||
// QueryPublicDashboard returns all results for a given panel on a public dashboard
|
||||
// POST /api/public/dashboard/:uid/panels/:panelId/query
|
||||
// POST /api/public/dashboard/:accessToken/panels/:panelId/query
|
||||
func (hs *HTTPServer) QueryPublicDashboard(c *models.ReqContext) response.Response {
|
||||
panelId, err := strconv.ParseInt(web.Params(c.Req)[":panelId"], 10, 64)
|
||||
if err != nil {
|
||||
return response.Error(http.StatusBadRequest, "invalid panel ID", err)
|
||||
}
|
||||
|
||||
dashboard, err := hs.dashboardService.GetPublicDashboard(c.Req.Context(), web.Params(c.Req)[":accessToken"])
|
||||
if err != nil {
|
||||
return response.Error(http.StatusInternalServerError, "could not fetch dashboard", err)
|
||||
}
|
||||
|
||||
publicDashboard, err := hs.dashboardService.GetPublicDashboardConfig(c.Req.Context(), dashboard.OrgId, dashboard.Uid)
|
||||
if err != nil {
|
||||
return response.Error(http.StatusInternalServerError, "could not fetch public dashboard", err)
|
||||
}
|
||||
|
||||
reqDTO, err := hs.dashboardService.BuildPublicDashboardMetricRequest(
|
||||
c.Req.Context(),
|
||||
web.Params(c.Req)[":uid"],
|
||||
dashboard,
|
||||
publicDashboard,
|
||||
panelId,
|
||||
)
|
||||
if err != nil {
|
||||
return handleDashboardErr(http.StatusInternalServerError, "Failed to get queries for public dashboard", err)
|
||||
}
|
||||
|
||||
resp, err := hs.queryDataService.QueryDataMultipleSources(c.Req.Context(), nil, c.SkipCache, reqDTO, true)
|
||||
// Get all needed datasource UIDs from queries
|
||||
var uids []string
|
||||
for _, query := range reqDTO.Queries {
|
||||
uids = append(uids, query.Get("datasource").Get("uid").MustString())
|
||||
}
|
||||
|
||||
// Create a temp user with read-only datasource permissions
|
||||
anonymousUser := &models.SignedInUser{OrgId: dashboard.OrgId, Permissions: make(map[int64]map[string][]string)}
|
||||
permissions := make(map[string][]string)
|
||||
datasourceScope := fmt.Sprintf("datasources:uid:%s", strings.Join(uids, ","))
|
||||
permissions[datasources.ActionQuery] = []string{datasourceScope}
|
||||
permissions[datasources.ActionRead] = []string{datasourceScope}
|
||||
anonymousUser.Permissions[dashboard.OrgId] = permissions
|
||||
|
||||
resp, err := hs.queryDataService.QueryDataMultipleSources(c.Req.Context(), anonymousUser, c.SkipCache, reqDTO, true)
|
||||
|
||||
if err != nil {
|
||||
return hs.handleQueryMetricsError(err)
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gofrs/uuid"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/require"
|
||||
@@ -18,10 +19,14 @@ import (
|
||||
"github.com/grafana/grafana-plugin-sdk-go/data"
|
||||
"github.com/grafana/grafana/pkg/api/dtos"
|
||||
"github.com/grafana/grafana/pkg/components/simplejson"
|
||||
"github.com/grafana/grafana/pkg/infra/localcache"
|
||||
"github.com/grafana/grafana/pkg/models"
|
||||
"github.com/grafana/grafana/pkg/services/dashboards"
|
||||
"github.com/grafana/grafana/pkg/services/datasources/service"
|
||||
"github.com/grafana/grafana/pkg/services/featuremgmt"
|
||||
"github.com/grafana/grafana/pkg/services/query"
|
||||
"github.com/grafana/grafana/pkg/services/sqlstore"
|
||||
"github.com/grafana/grafana/pkg/setting"
|
||||
"github.com/grafana/grafana/pkg/web/webtest"
|
||||
|
||||
fakeDatasources "github.com/grafana/grafana/pkg/services/datasources/fakes"
|
||||
@@ -54,39 +59,40 @@ func TestAPIGetPublicDashboard(t *testing.T) {
|
||||
assert.Equal(t, http.StatusNotFound, response.Code)
|
||||
})
|
||||
|
||||
dashboardUid := "dashboard-abcd1234"
|
||||
pubdashUid := "pubdash-abcd1234"
|
||||
DashboardUid := "dashboard-abcd1234"
|
||||
token, err := uuid.NewV4()
|
||||
require.NoError(t, err)
|
||||
accessToken := fmt.Sprintf("%x", token)
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
uid string
|
||||
expectedHttpResponse int
|
||||
Name string
|
||||
AccessToken string
|
||||
ExpectedHttpResponse int
|
||||
publicDashboardResult *models.Dashboard
|
||||
publicDashboardErr error
|
||||
}{
|
||||
{
|
||||
name: "It gets a public dashboard",
|
||||
uid: pubdashUid,
|
||||
expectedHttpResponse: http.StatusOK,
|
||||
Name: "It gets a public dashboard",
|
||||
AccessToken: accessToken,
|
||||
ExpectedHttpResponse: http.StatusOK,
|
||||
publicDashboardResult: &models.Dashboard{
|
||||
Data: simplejson.NewFromAny(map[string]interface{}{
|
||||
"Uid": dashboardUid,
|
||||
"Uid": DashboardUid,
|
||||
}),
|
||||
IsPublic: true,
|
||||
},
|
||||
publicDashboardErr: nil,
|
||||
},
|
||||
{
|
||||
name: "It should return 404 if isPublicDashboard is false",
|
||||
uid: pubdashUid,
|
||||
expectedHttpResponse: http.StatusNotFound,
|
||||
Name: "It should return 404 if isPublicDashboard is false",
|
||||
AccessToken: accessToken,
|
||||
ExpectedHttpResponse: http.StatusNotFound,
|
||||
publicDashboardResult: nil,
|
||||
publicDashboardErr: models.ErrPublicDashboardNotFound,
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range testCases {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
t.Run(test.Name, func(t *testing.T) {
|
||||
sc := setupHTTPServerWithMockDb(t, false, false, featuremgmt.WithFeatures(featuremgmt.FlagPublicDashboards))
|
||||
dashSvc := dashboards.NewFakeDashboardService(t)
|
||||
dashSvc.On("GetPublicDashboard", mock.Anything, mock.AnythingOfType("string")).
|
||||
@@ -97,20 +103,19 @@ func TestAPIGetPublicDashboard(t *testing.T) {
|
||||
response := callAPI(
|
||||
sc.server,
|
||||
http.MethodGet,
|
||||
fmt.Sprintf("/api/public/dashboards/%v", test.uid),
|
||||
fmt.Sprintf("/api/public/dashboards/%s", test.AccessToken),
|
||||
nil,
|
||||
t,
|
||||
)
|
||||
|
||||
assert.Equal(t, test.expectedHttpResponse, response.Code)
|
||||
assert.Equal(t, test.ExpectedHttpResponse, response.Code)
|
||||
|
||||
if test.publicDashboardErr == nil {
|
||||
var dashResp dtos.DashboardFullWithMeta
|
||||
err := json.Unmarshal(response.Body.Bytes(), &dashResp)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, dashboardUid, dashResp.Dashboard.Get("Uid").MustString())
|
||||
assert.Equal(t, true, dashResp.Meta.IsPublic)
|
||||
assert.Equal(t, DashboardUid, dashResp.Dashboard.Get("Uid").MustString())
|
||||
assert.Equal(t, false, dashResp.Meta.CanEdit)
|
||||
assert.Equal(t, false, dashResp.Meta.CanDelete)
|
||||
assert.Equal(t, false, dashResp.Meta.CanSave)
|
||||
@@ -127,44 +132,44 @@ func TestAPIGetPublicDashboard(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestAPIGetPublicDashboardConfig(t *testing.T) {
|
||||
pdc := &models.PublicDashboardConfig{IsPublic: true}
|
||||
pubdash := &models.PublicDashboard{IsEnabled: true}
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
dashboardUid string
|
||||
expectedHttpResponse int
|
||||
publicDashboardConfigResult *models.PublicDashboardConfig
|
||||
publicDashboardConfigError error
|
||||
Name string
|
||||
DashboardUid string
|
||||
ExpectedHttpResponse int
|
||||
PublicDashboardResult *models.PublicDashboard
|
||||
PublicDashboardError error
|
||||
}{
|
||||
{
|
||||
name: "retrieves public dashboard config when dashboard is found",
|
||||
dashboardUid: "1",
|
||||
expectedHttpResponse: http.StatusOK,
|
||||
publicDashboardConfigResult: pdc,
|
||||
publicDashboardConfigError: nil,
|
||||
Name: "retrieves public dashboard config when dashboard is found",
|
||||
DashboardUid: "1",
|
||||
ExpectedHttpResponse: http.StatusOK,
|
||||
PublicDashboardResult: pubdash,
|
||||
PublicDashboardError: nil,
|
||||
},
|
||||
{
|
||||
name: "returns 404 when dashboard not found",
|
||||
dashboardUid: "77777",
|
||||
expectedHttpResponse: http.StatusNotFound,
|
||||
publicDashboardConfigResult: nil,
|
||||
publicDashboardConfigError: models.ErrDashboardNotFound,
|
||||
Name: "returns 404 when dashboard not found",
|
||||
DashboardUid: "77777",
|
||||
ExpectedHttpResponse: http.StatusNotFound,
|
||||
PublicDashboardResult: nil,
|
||||
PublicDashboardError: models.ErrDashboardNotFound,
|
||||
},
|
||||
{
|
||||
name: "returns 500 when internal server error",
|
||||
dashboardUid: "1",
|
||||
expectedHttpResponse: http.StatusInternalServerError,
|
||||
publicDashboardConfigResult: nil,
|
||||
publicDashboardConfigError: errors.New("database broken"),
|
||||
Name: "returns 500 when internal server error",
|
||||
DashboardUid: "1",
|
||||
ExpectedHttpResponse: http.StatusInternalServerError,
|
||||
PublicDashboardResult: nil,
|
||||
PublicDashboardError: errors.New("database broken"),
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range testCases {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
t.Run(test.Name, func(t *testing.T) {
|
||||
sc := setupHTTPServerWithMockDb(t, false, false, featuremgmt.WithFeatures(featuremgmt.FlagPublicDashboards))
|
||||
dashSvc := dashboards.NewFakeDashboardService(t)
|
||||
dashSvc.On("GetPublicDashboardConfig", mock.Anything, mock.AnythingOfType("int64"), mock.AnythingOfType("string")).
|
||||
Return(test.publicDashboardConfigResult, test.publicDashboardConfigError)
|
||||
Return(test.PublicDashboardResult, test.PublicDashboardError)
|
||||
sc.hs.dashboardService = dashSvc
|
||||
|
||||
setInitCtxSignedInViewer(sc.initCtx)
|
||||
@@ -176,13 +181,13 @@ func TestAPIGetPublicDashboardConfig(t *testing.T) {
|
||||
t,
|
||||
)
|
||||
|
||||
assert.Equal(t, test.expectedHttpResponse, response.Code)
|
||||
assert.Equal(t, test.ExpectedHttpResponse, response.Code)
|
||||
|
||||
if response.Code == http.StatusOK {
|
||||
var pdcResp models.PublicDashboardConfig
|
||||
var pdcResp models.PublicDashboard
|
||||
err := json.Unmarshal(response.Body.Bytes(), &pdcResp)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, test.publicDashboardConfigResult, &pdcResp)
|
||||
assert.Equal(t, test.PublicDashboardResult, &pdcResp)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -190,40 +195,40 @@ func TestAPIGetPublicDashboardConfig(t *testing.T) {
|
||||
|
||||
func TestApiSavePublicDashboardConfig(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
dashboardUid string
|
||||
publicDashboardConfig *models.PublicDashboardConfig
|
||||
expectedHttpResponse int
|
||||
Name string
|
||||
DashboardUid string
|
||||
publicDashboardConfig *models.PublicDashboard
|
||||
ExpectedHttpResponse int
|
||||
saveDashboardError error
|
||||
}{
|
||||
{
|
||||
name: "returns 200 when update persists",
|
||||
dashboardUid: "1",
|
||||
publicDashboardConfig: &models.PublicDashboardConfig{IsPublic: true},
|
||||
expectedHttpResponse: http.StatusOK,
|
||||
Name: "returns 200 when update persists",
|
||||
DashboardUid: "1",
|
||||
publicDashboardConfig: &models.PublicDashboard{IsEnabled: true},
|
||||
ExpectedHttpResponse: http.StatusOK,
|
||||
saveDashboardError: nil,
|
||||
},
|
||||
{
|
||||
name: "returns 500 when not persisted",
|
||||
expectedHttpResponse: http.StatusInternalServerError,
|
||||
publicDashboardConfig: &models.PublicDashboardConfig{},
|
||||
Name: "returns 500 when not persisted",
|
||||
ExpectedHttpResponse: http.StatusInternalServerError,
|
||||
publicDashboardConfig: &models.PublicDashboard{},
|
||||
saveDashboardError: errors.New("backend failed to save"),
|
||||
},
|
||||
{
|
||||
name: "returns 404 when dashboard not found",
|
||||
expectedHttpResponse: http.StatusNotFound,
|
||||
publicDashboardConfig: &models.PublicDashboardConfig{},
|
||||
Name: "returns 404 when dashboard not found",
|
||||
ExpectedHttpResponse: http.StatusNotFound,
|
||||
publicDashboardConfig: &models.PublicDashboard{},
|
||||
saveDashboardError: models.ErrDashboardNotFound,
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range testCases {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
t.Run(test.Name, func(t *testing.T) {
|
||||
sc := setupHTTPServerWithMockDb(t, false, false, featuremgmt.WithFeatures(featuremgmt.FlagPublicDashboards))
|
||||
|
||||
dashSvc := dashboards.NewFakeDashboardService(t)
|
||||
dashSvc.On("SavePublicDashboardConfig", mock.Anything, mock.AnythingOfType("*dashboards.SavePublicDashboardConfigDTO")).
|
||||
Return(&models.PublicDashboardConfig{IsPublic: true}, test.saveDashboardError)
|
||||
Return(&models.PublicDashboard{IsEnabled: true}, test.saveDashboardError)
|
||||
sc.hs.dashboardService = dashSvc
|
||||
|
||||
setInitCtxSignedInViewer(sc.initCtx)
|
||||
@@ -235,7 +240,7 @@ func TestApiSavePublicDashboardConfig(t *testing.T) {
|
||||
t,
|
||||
)
|
||||
|
||||
assert.Equal(t, test.expectedHttpResponse, response.Code)
|
||||
assert.Equal(t, test.ExpectedHttpResponse, response.Code)
|
||||
|
||||
// check the result if it's a 200
|
||||
if response.Code == http.StatusOK {
|
||||
@@ -326,10 +331,14 @@ func TestAPIQueryPublicDashboard(t *testing.T) {
|
||||
t.Run("Returns query data when feature toggle is enabled", func(t *testing.T) {
|
||||
server, fakeDashboardService := setup(true)
|
||||
|
||||
fakeDashboardService.On("GetPublicDashboard", mock.Anything, mock.Anything).Return(&models.Dashboard{}, nil)
|
||||
fakeDashboardService.On("GetPublicDashboardConfig", mock.Anything, mock.Anything, mock.Anything).Return(&models.PublicDashboard{}, nil)
|
||||
|
||||
fakeDashboardService.On(
|
||||
"BuildPublicDashboardMetricRequest",
|
||||
mock.Anything,
|
||||
"abc123",
|
||||
mock.Anything,
|
||||
mock.Anything,
|
||||
int64(2),
|
||||
).Return(dtos.MetricRequest{
|
||||
Queries: []*simplejson.Json{
|
||||
@@ -385,10 +394,13 @@ func TestAPIQueryPublicDashboard(t *testing.T) {
|
||||
t.Run("Status code is 500 when the query fails", func(t *testing.T) {
|
||||
server, fakeDashboardService := setup(true)
|
||||
|
||||
fakeDashboardService.On("GetPublicDashboard", mock.Anything, mock.Anything).Return(&models.Dashboard{}, nil)
|
||||
fakeDashboardService.On("GetPublicDashboardConfig", mock.Anything, mock.Anything, mock.Anything).Return(&models.PublicDashboard{}, nil)
|
||||
fakeDashboardService.On(
|
||||
"BuildPublicDashboardMetricRequest",
|
||||
mock.Anything,
|
||||
"abc123",
|
||||
mock.Anything,
|
||||
mock.Anything,
|
||||
int64(2),
|
||||
).Return(dtos.MetricRequest{
|
||||
Queries: []*simplejson.Json{
|
||||
@@ -422,10 +434,13 @@ func TestAPIQueryPublicDashboard(t *testing.T) {
|
||||
t.Run("Status code is 200 when a panel has queries from multiple datasources", func(t *testing.T) {
|
||||
server, fakeDashboardService := setup(true)
|
||||
|
||||
fakeDashboardService.On("GetPublicDashboard", mock.Anything, mock.Anything).Return(&models.Dashboard{}, nil)
|
||||
fakeDashboardService.On("GetPublicDashboardConfig", mock.Anything, mock.Anything, mock.Anything).Return(&models.PublicDashboard{}, nil)
|
||||
fakeDashboardService.On(
|
||||
"BuildPublicDashboardMetricRequest",
|
||||
mock.Anything,
|
||||
"abc123",
|
||||
mock.Anything,
|
||||
mock.Anything,
|
||||
int64(2),
|
||||
).Return(dtos.MetricRequest{
|
||||
Queries: []*simplejson.Json{
|
||||
@@ -505,3 +520,111 @@ func TestAPIQueryPublicDashboard(t *testing.T) {
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
})
|
||||
}
|
||||
|
||||
func TestIntegrationUnauthenticatedUserCanGetPubdashPanelQueryData(t *testing.T) {
|
||||
config := setting.NewCfg()
|
||||
db := sqlstore.InitTestDB(t)
|
||||
scenario := setupHTTPServerWithCfgDb(t, false, false, config, db, db, featuremgmt.WithFeatures(featuremgmt.FlagPublicDashboards))
|
||||
scenario.initCtx.SkipCache = true
|
||||
cacheService := service.ProvideCacheService(localcache.ProvideService(), db)
|
||||
qds := query.ProvideService(
|
||||
nil,
|
||||
cacheService,
|
||||
nil,
|
||||
&fakePluginRequestValidator{},
|
||||
&fakeDatasources.FakeDataSourceService{},
|
||||
&fakePluginClient{
|
||||
QueryDataHandlerFunc: func(ctx context.Context, req *backend.QueryDataRequest) (*backend.QueryDataResponse, error) {
|
||||
resp := backend.Responses{
|
||||
"A": backend.DataResponse{
|
||||
Frames: []*data.Frame{{}},
|
||||
},
|
||||
}
|
||||
return &backend.QueryDataResponse{Responses: resp}, nil
|
||||
},
|
||||
},
|
||||
&fakeOAuthTokenService{},
|
||||
)
|
||||
scenario.hs.queryDataService = qds
|
||||
|
||||
_ = db.AddDataSource(context.Background(), &models.AddDataSourceCommand{
|
||||
Uid: "ds1",
|
||||
OrgId: 1,
|
||||
Name: "laban",
|
||||
Type: models.DS_MYSQL,
|
||||
Access: models.DS_ACCESS_DIRECT,
|
||||
Url: "http://test",
|
||||
Database: "site",
|
||||
ReadOnly: true,
|
||||
})
|
||||
|
||||
// Create Dashboard
|
||||
saveDashboardCmd := models.SaveDashboardCommand{
|
||||
OrgId: 1,
|
||||
FolderId: 1,
|
||||
IsFolder: false,
|
||||
Dashboard: simplejson.NewFromAny(map[string]interface{}{
|
||||
"id": nil,
|
||||
"title": "test",
|
||||
"panels": []map[string]interface{}{
|
||||
{
|
||||
"id": 1,
|
||||
"targets": []map[string]interface{}{
|
||||
{
|
||||
"datasource": map[string]string{
|
||||
"type": "mysql",
|
||||
"uid": "ds1",
|
||||
},
|
||||
"refId": "A",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
}
|
||||
dashboard, _ := scenario.dashboardsStore.SaveDashboard(saveDashboardCmd)
|
||||
|
||||
// Create public dashboard
|
||||
savePubDashboardCmd := &dashboards.SavePublicDashboardConfigDTO{
|
||||
DashboardUid: dashboard.Uid,
|
||||
OrgId: dashboard.OrgId,
|
||||
PublicDashboard: &models.PublicDashboard{
|
||||
IsEnabled: true,
|
||||
},
|
||||
}
|
||||
|
||||
pubdash, err := scenario.hs.dashboardService.SavePublicDashboardConfig(context.Background(), savePubDashboardCmd)
|
||||
require.NoError(t, err)
|
||||
|
||||
response := callAPI(
|
||||
scenario.server,
|
||||
http.MethodPost,
|
||||
fmt.Sprintf("/api/public/dashboards/%s/panels/1/query", pubdash.AccessToken),
|
||||
strings.NewReader(`{}`),
|
||||
t,
|
||||
)
|
||||
|
||||
require.Equal(t, http.StatusOK, response.Code)
|
||||
bodyBytes, err := ioutil.ReadAll(response.Body)
|
||||
require.NoError(t, err)
|
||||
require.JSONEq(
|
||||
t,
|
||||
`{
|
||||
"results": {
|
||||
"A": {
|
||||
"frames": [
|
||||
{
|
||||
"data": {
|
||||
"values": []
|
||||
},
|
||||
"schema": {
|
||||
"fields": []
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}`,
|
||||
string(bodyBytes),
|
||||
)
|
||||
}
|
||||
|
||||
+27
-28
@@ -7,34 +7,33 @@ import (
|
||||
)
|
||||
|
||||
type DashboardMeta struct {
|
||||
IsStarred bool `json:"isStarred,omitempty"`
|
||||
IsHome bool `json:"isHome,omitempty"`
|
||||
IsSnapshot bool `json:"isSnapshot,omitempty"`
|
||||
Type string `json:"type,omitempty"`
|
||||
CanSave bool `json:"canSave"`
|
||||
CanEdit bool `json:"canEdit"`
|
||||
CanAdmin bool `json:"canAdmin"`
|
||||
CanStar bool `json:"canStar"`
|
||||
CanDelete bool `json:"canDelete"`
|
||||
Slug string `json:"slug"`
|
||||
Url string `json:"url"`
|
||||
Expires time.Time `json:"expires"`
|
||||
Created time.Time `json:"created"`
|
||||
Updated time.Time `json:"updated"`
|
||||
UpdatedBy string `json:"updatedBy"`
|
||||
CreatedBy string `json:"createdBy"`
|
||||
Version int `json:"version"`
|
||||
HasAcl bool `json:"hasAcl"`
|
||||
IsFolder bool `json:"isFolder"`
|
||||
FolderId int64 `json:"folderId"`
|
||||
FolderUid string `json:"folderUid"`
|
||||
FolderTitle string `json:"folderTitle"`
|
||||
FolderUrl string `json:"folderUrl"`
|
||||
Provisioned bool `json:"provisioned"`
|
||||
ProvisionedExternalId string `json:"provisionedExternalId"`
|
||||
AnnotationsPermissions *AnnotationPermission `json:"annotationsPermissions"`
|
||||
IsPublic bool `json:"isPublic"`
|
||||
PublicDashboardUid string `json:"publicDashboardUid"`
|
||||
IsStarred bool `json:"isStarred,omitempty"`
|
||||
IsHome bool `json:"isHome,omitempty"`
|
||||
IsSnapshot bool `json:"isSnapshot,omitempty"`
|
||||
Type string `json:"type,omitempty"`
|
||||
CanSave bool `json:"canSave"`
|
||||
CanEdit bool `json:"canEdit"`
|
||||
CanAdmin bool `json:"canAdmin"`
|
||||
CanStar bool `json:"canStar"`
|
||||
CanDelete bool `json:"canDelete"`
|
||||
Slug string `json:"slug"`
|
||||
Url string `json:"url"`
|
||||
Expires time.Time `json:"expires"`
|
||||
Created time.Time `json:"created"`
|
||||
Updated time.Time `json:"updated"`
|
||||
UpdatedBy string `json:"updatedBy"`
|
||||
CreatedBy string `json:"createdBy"`
|
||||
Version int `json:"version"`
|
||||
HasAcl bool `json:"hasAcl"`
|
||||
IsFolder bool `json:"isFolder"`
|
||||
FolderId int64 `json:"folderId"`
|
||||
FolderUid string `json:"folderUid"`
|
||||
FolderTitle string `json:"folderTitle"`
|
||||
FolderUrl string `json:"folderUrl"`
|
||||
Provisioned bool `json:"provisioned"`
|
||||
ProvisionedExternalId string `json:"provisionedExternalId"`
|
||||
AnnotationsPermissions *AnnotationPermission `json:"annotationsPermissions"`
|
||||
PublicDashboardAccessToken string `json:"publicDashboardAccessToken"`
|
||||
}
|
||||
type AnnotationPermission struct {
|
||||
Dashboard AnnotationActions `json:"dashboard"`
|
||||
|
||||
Reference in New Issue
Block a user