2022-05-25 16:15:27 +00:00
|
|
|
package common
|
|
|
|
|
|
|
|
import (
|
2022-05-18 15:20:08 +00:00
|
|
|
"encoding/json"
|
2022-05-31 17:00:41 +00:00
|
|
|
"fmt"
|
2022-05-25 16:15:27 +00:00
|
|
|
"os"
|
|
|
|
|
|
|
|
"github.com/nspcc-dev/neofs-sdk-go/bearer"
|
|
|
|
"github.com/spf13/cobra"
|
|
|
|
)
|
|
|
|
|
|
|
|
// ReadBearerToken reads bearer token from the path provided in a specified flag.
|
|
|
|
func ReadBearerToken(cmd *cobra.Command, flagname string) *bearer.Token {
|
|
|
|
path, err := cmd.Flags().GetString(flagname)
|
|
|
|
ExitOnErr(cmd, "", err)
|
|
|
|
|
|
|
|
if len(path) == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
data, err := os.ReadFile(path)
|
|
|
|
ExitOnErr(cmd, "can't read bearer token file: %w", err)
|
|
|
|
|
|
|
|
var tok bearer.Token
|
|
|
|
if err := tok.UnmarshalJSON(data); err != nil {
|
|
|
|
err = tok.Unmarshal(data)
|
|
|
|
ExitOnErr(cmd, "can't decode bearer token: %w", err)
|
|
|
|
|
|
|
|
PrintVerbose("Using binary encoded bearer token")
|
|
|
|
} else {
|
|
|
|
PrintVerbose("Using JSON encoded bearer token")
|
|
|
|
}
|
|
|
|
|
|
|
|
return &tok
|
|
|
|
}
|
|
|
|
|
2022-05-31 17:00:41 +00:00
|
|
|
// ReadSessionToken calls ReadSessionTokenErr and exists on error.
|
2022-05-18 15:20:08 +00:00
|
|
|
func ReadSessionToken(cmd *cobra.Command, dst json.Unmarshaler, fPath string) {
|
2022-05-31 17:00:41 +00:00
|
|
|
ExitOnErr(cmd, "", ReadSessionTokenErr(dst, fPath))
|
|
|
|
}
|
|
|
|
|
|
|
|
// ReadSessionTokenErr reads session token as JSON file with session token
|
|
|
|
// from path provided in a specified flag.
|
|
|
|
func ReadSessionTokenErr(dst json.Unmarshaler, fPath string) error {
|
2022-05-25 16:15:27 +00:00
|
|
|
// try to read session token from file
|
2022-05-18 15:20:08 +00:00
|
|
|
data, err := os.ReadFile(fPath)
|
2022-05-31 17:00:41 +00:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("could not open file with session token <%s>: %w", fPath, err)
|
|
|
|
}
|
2022-05-25 16:15:27 +00:00
|
|
|
|
2022-05-18 15:20:08 +00:00
|
|
|
err = dst.UnmarshalJSON(data)
|
2022-05-31 17:00:41 +00:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("could not unmarshal session token from file: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
2022-05-25 16:15:27 +00:00
|
|
|
}
|