From 88d9a76785deb69fcaa99dc6a10861223078217a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Torjus=20H=C3=A5kestad?= Date: Thu, 20 Jan 2022 23:20:01 +0100 Subject: [PATCH] use client for login action --- cmd/client/actions/actions.go | 48 +++++------------------------------ 1 file changed, 7 insertions(+), 41 deletions(-) diff --git a/cmd/client/actions/actions.go b/cmd/client/actions/actions.go index 00b256a..9b856e2 100644 --- a/cmd/client/actions/actions.go +++ b/cmd/client/actions/actions.go @@ -52,49 +52,15 @@ func ActionLogin(c *cli.Context) error { return fmt.Errorf("error reading password: %w", err) } - url := fmt.Sprintf("%s/api/login", c.String("url")) - client := &http.Client{} - // 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, + clnt := client.Client{ + BaseURL: c.String("url"), } - encoder := json.NewEncoder(body) - if err := encoder.Encode(&requestData); err != nil { - return fmt.Errorf("error encoding response: %w", err) + if err := clnt.Login(c.Context, username, password); err != nil { + errmsg := fmt.Sprintf("Error logging in: %s", err) + return cli.Exit(errmsg, 1) } - req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, body) - if err != nil { - 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) + // TODO: Store this somewhere, so we don't need to log in each time + fmt.Println("Successfully logged in.") return nil }