grim/devweb

clean up the cli commands for managing api keys
draft
2020-11-14, Gary Kramlich
55f3ba42d58d
Parents 454462e98cfc
Children e397f720cc8e
clean up the cli commands for managing api keys
--- a/access/cmd.go Fri Nov 13 23:36:08 2020 -0600
+++ b/access/cmd.go Sat Nov 14 00:07:54 2020 -0600
@@ -3,4 +3,5 @@
type Cmd struct {
Create CreateCmd `kong:"cmd,help='Creates a new api key.'"`
Delete DeleteCmd `kong:"cmd,help='Deletes the given access key.'"`
+ List ListCmd `kong:"cmd,help='Lists the available api keys.'"`
}
--- a/access/delete.go Fri Nov 13 23:36:08 2020 -0600
+++ b/access/delete.go Sat Nov 14 00:07:54 2020 -0600
@@ -8,7 +8,7 @@
type DeleteCmd struct {
db.Options
- AccessKey string `kong:"arg,help='The access key to delete.'"`
+ AccessKeys []string `kong:"arg,help='The access key to delete.'"`
}
func (c *DeleteCmd) Run() error {
@@ -17,15 +17,20 @@
return err
}
- apiKey := db.APIKey{
- AccessKey: c.AccessKey,
- }
- if err := apiKey.Delete(); err != nil {
- db.Teardown()
- return err
+ removed := 0
+
+ for _, accessKey := range c.AccessKeys {
+ apiKey := db.APIKey{
+ AccessKey: accessKey,
+ }
+ if err := apiKey.Delete(); err != nil {
+ fmt.Printf("Failed to remove api key %s: %v\n", accessKey, err)
+ } else {
+ removed += 1
+ }
}
- fmt.Printf("Removed api keys %q\n", c.AccessKey)
+ fmt.Printf("Removed %d api keys\n", removed)
return db.Teardown()
}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/access/list.go Sat Nov 14 00:07:54 2020 -0600
@@ -0,0 +1,31 @@
+package access
+
+import (
+ "fmt"
+
+ "keep.imfreedom.org/grim/devweb/db"
+)
+
+type ListCmd struct {
+ db.Options
+}
+
+func (c *ListCmd) Run() error {
+ err := db.Setup(c.Options.Driver, c.Options.Options)
+ if err != nil {
+ return err
+ }
+
+ apiKeys, err := db.ListAPIKeys()
+ if err != nil {
+ db.Teardown()
+ return err
+ }
+
+ fmt.Printf("Found %d APIKeys\n", len(apiKeys))
+ for _, apiKey := range apiKeys {
+ fmt.Printf("%s\t%s\n", apiKey.AccessKey, apiKey.Description)
+ }
+
+ return db.Teardown()
+}
--- a/db/apikey.go Fri Nov 13 23:36:08 2020 -0600
+++ b/db/apikey.go Sat Nov 14 00:07:54 2020 -0600
@@ -1,5 +1,9 @@
package db
+import (
+ "fmt"
+)
+
type APIKey struct {
AccessKey string `db:"access_key"`
SecretKey string `db:"secret_key"`
@@ -26,7 +30,30 @@
func (a APIKey) Delete() error {
query := `DELETE FROM api_keys WHERE access_key=$1;`
- _, err := _db.Exec(query, a.AccessKey)
+ res, err := _db.Exec(query, a.AccessKey)
+ if err != nil {
+ return err
+ }
+
+ rows, err := res.RowsAffected()
+ if err != nil {
+ return err
+ }
+
+ if rows != 1 {
+ return fmt.Errorf("access key %s not found", a.AccessKey)
+ }
- return err
+ return nil
}
+
+func ListAPIKeys() ([]APIKey, error) {
+ api_keys := []APIKey{}
+
+ query := `SELECT access_key, description FROM api_keys ORDER BY access_key ASC`
+ if err := _db.Select(&api_keys, query); err != nil {
+ return nil, err
+ }
+
+ return api_keys, nil
+}