/
change.go
79 lines (67 loc) · 1.74 KB
/
change.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package cmd
import (
"encoding/json"
"errors"
"fmt"
"github.com/AlecAivazis/survey/v2"
"github.com/nnachevv/passmag/storage"
"github.com/spf13/cobra"
)
// NewChangeCmd creates a new newCmd
func NewChangeCmd() *cobra.Command {
changeCmd := &cobra.Command{
Use: "change",
Short: "Change password for given host",
Long: `Change password for given host`,
RunE: func(cmd *cobra.Command, args []string) error {
u, err := EnterSession()
if err != nil {
return err
}
var s storage.Storage
err = json.Unmarshal(u.VaultData, &s)
if err != nil {
return err
}
answers := struct {
Name string
Password string
}{}
changeQs := []*survey.Question{
{
Name: "name",
Prompt: &survey.Input{Message: "Enter name for which you want to change your password:"},
},
{
Name: "password",
Prompt: &survey.Password{Message: "Enter new password:"},
Validate: func(val interface{}) error {
if str, ok := val.(string); !ok || len(str) < 8 {
return errors.New("password should be longer than 8 characters")
}
return nil
},
},
}
err = survey.Ask(changeQs, &answers, survey.WithStdio(Stdio.In, Stdio.Out, Stdio.Err))
if err != nil {
return err
}
if _, ok := s.Passwords[answers.Name]; !ok {
return errors.New("failed to find this name")
}
s.Change(answers.Name, answers.Password)
byteData, err := json.Marshal(s)
if err != nil {
return fmt.Errorf("failed to marshal map : %w", err)
}
err = Crypt.EncryptFile(u.VaultPath, byteData, u.VaultPwd)
if err != nil {
return fmt.Errorf("failed to encrypt your data: %w", err)
}
s.SyncStorage(u.Password, MongoDB, Client)
return nil
},
}
return changeCmd
}