-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathaccess_token.go
321 lines (283 loc) · 9.64 KB
/
access_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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
package disgoauth
// Import Packages
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
)
// The accessTokenBody() function is used to return
// the request body bytes being used in the
// GetAccessToken() function
func (dc *Client) accessTokenBody(code string) *bytes.Buffer {
return bytes.NewBuffer([]byte(fmt.Sprintf(
"client_id=%s&client_secret=%s&grant_type=authorization_code&redirect_uri=%s&code=%s&scope=identify",
dc.ClientID, dc.ClientSecret, dc.RedirectURI, code,
)))
}
// The refreshAccessTokenBody() function is used to return
// the request body bytes being used in the
// RefreshAccessToken() function
func (dc *Client) refreshAccessTokenBody(refreshToken string) *bytes.Buffer {
return bytes.NewBuffer([]byte(fmt.Sprintf(
"client_id=%s&client_secret=%s&grant_type=refresh_token&redirect_uri=%s&refresh_token=%s",
dc.ClientID, dc.ClientSecret, dc.RefreshRedirectURI, refreshToken,
)))
}
// The credentialsAccessTokenBody() function is used to return
// the request body bytes being used in the
// GetCredentialsAccessToken() function
//
// Using append() and a byte slice is much faster than
// using += to a string!
func credentialsAccessTokenBody(scopes []string) *bytes.Buffer {
var body []byte = []byte("grant_type=client_credentials")
// Check to make sure the user provided a
// valid amount of scopes
if len(scopes) > 0 {
body = append(body, "&scope="...)
// For each of the scopes
for i := 0; i < len(scopes); i++ {
// Append the scope to the url
body = append(body, scopes[i]...)
// If there are multiple scopes and the
// current index isn't the last scope
if i != len(scopes)+1 {
// Append %20 (space)
body = append(body, "%20"...)
}
}
}
// Return the url bytes
return bytes.NewBuffer(body)
}
// The accessTokenRequestObject() function is used to establish
// a new request object that will be used for sending
// the api request to the discord oauth token endpoint.
func (dc *Client) accessTokenRequestObject(body *bytes.Buffer, creds bool) (*http.Request, error) {
// Establish a new request object
var req, err = http.NewRequest("POST",
"https://discordapp.com/api/oauth2/token", body,
)
// Handle the error
if err != nil {
return req, err
}
// Set the request object's headers
req.Header = http.Header{
"Content-Type": []string{"application/x-www-form-urlencoded"},
"Accept": []string{"application/json"},
}
// If using the credentials access token endpoint
if creds {
// Base64 encode the client id and secret
var auth string = base64.StdEncoding.EncodeToString([]byte(dc.ClientID + ":" + dc.ClientSecret))
// Set the authorization header
req.Header["Authorization"] = []string{"Basic " + auth}
}
return req, nil
}
// The accessTokenRequest() function is used to send an api
// request to discord's oauth2/token endpoint.
// The function returns the data required for
// accessing the authorized users data
func (dc *Client) accessTokenRequest(req *http.Request) (map[string]interface{}, error) {
// Send the http request
resp, err := RequestClient.Do(req)
// Handle the error
// If the response status isn't a success
if resp.StatusCode != 200 || err != nil {
// Read the http body
body, _err := io.ReadAll(resp.Body)
// Handle the read body error
if _err != nil {
return map[string]interface{}{}, _err
}
// Handle http response error
return map[string]interface{}{},
fmt.Errorf("status: %d, code: %v, body: %s",
resp.StatusCode, err, string(body))
}
// Readable golang map used for storing
// the response body
var data map[string]interface{}
// Decode the data and handle errors
if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
return map[string]interface{}{}, err
}
return data, nil
}
/////////////////////////////////////////
// Get Access Token
/////////////////////////////////////////
// The GetAccessToken() function is used to get the users
// bearer access token, refresh token, the token expiry
// and any errors that occured.
func (dc *Client) GetAccessToken(code string) (string, string, int, error) {
// Define Variables
var (
// The Access Token Request Body
tokenBody *bytes.Buffer = dc.accessTokenBody(code)
// The Access Token Request Object
tokenReq, err = dc.accessTokenRequestObject(tokenBody, false)
)
// Handle the token request object error
if err != nil {
return "", "", -1, err
}
// Get the token data map
var data, _err = dc.accessTokenRequest(tokenReq)
// Handle the token request error
if _err != nil {
return "", "", -1, _err
}
// The Bearer access token
var accessToken string = data["token_type"].(string) + " " + data["access_token"].(string)
// Return the bearer token from said data
return accessToken, data["refresh_token"].(string), data["expires_in"].(int), nil
}
/////////////////////////////////////////
// Get Only Access Token
/////////////////////////////////////////
// The GetOnlyAccessToken() function is used to get
// the users bearer access token.
func (dc *Client) GetOnlyAccessToken(code string) (string, error) {
// Define Variables
var (
// The Access Token Request Body
tokenBody *bytes.Buffer = dc.accessTokenBody(code)
// The Access Token Request Object
tokenReq, err = dc.accessTokenRequestObject(tokenBody, false)
)
// Handle the token request object error
if err != nil {
return "", err
}
// Get the token data map
var data, _err = dc.accessTokenRequest(tokenReq)
// Handle the token request error
if _err != nil {
return "", _err
}
// The Bearer access token
var accessToken string = data["token_type"].(string) + " " + data["access_token"].(string)
// Return the bearer token from said data
return accessToken, nil
}
/////////////////////////////////////////
// Get Access Token + Data
/////////////////////////////////////////
// The GetAccessTokenMap() function is used to return all
// the map data revolving around the access token
func (dc *Client) GetAccessTokenMap(code string) (map[string]interface{}, error) {
// Define Variables
var (
// The Access Token Request Body
tokenBody *bytes.Buffer = dc.accessTokenBody(code)
// The Access Token Request Object
tokenReq, err = dc.accessTokenRequestObject(tokenBody, false)
)
// Handle the token request object error
if err != nil {
return map[string]interface{}{}, err
}
return dc.accessTokenRequest(tokenReq)
}
/////////////////////////////////////////
// Refresh Access Token
/////////////////////////////////////////
// The RefreshAccessToken() function is used to refresh
// the users bearer authorization token.
func (dc *Client) RefreshAccessToken(refreshToken string) (map[string]interface{}, error) {
// Define Variables
var (
// The Access Token Request Body
tokenBody *bytes.Buffer = dc.refreshAccessTokenBody(refreshToken)
// The Access Token Request Object
tokenReq, err = dc.accessTokenRequestObject(tokenBody, false)
)
// Handle the token request object error
if err != nil {
return map[string]interface{}{}, err
}
return dc.accessTokenRequest(tokenReq)
}
/////////////////////////////////////////
// Get Credentials Access Token
/////////////////////////////////////////
// The GetCredentialsAccessToken() function is used to get
// the credentials auth token, refresh token, the token expiry
// timing, and any errors that had occured.
func (dc *Client) GetCredentialsAccessToken(scopes []string) (string, string, int, error) {
// Define Variables
var (
// The Access Token Request Body
tokenBody *bytes.Buffer = credentialsAccessTokenBody(scopes)
// The Access Token Request Object
tokenReq, err = dc.accessTokenRequestObject(tokenBody, true)
)
// Handle the error
if err != nil {
return "", "", -1, err
}
// Send http request to get token data
var data, _err = dc.accessTokenRequest(tokenReq)
// Handle the token request error
if _err != nil {
return "", "", -1, _err
}
// The Bearer access token
var accessToken string = data["token_type"].(string) + " " + data["access_token"].(string)
// Return the bearer token from said data
return accessToken, data["refresh_token"].(string), data["expires_in"].(int), nil
}
/////////////////////////////////////////
// Get Only Credentials Access Token
/////////////////////////////////////////
// The GetOnlyCredentialsAccessToken() function is used to get
// the users credentials access bearer auth token.
func (dc *Client) GetOnlyCredentialsAccessToken(scopes []string) (string, error) {
// Define Variables
var (
// The Access Token Request Body
tokenBody *bytes.Buffer = credentialsAccessTokenBody(scopes)
// The Access Token Request Object
tokenReq, err = dc.accessTokenRequestObject(tokenBody, true)
)
// Handle the error
if err != nil {
return "", err
}
// Send http request to get token data
var data, _err = dc.accessTokenRequest(tokenReq)
// Handle the error
if _err != nil {
return "", _err
}
// The Bearer access token
var accessToken string = data["token_type"].(string) + " " + data["access_token"].(string)
// Return the bearer token from said data
return accessToken, nil
}
/////////////////////////////////////////
// Get Credentials Access Token + Data
/////////////////////////////////////////
// The GetCredentialsAccessTokenMap() function
// is used to return all the map data revolving
// around the credentials access token
func (dc *Client) GetCredentialsAccessTokenMap(scopes []string) (map[string]interface{}, error) {
// Define Variables
var (
// The Access Token Request Body
tokenBody *bytes.Buffer = credentialsAccessTokenBody(scopes)
// The Access Token Request Object
tokenReq, err = dc.accessTokenRequestObject(tokenBody, true)
)
// Handle the token request object error
if err != nil {
return map[string]interface{}{}, err
}
return dc.accessTokenRequest(tokenReq)
}