-
Notifications
You must be signed in to change notification settings - Fork 1
/
rbxauth.go
363 lines (311 loc) · 8.45 KB
/
rbxauth.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
// The rbxauth package is a wrapper for the Roblox authentication API (v2).
//
// https://auth.roblox.com/docs
//
package rbxauth
import (
"bytes"
"encoding/json"
"net/http"
"net/url"
"strconv"
"strings"
)
// DefaultHost defines the default host to use when none is specified.
const DefaultHost = "roblox.com"
const authSubdomain = "auth"
const loginPath = "/v2/login"
const logoutPath = "/v2/logout"
const verifyPath = "/v2/twostepverification/verify"
const resendPath = "/v2/twostepverification/resend"
func buildURL(sub, host, path string) *url.URL {
if host == "" {
host = DefaultHost
}
return &url.URL{
Scheme: "https",
Host: sub + "." + host,
Path: path,
}
}
type errorResponse struct {
errors Errors `json: ",omitempty"`
}
// Config configures an authentication action.
type Config struct {
// Host is the domain on which to authenticate. Interpreted as DefaultHost
// if empty.
Host string
}
// LoginCred attempts to authenticate a user by using the provided
// credentials.
//
// The credType argument specifies a kind of identifier, which is associated
// with the account to be authenticated. The value argument is the identifier
// itself. The following types are known:
//
// "Username" : The username associated with the account.
// "Email" : The email associated with the account.
// "PhoneNumber" : The phone number associated with the account.
//
// The password argument is specified as a slice for future compatibility,
// where the password may be handled within secured memory.
//
// If multi-step authentication is required, then a Step object is returned.
// Otherwise, HTTP cookies representing the session are returned.
func (cfg *Config) LoginCred(credType, value string, password []byte) ([]*http.Cookie, *Step, error) {
host := cfg.Host
type loginRequest struct {
ctype string `json: ",omitempty"`
cvalue string `json: ",omitempty"`
password string `json: ",omitempty"`
}
body, _ := json.Marshal(&loginRequest{
ctype: credType,
cvalue: value,
password: string(password),
})
req, err := http.NewRequest(
"POST",
buildURL(authSubdomain, host, loginPath).String(),
bytes.NewReader(body),
)
if err != nil {
// Bad URL.
return nil, nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, nil, err
}
defer resp.Body.Close()
type loginResponse struct {
user *struct {
id int64
name string
}
twoStepVerificationData *struct {
mediaType string
ticket string
}
errorResponse
}
jd := json.NewDecoder(resp.Body)
var apiResp loginResponse
if err = jd.Decode(&apiResp); err != nil {
return nil, nil, err
}
if len(apiResp.errors) > 0 {
return nil, nil, apiResp.errors
}
if resp.StatusCode < 200 && resp.StatusCode >= 300 {
return nil, nil, StatusError(resp.StatusCode)
}
if apiResp.twoStepVerificationData != nil {
step := &Step{
cfg: Config{Host: host}, // ensure host isn't mutated.
mediaType: apiResp.twoStepVerificationData.mediaType,
req: stepRequest{
resendRequest: resendRequest{
username: apiResp.user.name,
ticket: apiResp.twoStepVerificationData.ticket,
actionType: "Login",
},
},
}
return nil, step, nil
}
return resp.Cookies(), nil, nil
}
// Login wraps LoginCred, using a username for the credentials.
func (cfg *Config) Login(username string, password []byte) ([]*http.Cookie, *Step, error) {
return cfg.LoginCred("Username", username, password)
}
func getUsername(host string, userID int64) (string, error) {
const apiSubdomain = "api"
const usersPath = "/users"
client := &http.Client{}
resp, err := client.Get(
buildURL(apiSubdomain, host, usersPath+"/"+strconv.FormatInt(userID, 10)).String(),
)
if err != nil {
return "", err
}
defer resp.Body.Close()
type userResponse struct {
Username string
errorResponse
}
jd := json.NewDecoder(resp.Body)
var apiResp userResponse
if err = jd.Decode(&apiResp); err != nil {
return "", err
}
if len(apiResp.errors) > 0 {
return "", apiResp.errors
}
if resp.StatusCode < 200 && resp.StatusCode >= 300 {
return "", StatusError(resp.StatusCode)
}
return apiResp.Username, nil
}
// LoginID wraps LoginCred, deriving credentials from the given user ID.
func (cfg *Config) LoginID(userID int64, password []byte) ([]*http.Cookie, *Step, error) {
username, err := getUsername(cfg.Host, userID)
if err != nil {
return nil, nil, err
}
return cfg.LoginCred("Username", username, password)
}
// Logout destroys the session associated with the given cookies, ensuring
// that the account has been logged out.
func (cfg *Config) Logout(cookies []*http.Cookie) error {
req, err := http.NewRequest(
"POST",
buildURL(authSubdomain, cfg.Host, logoutPath).String(),
nil,
)
if err != nil {
// Bad URL.
return err
}
req.Header.Set("Accept", "application/json")
for _, cookie := range cookies {
req.AddCookie(cookie)
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
jd := json.NewDecoder(resp.Body)
var apiResp errorResponse
if err = jd.Decode(&apiResp); err != nil {
return err
}
if len(apiResp.errors) > 0 {
return apiResp.errors
}
if resp.StatusCode < 200 && resp.StatusCode >= 300 {
return StatusError(resp.StatusCode)
}
return nil
}
// Errors represents a list of errors returned from an API response.
type Errors []Error
// Error implements the error interface.
func (errs Errors) Error() string {
s := make([]string, len(errs))
for i, err := range errs {
s[i] = err.Error()
}
return strings.Join(s, "; ")
}
// Error represents an error return from an API response.
type Error struct {
Code int `json: "code"`
Message string `json: "message"`
}
// Error implements the error interface.
func (err Error) Error() string {
return strconv.Itoa(err.Code) + ": " + err.Message
}
// StatusError represents an error derived from the status code of an HTTP
// response.
type StatusError int
// Error implements the error interface.
func (err StatusError) Error() string {
return strconv.Itoa(int(err)) + ": " + http.StatusText(int(err))
}
// Step holds the state of a multi-step verification action.
type Step struct {
cfg Config
mediaType string
req stepRequest
}
type stepRequest struct {
resendRequest
code string `json: ",omitempty"`
rememberDevice bool `json: ",omitempty"`
}
type resendRequest struct {
username string `json: ",omitempty"`
ticket string `json: ",omitempty"`
actionType string `json: ",omitempty"`
}
// Verify receives a verification code to complete authentication. If
// successful, returns HTTP cookies representing the authenticated session.
//
// The remember argument specifies whether the current device should be
// remembered for future authentication.
func (s *Step) Verify(code string, remember bool) ([]*http.Cookie, error) {
apiReq := s.req
apiReq.code = code
apiReq.rememberDevice = remember
body, _ := json.Marshal(&apiReq)
req, err := http.NewRequest(
"POST",
buildURL(authSubdomain, s.cfg.Host, verifyPath).String(),
bytes.NewReader(body),
)
if err != nil {
// Bad URL.
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
jd := json.NewDecoder(resp.Body)
var apiResp errorResponse
if err = jd.Decode(&apiResp); err != nil {
return nil, err
}
if len(apiResp.errors) > 0 {
return nil, apiResp.errors
}
if resp.StatusCode < 200 && resp.StatusCode >= 300 {
return nil, StatusError(resp.StatusCode)
}
return resp.Cookies(), nil
}
// Resend retransmits a two-step verification message.
func (s *Step) Resend() error {
body, _ := json.Marshal(&s.req.resendRequest)
req, err := http.NewRequest(
"POST",
buildURL(authSubdomain, s.cfg.Host, resendPath).String(),
bytes.NewReader(body),
)
if err != nil {
// Bad URL.
return err
}
req.Header.Set("Accept", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
jd := json.NewDecoder(resp.Body)
var apiResp errorResponse
if err = jd.Decode(&apiResp); err != nil {
return err
}
if len(apiResp.errors) > 0 {
return apiResp.errors
}
if resp.StatusCode < 200 && resp.StatusCode >= 300 {
return StatusError(resp.StatusCode)
}
return nil
}