use client for login action

This commit is contained in:
Torjus Håkestad 2022-01-20 23:20:01 +01:00
parent 193b0d3926
commit 88d9a76785

View File

@ -52,49 +52,15 @@ func ActionLogin(c *cli.Context) error {
return fmt.Errorf("error reading password: %w", err) return fmt.Errorf("error reading password: %w", err)
} }
url := fmt.Sprintf("%s/api/login", c.String("url")) clnt := client.Client{
client := &http.Client{} BaseURL: c.String("url"),
// TODO: Change timeout
ctx, cancel := context.WithTimeout(c.Context, 10*time.Second)
defer cancel()
body := new(bytes.Buffer)
requestData := struct {
Username string `json:"username"`
Password string `json:"password"`
}{
Username: username,
Password: password,
} }
encoder := json.NewEncoder(body) if err := clnt.Login(c.Context, username, password); err != nil {
if err := encoder.Encode(&requestData); err != nil { errmsg := fmt.Sprintf("Error logging in: %s", err)
return fmt.Errorf("error encoding response: %w", err) return cli.Exit(errmsg, 1)
} }
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, body) // TODO: Store this somewhere, so we don't need to log in each time
if err != nil { fmt.Println("Successfully logged in.")
return fmt.Errorf("error creating request: %w", err)
}
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("unable to perform request: %s", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return cli.Exit("got non-ok response from server", 0)
}
responseData := struct {
Token string `json:"token"`
}{}
decoder := json.NewDecoder(resp.Body)
if err := decoder.Decode(&responseData); err != nil {
return fmt.Errorf("unable to parse response: %s", err)
}
fmt.Printf("Token: %s", responseData.Token)
return nil return nil
} }