forked from cloudmode/go-primetrust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprimetrust.go
87 lines (74 loc) · 1.72 KB
/
primetrust.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
package primetrust
import (
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/fatih/color"
)
const (
Version = "1.0.17"
SandboxAPIPrefix = "https://sandbox.primetrust.com/v2"
ProductionAPIPrefix = "https://api.primetrust.com/v2"
)
var _apiPrefix string
var _authHeader string
var _jwt string
func basicAuth(username string, password string) string {
auth := base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
return auth
}
type JWT struct {
Token string `json:"token`
}
func getJWT() string {
url := "https://sandbox.primetrust.com/auth/jwts"
method := "POST"
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
req, err := http.NewRequest(method, url, nil)
if err != nil {
fmt.Println(err)
}
req.Header.Set("Authorization", _authHeader)
res, err := client.Do(req)
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
jwt := new(JWT)
if err = json.Unmarshal(body, &jwt); err != nil {
fmt.Println("primetrust.init().getJWT error parsing body:", err)
return ""
}
if len(jwt.Token) == 0 {
fmt.Println("error creating JWT")
panic(0)
}
bearer := fmt.Sprintf("Bearer %+v", jwt.Token)
return bearer
}
func Init(sandbox bool, login string, password string) {
if sandbox {
_apiPrefix = SandboxAPIPrefix
} else {
_apiPrefix = ProductionAPIPrefix
}
_authHeader = fmt.Sprintf("Basic %s", basicAuth(login, password))
color.Blue("%s", _authHeader)
_jwt = getJWT()
color.Blue("%s", _jwt)
// periodically update JWT
go func() {
jwtTicker := time.NewTicker(1 * time.Hour)
for {
select {
case <-jwtTicker.C:
_jwt = getJWT()
}
}
}()
}