forked from sonda2208/gpass
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gpass.go
124 lines (102 loc) · 2.43 KB
/
gpass.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package gpass
import (
"context"
"crypto/rsa"
"encoding/json"
"io/ioutil"
"time"
"google.golang.org/api/option"
"github.com/missmp/jwt-go"
"golang.org/x/oauth2/google"
"github.com/sonda2208/gpass/walletobjects"
)
type Client struct {
ProjectID string
wos *walletobjects.Service
credentials credentials
}
func NewClient(ctx context.Context, credentialFile string) (*Client, error) {
var jsonData []byte
if credentialFile != "" {
b, err := ioutil.ReadFile(credentialFile)
if err != nil {
return nil, err
}
jsonData = b
} else {
c, err := google.FindDefaultCredentials(ctx)
if err != nil {
return nil, err
}
jsonData = c.JSON
}
var cred credentials
err := json.Unmarshal(jsonData, &cred)
if err != nil {
return nil, err
}
wos, err := walletobjects.NewService(ctx, option.WithCredentialsJSON(jsonData))
if err != nil {
return nil, err
}
c := &Client{
ProjectID: cred.ProjectID,
wos: wos,
credentials: cred,
}
return c, nil
}
func (c *Client) Close() error {
return nil
}
type credentials struct {
Type string `json:"type"`
ClientEmail string `json:"client_email"`
PrivateKeyID string `json:"private_key_id"`
PrivateKey string `json:"private_key"`
TokenURL string `json:"token_uri"`
ProjectID string `json:"project_id"`
}
type JWT struct {
token *jwt.Token
signKey *rsa.PrivateKey
offerObjects []*walletobjects.OfferObject
origins []string
}
func NewJWT(c *Client) (*JWT, error) {
token := jwt.New(jwt.SigningMethodRS256)
token.Claims["iss"] = c.credentials.ClientEmail
token.Claims["aud"] = "google"
token.Claims["typ"] = "savetoandroidpay"
signKey, err := jwt.ParseRSAPrivateKeyFromPEM([]byte(c.credentials.PrivateKey))
if err != nil {
return nil, err
}
return &JWT{
token: token,
signKey: signKey,
}, nil
}
func (j *JWT) AddOfferObject(oo *OfferObject) *JWT {
j.offerObjects = append(j.offerObjects, &walletobjects.OfferObject{
ClassId: oo.OfferClassID,
Id: oo.OfferObjectID,
})
return j
}
func (j *JWT) AddOrigin(origins ...string) *JWT {
j.origins = append(j.origins, origins...)
return j
}
func (j *JWT) Sign() (string, error) {
j.token.Claims["iat"] = time.Now().UTC().Unix()
j.token.Claims["payload"] = map[string]interface{}{
"offerObjects": j.offerObjects,
}
j.token.Claims["origins"] = j.origins
res, err := j.token.SignedString(j.signKey)
if err != nil {
return "", err
}
return res, nil
}