an updated and hopefully faster version of the ST Toolbox
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

104 lines
2.2 KiB

package api
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)
const BaseURL = "https://api.servicetrade.com/api"
type Session struct {
Client *http.Client
Cookie string
LastAccessed time.Time
}
func NewSession() *Session {
return &Session{
Client: &http.Client{},
LastAccessed: time.Now(),
}
}
func (s *Session) ValidateSession() error {
url := fmt.Sprintf("%s/auth/validate", BaseURL)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return err
}
req.Header.Set("Cookie", s.Cookie)
resp, err := s.Client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("session validation failed")
}
s.LastAccessed = time.Now()
return nil
}
func (s *Session) DoRequest(method, endpoint string, body io.Reader) (*http.Response, error) {
url := fmt.Sprintf("%s%s", BaseURL, endpoint)
fmt.Println(url)
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, fmt.Errorf("error creating request: %v", err)
}
req.Header.Set("Cookie", s.Cookie)
req.Header.Set("Content-Type", "application/json")
return s.Client.Do(req)
}
func (s *Session) Login(email, password string) error {
payload := map[string]string{
"username": email,
"password": password,
}
payloadBytes, _ := json.Marshal(payload)
resp, err := s.DoRequest("POST", "/auth", bytes.NewBuffer(payloadBytes))
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("failed to authenticate: %s, response: %s", resp.Status, string(body))
}
for _, cookie := range resp.Cookies() {
if cookie.Name == "PHPSESSID" {
s.Cookie = cookie.String()
return nil
}
}
return fmt.Errorf("failed to retrieve session cookie")
}
func (s *Session) Logout() error {
resp, err := s.DoRequest("DELETE", "/auth", nil)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("failed to end session: %s, response: %s", resp.Status, string(body))
}
s.Cookie = ""
return nil
}