github.com/hechain20/hechain@v0.0.0-20220316014945-b544036ba106/core/policy/principal.go (about)

     1  /*
     2  Copyright hechain. 2017 All Rights Reserved.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8  		 http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package policy
    18  
    19  import (
    20  	"github.com/golang/protobuf/proto"
    21  	"github.com/hechain20/hechain/msp"
    22  	protomsp "github.com/hyperledger/fabric-protos-go/msp"
    23  	"github.com/pkg/errors"
    24  )
    25  
    26  const (
    27  	// Admins is the label for the local MSP admins
    28  	Admins = "Admins"
    29  	// Members is the label for the local MSP members
    30  	Members = "Members"
    31  )
    32  
    33  type MSPPrincipalGetter interface {
    34  	// Get returns an MSP principal for the given role
    35  	Get(role string) (*protomsp.MSPPrincipal, error)
    36  }
    37  
    38  func NewLocalMSPPrincipalGetter(localMSP msp.MSP) MSPPrincipalGetter {
    39  	return &localMSPPrincipalGetter{
    40  		localMSP: localMSP,
    41  	}
    42  }
    43  
    44  type localMSPPrincipalGetter struct {
    45  	localMSP msp.MSP
    46  }
    47  
    48  func (m *localMSPPrincipalGetter) Get(role string) (*protomsp.MSPPrincipal, error) {
    49  	mspid, err := m.localMSP.GetIdentifier()
    50  	if err != nil {
    51  		return nil, errors.WithMessage(err, "could not extract local msp identifier")
    52  	}
    53  
    54  	switch role {
    55  	case Admins:
    56  		principalBytes, err := proto.Marshal(&protomsp.MSPRole{Role: protomsp.MSPRole_ADMIN, MspIdentifier: mspid})
    57  		if err != nil {
    58  			return nil, errors.Wrap(err, "marshalling failed")
    59  		}
    60  
    61  		return &protomsp.MSPPrincipal{
    62  			PrincipalClassification: protomsp.MSPPrincipal_ROLE,
    63  			Principal:               principalBytes,
    64  		}, nil
    65  	case Members:
    66  		principalBytes, err := proto.Marshal(&protomsp.MSPRole{Role: protomsp.MSPRole_MEMBER, MspIdentifier: mspid})
    67  		if err != nil {
    68  			return nil, errors.Wrap(err, "marshalling failed")
    69  		}
    70  
    71  		return &protomsp.MSPPrincipal{
    72  			PrincipalClassification: protomsp.MSPPrincipal_ROLE,
    73  			Principal:               principalBytes,
    74  		}, nil
    75  	default:
    76  		return nil, errors.Errorf("MSP Principal role [%s] not recognized", role)
    77  	}
    78  }