diff --git a/key.go b/key.go index 1f50033..209ede5 100644 --- a/key.go +++ b/key.go @@ -117,6 +117,15 @@ func (k *Key) Delete() error { return k.secret.Remove() } +func (k *Key) Rename(newName string) error { + err := k.secret.Rename(newName) + if err != nil { + return err + } + k.Name = newName + return nil +} + // func (this Key) MarshalJSON() ([]byte, error) { // m := map[string]interface{}{} // ideally use make with the right capacity // m["digits"] = this.Digits diff --git a/main.go b/main.go index d11bd98..b4bb916 100644 --- a/main.go +++ b/main.go @@ -36,6 +36,7 @@ Usage: two-factor-authenticator generate [-c|--clip] [--verbose] two-factor-authenticator list [--verbose] two-factor-authenticator remove [--verbose] + two-factor-authenticator rename two-factor-authenticator -h | --help two-factor-authenticator --version @@ -154,6 +155,21 @@ func main() { } os.Exit(0) } + if arguments["rename"].(bool) { + oldName := arguments[""].(string) + newName := arguments[""].(string) + if oldName == newName { + ui.Error("old-name and new-name are equal, aborting") + os.Exit(1) + } + err := rename(&ui, storage, oldName, newName) + if err != nil { + ui.Error(err.Error()) + os.Exit(1) + } + ui.Info("Key renamed") + os.Exit(0) + } if arguments["--version"].(bool) { ui.Output(version) os.Exit(0) @@ -295,6 +311,24 @@ func remove(ui cli.Ui, storage Storage, name string) error { return nil } +func rename(ui cli.Ui, storage Storage, oldName string, newName string) error { + key := KeyFromStorage(storage, oldName) + key.Rename(newName) + marshal, _ := json.Marshal(key) + debugPrint(fmt.Sprintf("%s", marshal)) + + result, err := storage.AddKey(key.Name, []byte(marshal)) + if err != nil { + return err + } + storage.RemoveKey(oldName) + if !result { + ui.Error("something went wrong adding key") + os.Exit(1) + } + return nil +} + func getDatabaseConfigurations() (databaseLocation, databaseFilename string) { // first load fron env variable dbPath, dbPathEnvPresent := os.LookupEnv("2FA_DB_PATH") diff --git a/secret-string.go b/secret-string.go index d74d514..5029396 100644 --- a/secret-string.go +++ b/secret-string.go @@ -62,3 +62,17 @@ func (s *SecretString) Value() ([]byte, error) { func (s *SecretString) Remove() error { return s.ring.Remove(s.Name) } + +func (s *SecretString) Rename(name string) error { + data, err := s.Value() + if err != nil { + return err + } + s.Remove() + s.Name = name + err = s.Set(data) + if err != nil { + return err + } + return nil +}