github.com/nats-io/jwt/v2@v2.5.6/decoder_operator.go (about)

     1  /*
     2   * Copyright 2020 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 jwt
    17  
    18  import (
    19  	"encoding/json"
    20  	"fmt"
    21  )
    22  
    23  type v1NatsOperator struct {
    24  	SigningKeys         StringList `json:"signing_keys,omitempty"`
    25  	AccountServerURL    string     `json:"account_server_url,omitempty"`
    26  	OperatorServiceURLs StringList `json:"operator_service_urls,omitempty"`
    27  	SystemAccount       string     `json:"system_account,omitempty"`
    28  }
    29  
    30  func loadOperator(data []byte, version int) (*OperatorClaims, error) {
    31  	switch version {
    32  	case 1:
    33  		var v1a v1OperatorClaims
    34  		if err := json.Unmarshal(data, &v1a); err != nil {
    35  			return nil, err
    36  		}
    37  		return v1a.Migrate()
    38  	case 2:
    39  		var v2a OperatorClaims
    40  		if err := json.Unmarshal(data, &v2a); err != nil {
    41  			return nil, err
    42  		}
    43  		return &v2a, nil
    44  	default:
    45  		return nil, fmt.Errorf("library supports version %d or less - received %d", libVersion, version)
    46  	}
    47  }
    48  
    49  type v1OperatorClaims struct {
    50  	ClaimsData
    51  	v1ClaimsDataDeletedFields
    52  	v1NatsOperator `json:"nats,omitempty"`
    53  }
    54  
    55  func (oa v1OperatorClaims) Migrate() (*OperatorClaims, error) {
    56  	return oa.migrateV1()
    57  }
    58  
    59  func (oa v1OperatorClaims) migrateV1() (*OperatorClaims, error) {
    60  	var a OperatorClaims
    61  	// copy the base claim
    62  	a.ClaimsData = oa.ClaimsData
    63  	// move the moved fields
    64  	a.Operator.Type = oa.v1ClaimsDataDeletedFields.Type
    65  	a.Operator.Tags = oa.v1ClaimsDataDeletedFields.Tags
    66  	// copy the account data
    67  	a.Operator.SigningKeys = oa.v1NatsOperator.SigningKeys
    68  	a.Operator.AccountServerURL = oa.v1NatsOperator.AccountServerURL
    69  	a.Operator.OperatorServiceURLs = oa.v1NatsOperator.OperatorServiceURLs
    70  	a.Operator.SystemAccount = oa.v1NatsOperator.SystemAccount
    71  	a.Version = 1
    72  	return &a, nil
    73  }