Skip to content

Commit

Permalink
Adding Dashboard Folder Permissions
Browse files Browse the repository at this point in the history
  • Loading branch information
safaci2000 committed Sep 12, 2024
1 parent 5e5f2a2 commit 4d915e0
Show file tree
Hide file tree
Showing 14 changed files with 931 additions and 98 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ jobs:
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: '1.22.1'
go-version: '1.22.2'
- name: Log in to Docker Hub
uses: docker/login-action@v2
with:
Expand Down
2 changes: 1 addition & 1 deletion cli/backup/connection_permissions.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ func newConnectionsPermissionCmd() simplecobra.Commander {
Short: description,
Long: description,
WithCFunc: func(cmd *cobra.Command, r *support.RootCommand) {
cmd.Aliases = []string{"l", "permissions"}
cmd.Aliases = []string{"p", "permissions"}
},
CommandsList: []simplecobra.Commander{
newConnectionsPermissionListCmd(),
Expand Down
32 changes: 18 additions & 14 deletions cli/backup/dashboard.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import (
"net/url"
"strings"

"github.com/grafana/grafana-openapi-client-go/models"

"github.com/bep/simplecobra"
"github.com/esnet/gdg/cli/support"
"github.com/esnet/gdg/internal/config"
Expand Down Expand Up @@ -50,6 +52,8 @@ func newDashboardCommand() simplecobra.Commander {
newDownloadDashboardsCmd(),
newUploadDashboardsCmd(),
newClearDashboardsCmd(),
// Permissions
newDashboardPermissionCmd(),
},
RunFunc: func(ctx context.Context, cd *simplecobra.Commandeer, rootCmd *support.RootCommand, args []string) error {
return cd.CobraCommand.Help()
Expand Down Expand Up @@ -151,6 +155,19 @@ func newDownloadDashboardsCmd() simplecobra.Commander {
}
}

func getDashboardUrl(link *models.Hit) string {
base, err := url.Parse(config.Config().GetDefaultGrafanaConfig().URL)
var baseHost string
if err != nil {
baseHost = "http://unknown/"
slog.Warn("unable to determine grafana base host for dashboard", slog.String("dashboard-uid", link.UID))
} else {
base.Path = ""
baseHost = base.String()
}
return fmt.Sprintf("%s%s", baseHost, link.URL)
}

func newListDashboardsCmd() simplecobra.Commander {
description := "List all dashboards from grafana"
return &support.SimpleCommand{
Expand Down Expand Up @@ -181,21 +198,8 @@ func newListDashboardsCmd() simplecobra.Commander {
count := 0

for _, link := range boards {
base, err := url.Parse(config.Config().GetDefaultGrafanaConfig().URL)
var baseHost string
if err != nil {
baseHost = "http://unknown/"
slog.Warn("unable to determine grafana base host for dashboard", slog.String("dashboard-uid", link.UID))
} else {
base.Path = ""
baseHost = base.String()
}
if string(link.Type) == service.SearchTypeFolder {
slog.Debug("skipping entry for", slog.Any("slug", link.Slug), slog.Any("url", fmt.Sprintf("%s/%s", baseHost, link.UID)), slog.Any("type", link.Type))
continue
}
urlValue := getDashboardUrl(link)
count++
urlValue := fmt.Sprintf("%s%s", baseHost, link.URL)
var tagVal string
if len(link.Tags) > 0 {
tagValByte, err := json.Marshal(link.Tags)
Expand Down
189 changes: 189 additions & 0 deletions cli/backup/dashboard_permissions.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
package backup

import (
"context"
"fmt"
"log/slog"
"os"

"github.com/bep/simplecobra"
"github.com/esnet/gdg/cli/support"
"github.com/esnet/gdg/internal/config"
"github.com/esnet/gdg/internal/service"
"github.com/esnet/gdg/internal/tools"
"github.com/jedib0t/go-pretty/v6/table"

"github.com/spf13/cobra"
)

func newDashboardPermissionCmd() simplecobra.Commander {
description := "Dashboard Permission"
return &support.SimpleCommand{
NameP: "permission",
Short: description,
Long: description,
WithCFunc: func(cmd *cobra.Command, r *support.RootCommand) {
cmd.Aliases = []string{"p", "permissions"}
},
CommandsList: []simplecobra.Commander{
newDashboardPermissionListCmd(),
newDashboardPermissionDownloadCmd(),
newDashboardPermissionUploadCmd(),
newDashboardPermissionClearCmd(),
},
RunFunc: func(ctx context.Context, cd *simplecobra.Commandeer, rootCmd *support.RootCommand, args []string) error {
return cd.CobraCommand.Help()
},
}
}

// getConnectionTbWriter returns a table object for use with newConnectionsPermissionListCmd
func getDashboardPermTblWriter() table.Writer {
writer := table.NewWriter()
writer.SetOutputMirror(os.Stdout)
writer.SetStyle(table.StyleLight)
writer.AppendHeader(table.Row{"id", "name", "slug", "type", "uid", "url"}, table.RowConfig{AutoMerge: true})
return writer
}

func newDashboardPermissionListCmd() simplecobra.Commander {
description := "List Dashboard Permissions"
return &support.SimpleCommand{
NameP: "list",
Short: description,
Long: description,
WithCFunc: func(cmd *cobra.Command, r *support.RootCommand) {
cmd.Aliases = []string{"l"}
},
RunFunc: func(ctx context.Context, cd *simplecobra.Commandeer, rootCmd *support.RootCommand, args []string) error {
slog.Info("Listing Dashboard Permissions for context", "context", config.Config().GetGDGConfig().GetContext())
filters := service.NewDashboardFilter(parseDashboardGlobalFlags(cd.CobraCommand)...)
permissions, err := rootCmd.GrafanaSvc().ListDashboardPermissions(filters)
if err != nil {
slog.Error("Failed to retrieve Dashboard Permissions", "error", err)
os.Exit(1)
}

if len(permissions) == 0 {
slog.Info("No Dashboards found")
} else {
for _, perms := range permissions {
writer := getDashboardPermTblWriter()
urlValue := getDashboardUrl(perms.Dashboard)
link := perms.Dashboard
writer.AppendRow(table.Row{
link.ID, link.Title, link.Slug, link.FolderTitle,
link.UID, urlValue,
})
writer.Render()
if perms.Permissions != nil {
twConfigs := table.NewWriter()
twConfigs.SetOutputMirror(os.Stdout)
twConfigs.SetStyle(table.StyleColoredCyanWhiteOnBlack)
twConfigs.AppendHeader(table.Row{"Dashboard UID", "Dashboard Title", "UserId", "Team", "RoleName", "Permission"})
for _, dashPerm := range perms.Permissions {
twConfigs.AppendRow(table.Row{link.UID, link.Title, dashPerm.UserID, dashPerm.Team, dashPerm.Role, dashPerm.Permission})
}
if len(perms.Permissions) > 0 {
twConfigs.Render()
}
}
}
}
return nil
},
}
}

func newDashboardPermissionClearCmd() simplecobra.Commander {
description := "Clear Connection Permissions"
return &support.SimpleCommand{
NameP: "clear",
Short: description,
Long: description,
WithCFunc: func(cmd *cobra.Command, r *support.RootCommand) {
cmd.Aliases = []string{"c"}
},
RunFunc: func(ctx context.Context, cd *simplecobra.Commandeer, rootCmd *support.RootCommand, args []string) error {
slog.Info("Clear all Dashboard permissions")
tools.GetUserConfirmation(fmt.Sprintf("WARNING: this will clear all permission from all Dashboards on: '%s' "+
"(Or all permission matching your filters). Do you wish to continue (y/n) ", config.Config().GetGDGConfig().ContextName,
), "", true)
rootCmd.TableObj.AppendHeader(table.Row{"cleared Dashboard permissions"})
filters := service.NewDashboardFilter(parseDashboardGlobalFlags(cd.CobraCommand)...)
err := rootCmd.GrafanaSvc().ClearDashboardPermissions(filters)
if err != nil {
slog.Error("Failed to retrieve Dashboard Permissions", "error", err)
} else {
slog.Info("All dashboard permissions have been cleared")
}
return nil
},
}
}

func newDashboardPermissionDownloadCmd() simplecobra.Commander {
description := "Download Connection Permissions"
return &support.SimpleCommand{
NameP: "download",
Short: description,
Long: description,
WithCFunc: func(cmd *cobra.Command, r *support.RootCommand) {
cmd.Aliases = []string{"d"}
},
RunFunc: func(ctx context.Context, cd *simplecobra.Commandeer, rootCmd *support.RootCommand, args []string) error {
slog.Info("Download Connections for context",
"context", config.Config().GetGDGConfig().GetContext())
rootCmd.TableObj.AppendHeader(table.Row{"filename"})
filters := service.NewDashboardFilter(parseDashboardGlobalFlags(cd.CobraCommand)...)
permissions, err := rootCmd.GrafanaSvc().DownloadDashboardPermissions(filters)
if err != nil {
slog.Error("Failed to retrieve Dashboard Permissions", "error", err)
os.Exit(1)
}
slog.Info("Downloading Dashboard permissions")

if len(permissions) == 0 {
slog.Info("No Dashboard permissions")
} else {
for _, perm := range permissions {
rootCmd.TableObj.AppendRow(table.Row{perm})
}
rootCmd.Render(cd.CobraCommand, permissions)
}
return nil
},
}
}

func newDashboardPermissionUploadCmd() simplecobra.Commander {
description := "Upload Connection Permissions"
return &support.SimpleCommand{
NameP: "upload",
Short: description,
Long: description,
WithCFunc: func(cmd *cobra.Command, r *support.RootCommand) {
cmd.Aliases = []string{"u"}
},
RunFunc: func(ctx context.Context, cd *simplecobra.Commandeer, rootCmd *support.RootCommand, args []string) error {
slog.Info("Uploading dashboard permissions")
rootCmd.TableObj.AppendHeader(table.Row{"dashboard permission"})
filters := service.NewDashboardFilter(parseDashboardGlobalFlags(cd.CobraCommand)...)
permissions, err := rootCmd.GrafanaSvc().UploadDashboardPermissions(filters)
if err != nil {
slog.Error("Failed to retrieve Dashboard Permissions", "error", err)
os.Exit(1)
}

if len(permissions) == 0 {
slog.Info("No permissions found")
} else {
for _, perm := range permissions {
rootCmd.TableObj.AppendRow(table.Row{perm})
}
rootCmd.Render(cd.CobraCommand, permissions)
}
return nil
},
}
}
6 changes: 4 additions & 2 deletions cli/tools/org_users.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ func newUpdateUserRoleCmd() simplecobra.Commander {
if err != nil {
log.Fatal("unable to parse userId to numeric value")
}
slog.Info("Listing org users for context", "context", config.Config().GetGDGConfig().GetContext())
slog.Info("Updating User role for context", slog.Any("context", config.Config().GetGDGConfig().GetContext()))
rootCmd.TableObj.AppendHeader(table.Row{"login", "orgId", "name", "email", "role"})
err = rootCmd.GrafanaSvc().UpdateUserInOrg(roleName, orgSlug, userId)
if err != nil {
Expand Down Expand Up @@ -143,6 +143,8 @@ func newAddUserRoleCmd() simplecobra.Commander {
log.Fatal("unable to parse userId to numeric value")
}
slog.Info("Add user to org for context",
slog.Any("userId", userId),
slog.Any("orgSlug", orgSlug),
slog.Any("context", config.Config().GetGDGConfig().GetContext()),
slog.Any("organization", config.Config().GetDefaultGrafanaConfig().OrganizationName),
)
Expand All @@ -152,7 +154,7 @@ func newAddUserRoleCmd() simplecobra.Commander {
rootCmd.TableObj.AppendHeader(table.Row{"login", "orgId", "name", "email", "role"})
err = rootCmd.GrafanaSvc().AddUserToOrg(role, orgSlug, userId)
if err != nil {
slog.Error("Unable to add user to Org", slog.Any("err", err.Error()))
slog.Error("Unable to add user to Org, already exists", slog.Any("err", err.Error()))
} else {
slog.Info("User has been add to Org", slog.Any("userId", userId), slog.String("organization", orgSlug))
}
Expand Down
Loading

0 comments on commit 4d915e0

Please sign in to comment.