github.com/nats-io/jwt/v2@v2.5.6/decoder_user.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 v1User struct {
    24  	Permissions
    25  	Limits
    26  	BearerToken bool `json:"bearer_token,omitempty"`
    27  	// Limit values deprecated inv v2
    28  	Max int64 `json:"max,omitempty"`
    29  }
    30  
    31  type v1UserClaimsDataDeletedFields struct {
    32  	v1ClaimsDataDeletedFields
    33  	IssuerAccount string `json:"issuer_account,omitempty"`
    34  }
    35  
    36  type v1UserClaims struct {
    37  	ClaimsData
    38  	v1UserClaimsDataDeletedFields
    39  	v1User `json:"nats,omitempty"`
    40  }
    41  
    42  func loadUser(data []byte, version int) (*UserClaims, error) {
    43  	switch version {
    44  	case 1:
    45  		var v1a v1UserClaims
    46  		v1a.Limits = Limits{NatsLimits: NatsLimits{NoLimit, NoLimit, NoLimit}}
    47  		v1a.Max = NoLimit
    48  		if err := json.Unmarshal(data, &v1a); err != nil {
    49  			return nil, err
    50  		}
    51  		return v1a.Migrate()
    52  	case 2:
    53  		var v2a UserClaims
    54  		if err := json.Unmarshal(data, &v2a); err != nil {
    55  			return nil, err
    56  		}
    57  		return &v2a, nil
    58  	default:
    59  		return nil, fmt.Errorf("library supports version %d or less - received %d", libVersion, version)
    60  	}
    61  }
    62  
    63  func (oa v1UserClaims) Migrate() (*UserClaims, error) {
    64  	return oa.migrateV1()
    65  }
    66  
    67  func (oa v1UserClaims) migrateV1() (*UserClaims, error) {
    68  	var u UserClaims
    69  	// copy the base claim
    70  	u.ClaimsData = oa.ClaimsData
    71  	// move the moved fields
    72  	u.User.Type = oa.v1ClaimsDataDeletedFields.Type
    73  	u.User.Tags = oa.v1ClaimsDataDeletedFields.Tags
    74  	u.User.IssuerAccount = oa.IssuerAccount
    75  	// copy the user data
    76  	u.User.Permissions = oa.v1User.Permissions
    77  	u.User.Limits = oa.v1User.Limits
    78  	u.User.BearerToken = oa.v1User.BearerToken
    79  	u.Version = 1
    80  	return &u, nil
    81  }