{-# LANGUAGE OverloadedStrings #-}
module Kubernetes.Client.Auth.Token where

import           Data.Monoid                    ( (<>) )
import           Kubernetes.Client.Auth.Internal.Types
import           Kubernetes.Client.KubeConfig   ( AuthInfo(..) )
import           Kubernetes.OpenAPI.Core        ( AnyAuthMethod(..)
                                                , KubernetesClientConfig(..)
                                                )
import           Kubernetes.OpenAPI.Model       ( AuthApiKeyBearerToken(..) )

import qualified Data.Text                     as T

-- |Detects if token is specified in AuthConfig, if it is configures 'KubernetesClientConfig' with 'AuthApiKeyBearerToken'
tokenAuth :: DetectAuth
tokenAuth :: DetectAuth
tokenAuth AuthInfo
auth (ClientParams
tlsParams, KubernetesClientConfig
cfg) = do
  Text
t <- AuthInfo -> Maybe Text
token AuthInfo
auth
  IO (ClientParams, KubernetesClientConfig)
-> Maybe (IO (ClientParams, KubernetesClientConfig))
forall (m :: * -> *) a. Monad m => a -> m a
return (IO (ClientParams, KubernetesClientConfig)
 -> Maybe (IO (ClientParams, KubernetesClientConfig)))
-> IO (ClientParams, KubernetesClientConfig)
-> Maybe (IO (ClientParams, KubernetesClientConfig))
forall a b. (a -> b) -> a -> b
$ (ClientParams, KubernetesClientConfig)
-> IO (ClientParams, KubernetesClientConfig)
forall (m :: * -> *) a. Monad m => a -> m a
return (ClientParams
tlsParams, Text -> KubernetesClientConfig -> KubernetesClientConfig
setTokenAuth Text
t KubernetesClientConfig
cfg)

-- |Configures the 'KubernetesClientConfig' to use token authentication.
setTokenAuth
  :: T.Text                 -- ^Authentication token
  -> KubernetesClientConfig
  -> KubernetesClientConfig
setTokenAuth :: Text -> KubernetesClientConfig -> KubernetesClientConfig
setTokenAuth Text
t KubernetesClientConfig
kcfg = KubernetesClientConfig
kcfg
  { configAuthMethods :: [AnyAuthMethod]
configAuthMethods = [AuthApiKeyBearerToken -> AnyAuthMethod
forall a. AuthMethod a => a -> AnyAuthMethod
AnyAuthMethod (Text -> AuthApiKeyBearerToken
AuthApiKeyBearerToken (Text -> AuthApiKeyBearerToken) -> Text -> AuthApiKeyBearerToken
forall a b. (a -> b) -> a -> b
$ Text
"Bearer " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
t)]
  }