81 lines
1.6 KiB
Go
81 lines
1.6 KiB
Go
package roblox
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"net/http/cookiejar"
|
|
)
|
|
|
|
// Session struct for roblox login session data and members
|
|
type Session struct {
|
|
ID int
|
|
Username string
|
|
client *http.Client
|
|
}
|
|
|
|
// New create a new session and logs in with provided data
|
|
func New(username, password string) (*Session, error) {
|
|
cookieJar, _ := cookiejar.New(nil)
|
|
client := &http.Client{
|
|
Jar: cookieJar,
|
|
}
|
|
|
|
session := Session{0, username, client}
|
|
|
|
err := session.Login(username, password)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("Failed to login: %s", err)
|
|
}
|
|
|
|
info, err := session.GetUserInfo()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("Failed to retrieve user information: %s", err)
|
|
}
|
|
|
|
session.ID = info.UserID
|
|
|
|
return &session, err
|
|
}
|
|
|
|
func (s *Session) Login(username, password string) error {
|
|
details := struct {
|
|
Ctype string `json:"ctype"`
|
|
Cvalue string `json:"cvalue"`
|
|
Password string `json:"password"`
|
|
}{
|
|
"Username",
|
|
username,
|
|
password,
|
|
}
|
|
payload, err := json.Marshal(&details)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
resp, err := s.client.Post("https://auth.roblox.com/v1/login", "application/json", bytes.NewBuffer(payload))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
resp.Body.Close()
|
|
|
|
if resp.StatusCode == 403 {
|
|
req, err := http.NewRequest("POST", "https://auth.roblox.com/v1/login", bytes.NewBuffer(payload))
|
|
req.Header.Set("X-Csrf-Token", resp.Header["X-Csrf-Token"][0])
|
|
req.Header.Set("Content-Type", "application/json")
|
|
|
|
resp, err := s.client.Do(req)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode != 200 {
|
|
return fmt.Errorf("Status %d", resp.StatusCode)
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|