cosmos-sdk/client/keys/update.go

105 lines
2.2 KiB
Go
Raw Normal View History

2018-02-22 07:17:19 -08:00
package keys
import (
2018-09-23 00:41:41 -07:00
"encoding/json"
2018-02-22 07:17:19 -08:00
"fmt"
"net/http"
2018-02-22 07:17:19 -08:00
2018-02-23 01:40:10 -08:00
"github.com/cosmos/cosmos-sdk/client"
2018-09-23 00:41:41 -07:00
keys "github.com/cosmos/cosmos-sdk/crypto/keys"
"github.com/gorilla/mux"
2018-02-22 07:17:19 -08:00
"github.com/cosmos/cosmos-sdk/crypto/keys/keyerror"
2018-10-24 06:37:06 -07:00
"github.com/spf13/cobra"
2018-02-22 07:17:19 -08:00
)
2018-02-22 08:20:25 -08:00
func updateKeyCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "update <name>",
Short: "Change the password used to protect private key",
RunE: runUpdateCmd,
2018-04-26 14:32:20 -07:00
Args: cobra.ExactArgs(1),
2018-02-22 08:20:25 -08:00
}
return cmd
2018-02-22 07:17:19 -08:00
}
func runUpdateCmd(cmd *cobra.Command, args []string) error {
name := args[0]
buf := client.BufferStdin()
kb, err := GetKeyBaseWithWritePerm()
2018-02-22 07:17:19 -08:00
if err != nil {
return err
}
oldpass, err := client.GetPassword(
"Enter the current passphrase:", buf)
2018-02-22 07:17:19 -08:00
if err != nil {
return err
}
getNewpass := func() (string, error) {
return client.GetCheckPassword(
"Enter the new passphrase:",
"Repeat the new passphrase:", buf)
2018-02-22 07:17:19 -08:00
}
err = kb.Update(name, oldpass, getNewpass)
2018-02-22 07:17:19 -08:00
if err != nil {
return err
}
fmt.Println("Password successfully updated!")
return nil
}
2018-04-18 21:49:24 -07:00
///////////////////////
// REST
2018-04-18 21:49:24 -07:00
// update key request REST body
type UpdateKeyBody struct {
NewPassword string `json:"new_password"`
OldPassword string `json:"old_password"`
}
2018-04-18 21:49:24 -07:00
// update key REST handler
func UpdateKeyRequestHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
name := vars["name"]
var kb keys.Keybase
var m UpdateKeyBody
2018-09-23 00:41:41 -07:00
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&m)
if err != nil {
2018-10-04 05:27:43 -07:00
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
kb, err = GetKeyBaseWithWritePerm()
if err != nil {
2018-10-04 05:27:43 -07:00
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}
getNewpass := func() (string, error) { return m.NewPassword, nil }
err = kb.Update(name, m.OldPassword, getNewpass)
if keyerror.IsErrKeyNotFound(err) {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte(err.Error()))
return
} else if keyerror.IsErrWrongPassword(err) {
2018-10-04 05:27:43 -07:00
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte(err.Error()))
return
} else if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}
w.Header().Set("Content-Type", "application/json")
2018-10-04 05:27:43 -07:00
w.WriteHeader(http.StatusOK)
}