github.com/vchain-us/vcn@v0.9.11-0.20210921212052-a2484d23c0b3/pkg/cmd/set/secret/secret.go (about)

     1  /*
     2   * Copyright (c) 2018-2020 vChain, Inc. All Rights Reserved.
     3   * This software is released under GPL3.
     4   * The full license information can be found under:
     5   * https://www.gnu.org/licenses/gpl-3.0.en.html
     6   *
     7   */
     8  
     9  package secret
    10  
    11  import (
    12  	"fmt"
    13  
    14  	"github.com/spf13/cobra"
    15  	"github.com/vchain-us/vcn/pkg/api"
    16  	"github.com/vchain-us/vcn/pkg/cmd/internal/cli"
    17  	"github.com/vchain-us/vcn/pkg/mnemonic"
    18  	"github.com/vchain-us/vcn/pkg/store"
    19  )
    20  
    21  // NewCommand returns the cobra command for `vcn set secret`
    22  func NewCommand() *cobra.Command {
    23  	cmd := &cobra.Command{
    24  		Use:   "secret",
    25  		Short: "Import the user's secret",
    26  		Long: `Import a secret for the current user from a given mnemonic code and securely store it into the local vcn installation,
    27  if successful, any pre-stored secret will be overwritten.
    28  This feature is for advanced user only.
    29  		`,
    30  		RunE: func(cmd *cobra.Command, args []string) error {
    31  			cmd.SilenceUsage = true
    32  			fmt.Println("Please, provide your mnemonic code in order to recover your secret.")
    33  			return Execute()
    34  		},
    35  		Args: cobra.NoArgs,
    36  	}
    37  
    38  	return cmd
    39  }
    40  
    41  // Execute recover secret action
    42  func Execute() error {
    43  
    44  	u := api.NewUser(store.Config().CurrentContext.Email)
    45  	hasAuth, err := u.IsAuthenticated()
    46  	if err != nil {
    47  		return err
    48  	}
    49  	if !hasAuth {
    50  		return fmt.Errorf("you need to be logged in, please use <vcn login>")
    51  	}
    52  
    53  	userCfg := u.Config()
    54  	code, err := cli.PromptMnemonic()
    55  	if err != nil {
    56  		return err
    57  	}
    58  
    59  	privKey, err := mnemonic.ToECDSA(code)
    60  	if err != nil {
    61  		return err
    62  	}
    63  
    64  	passphrase, err := cli.PromptPassphrase()
    65  	if err != nil {
    66  		return err
    67  	}
    68  
    69  	if err := userCfg.ImportSecret(*privKey, passphrase); err != nil {
    70  		return err
    71  	}
    72  
    73  	fmt.Println("Secret successfully imported.")
    74  	fmt.Println("Secret Storage:\t", userCfg.KeyStore)
    75  	fmt.Println("SignerID:\t", userCfg.SignerIDFromSecret())
    76  	return nil
    77  }