github.com/henvic/wedeploycli@v1.7.6-0.20200319005353-3630f582f284/command/inspect/token/token.go (about)

     1  package token
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  	"fmt"
     7  
     8  	"github.com/henvic/wedeploycli/cmdflagsfromhost"
     9  	"github.com/henvic/wedeploycli/command/internal/we"
    10  	"github.com/henvic/wedeploycli/templates"
    11  	"github.com/henvic/wedeploycli/usertoken"
    12  	"github.com/spf13/cobra"
    13  )
    14  
    15  // TokenCmd gets the user credential
    16  var TokenCmd = &cobra.Command{
    17  	Use:     "token",
    18  	Short:   "Get current logged-in user token",
    19  	PreRunE: preRun,
    20  	RunE:    tokenRun,
    21  	Args:    cobra.NoArgs,
    22  }
    23  
    24  var setupHost = cmdflagsfromhost.SetupHost{
    25  	Pattern: cmdflagsfromhost.RemotePattern,
    26  }
    27  
    28  var format string
    29  
    30  func init() {
    31  	TokenCmd.Flags().StringVarP(&format, "format", "f", "", "Format the output using the given go template")
    32  	TokenCmd.Flag("format").Hidden = true
    33  	setupHost.Init(TokenCmd)
    34  }
    35  
    36  func preRun(cmd *cobra.Command, args []string) error {
    37  	return setupHost.Process(context.Background(), we.Context())
    38  }
    39  
    40  func tokenRun(cmd *cobra.Command, args []string) error {
    41  	var wectx = we.Context()
    42  	var conf = wectx.Config()
    43  	var params = conf.GetParams()
    44  	var rl = params.Remotes
    45  	var remote = rl.Get(setupHost.Remote())
    46  
    47  	if remote.Token == "" {
    48  		return errors.New("user is not logged in")
    49  	}
    50  
    51  	if format == "" {
    52  		fmt.Println(remote.Token)
    53  		return nil
    54  	}
    55  
    56  	t, err := usertoken.ParseUnsignedJSONWebToken(remote.Token)
    57  
    58  	if err != nil {
    59  		return err
    60  	}
    61  
    62  	print, err := templates.ExecuteOrList(format, t)
    63  
    64  	if err != nil {
    65  		return err
    66  	}
    67  
    68  	fmt.Println(print)
    69  	return nil
    70  }