Check response for successful log in and chat

This commit is contained in:
tyler 2024-01-05 11:21:44 -05:00
parent dd9a42a135
commit b94b156f18
2 changed files with 43 additions and 0 deletions

20
chat.go
View file

@ -82,6 +82,16 @@ type ChatRequest struct {
Data ChatData `json:"data"`
}
type Error struct {
Code string `json:"code"`
Message string `json:"message"`
Type string `json:"type"`
}
type ChatResponse struct {
Errors []Error `json:"errors"`
}
func (c *Client) Chat(asChannel bool, message string) error {
if c.httpClient == nil {
return pkgErr("", fmt.Errorf("http client is nil"))
@ -125,5 +135,15 @@ func (c *Client) Chat(asChannel bool, message string) error {
return fmt.Errorf("http Post response status not %s: %s", http.StatusText(http.StatusOK), resp.Status)
}
var cr ChatResponse
err = json.NewDecoder(strings.NewReader(string(bodyB))).Decode(&cr)
if err != nil {
return fmt.Errorf("error decoding response body from server: %v", err)
}
if len(cr.Errors) != 0 {
return fmt.Errorf("server returned an error: %s", cr.Errors[0].Message)
}
return nil
}

View file

@ -132,6 +132,14 @@ func (c *Client) getSalts(username string) ([]string, error) {
return gsr.Data.Salts, nil
}
type User struct {
LoggedIn bool `json:"logged_in"`
}
type LoginResponse struct {
User User `json:"user"`
}
func (c *Client) userLogin(username string, password string, salts []string) error {
hashes, err := generateHashes(password, salts)
if err != nil {
@ -152,6 +160,21 @@ func (c *Client) userLogin(username string, password string, salts []string) err
return fmt.Errorf("http Post response status not %s: %s", http.StatusText(http.StatusOK), resp.Status)
}
bodyB, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("error reading body bytes: %v", err)
}
var lr LoginResponse
err = json.NewDecoder(strings.NewReader(string(bodyB))).Decode(&lr)
if err != nil {
return fmt.Errorf("error decoding response body from server: %v", err)
}
if !lr.User.LoggedIn {
return fmt.Errorf("failed to log in")
}
return nil
}