Skip to content

Commit

Permalink
fix(pactus-shell): pactus shell support basic auth (#1384)
Browse files Browse the repository at this point in the history
  • Loading branch information
Ja7ad authored Jul 1, 2024
1 parent baa4a13 commit 22b04e7
Showing 1 changed file with 21 additions and 13 deletions.
34 changes: 21 additions & 13 deletions cmd/shell/main.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
package main

import (
"context"
"encoding/base64"
"fmt"

"github.com/NathanBaulch/protoc-gen-cobra/client"
"github.com/NathanBaulch/protoc-gen-cobra/naming"
"github.com/pactus-project/pactus/cmd"
"github.com/pactus-project/pactus/www/grpc/basicauth"
pb "github.com/pactus-project/pactus/www/grpc/gen/go"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
)

const (
Expand All @@ -19,23 +19,20 @@ const (
)

func main() {
var (
username string
password string
)

rootCmd := &cobra.Command{
Use: "shell",
Short: "Pactus Shell",
Long: `pactus-shell is a command line tool for interacting with the Pactus blockchain using gRPC`,
}

auth := &basicauth.BasicAuth{}

client.RegisterFlagBinder(func(fs *pflag.FlagSet, namer naming.Namer) {
fs.StringVar(&auth.Username, namer("auth-username"), "", "username for gRPC basic authentication")
fs.StringVar(&auth.Password, namer("auth-password"), "", "password for gRPC basic authentication")
})

client.RegisterPreDialer(func(_ context.Context, opts *[]grpc.DialOption) error {
*opts = append(*opts, grpc.WithPerRPCCredentials(auth))

return nil
fs.StringVar(&username, namer("auth-username"), "", "username for gRPC basic authentication")
fs.StringVar(&password, namer("auth-password"), "", "password for gRPC basic authentication")
})

changeDefaultParameters := func(c *cobra.Command) *cobra.Command {
Expand All @@ -48,6 +45,17 @@ func main() {
return c
}

rootCmd.PersistentPreRunE = func(cmd *cobra.Command, _ []string) error {
if username != "" && password != "" {
auth := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", username, password)))
md := metadata.Pairs("authorization", "Basic "+auth)
ctx := metadata.NewOutgoingContext(cmd.Context(), md)
cmd.SetContext(ctx)
}

return nil
}

rootCmd.AddCommand(changeDefaultParameters(pb.BlockchainClientCommand()))
rootCmd.AddCommand(changeDefaultParameters(pb.NetworkClientCommand()))
rootCmd.AddCommand(changeDefaultParameters(pb.TransactionClientCommand()))
Expand Down

0 comments on commit 22b04e7

Please sign in to comment.