This repository has been archived by the owner on Aug 16, 2023. It is now read-only.
forked from rinchsan/device-check-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
query.go
90 lines (72 loc) · 2.14 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
package devicecheck
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"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) {
return json.Marshal(t.Format(timeFormat))
}
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(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),
}
resp, err := client.api.do(jwt, queryTwoBitsPath, body)
if err != nil {
return fmt.Errorf("devicecheck: failed to query two bits: %w", err)
}
defer resp.Body.Close()
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("devicecheck: failed to read response body: %w", err)
}
switch resp.StatusCode {
case http.StatusOK:
if isErrBitStateNotFound(string(respBody)) {
return fmt.Errorf("devicecheck: %w", ErrBitStateNotFound)
}
return json.NewDecoder(bytes.NewReader(respBody)).Decode(result)
default:
return fmt.Errorf("devicecheck: %w", newError(resp.StatusCode, string(respBody)))
}
}