-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfirebaseAuth.go
72 lines (59 loc) · 1.52 KB
/
firebaseAuth.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package auth
import (
"bytes"
"encoding/json"
"firebase.google.com/go"
"fmt"
"github.com/Sirupsen/logrus"
"golang.org/x/net/context"
"google.golang.org/api/option"
"io/ioutil"
"net/http"
)
type FAuth struct{}
type authResponse struct {
Kind string
IDToken string
RefreshToken string
ExpiresIn string
}
func (auth FAuth) GetToken(ctx context.Context, cPath string, uid string, urlGoogleAPI string) (token string, err error) {
opt := option.WithCredentialsFile(cPath)
app, err := firebase.NewApp(ctx, nil, opt)
if err != nil {
return
}
client, err := app.Auth(ctx)
if err != nil {
return
}
token, err = client.CustomToken(ctx, uid)
if err != nil {
return
}
token, err = client.CustomToken(context.Background(), uid)
if err != nil {
logrus.Fatalf("error setting custom token: %v\n", err)
}
var jsonStr = []byte(`{
"token": "` + token + `",
"returnSecureToken": true
}`)
res, err := http.Post(urlGoogleAPI, "application/json", bytes.NewBuffer(jsonStr))
if err != nil || res.StatusCode != http.StatusOK {
fmt.Printf("%+v\n", string(jsonStr))
logrus.Fatalf("error retrieving id token: %v\n", err)
}
resBody, err := ioutil.ReadAll(res.Body)
if err != nil {
logrus.Fatalf("error reading body of id token retrieve req: %v\n", err)
}
var resParsed authResponse
err = json.Unmarshal(resBody, &resParsed)
if err != nil {
logrus.Fatalf("error parsing json of id token request: %v\n", err)
}
token = resParsed.IDToken
logrus.Infof("Firebase token: %v", resParsed.IDToken)
return
}