Skip to content

Commit

Permalink
add rename command
Browse files Browse the repository at this point in the history
  • Loading branch information
endorama committed May 21, 2019
1 parent 474b8fd commit c201469
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 0 deletions.
9 changes: 9 additions & 0 deletions key.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
34 changes: 34 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ Usage:
two-factor-authenticator generate <name> [-c|--clip] [--verbose]
two-factor-authenticator list [--verbose]
two-factor-authenticator remove <name> [--verbose]
two-factor-authenticator rename <old-name> <new-name>
two-factor-authenticator -h | --help
two-factor-authenticator --version
Expand Down Expand Up @@ -154,6 +155,21 @@ func main() {
}
os.Exit(0)
}
if arguments["rename"].(bool) {
oldName := arguments["<old-name>"].(string)
newName := arguments["<new-name>"].(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)
Expand Down Expand Up @@ -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")
Expand Down
14 changes: 14 additions & 0 deletions secret-string.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

0 comments on commit c201469

Please sign in to comment.