github.com/esnet/gdg@v0.6.1-0.20240412190737-6b6eba9c14d8/cli/tools/auth_tokens.go (about)

     1  package tools
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  	"github.com/bep/simplecobra"
     7  	"github.com/esnet/gdg/cli/support"
     8  	"github.com/esnet/gdg/internal/config"
     9  	"github.com/jedib0t/go-pretty/v6/table"
    10  	"github.com/spf13/cobra"
    11  	"log"
    12  	"log/slog"
    13  	"slices"
    14  	"sort"
    15  	"strconv"
    16  )
    17  
    18  func newTokensCmd() simplecobra.Commander {
    19  	description := "Provides some utility to help the user manage their API token keys"
    20  	return &support.SimpleCommand{
    21  		NameP: "tokens",
    22  		Short: description,
    23  		Long:  description,
    24  		RunFunc: func(ctx context.Context, cd *simplecobra.Commandeer, rootCmd *support.RootCommand, args []string) error {
    25  			return cd.CobraCommand.Help()
    26  		},
    27  		WithCFunc: func(cmd *cobra.Command, r *support.RootCommand) {
    28  			cmd.Aliases = []string{"token", "apikeys"}
    29  		},
    30  		CommandsList: []simplecobra.Commander{
    31  			newListTokensCmd(),
    32  			newDeleteTokenCmd(),
    33  			newNewTokenCmd(),
    34  		},
    35  	}
    36  }
    37  
    38  func newListTokensCmd() simplecobra.Commander {
    39  	description := "List API Keys"
    40  	return &support.SimpleCommand{
    41  		NameP:        "list",
    42  		Short:        description,
    43  		Long:         description,
    44  		CommandsList: []simplecobra.Commander{},
    45  		RunFunc: func(ctx context.Context, cd *simplecobra.Commandeer, rootCmd *support.RootCommand, args []string) error {
    46  
    47  			rootCmd.TableObj.AppendHeader(table.Row{"id", "name", "role", "expiration"})
    48  			apiKeys := rootCmd.GrafanaSvc().ListAPIKeys()
    49  			sort.SliceStable(apiKeys, func(i, j int) bool {
    50  				return apiKeys[i].ID < apiKeys[j].ID
    51  			})
    52  			if len(apiKeys) == 0 {
    53  				slog.Info("No apiKeys found")
    54  			} else {
    55  				for _, apiKey := range apiKeys {
    56  					var formattedDate string = apiKey.Expiration.String()
    57  					date, _ := apiKey.Expiration.Value()
    58  					if date.(string) == "0001-01-01T00:00:00.000Z" {
    59  						formattedDate = "No Expiration"
    60  					}
    61  
    62  					rootCmd.TableObj.AppendRow(table.Row{apiKey.ID, apiKey.Name, apiKey.Role, formattedDate})
    63  				}
    64  				rootCmd.Render(cd.CobraCommand, apiKeys)
    65  			}
    66  			return nil
    67  		},
    68  	}
    69  }
    70  
    71  func newDeleteTokenCmd() simplecobra.Commander {
    72  	description := "delete all Tokens from grafana"
    73  	return &support.SimpleCommand{
    74  		NameP:        "clear",
    75  		Short:        description,
    76  		Long:         description,
    77  		CommandsList: []simplecobra.Commander{},
    78  		RunFunc: func(ctx context.Context, cd *simplecobra.Commandeer, rootCmd *support.RootCommand, args []string) error {
    79  
    80  			savedFiles := rootCmd.GrafanaSvc().DeleteAllTokens()
    81  			slog.Info("Delete Tokens for context: ", "context", config.Config().GetGDGConfig().GetContext())
    82  			rootCmd.TableObj.AppendHeader(table.Row{"type", "filename"})
    83  			if len(savedFiles) == 0 {
    84  				slog.Info("No Tokens found")
    85  			} else {
    86  				for _, file := range savedFiles {
    87  					rootCmd.TableObj.AppendRow(table.Row{"user", file})
    88  				}
    89  				rootCmd.Render(cd.CobraCommand, savedFiles)
    90  			}
    91  			return nil
    92  		},
    93  	}
    94  }
    95  
    96  func newNewTokenCmd() simplecobra.Commander {
    97  	description := "new <name> <role> [ttl in seconds]"
    98  	return &support.SimpleCommand{
    99  		NameP:        "new",
   100  		Short:        description,
   101  		Long:         description,
   102  		CommandsList: []simplecobra.Commander{},
   103  		RunFunc: func(ctx context.Context, cd *simplecobra.Commandeer, rootCmd *support.RootCommand, args []string) error {
   104  			if len(args) < 2 {
   105  				return errors.New("requires a key name and a role('admin','viewer','editor') [ttl optional] ")
   106  			}
   107  			name := args[0]
   108  			role := args[1]
   109  			ttl := "0"
   110  			if len(args) > 2 {
   111  				ttl = args[2]
   112  			}
   113  			var (
   114  				expiration int64
   115  				err        error
   116  			)
   117  
   118  			expiration, err = strconv.ParseInt(ttl, 10, 64)
   119  			if err != nil {
   120  				expiration = 0
   121  			}
   122  
   123  			if !slices.Contains([]string{"admin", "editor", "viewer"}, role) {
   124  				log.Fatal("Invalid role specified")
   125  			}
   126  			key, err := rootCmd.GrafanaSvc().CreateAPIKey(name, role, expiration)
   127  			if err != nil {
   128  				log.Fatal("unable to create api key", "err", err)
   129  			} else {
   130  
   131  				rootCmd.TableObj.AppendHeader(table.Row{"id", "name", "token"})
   132  				rootCmd.TableObj.AppendRow(table.Row{key.ID, key.Name, key.Key})
   133  				rootCmd.Render(cd.CobraCommand, map[string]interface{}{"id": key.ID, "name": key.Name, "token": key.Key})
   134  			}
   135  
   136  			return nil
   137  		},
   138  	}
   139  }