-
Notifications
You must be signed in to change notification settings - Fork 4
/
route.go
404 lines (340 loc) · 10.7 KB
/
route.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
404
package create_oauth2_login
import (
"errors"
"io"
"net/http"
"net/url"
"strings"
"time"
"github.com/anti-raid/splashtail/splashcore/types"
"github.com/anti-raid/splashtail/webserver/state"
"github.com/redis/rueidis"
"github.com/infinitybotlist/eureka/ratelimit"
docs "github.com/infinitybotlist/eureka/doclib"
"github.com/infinitybotlist/eureka/uapi"
"github.com/go-playground/validator/v10"
"github.com/infinitybotlist/eureka/crypto"
jsoniter "github.com/json-iterator/go"
"go.uber.org/zap"
"golang.org/x/exp/slices"
)
var (
json = jsoniter.ConfigCompatibleWithStandardLibrary
compiledMessages = uapi.CompileValidationErrors(types.AuthorizeRequest{})
)
func Docs() *docs.Doc {
return &docs.Doc{
Summary: "Create Oauth2 Login",
Description: "Takes in a ``code`` query parameter and returns a temporary session token`. **Cannot be used outside of the site for security reasons**",
Req: types.AuthorizeRequest{},
Resp: types.UserLogin{},
}
}
// OauthInfo struct for oauth2 info
type oauthUser struct {
ID string `json:"id"`
Username string `json:"username"`
Disc string `json:"discriminator"`
}
func Route(d uapi.RouteData, r *http.Request) uapi.HttpResponse {
limit, err := ratelimit.Ratelimit{
Expiry: 5 * time.Minute,
MaxRequests: 15,
Bucket: "oauth2_login",
}.Limit(d.Context, r)
if err != nil {
state.Logger.Error("Error while ratelimiting", zap.Error(err), zap.String("bucket", "login"))
return uapi.DefaultResponse(http.StatusInternalServerError)
}
if limit.Exceeded {
return uapi.HttpResponse{
Json: types.ApiError{
Message: "You are being ratelimited. Please try again in " + limit.TimeToReset.String(),
},
Headers: limit.Headers(),
Status: http.StatusTooManyRequests,
}
}
var req types.AuthorizeRequest
hresp, ok := uapi.MarshalReqWithHeaders(r, &req, limit.Headers())
if !ok {
return hresp
}
// Validate the payload
err = state.Validator.Struct(req)
if err != nil {
errors := err.(validator.ValidationErrors)
return uapi.ValidatorErrorResponse(compiledMessages, errors)
}
if req.Protocol != "a1" {
return uapi.HttpResponse{
Json: types.ApiError{
Message: "Your client is outdated and is not supported. Please contact the developers of this client.",
},
Status: http.StatusBadRequest,
Headers: limit.Headers(),
}
}
if !slices.Contains(state.Config.DiscordAuth.AllowedRedirects, req.RedirectURI) {
return uapi.HttpResponse{
Json: types.ApiError{
Message: "Malformed redirect_uri",
},
Status: http.StatusBadRequest,
Headers: limit.Headers(),
}
}
codeused, _ := state.Rueidis.Do(d.Context, state.Rueidis.B().Exists().Key("codecache:"+req.Code).Build()).ToInt64()
if codeused == 1 {
return uapi.HttpResponse{
Json: types.ApiError{
Message: "Code has been clearly used before and is as such invalid",
},
Status: http.StatusBadRequest,
Headers: limit.Headers(),
}
}
err = state.Rueidis.Do(d.Context, state.Rueidis.B().Set().Key("codecache:"+req.Code).Value("0").Ex(5*time.Minute).Build()).Error()
if err != nil && !errors.Is(err, rueidis.Nil) {
state.Logger.Error("Failed to set code cache", zap.Error(err))
return uapi.HttpResponse{
Json: types.ApiError{
Message: "Failed to set code cache",
},
Status: http.StatusInternalServerError,
Headers: limit.Headers(),
}
}
httpResp, err := http.PostForm("https://discord.com/api/v10/oauth2/token", url.Values{
"client_id": {state.Config.DiscordAuth.ClientID},
"client_secret": {state.Config.DiscordAuth.ClientSecret},
"grant_type": {"authorization_code"},
"code": {req.Code},
"redirect_uri": {req.RedirectURI},
"scope": {"identify"},
})
if err != nil {
state.Logger.Error("Failed to send oauth2 token request to discord", zap.Error(err))
return uapi.HttpResponse{
Json: types.ApiError{
Message: "Failed to send token request to Discord",
},
Status: http.StatusInternalServerError,
Headers: limit.Headers(),
}
}
defer httpResp.Body.Close()
body, err := io.ReadAll(httpResp.Body)
if err != nil {
state.Logger.Error("Failed to read oauth2 token response from discord", zap.Error(err))
return uapi.HttpResponse{
Json: types.ApiError{
Message: "Failed to read token response from Discord",
},
Status: http.StatusInternalServerError,
Headers: limit.Headers(),
}
}
var token struct {
AccessToken string `json:"access_token"`
Scope string `json:"scope"`
}
err = json.Unmarshal(body, &token)
if err != nil {
state.Logger.Error("Failed to parse oauth2 token response from discord", zap.Error(err))
return uapi.HttpResponse{
Json: types.ApiError{
Message: "Failed to parse token response from Discord",
},
Status: http.StatusBadRequest,
Headers: limit.Headers(),
}
}
// Validate scope
scopesStr := strings.Split(strings.ReplaceAll(token.Scope, "%20", ""), " ")
if !slices.Contains(scopesStr, "identify") {
return uapi.HttpResponse{
Json: types.ApiError{
Message: "Required identify scope not granted",
},
Status: http.StatusBadRequest,
Headers: limit.Headers(),
}
}
if !slices.Contains(scopesStr, "guilds") {
return uapi.HttpResponse{
Json: types.ApiError{
Message: "Required guilds scope not granted",
},
Status: http.StatusBadRequest,
Headers: limit.Headers(),
}
}
if token.AccessToken == "" {
state.Logger.Error("No access token provided by discord")
return uapi.HttpResponse{
Json: types.ApiError{
Message: "No access token provided by Discord",
},
Status: http.StatusBadRequest,
Headers: limit.Headers(),
}
}
cli := &http.Client{}
var httpReq *http.Request
httpReq, err = http.NewRequestWithContext(d.Context, "GET", "https://discord.com/api/v10/users/@me", nil)
if err != nil {
state.Logger.Error("Failed to create oauth2 request to discord", zap.Error(err))
return uapi.HttpResponse{
Json: types.ApiError{
Message: "Failed to create request to Discord to fetch user info",
},
Status: http.StatusInternalServerError,
Headers: limit.Headers(),
}
}
httpReq.Header.Set("Authorization", "Bearer "+token.AccessToken)
httpResp, err = cli.Do(httpReq)
if err != nil {
state.Logger.Error("Failed to send oauth2 request to discord", zap.Error(err))
return uapi.HttpResponse{
Json: types.ApiError{
Message: "Failed to send oauth2 request to Discord",
},
Status: http.StatusInternalServerError,
Headers: limit.Headers(),
}
}
defer httpResp.Body.Close()
body, err = io.ReadAll(httpResp.Body)
if err != nil {
state.Logger.Error("Failed to read oauth2 response from discord", zap.Error(err))
return uapi.HttpResponse{
Json: types.ApiError{
Message: "Failed to read oauth2 response from Discord",
},
Status: http.StatusInternalServerError,
Headers: limit.Headers(),
}
}
var user oauthUser
err = json.Unmarshal(body, &user)
if err != nil {
state.Logger.Error("Failed to parse oauth2 response from discord", zap.Error(err))
return uapi.HttpResponse{
Json: types.ApiError{
Message: "Failed to parse oauth2 response from Discord",
},
Status: http.StatusInternalServerError,
Headers: limit.Headers(),
}
}
if user.ID == "" {
state.Logger.Error("No user ID provided by discord. Invalid code/access token?")
return uapi.HttpResponse{
Json: types.ApiError{
Message: "No user ID provided by Discord. Invalid code/access token?",
},
Status: http.StatusBadRequest,
Headers: limit.Headers(),
}
}
// Check if user exists on database
var exists bool
err = state.Pool.QueryRow(d.Context, "SELECT EXISTS(SELECT 1 FROM users WHERE user_id = $1)", user.ID).Scan(&exists)
if err != nil {
state.Logger.Error("Failed to check if user exists on database", zap.Error(err), zap.String("userID", user.ID))
return uapi.HttpResponse{
Json: types.ApiError{
Message: "Failed to check if user exists on database",
},
Status: http.StatusInternalServerError,
Headers: limit.Headers(),
}
}
if !exists {
// Create user
_, err = state.Pool.Exec(
d.Context,
"INSERT INTO users (user_id, access_token) VALUES ($1, $2)",
user.ID,
token.AccessToken,
)
if err != nil {
state.Logger.Error("Failed to create user on database", zap.Error(err), zap.String("userID", user.ID))
return uapi.HttpResponse{
Json: types.ApiError{
Message: "Failed to create user on database",
},
Status: http.StatusInternalServerError,
Headers: limit.Headers(),
}
}
} else {
// Get state
var s string
err = state.Pool.QueryRow(d.Context, "SELECT state FROM users WHERE user_id = $1", user.ID).Scan(&s)
if err != nil {
state.Logger.Error("Failed to get user state from database", zap.Error(err), zap.String("userID", user.ID))
return uapi.HttpResponse{
Json: types.ApiError{
Message: "Failed to get user state from database",
},
Status: http.StatusInternalServerError,
Headers: limit.Headers(),
}
}
banned := s == "banned" || s == "api_banned"
if banned && req.Scope != "ban_exempt" {
return uapi.HttpResponse{
Json: types.ApiError{
Message: "You are banned from Anti-Raid. If you think this is a mistake, please contact support.",
},
Status: http.StatusForbidden,
Headers: limit.Headers(),
}
}
if !banned && req.Scope == "ban_exempt" {
return uapi.HttpResponse{
Json: types.ApiError{
Message: "The selected scope is not allowed for unbanned users [ban_exempt].",
},
Status: http.StatusForbidden,
Headers: limit.Headers(),
}
}
// Update access token
err = state.Pool.QueryRow(d.Context, "UPDATE users SET access_token = $1 WHERE user_id = $2 RETURNING access_token", token.AccessToken, user.ID).Scan(&token.AccessToken)
if err != nil {
state.Logger.Error("Failed to update access token on database", zap.Error(err), zap.String("userID", user.ID))
return uapi.HttpResponse{
Json: types.ApiError{
Message: "Failed to update access token on database",
},
Status: http.StatusInternalServerError,
Headers: limit.Headers(),
}
}
}
var sessionToken = crypto.RandString(128)
_, err = state.Pool.Exec(d.Context, "INSERT INTO web_api_tokens (user_id, type, token, expiry) VALUES ($1, 'login', $2, NOW() + INTERVAL '1 hour')", user.ID, sessionToken)
if err != nil {
state.Logger.Error("Failed to create session token", zap.Error(err), zap.String("userID", user.ID))
return uapi.HttpResponse{
Json: types.ApiError{
Message: "Failed to create session token",
},
Status: http.StatusInternalServerError,
Headers: limit.Headers(),
}
}
// Create authUser and send
var authUser = types.UserLogin{
UserID: user.ID,
Token: sessionToken,
}
return uapi.HttpResponse{
Json: authUser,
Headers: limit.Headers(),
}
}