gitee.com/zhaochuninhefei/fabric-ca-gm@v0.0.2/cmd/fabric-ca-client/command/enroll.go (about)

     1  /*
     2  Copyright IBM Corp. All Rights Reserved.
     3  
     4  SPDX-License-Identifier: Apache-2.0
     5  */
     6  
     7  package command
     8  
     9  import (
    10  	"io/ioutil"
    11  	"path/filepath"
    12  	"strings"
    13  
    14  	log "gitee.com/zhaochuninhefei/zcgolog/zclog"
    15  	"github.com/pkg/errors"
    16  	"github.com/spf13/cobra"
    17  )
    18  
    19  type enrollCmd struct {
    20  	Command
    21  }
    22  
    23  func newEnrollCmd(c Command) *enrollCmd {
    24  	enrollCmd := &enrollCmd{c}
    25  	return enrollCmd
    26  }
    27  
    28  func (c *enrollCmd) getCommand() *cobra.Command {
    29  	cmd := &cobra.Command{
    30  		Use:     "enroll -u http://user:userpw@serverAddr:serverPort",
    31  		Short:   "Enroll an identity",
    32  		Long:    "Enroll identity with Fabric CA server",
    33  		PreRunE: c.preRunEnroll,
    34  		RunE:    c.runEnroll,
    35  	}
    36  	return cmd
    37  }
    38  
    39  func (c *enrollCmd) preRunEnroll(cmd *cobra.Command, args []string) error {
    40  	if len(args) > 0 {
    41  		return errors.Errorf(extraArgsError, args, cmd.UsageString())
    42  	}
    43  
    44  	err := c.ConfigInit()
    45  	if err != nil {
    46  		return err
    47  	}
    48  
    49  	log.Debugf("Client configuration settings: %+v", c.GetClientCfg())
    50  
    51  	return nil
    52  }
    53  
    54  func (c *enrollCmd) runEnroll(cmd *cobra.Command, args []string) error {
    55  	log.Debug("Entered runEnroll")
    56  	cfgFileName := c.GetCfgFileName()
    57  	cfg := c.GetClientCfg()
    58  	resp, err := cfg.Enroll(cfg.URL, filepath.Dir(cfgFileName))
    59  	if err != nil {
    60  		return err
    61  	}
    62  
    63  	ID := resp.Identity
    64  
    65  	cfgFile, err := ioutil.ReadFile(cfgFileName)
    66  	if err != nil {
    67  		return errors.Wrapf(err, "Failed to read file at '%s'", cfgFileName)
    68  	}
    69  
    70  	cfgStr := strings.Replace(string(cfgFile), "<<<ENROLLMENT_ID>>>", ID.GetName(), 1)
    71  
    72  	err = ioutil.WriteFile(cfgFileName, []byte(cfgStr), 0644)
    73  	if err != nil {
    74  		return errors.Wrapf(err, "Failed to write file at '%s'", cfgFileName)
    75  	}
    76  
    77  	err = ID.Store()
    78  	if err != nil {
    79  		return errors.WithMessage(err, "Failed to store enrollment information")
    80  	}
    81  
    82  	// Store issuer public key
    83  	err = storeCAChain(cfg, &resp.CAInfo)
    84  	if err != nil {
    85  		return err
    86  	}
    87  	err = storeIssuerPublicKey(cfg, &resp.CAInfo)
    88  	if err != nil {
    89  		return err
    90  	}
    91  	return storeIssuerRevocationPublicKey(cfg, &resp.CAInfo)
    92  }