Skip to content

Instantly share code, notes, and snippets.

@graphaelli

graphaelli/zube.go

Created Dec 5, 2019
Embed
What would you like to do?
Zube API Client
package main
import (
"crypto/rsa"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"time"
"github.com/dgrijalva/jwt-go"
)
func zubeRequest(method, url string, body io.Reader, clientId, token string) (*http.Request, error) {
req, err := http.NewRequest(method, url, nil)
if err != nil {
return nil, err
}
req.Header.Add("Authorization", "Bearer "+token)
req.Header.Add("X-Client-ID", clientId)
req.Header.Add("Accept", "application/json")
return req, nil
}
func access(clientId, refreshToken string) (string, error) {
req, _ := zubeRequest(http.MethodPost, "https://zube.io/api/users/tokens", nil, clientId, refreshToken)
rsp, err := http.DefaultClient.Do(req)
if err != nil {
return "", err
}
var accessTokenRsp struct {
AccessToken string `json:"access_token"`
}
if err := json.NewDecoder(rsp.Body).Decode(&accessTokenRsp); err != nil {
return "", err
}
return accessTokenRsp.AccessToken, nil
}
func refresh(clientId string, key *rsa.PrivateKey) (string, error) {
now := time.Now()
claims := &jwt.StandardClaims{
IssuedAt: now.Unix(),
ExpiresAt: (now.Add(time.Minute)).Unix(),
Issuer: clientId,
}
if err := claims.Valid(); err != nil {
log.Fatalf("invalid claims: %s", err)
}
token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
return token.SignedString(key)
}
func dump(clientId, accessToken, api string) (string, error) {
req, _ := zubeRequest(http.MethodGet, "https://zube.io/api/"+api, nil, clientId, accessToken)
rsp, err := http.DefaultClient.Do(req)
if err != nil {
return "", err
}
body, err := ioutil.ReadAll(rsp.Body)
return string(body), err
}
func main() {
api := os.Args[1]
clientId := "here"
privateKey, err := ioutil.ReadFile("zube_api_key.pem")
if err != nil {
log.Fatal(err)
}
key, err := jwt.ParseRSAPrivateKeyFromPEM(privateKey)
if err != nil {
log.Fatal(err)
}
refreshToken, err := refresh(clientId, key)
if err != nil {
log.Fatal(err)
}
accessToken, err := access(clientId, refreshToken)
if err != nil {
log.Fatal(err)
}
if body, err := dump(clientId, accessToken, api); err != nil {
log.Println(err)
} else {
fmt.Println(body)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment