@@ -20,20 +20,21 @@ module Network.Google.Auth.ApplicationDefault where
2020
2121import Control.Applicative
2222import Control.Exception.Lens (catching, throwingM)
23−import Control.Monad (unless)
23+import Control.Monad (unless, when)
2424import Control.Monad.Catch
2525import Control.Monad.IO.Class (MonadIO (..))
2626import Data.Aeson
2727import Data.Aeson.Types (parseEither)
2828import qualified Data.ByteString.Lazy as LBS
29+import Data.Maybe (maybe)
2930import qualified Data.Text as Text
3031import Network.Google.Compute.Metadata (isGCE)
3132import Network.Google.Internal.Auth
3233
3334import Network.HTTP.Conduit (Manager)
34−import System.Directory (doesFileExist, getHomeDirectory)
35+import System.Directory (doesFileExist, getHomeDirectory, createDirectoryIfMissing)
3536import System.Environment (lookupEnv)
36−import System.FilePath ((</>))
37+import System.FilePath ((</>), takeDirectory)
3738import System.Info (os)
3839
3940-- | The environment variable name which is used to specify the directory
@@ -126,6 +127,30 @@ fromFilePath f = do
126127 either (throwM . InvalidFileError f . Text.pack) pure
127128 (fromJSONCredentials bs)
128129
130+-- | Save 'AuthorizedUser'
131+-- /See:/ 'cloudSDKConfigPath', 'defaultCredentialsPath'.
132+saveAuthorizedUserToWellKnownPath :: (MonadIO m, MonadCatch m)
133+ => Bool -- ^ Force to save if True
134+ -> AuthorizedUser
135+ -> m ()
136+saveAuthorizedUserToWellKnownPath b a = do
137+ d <- defaultCredentialsPath
138+ f <- maybe cloudSDKConfigPath pure d
139+ liftIO $ createDirectoryIfMissing True $ takeDirectory f
140+ saveAuthorizedUser f b a
141+
142+-- | Save 'AuthorizedUser'
143+saveAuthorizedUser :: (MonadIO m, MonadCatch m)
144+ => FilePath
145+ -> Bool -- ^ Force to save if True
146+ -> AuthorizedUser
147+ -> m ()
148+saveAuthorizedUser f b a = do
149+ p <- liftIO (doesFileExist f)
150+ when (p && not b) $
151+ throwM (FileExistError f)
152+ liftIO (LBS.writeFile f $ encode a)
153+
129154-- | Attempt to parse either a @service_account@ or @authorized_user@ formatted
130155-- JSON value to obtain credentials.
131156fromJSONCredentials :: LBS.ByteString -> Either String (Credentials s)