-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathquery.go
91 lines (71 loc) · 2.11 KB
/
query.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
package devicecheck
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
"github.com/google/uuid"
)
const queryTwoBitsPath = "/query_two_bits"
type queryTwoBitsRequestBody struct {
DeviceToken string `json:"device_token"`
TransactionID string `json:"transaction_id"`
Timestamp int64 `json:"timestamp"`
}
// QueryTwoBitsResult provides a result of query-two-bits method.
type QueryTwoBitsResult struct {
Bit0 bool `json:"bit0"`
Bit1 bool `json:"bit1"`
LastUpdateTime Time `json:"last_update_time"`
}
type Time struct {
time.Time
}
const timeFormat = "2006-01"
func (t Time) MarshalJSON() ([]byte, error) {
b, err := json.Marshal(t.Format(timeFormat))
if err != nil {
return nil, fmt.Errorf("json: %w", err)
}
return b, nil
}
func (t *Time) UnmarshalJSON(b []byte) error {
tm, err := time.Parse(timeFormat, strings.Trim(string(b), `"`))
if err != nil {
return fmt.Errorf("time: %w", err)
}
t.Time = tm
return nil
}
// QueryTwoBits queries two bits for device token. Returns ErrBitStateNotFound if the bits have not been set.
func (client *Client) QueryTwoBits(ctx context.Context, deviceToken string, result *QueryTwoBitsResult) error {
key, err := client.cred.key()
if err != nil {
return fmt.Errorf("devicecheck: failed to create key: %w", err)
}
jwt, err := client.jwt.generate(key)
if err != nil {
return fmt.Errorf("devicecheck: failed to generate jwt: %w", err)
}
body := queryTwoBitsRequestBody{
DeviceToken: deviceToken,
TransactionID: uuid.New().String(),
Timestamp: time.Now().UTC().UnixNano() / int64(time.Millisecond),
}
code, respBody, err := client.api.do(ctx, jwt, queryTwoBitsPath, body)
if err != nil {
return fmt.Errorf("devicecheck: failed to query two bits: %w: %s", err, respBody)
}
if code != http.StatusOK {
return fmt.Errorf("devicecheck: %w", newError(code, respBody))
}
if isErrBitStateNotFound(respBody) {
return fmt.Errorf("devicecheck: %w", ErrBitStateNotFound)
}
if err := json.NewDecoder(strings.NewReader(respBody)).Decode(result); err != nil {
return fmt.Errorf("json: %w", err)
}
return nil
}