-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcloudfunction.go
More file actions
90 lines (81 loc) · 2.04 KB
/
Copy pathcloudfunction.go
File metadata and controls
90 lines (81 loc) · 2.04 KB
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package cloudfunction
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"strings"
"time"
"github.com/CodeLinkIO/go-cloudfunction-auth/internal"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
)
const GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token"
func JWTAccessTokenSourceFromJSON(jsonKey []byte, audience string) (oauth2.TokenSource, error) {
cfg, err := google.JWTConfigFromJSON(jsonKey)
if err != nil {
return nil, fmt.Errorf("google: could not parse JSON key: %v", err)
}
pk, err := internal.ParseKey(cfg.PrivateKey)
if err != nil {
return nil, fmt.Errorf("google: could not parse key: %v", err)
}
ts := &jwtAccessTokenSource{
email: cfg.Email,
audience: audience,
pk: pk,
pkID: cfg.PrivateKeyID,
}
tok, err := ts.Token()
if err != nil {
return nil, err
}
return oauth2.ReuseTokenSource(tok, ts), nil
}
type TokenResponse struct {
IdToken string `json:"id_token"`
}
func Authenticate(tokenSource oauth2.TokenSource) (token oauth2.Token, err error) {
jwt, err := tokenSource.Token()
if err != nil {
return
}
client := &http.Client{Timeout: time.Second * 10}
payload := strings.NewReader("grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=" + jwt.AccessToken)
req, _ := http.NewRequest("POST", GOOGLE_TOKEN_URL, payload)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
res, err := client.Do(req)
if err != nil {
return
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return
}
tokenRes := &TokenResponse{}
err = json.Unmarshal(body, tokenRes)
if err != nil {
fmt.Println(err.Error())
}
token = oauth2.Token{
AccessToken: tokenRes.IdToken,
}
return
}
func NewClient(jwtSource oauth2.TokenSource) *http.Client {
token, err := Authenticate(jwtSource)
if err != nil {
fmt.Printf("cannot authenticate with google: %v", err)
os.Exit(1)
}
return &http.Client{
Transport: &oauth2.Transport{
Base: http.DefaultClient.Transport,
Source: &googleTokenSource{
GoogleToken: &token,
},
},
}
}