我想在命令行上使用curl运行Google Analytics API查询,并且我对可用的身份验证方法感到困惑。我希望我能简单地获得一个客户端ID和一个秘密来传递curl请求,但是所有OAuth身份验证的东西看起来都坚持要通过服务器或浏览器进行往返。
什么是最简单的方法来"持久",一劳永逸,直到撤销,验证命令行脚本查询谷歌分析,然后?我不想每次运行脚本时都打开浏览器
到目前为止,我得出的结论是:
{-# LANGUAGE OverloadedStrings #-}
import Data.Yaml
import Control.Monad
import Data.ByteString.Char8 (pack, unpack)
import Data.Monoid
import Network.Google.OAuth2
import Network.HTTP.Conduit
import Network.HTTP.Types (hAuthorization)
import qualified Data.ByteString.Char8 as B8
import qualified Data.ByteString.Lazy.Char8 as L8
data OAuth2Credentials = OAuth2Credentials {
getClientID :: String,
getClientSecret :: String
} deriving (Show, Eq)
instance FromJSON OAuth2Credentials where
parseJSON (Object value) = OAuth2Credentials <$>
value .: "clientID" <*>
value .: "clientSecret"
parseJSON _ = mzero
parseOAuth2Credentials :: String -> Maybe OAuth2Credentials
parseOAuth2Credentials source = Data.Yaml.decode $ pack source
main :: IO ()
main = do
source <- readFile "analytics-credentials.yml"
let creds = parseOAuth2Credentials source
case creds of
Just creds -> do
let client = OAuth2Client (getClientID creds) (getClientSecret creds)
token <- getAccessToken client authScope (Just tokenCacheFile)
request <- parseUrl analyticsQueryURL
response <- withManager $ httpLbs $ authorize token request
L8.putStrLn $ responseBody response
Nothing -> return ()
where
authorize token request = request { requestHeaders = [(hAuthorization, B8.pack $ "Bearer " <> token)] }
analyticsQueryURL = "…"
authScope = ["https://www.google.com/analytics/feeds/"]
tokenCacheFile = "analytics-token.yml"
不完全是卷曲的,也不完全是简单的,但是在初始的基于浏览器的令牌生成之后,访问令牌缓存在文件中,随后的请求不需要任何人工交互。