Firebase: Failed to validate MAC - go

I am using fireauth and firego from zabawaba99. I am getting an error (please see below) when pushing data to my firebase database. I have been following his examples but I cannot get it to work. Someone got a idea why this is happening?
Error:
2016/06/03 14:30:13 {
"error" : "Failed to validate MAC."
}
Code:
gen := fireauth.New("<API-KEY/SECRET>")
data := fireauth.Data{"uid": "1"}
token, err := gen.CreateToken(data, nil)
if err != nil {
log.Fatal(err)
}
fb := firego.New("https://myapp.firebaseio.com" , nil)
log.Println(token)
fb.Auth(token)
for i := 0; i<len(items); i++ {
item := items[i]
pushedItem, err := fb.Child("items").Push(items)
if err != nil {
log.Fatal(err) // error is happening here
}
var itemTest string
if err := pushedItem.Value(&itemTest); err != nil {
log.Fatal(err)
}
fmt.Printf("%s: %s\n", pusedItem, itemTest)
}

Unfortunately there isn't Go-specific documentation, but I believe, based on the new docs, that the old REST way to authenticate doesn't work any longer.
Having said that, I have been able to get your code to work reading a bunch of docs, lots of trial & error, and by using OAuth authentication by means of JWT.
Firstly, follow this guide: https://firebase.google.com/docs/server/setup but just the "Add Firebase to your App" section.
Issue a go get -u golang.org/x/oauth2 and go get -u golang.org/x/oauth2/google (or use your favorite vendoring way).
Change your code as such:
package main
import (
"fmt"
"io/ioutil"
"log"
"github.com/zabawaba99/firego"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
)
func main() {
jsonKey, err := ioutil.ReadFile("./key.json") // or path to whatever name you downloaded the JWT to
if err != nil {
log.Fatal(err)
}
conf, err := google.JWTConfigFromJSON(jsonKey, "https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/firebase.database")
if err != nil {
log.Fatal(err)
}
client := conf.Client(oauth2.NoContext)
fb := firego.New("https://myapp.firebaseio.com" , client)
for i := 0; i<len(items); i++ {
item := items[i]
pushedItem, err := fb.Child("items").Push(items)
if err != nil {
log.Fatal(err) // error is happening here
}
var itemTest string
if err := pushedItem.Value(&itemTest); err != nil {
log.Fatal(err)
}
fmt.Printf("%s: %s\n", pusedItem, itemTest)
}
}
The above worked for me!
Edit: Adding reference to StackOverflow answers that helped me:
Using Custom Tokens to make REST requests to FB DB as an admin
Is it still possible to do server side verification of tokens in Firebase 3?

Related

How to start a telegram bot with different tokens, on 1 server in golang

There is a piece of working code that launches a bot to receive webhooks.
package main
import (
"log"
"net/http"
)
func main() {
bot, err := tgbotapi.NewBotAPI("MyAwesomeBotToken")
if err != nil {
log.Fatal(err)
}
bot.Debug = true
log.Printf("Authorized on account %s", bot.Self.UserName)
_, err = bot.SetWebhook(tgbotapi.NewWebhookWithCert("https://example.com:8443/"+bot.Token, "cert.pem"))
if err != nil {
log.Fatal(err)
}
info, err := bot.GetWebhookInfo()
if err != nil {
log.Fatal(err)
}
if info.LastErrorDate != 0 {
log.Printf("Telegram callback failed: %s", info.LastErrorMessage)
}
updates := bot.ListenForWebhook("/" + bot.Token)
go http.ListenAndServeTLS("0.0.0.0:8443", "cert.pem", "key.pem", nil)
for update := range updates {
log.Printf("%+v\n", update)
}
}
Library for golang - tgbotapi
When I try to launch another bot on the same server, with the same code,
but with a different token, of course, the following happens, the bot is successfully authorized but does not respond to commands, or it simply does not receive a webhook, who knows the reason?
I turn off 1 bot, then the second one starts without problems, at the same time they do not want to..

How to use kubernetes go-client on amazon eks service?

I've been looking for documentation for a long time and still couldn't find any clear connection procedure.
I came up with this code sample :
package aws
import (
"fmt"
"net/http"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/eks"
"github.com/joho/godotenv"
)
func Connect() {
godotenv.Load(".env")
session := session.Must(session.NewSession())
svc := eks.New(session)
clusters, err := svc.ListClusters(&eks.ListClustersInput{})
if err != nil {
fmt.Println(err.Error())
}
fmt.Println(clusters)
}
i mean, this still returns a 403 forbidden error because of env variable mess, but the code is valid i guess. My question is, having this connection established : how to convert this svc variable into the *kubernetes.Clientset one from the go driver ?
Have you had a look at the client-go example on how to authenticate in-cluster?
Code that authenticate to the Kubernetes API typically start like this:
// creates the in-cluster config
config, err := rest.InClusterConfig()
if err != nil {
panic(err.Error())
}
// creates the clientset
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
I use the following code to automatically detect where its running from local machine or any kubernetes cluster.
var config *rest.Config
if _, err := os.Stat("/var/run/secrets/kubernetes.io/serviceaccount/token"); err == nil {
config, err = rest.InClusterConfig()
if err != nil {
log.Fatal(err)
}
} else if os.IsNotExist(err) {
config, err = clientcmd.BuildConfigFromFlags("", *kubeConfig)
if err != nil {
log.Fatal("No serviceaccount mounted or -kubeconfig flag passed or .kube/config file \n " ,err)
}
}
// Create an rest client not targeting specific API version
clientSet, err := kubernetes.NewForConfig(config)
if err != nil {
log.Fatal(err)
}

Google Sheets API: golang BatchUpdateValuesRequest

I'm trying to follow the Google Sheets API quickstart here:
https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchUpdate
(scroll down to "Examples" then click "GO")
This is how I tried to update a spreadsheet:
package main
// BEFORE RUNNING:
// ---------------
// 1. If not already done, enable the Google Sheets API
// and check the quota for your project at
// https://console.developers.google.com/apis/api/sheets
// 2. Install and update the Go dependencies by running `go get -u` in the
// project directory.
import (
"errors"
"fmt"
"log"
"net/http"
"golang.org/x/net/context"
"google.golang.org/api/sheets/v4"
)
func main() {
ctx := context.Background()
c, err := getClient(ctx)
if err != nil {
log.Fatal(err)
}
sheetsService, err := sheets.New(c)
if err != nil {
log.Fatal(err)
}
// The ID of the spreadsheet to update.
spreadsheetId := "1diQ943LGMDNkbCRGG4VqgKZdzyanCtT--V8o7r6kCR0"
var jsonPayloadVar []string
monthVar := "Apr"
thisCellVar := "A26"
thisLinkVar := "http://test.url"
jsonRackNumberVar := "\"RACKNUM01\""
jsonPayloadVar = append(jsonPayloadVar, fmt.Sprintf("(\"range\": \"%v!%v\", \"values\": [[\"%v,%v)\"]]),", monthVar, thisCellVar, thisLinkVar, jsonRackNumberVar))
rb := &sheets.BatchUpdateValuesRequest{"ValueInputOption": "USER_ENTERED", "data": jsonPayloadVar}
resp, err := sheetsService.Spreadsheets.Values.BatchUpdate(spreadsheetId, rb).Context(ctx).Do()
if err != nil {
log.Fatal(err)
}
fmt.Printf("%#v\n", resp)
}
func getClient(ctx context.Context) (*http.Client, error) {
// https://developers.google.com/sheets/quickstart/go#step_3_set_up_the_sample
//
// Authorize using the following scopes:
// sheets.DriveScope
// sheets.DriveFileScope
sheets.SpreadsheetsScope
return nil, errors.New("not implemented")
}
Output:
hello.go:43: invalid field name "ValueInputOption" in struct initializer
hello.go:43: invalid field name "data" in struct initializer
hello.go:58: sheets.SpreadsheetsScope evaluated but not used
There are 2 things that aren't working:
It's not obvious how to enter the fields into variable rb
I need to use sheets.SpreadsheetsScope
Can anyone provide a working example that does a BatchUpdate?
References:
This article shows how to do an update that is not a BatchUpdate: Golang google sheets API V4 - Write/Update example?
Google's API reference - see the ValueInputOption section starting at line 1437: https://github.com/google/google-api-go-client/blob/master/sheets/v4/sheets-gen.go
This article shows how to do a BatchUpdate in Java: Write data to Google Sheet using Google Sheet API V4 - Java Sample Code
How about the following sample script? This is a simple sample script for updating sheet on Spreadsheet. So if you want to do various update, please modify it. The detail of parameters for spreadsheets.values.batchUpdate is here.
Flow :
At first, in ordet to use the link in your question, please use Go Quickstart. In my sample script, the script was made using the Quickstart.
The flow to use this sample script is as follows.
For Go Quickstart, please do Step 1 and Step 2.
Please put client_secret.json to the same directory with my sample script.
Copy and paste my sample script, and create it as new script file.
Run the script.
When Go to the following link in your browser then type the authorization code: is shown on your terminal, please copy the URL and paste to your browser. And then, please authorize and get code.
Put the code to the terminal.
When Done. is displayed, it means that the update of spreadsheet is done.
Request body :
For Spreadsheets.Values.BatchUpdate, BatchUpdateValuesRequest is required as one of parameters. In this case, the range, values and so on that you want to update are included in BatchUpdateValuesRequest. The detail information of this BatchUpdateValuesRequest can be seen at godoc. When it sees BatchUpdateValuesRequest, Data []*ValueRange can be seen. Here, please be carefull that Data is []*ValueRange. Also ValueRange can be seen at godoc. You can see MajorDimension, Range and Values in ValueRange.
When above infomation is reflected to the script, the script can be modified as follows.
Sample script :
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"golang.org/x/net/context"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"google.golang.org/api/sheets/v4"
)
// getClient uses a Context and Config to retrieve a Token
// then generate a Client. It returns the generated Client.
func getClient(ctx context.Context, config *oauth2.Config) *http.Client {
cacheFile := "./go-quickstart.json"
tok, err := tokenFromFile(cacheFile)
if err != nil {
tok = getTokenFromWeb(config)
saveToken(cacheFile, tok)
}
return config.Client(ctx, tok)
}
// getTokenFromWeb uses Config to request a Token.
// It returns the retrieved Token.
func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {
authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline)
fmt.Printf("Go to the following link in your browser then type the "+
"authorization code: \n%v\n", authURL)
var code string
if _, err := fmt.Scan(&code); err != nil {
log.Fatalf("Unable to read authorization code %v", err)
}
tok, err := config.Exchange(oauth2.NoContext, code)
if err != nil {
log.Fatalf("Unable to retrieve token from web %v", err)
}
return tok
}
// tokenFromFile retrieves a Token from a given file path.
// It returns the retrieved Token and any read error encountered.
func tokenFromFile(file string) (*oauth2.Token, error) {
f, err := os.Open(file)
if err != nil {
return nil, err
}
t := &oauth2.Token{}
err = json.NewDecoder(f).Decode(t)
defer f.Close()
return t, err
}
func saveToken(file string, token *oauth2.Token) {
fmt.Printf("Saving credential file to: %s\n", file)
f, err := os.Create(file)
if err != nil {
log.Fatalf("Unable to cache oauth token: %v", err)
}
defer f.Close()
json.NewEncoder(f).Encode(token)
}
type body struct {
Data struct {
Range string `json:"range"`
Values [][]string `json:"values"`
} `json:"data"`
ValueInputOption string `json:"valueInputOption"`
}
func main() {
ctx := context.Background()
b, err := ioutil.ReadFile("client_secret.json")
if err != nil {
log.Fatalf("Unable to read client secret file: %v", err)
}
config, err := google.ConfigFromJSON(b, "https://www.googleapis.com/auth/spreadsheets")
if err != nil {
log.Fatalf("Unable to parse client secret file to config: %v", err)
}
client := getClient(ctx, config)
sheetsService, err := sheets.New(client)
if err != nil {
log.Fatalf("Unable to retrieve Sheets Client %v", err)
}
spreadsheetId := "### spreadsheet ID ###"
rangeData := "sheet1!A1:B3"
values := [][]interface{}{{"sample_A1", "sample_B1"}, {"sample_A2", "sample_B2"}, {"sample_A3", "sample_A3"}}
rb := &sheets.BatchUpdateValuesRequest{
ValueInputOption: "USER_ENTERED",
}
rb.Data = append(rb.Data, &sheets.ValueRange{
Range: rangeData,
Values: values,
})
_, err = sheetsService.Spreadsheets.Values.BatchUpdate(spreadsheetId, rb).Context(ctx).Do()
if err != nil {
log.Fatal(err)
}
fmt.Println("Done.")
}
Result :
References :
The detail infomation of spreadsheets.values.batchUpdate is here.
The detail infomation of Go Quickstart is here.
The detail infomation of BatchUpdateValuesRequest is here.
The detail infomation of ValueRange is here.
If I misunderstand your question, I'm sorry.

Golang google sheets API V4 - Write/Update example?

Trying to write a simple three column table ([][]string) with Go, but can't.
The quick start guide is very nice, I now can read sheets, but there no any example of how to write data to a sheet, maybe it is trivial, but not for me it seems.
The Golang library for my brains is just too complicated to figure out.
And there not a single example I could google...
This C# example very looks close, but I am not sure I clearly understand C#
Well after some tryouts, there is an answer. Everything is same as in https://developers.google.com/sheets/quickstart/go Just changes in the main function
func write() {
ctx := context.Background()
b, err := ioutil.ReadFile("./Google_Sheets_API_Quickstart/client_secret.json")
if err != nil {
log.Fatalf("Unable to read client secret file: %v", err)
}
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/sheets.googleapis.com-go-quickstart.json
config, err := google.ConfigFromJSON(b, "https://www.googleapis.com/auth/spreadsheets")
if err != nil {
log.Fatalf("Unable to parse client secret file to config: %v", err)
}
client := getClient(ctx, config)
srv, err := sheets.New(client)
if err != nil {
log.Fatalf("Unable to retrieve Sheets Client %v", err)
}
spreadsheetId := "YOUR SPREADSHEET ID"
writeRange := "A1"
var vr sheets.ValueRange
myval := []interface{}{"One", "Two", "Three"}
vr.Values = append(vr.Values, myval)
_, err = srv.Spreadsheets.Values.Update(spreadsheetId, writeRange, &vr).ValueInputOption("RAW").Do()
if err != nil {
log.Fatalf("Unable to retrieve data from sheet. %v", err)
}
}
Well if you are looking for Service Account based authentication, then the following worked for me.
Download the client secret file for service account from https://console.developers.google.com
import (
"fmt"
"golang.org/x/net/context"
"google.golang.org/api/option"
"google.golang.org/api/sheets/v4"
"log"
)
const (
client_secret_path = "./credentials/client_secret.json"
)
func NewSpreadsheetService() (*SpreadsheetService, error) {
// Service account based oauth2 two legged integration
ctx := context.Background()
srv, err := sheets.NewService(ctx, option.WithCredentialsFile(client_secret_path), option.WithScopes(sheets.SpreadsheetsScope))
if err != nil {
log.Fatalf("Unable to retrieve Sheets Client %v", err)
}
c := &SpreadsheetService{
service: srv,
}
return c, nil
}
func (s *SpreadsheetService) WriteToSpreadsheet(object *SpreadsheetPushRequest) error {
var vr sheets.ValueRange
vr.Values = append(vr.Values, object.Values)
res, err := s.service.Spreadsheets.Values.Append(object.SpreadsheetId, object.Range, &vr).ValueInputOption("RAW").Do()
fmt.Println("spreadsheet push ", res)
if err != nil {
fmt.Println("Unable to update data to sheet ", err)
}
return err
}
type SpreadsheetPushRequest struct {
SpreadsheetId string `json:"spreadsheet_id"`
Range string `json:"range"`
Values []interface{} `json:"values"`
}
change the scope in the quickstart example from spreadsheets.readonly to spreadsheets for r/w access
here is the write snippet:
writeRange := "A1" // or "sheet1:A1" if you have a different sheet
values := []interface{}{"It worked!"}
var vr sheets.ValueRange
vr.Values = append(vr.Values,values
_, err = srv.Spreadsheets.Values.Update(spreadsheetId,writeRange,&vr).ValueInputOption("RAW").Do()
and that should work:

List Openshift objects via Go client API

Trying to write a microservice to manage imagestreams on my Openshift cluster. I read the oc client code to work out how to read my kubeconfig and create the Client.
I can make requests with the Kubernetes Client to get the Kubernetes objects, e.g. pods, but any requests I make with the Openshift Client returns back an empty list.
I'm new to Go as well, so I'm sure I'm doing something wrong. Here's what I have so far:
package main
import (
"fmt"
"log"
"github.com/spf13/pflag"
kapi "k8s.io/kubernetes/pkg/api"
"github.com/openshift/origin/pkg/cmd/util/clientcmd"
)
func main() {
flags := pflag.FlagSet{}
factory := clientcmd.New(&flags)
osclient, kclient, err := factory.Clients()
if err != nil {
log.Fatalln("Error:", err)
}
config, _ := factory.ClientConfig()
fmt.Println("KClient config", config)
config, _ = factory.OpenShiftClientConfig.ClientConfig()
fmt.Println("OSClient config", config)
// Empty list!
projects, err := osclient.Projects().List(kapi.ListOptions{})
if err != nil {
log.Println("Error:", err)
} else {
fmt.Println("Projects", projects, len(projects.Items))
}
// Also empty list
buildconfigs, err := osclient.BuildConfigs("my-project").List(kapi.ListOptions{})
if err != nil {
log.Println("Error:", err)
} else {
fmt.Println("Buildconfigs", buildconfigs, len(buildconfigs.Items))
}
// Works!
pods, err := kclient.Pods("my-project").List(kapi.ListOptions{})
if err != nil {
log.Println("Error:", err)
} else {
fmt.Println("Pods", len(pods.Items))
for _, pod := range pods.Items {
fmt.Println(pod.ObjectMeta.Name)
}
}
// Permission error, as expected
namespaces, err := kclient.Namespaces().List(kapi.ListOptions{})
if err != nil {
log.Println("Error:", err)
} else {
fmt.Println("Namespaces", namespaces, len(namespaces.Items))
}
}
You were ever so close and the issue was a tiny one: you needed to include the following additional import:
import _ "github.com/openshift/origin/pkg/api/install"
I'm not fully clear what the import actually does, but evidently it causes necessary additional functionality to be linked into the binary, without which the OpenShift client doesn't work (returns empty lists).
All of the OpenShift command line tools include that import, and as of writing many include some/all of the following as well:
import (
_ "github.com/openshift/origin/pkg/api/install"
_ "k8s.io/kubernetes/pkg/api/install"
_ "k8s.io/kubernetes/pkg/apis/autoscaling/install"
_ "k8s.io/kubernetes/pkg/apis/batch/install"
_ "k8s.io/kubernetes/pkg/apis/extensions/install"
)
Finally, here's a full code example which works for me (updated against origin v3.6.0-alpha):
package main
import (
"fmt"
_ "github.com/openshift/origin/pkg/api/install"
"github.com/openshift/origin/pkg/cmd/util/clientcmd"
"github.com/spf13/pflag"
"k8s.io/apimachinery/pkg/apis/meta/v1"
)
func main() {
factory := clientcmd.New(pflag.CommandLine)
pflag.Parse()
oc, kc, err := factory.Clients()
if err != nil {
panic(err)
}
namespace, _, err := factory.DefaultNamespace()
if err != nil {
panic(err)
}
pods, err := kc.Core().Pods(namespace).List(v1.ListOptions{})
if err != nil {
panic(err)
}
for _, pod := range pods.Items {
fmt.Printf("Pod: %s\n", pod.Name)
}
buildconfigs, err := oc.BuildConfigs(namespace).List(v1.ListOptions{})
if err != nil {
panic(err)
}
for _, buildconfig := range buildconfigs.Items {
fmt.Printf("BuildConfig: %s\n", buildconfig.Name)
}
}
To run this example, you will currently need to vendor OpenShift and its dependencies. One very hacky way to do this is as follows:
rm -rf vendor
mkdir -p vendor/github.com/openshift/origin
ln -s $GOPATH/src/github.com/openshift/origin/vendor/* vendor
ln -s $GOPATH/src/github.com/openshift/origin/vendor/github.com/* vendor/github.com
ln -s $GOPATH/src/github.com/openshift/origin/vendor/github.com/openshift/* vendor/github.com/openshift
ln -s $GOPATH/src/github.com/openshift/origin/pkg vendor/github.com/openshift/origin
Finally, it is intended to make a proper standalone Go client for OpenShift - the backlog card for this is at https://trello.com/c/PTDrY0GF/794-13-client-provide-go-client-similar-to-kubernetes.

Resources