-
Notifications
You must be signed in to change notification settings - Fork 6
/
token.go
125 lines (92 loc) · 2.14 KB
/
token.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
125
package hsuanfuzz
import (
"crypto/tls"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"strings"
"github.com/valyala/fastjson"
"gopkg.in/yaml.v2"
)
// Token is used to manually enter service authorization information.
type Token struct {
URL string `yaml:"url"`
Method string `yaml:"method"`
Key string `yaml:"key"`
Bearer string `yaml:"bearer"` // is empty when initial
ContentType string `yaml:"type"`
Body interface{} `yaml:"body"`
Hardcode bool `yaml:"hardcode"`
In string `yaml:"in"`
}
// GetToken obtains the authorization key based on the input information.
func GetToken(t Token, print bool) string {
/* For https */
http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
// hardcode
if t.Hardcode {
return t.Bearer
}
b, err := yaml.Marshal(t.Body)
if err != nil {
panic(err)
}
body := string(b)
if strings.HasPrefix(body, "'") {
body = body[1 : len(body)-2]
}
req, err := http.NewRequest(t.Method, t.URL, strings.NewReader(body))
if err != nil {
panic(err)
}
if t.ContentType != "" {
req.Header.Set("Content-Type", t.ContentType)
}
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
panic(err)
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
panic("Invalid log in, code: " + strconv.Itoa(res.StatusCode))
}
b, err = ioutil.ReadAll(res.Body)
if err != nil {
panic(err)
}
// fastjson keys
keys := []string{}
key := ""
for _, c := range t.Key {
if c == '{' {
keys = append(keys, key)
key = ""
} else if c == '[' {
keys = append(keys, key)
key = ""
key += "0"
} else if c == ']' || c == '}' {
if len(key) > 0 {
keys = append(keys, key)
key = ""
}
} else {
key += string(c)
}
}
/* Customized token info */
v := fastjson.MustParseBytes(b).Get(keys...)
/* SPREE: access_token */
/* REALWORLD: user{token} */
bearer := string(v.GetStringBytes())
if bearer == "" {
/* MAGENTO: w/o key */
bearer = strings.ReplaceAll(string(b), "\"", "")
}
if print {
fmt.Println(bearer)
}
return bearer
}