-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathoauth2.go
403 lines (353 loc) · 13.8 KB
/
oauth2.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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
package wrapper
import (
"encoding/base64"
"net/url"
"strconv"
"strings"
"github.com/rs/xid"
"github.com/valyala/fasthttp"
)
const (
grantTypeAuthorizationCodeGrant = "authorization_code"
grantTypeRefreshToken = "refresh_token"
grantTypeClientCredentials = "client_credentials"
amountAuthURLParams = 6
amountAuthURLParamsBot = 3
)
// GenerateAuthorizationURL generates an authorization URL from a given client and response type.
func GenerateAuthorizationURL(bot *Client, response string) string {
params := make([]string, 0, amountAuthURLParams)
// response_type is the type of response the redirect will return.
if response != "" {
params = append(params, "responsetype="+response)
}
// client_id is the application client id.
params = append(params, "client_id="+bot.Authorization.ClientID)
// scope is a list of OAuth2 scopes separated by url encoded spaces (%20).
scope := urlQueryStringScope(bot.Authorization.Scopes)
if scope != "" {
params = append(params, scope)
}
// redirect_uri is the URL registered while creating the application.
if bot.Authorization.RedirectURI != "" {
params = append(params, "redirect_uri="+url.QueryEscape(bot.Authorization.RedirectURI))
}
// state is the unique string mentioned in State and Security.
if bot.Authorization.State != "" {
params = append(params, "state="+bot.Authorization.State)
}
// prompt controls how the authorization flow handles existing authorizations.
if bot.Authorization.Prompt != "" {
params = append(params, "prompt="+bot.Authorization.Prompt)
}
return EndpointAuthorizationURL() + "?" + strings.Join(params, "&")
}
// BotAuthParams represents parameters used to generate a bot authorization URL.
type BotAuthParams struct {
// Bot provides the client_id and scopes parameters.
Bot *Client
// GuildID pre-selects a guild in the authorization prompt.
GuildID string
// ResponseType provides the type of response the OAuth2 flow will return.
//
// In the context of bot authorization, response_type is only provided when
// a scope outside of `bot` and `applications.commands` is requested.
ResponseType string
// Permissions represents the permissions the bot is requesting.
Permissions BitFlag
// DisableGuildSelect disables the ability to select other guilds
// in the authorization prompt (when GuildID is provided).
DisableGuildSelect bool
}
// GenerateBotAuthorizationURL generates a bot authorization URL using the given BotAuthParams.
//
// Bot.Scopes must include "bot" to enable the OAuth2 Bot Flow.
func GenerateBotAuthorizationURL(p BotAuthParams) string {
params := make([]string, 0, amountAuthURLParamsBot)
// permissions is permissions the bot is requesting.
params = append(params, "permissions="+strconv.FormatUint(uint64(p.Permissions), base10))
// guild_id is the Guild ID of the guild that is pre-selected in the authorization prompt.
if p.GuildID != "" {
params = append(params, "guild_id="+p.GuildID)
}
// disable_guild_select determines whether the user will be allowed to select a guild
// other than the guild_id.
params = append(params, "disable_guild_select="+strconv.FormatBool(p.DisableGuildSelect))
return GenerateAuthorizationURL(p.Bot, p.ResponseType) + "&" + strings.Join(params, "&")
}
// AuthorizationCodeGrant performs an OAuth2 authorization code grant.
//
// Send the user a valid Authorization URL, which can be generated using
// GenerateAuthorizationURL(bot, "code").
//
// When the user visits the Authorization URL, they will be prompted for authorization.
// If the user accepts the prompt, they will be redirected to the `redirect_uri`.
// This issues a GET request to the `redirect_uri` web server which YOU MUST HANDLE
// by parsing the request's URL Query String into a disgo.RedirectURL object.
//
// Retrieve the user's access token by calling THIS FUNCTION (with the disgo.RedirectURL parameter),
// which performs an Access Token Exchange.
//
// Refresh the token by using RefreshAuthorizationCodeGrant(bot, token).
//
// For more information, read https://discord.com/developers/docs/topics/oauth2#authorization-code-grant
func AuthorizationCodeGrant(bot *Client, ru *RedirectURL) (*AccessTokenResponse, error) {
exchange := &AccessTokenExchange{
ClientID: bot.Authorization.ClientID,
ClientSecret: bot.Authorization.ClientSecret,
GrantType: grantTypeAuthorizationCodeGrant,
Code: ru.Code,
RedirectURI: bot.Authorization.RedirectURI,
}
return exchange.Send(bot)
}
// RefreshAuthorizationCodeGrant refreshes an Access Token from an OAuth2 authorization code grant.
func RefreshAuthorizationCodeGrant(bot *Client, token *AccessTokenResponse) (*AccessTokenResponse, error) {
exchange := &RefreshTokenExchange{
ClientID: bot.Authorization.ClientID,
ClientSecret: bot.Authorization.ClientSecret,
GrantType: grantTypeRefreshToken,
RefreshToken: token.RefreshToken,
}
return exchange.Send(bot)
}
// ImplicitGrant converts a RedirectURI (from a simplified OAuth2 grant) to an AccessTokenResponse.
//
// Send the user a valid Authorization URL, which can be generated using
// GenerateAuthorizationURL(bot, "token").
//
// When the user visits the Authorization URL, they will be prompted for authorization.
// If the user accepts the prompt, they will be redirected to the `redirect_uri`.
// This issues a GET request to the `redirect_uri` web server which YOU MUST HANDLE
// by parsing the request's URI Fragments into a disgo.RedirectURI object.
//
// A disgo.RedirectURI object is equivalent to a disgo.AccessTokenResponse,
// but it does NOT contain a refresh token.
//
// For more information, read https://discord.com/developers/docs/topics/oauth2#implicit-grant
func ImplicitGrant(ru *RedirectURI) *AccessTokenResponse {
return &AccessTokenResponse{
AccessToken: ru.AccessToken,
TokenType: ru.TokenType,
ExpiresIn: ru.ExpiresIn,
RefreshToken: "",
Scope: ru.Scope,
}
}
// ClientCredentialsGrant performs a client credential OAuth2 grant for TESTING PURPOSES.
//
// The bot client's Authentication Header will be set to a Basic Authentication Header that
// uses the bot's ClientID as a username and ClientSecret as a password.
//
// A request will be made for a Client Credential grant which returns a disgo.AccessTokenResponse
// that does NOT contain a refresh token.
//
// For more information, read https://discord.com/developers/docs/topics/oauth2#client-credentials-grant
func ClientCredentialsGrant(bot *Client) (*AccessTokenResponse, error) {
bot.Authentication.Header = "Basic " +
base64.StdEncoding.EncodeToString([]byte(bot.Authorization.ClientID+":"+bot.Authorization.ClientSecret))
grant := &ClientCredentialsTokenRequest{
GrantType: grantTypeClientCredentials,
Scope: urlQueryStringScope(bot.Authorization.Scopes),
}
return grant.Send(bot)
}
// BotAuthorization performs a specialized OAuth2 flow for users to add bots to guilds.
//
// Send the user a valid Bot Authorization URL, which can be generated using
// GenerateBotAuthorizationURL(disgo.BotAuthParams{...}).
//
// When the user visits the Bot Authorization URL, they will be prompted for authorization.
// If the user accepts the prompt (with a guild), the bot will be added to the selected guild.
//
// For more information read, https://discord.com/developers/docs/topics/oauth2#bot-authorization-flow
func BotAuthorization() {}
// AdvancedBotAuthorization performs a specialized OAuth2 flow for users to add bots to guilds.
//
// Send the user a valid Bot Authorization URL, which can be generated using
// GenerateBotAuthorizationURL(disgo.BotAuthParams{...}).
//
// If the user accepts the prompt (with a guild), they will be redirected to the `redirect_uri`.
// This issues a GET request to the `redirect_uri` web server which YOU MUST HANDLE
// by parsing the request's URL Query String into a disgo.RedirectURL object.
//
// Retrieve the user's access token by calling THIS FUNCTION (with the disgo.RedirectURL parameter),
// which performs an Access Token Exchange.
//
// Refresh the token by using RefreshAuthorizationCodeGrant(bot, token).
//
// For more information read, https://discord.com/developers/docs/topics/oauth2#advanced-bot-authorization
func AdvancedBotAuthorization(bot *Client, ru *RedirectURL) (*AccessTokenResponse, error) {
return AuthorizationCodeGrant(bot, ru)
}
// WebhookAuthorization performs a specialized OAuth2 authorization code grant.
//
// Send the user a valid Authorization URL, which can be generated using
// GenerateAuthorizationURL(bot, "code") when bot.Scopes is set to `webhook.incoming`.
//
// When the user visits the Authorization URL, they will be prompted for authorization.
// If the user accepts the prompt (with a channel), they will be redirected to the `redirect_uri`.
// This issues a GET request to the `redirect_uri` web server which YOU MUST HANDLE
// by parsing the request's URL Query String into a disgo.RedirectURL object.
//
// Retrieve the user's access token by calling THIS FUNCTION (with the disgo.RedirectURL parameter),
// which performs an Access Token Exchange.
//
// Refresh the token by using RefreshAuthorizationCodeGrant(bot, token).
//
// For more information read, https://discord.com/developers/docs/topics/oauth2#webhooks
func WebhookAuthorization(bot *Client, ru *RedirectURL) (*AccessTokenResponse, *Webhook, error) {
exchange := &AccessTokenExchange{
ClientID: bot.Authorization.ClientID,
ClientSecret: bot.Authorization.ClientSecret,
GrantType: grantTypeAuthorizationCodeGrant,
Code: ru.Code,
RedirectURI: bot.Authorization.RedirectURI,
}
var err error
xid := xid.New().String()
routeid, resourceid := RateLimitHashFuncs[1]("1")
query, err := EndpointQueryString(exchange)
if err != nil {
return nil, nil, ErrorRequest{
ClientID: bot.ApplicationID,
CorrelationID: xid,
RouteID: routeid,
ResourceID: resourceid,
Endpoint: "",
Err: err,
}
}
endpoint := EndpointTokenURL() + "?" + query
result := new(WebhookTokenResponse)
err = SendRequest(bot, xid, routeid, resourceid, fasthttp.MethodPost, endpoint, ContentTypeURLQueryString, nil, result)
if err != nil {
return nil, nil, ErrorRequest{
ClientID: bot.ApplicationID,
CorrelationID: xid,
RouteID: routeid,
ResourceID: resourceid,
Endpoint: endpoint,
Err: err,
}
}
// convert the webhook token response to an access token response (and webhook).
token := &AccessTokenResponse{
AccessToken: result.AccessToken,
TokenType: result.TokenType,
ExpiresIn: result.ExpiresIn,
RefreshToken: result.RefreshToken,
Scope: result.Scope,
}
return token, result.Webhook, nil
}
// Send sends an AccessTokenExchange request to Discord and returns an AccessTokenResponse.
func (r *AccessTokenExchange) Send(bot *Client) (*AccessTokenResponse, error) {
var err error
xid := xid.New().String()
routeid, resourceid := RateLimitHashFuncs[1]("1")
query, err := EndpointQueryString(r)
if err != nil {
return nil, ErrorRequest{
ClientID: bot.ApplicationID,
CorrelationID: xid,
RouteID: routeid,
ResourceID: resourceid,
Endpoint: "",
Err: err,
}
}
endpoint := EndpointTokenURL() + "?" + query
result := new(AccessTokenResponse)
err = SendRequest(bot, xid, routeid, resourceid, fasthttp.MethodPost, endpoint, ContentTypeURLQueryString, nil, result)
if err != nil {
return nil, ErrorRequest{
ClientID: bot.ApplicationID,
CorrelationID: xid,
RouteID: routeid,
ResourceID: resourceid,
Endpoint: endpoint,
Err: err,
}
}
return result, nil
}
// Send sends a RefreshTokenExchange request to Discord and returns an AccessTokenResponse.
//
// Uses the RefreshTokenExchange ClientID and ClientSecret.
func (r *RefreshTokenExchange) Send(bot *Client) (*AccessTokenResponse, error) {
var err error
xid := xid.New().String()
routeid, resourceid := RateLimitHashFuncs[1]("1")
query, err := EndpointQueryString(r)
if err != nil {
return nil, ErrorRequest{
ClientID: bot.ApplicationID,
CorrelationID: xid,
RouteID: routeid,
ResourceID: resourceid,
Endpoint: "",
Err: err,
}
}
endpoint := EndpointTokenURL() + "?" + query
result := new(AccessTokenResponse)
err = SendRequest(bot, xid, routeid, resourceid, fasthttp.MethodPost, endpoint, ContentTypeURLQueryString, nil, result)
if err != nil {
return nil, ErrorRequest{
ClientID: bot.ApplicationID,
CorrelationID: xid,
RouteID: routeid,
ResourceID: resourceid,
Endpoint: endpoint,
Err: err,
}
}
return result, nil
}
// Send sends a ClientCredentialsTokenRequest to Discord and returns a ClientCredentialsTokenRequest.
func (r *ClientCredentialsTokenRequest) Send(bot *Client) (*AccessTokenResponse, error) {
var err error
xid := xid.New().String()
routeid, resourceid := RateLimitHashFuncs[1]("1")
query, err := EndpointQueryString(r)
if err != nil {
return nil, ErrorRequest{
ClientID: bot.ApplicationID,
CorrelationID: xid,
RouteID: routeid,
ResourceID: resourceid,
Endpoint: "",
Err: err,
}
}
endpoint := EndpointTokenURL() + "?" + query
result := new(AccessTokenResponse)
err = SendRequest(bot, xid, routeid, resourceid, fasthttp.MethodPost, endpoint, ContentTypeURLQueryString, nil, result)
if err != nil {
return nil, ErrorRequest{
ClientID: bot.ApplicationID,
CorrelationID: xid,
RouteID: routeid,
ResourceID: resourceid,
Endpoint: endpoint,
Err: err,
}
}
return result, nil
}
// urlQueryStringScope parses a given slice of scopes to generate a valid URL Query String.
func urlQueryStringScope(scopes []string) string {
if len(scopes) > 0 {
var scope strings.Builder
scope.WriteString("scope=")
for i, s := range scopes {
if i > 0 {
scope.WriteString("%20")
}
scope.WriteString(s)
}
return scope.String()
}
return ""
}