github.com/nats-io/nsc@v0.0.0-20221206222106-35db9400b257/cmd/friendlynamecollector.go (about)

     1  /*
     2   * Copyright 2018-2019 The NATS Authors
     3   * Licensed under the Apache License, Version 2.0 (the "License");
     4   * you may not use this file except in compliance with the License.
     5   * You may obtain a copy of the License at
     6   *
     7   * http://www.apache.org/licenses/LICENSE-2.0
     8   *
     9   * Unless required by applicable law or agreed to in writing, software
    10   * distributed under the License is distributed on an "AS IS" BASIS,
    11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12   * See the License for the specific language governing permissions and
    13   * limitations under the License.
    14   */
    15  
    16  package cmd
    17  
    18  import (
    19  	"fmt"
    20  
    21  	"github.com/nats-io/nsc/cmd/store"
    22  )
    23  
    24  // NewFriendlyNameCollector returns a map of public keys to
    25  // friendly names - if resources from outside the current
    26  // operator are returned as <operator>/<name>
    27  func friendlyNames(operator string) (map[string]string, error) {
    28  	m := make(map[string]string)
    29  	operators := config.ListOperators()
    30  	hasMany := len(operators) > 1
    31  	for _, o := range operators {
    32  		if o == "" {
    33  			continue
    34  		}
    35  		s, err := config.LoadStore(o)
    36  		if err != nil {
    37  			return nil, err
    38  		}
    39  		oc, err := s.ReadOperatorClaim()
    40  		if err != nil {
    41  			continue
    42  		}
    43  		m[oc.Subject] = oc.Name
    44  		for _, sk := range oc.SigningKeys {
    45  			m[sk] = oc.Name
    46  		}
    47  		accounts, err := s.ListSubContainers(store.Accounts)
    48  		if err != nil {
    49  			return nil, err
    50  		}
    51  		for _, a := range accounts {
    52  			ac, err := s.ReadAccountClaim(a)
    53  			if err != nil {
    54  				return nil, err
    55  			}
    56  			name := ac.Name
    57  			if hasMany && oc.Name != operator {
    58  				name = fmt.Sprintf("%s/%s", oc.Name, ac.Name)
    59  			}
    60  			m[ac.Subject] = name
    61  			for sk := range ac.SigningKeys {
    62  				m[sk] = name
    63  			}
    64  		}
    65  	}
    66  	return m, nil
    67  }