package auth import ( "bytes" "encoding/json" "fmt" "io" "net/http" "strings" ) type Session struct { Client *http.Client Cookie string } func NewSession() *Session { return &Session{Client: &http.Client{}} } func (s *Session) Login(email, password string) error { url := "https://api.servicetrade.com/api/auth" payload := map[string]string{ "username": email, "password": password, } payloadBytes, _ := json.Marshal(payload) req, err := http.NewRequest("POST", url, bytes.NewBuffer(payloadBytes)) if err != nil { return fmt.Errorf("error creating request: %v", err) } req.Header.Set("Content-Type", "application/json") resp, err := s.Client.Do(req) if err != nil { return fmt.Errorf("error sending request: %v", err) } defer resp.Body.Close() body, _ := io.ReadAll(resp.Body) if resp.StatusCode != 200 { return fmt.Errorf("failed to authenticate: %s, response: %s", resp.Status, string(body)) } for _, cookie := range resp.Cookies() { if strings.Contains(cookie.Name, "PHPSESSID") { s.Cookie = cookie.String() return nil } } return fmt.Errorf("failed to retrieve session cookie; authentication may have failed") } func (s *Session) Logout() error { if s.Cookie == "" { return fmt.Errorf("no active session to end") } url := "https://api.servicetrade.com/api/auth" req, err := http.NewRequest("DELETE", url, nil) if err != nil { return fmt.Errorf("failed to create DELETE request to end session: %v", err) } req.Header.Set("Cookie", s.Cookie) resp, err := s.Client.Do(req) if err != nil { return fmt.Errorf("failed to send DELETE request to end session: %v", err) } defer resp.Body.Close() if resp.StatusCode != 200 && resp.StatusCode != 204 { body, _ := io.ReadAll(resp.Body) return fmt.Errorf("failed to end session: %s, response: %s", resp.Status, string(body)) } s.Cookie = "" return nil }