2022-05-25 16:15:27 +00:00
|
|
|
package common
|
|
|
|
|
|
|
|
import (
|
2022-05-18 15:20:08 +00:00
|
|
|
"encoding/json"
|
2022-10-20 09:40:33 +00:00
|
|
|
"errors"
|
2022-05-31 17:00:41 +00:00
|
|
|
"fmt"
|
2022-05-25 16:15:27 +00:00
|
|
|
"os"
|
|
|
|
|
2022-12-23 17:35:35 +00:00
|
|
|
"github.com/TrueCloudLab/frostfs-sdk-go/bearer"
|
2022-05-25 16:15:27 +00:00
|
|
|
"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
|
|
|
|
}
|
|
|
|
|
2022-10-20 09:40:33 +00:00
|
|
|
PrintVerbose("Reading bearer token from file [%s]...", path)
|
2022-05-25 16:15:27 +00:00
|
|
|
|
|
|
|
var tok bearer.Token
|
|
|
|
|
2022-10-20 09:40:33 +00:00
|
|
|
err = ReadBinaryOrJSON(&tok, path)
|
|
|
|
ExitOnErr(cmd, "invalid bearer token: %v", err)
|
2022-05-25 16:15:27 +00:00
|
|
|
|
|
|
|
return &tok
|
|
|
|
}
|
|
|
|
|
2022-10-20 09:40:33 +00:00
|
|
|
// BinaryOrJSON is an interface of entities which provide json.Unmarshaler
|
|
|
|
// and NeoFS binary decoder.
|
|
|
|
type BinaryOrJSON interface {
|
|
|
|
Unmarshal([]byte) error
|
|
|
|
json.Unmarshaler
|
2022-05-31 17:00:41 +00:00
|
|
|
}
|
|
|
|
|
2022-10-20 09:40:33 +00:00
|
|
|
// ReadBinaryOrJSON reads file data using provided path and decodes
|
|
|
|
// BinaryOrJSON from the data.
|
|
|
|
func ReadBinaryOrJSON(dst BinaryOrJSON, fPath string) error {
|
|
|
|
PrintVerbose("Reading file [%s]...", fPath)
|
|
|
|
|
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 {
|
2022-10-20 09:40:33 +00:00
|
|
|
return fmt.Errorf("read file <%s>: %w", fPath, err)
|
2022-05-31 17:00:41 +00:00
|
|
|
}
|
2022-05-25 16:15:27 +00:00
|
|
|
|
2022-10-20 09:40:33 +00:00
|
|
|
PrintVerbose("Trying to decode binary...")
|
|
|
|
|
|
|
|
err = dst.Unmarshal(data)
|
2022-05-31 17:00:41 +00:00
|
|
|
if err != nil {
|
2022-10-20 09:40:33 +00:00
|
|
|
PrintVerbose("Failed to decode binary: %v", err)
|
|
|
|
|
|
|
|
PrintVerbose("Trying to decode JSON...")
|
|
|
|
|
|
|
|
err = dst.UnmarshalJSON(data)
|
|
|
|
if err != nil {
|
|
|
|
PrintVerbose("Failed to decode JSON: %v", err)
|
|
|
|
return errors.New("invalid format")
|
|
|
|
}
|
2022-05-31 17:00:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
2022-05-25 16:15:27 +00:00
|
|
|
}
|