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

     1  /*
     2  Copyright (c) 2019 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 functions that extract information from the context.
    18  
    19  package authentication
    20  
    21  import (
    22  	"context"
    23  	"fmt"
    24  
    25  	"github.com/golang-jwt/jwt/v4"
    26  )
    27  
    28  // ContextWithToken creates a new context containing the given token.
    29  func ContextWithToken(parent context.Context, token *jwt.Token) context.Context {
    30  	return context.WithValue(parent, tokenKeyValue, token)
    31  }
    32  
    33  // TokenFromContext extracts the JSON web token of the user from the context. If no token is found
    34  // in the context then the result will be nil.
    35  func TokenFromContext(ctx context.Context) (result *jwt.Token, err error) {
    36  	switch token := ctx.Value(tokenKeyValue).(type) {
    37  	case nil:
    38  	case *jwt.Token:
    39  		result = token
    40  	default:
    41  		err = fmt.Errorf(
    42  			"expected a token in the '%s' context value, but got '%T'",
    43  			tokenKeyValue, token,
    44  		)
    45  	}
    46  	return
    47  }
    48  
    49  // BearerFromContext extracts the bearer token of the user from the context. If no user is found in
    50  // the context then the result will be the empty string.
    51  func BearerFromContext(ctx context.Context) (result string, err error) {
    52  	token, err := TokenFromContext(ctx)
    53  	if err != nil {
    54  		return
    55  	}
    56  	if token == nil {
    57  		return
    58  	}
    59  	result = token.Raw
    60  	return
    61  }
    62  
    63  // tokenKeyType is the type of the key used to store the token in the context.
    64  type tokenKeyType string
    65  
    66  // tokenKeyValue is the key used to store the token in the context:
    67  const tokenKeyValue tokenKeyType = "token"