github.com/openshift-online/ocm-sdk-go@v0.1.473/authentication/helpers.go (about)

     1  /*
     2  Copyright (c) 2021 Red Hat, Inc.
     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  // This file contains helper functions used in several places in the package.
    18  
    19  package authentication
    20  
    21  import (
    22  	"fmt"
    23  	"time"
    24  
    25  	"github.com/golang-jwt/jwt/v4"
    26  )
    27  
    28  // tokenRemaining determines if the given token will eventually expire (offile access tokens and
    29  // opaque tokens, for example, never expire) and the time till it expires. That time will be
    30  // positive if the token isn't expired, and negative if the token has already expired.
    31  //
    32  // For tokens that don't have the `exp` claim, or that have it with value zero (typical for offline
    33  // access tokens) the result will always be `false` and zero.
    34  func tokenRemaining(token *tokenInfo, now time.Time) (expires bool, duration time.Duration,
    35  	err error) {
    36  	// For opaque tokens we can't use the claims to determine when they expire, so we will
    37  	// assume that they never expire.
    38  	if token == nil || token.object == nil {
    39  		return
    40  	}
    41  
    42  	// For JSON web tokens we use tthe `exp` claim to determine when they expire.
    43  	claims, ok := token.object.Claims.(jwt.MapClaims)
    44  	if !ok {
    45  		err = fmt.Errorf("expected map claims but got %T", claims)
    46  		return
    47  	}
    48  	var exp float64
    49  	claim, ok := claims["exp"]
    50  	if !ok {
    51  		return
    52  	}
    53  	exp, ok = claim.(float64)
    54  	if !ok {
    55  		err = fmt.Errorf("expected floating point 'exp' but got %T", claim)
    56  		return
    57  	}
    58  	if exp == 0 {
    59  		return
    60  	}
    61  	duration = time.Unix(int64(exp), 0).Sub(now)
    62  	expires = true
    63  	return
    64  }