2018-05-04 16:53:21 +00:00
|
|
|
package service
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
2021-11-22 14:13:26 +00:00
|
|
|
"fmt"
|
2018-05-04 16:53:21 +00:00
|
|
|
"net/http"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Login attempts to login to the current Fleet instance. If login is successful,
|
|
|
|
// an auth token is returned.
|
|
|
|
func (c *Client) Login(email, password string) (string, error) {
|
|
|
|
params := loginRequest{
|
2021-06-24 20:42:29 +00:00
|
|
|
Email: email,
|
2018-05-04 16:53:21 +00:00
|
|
|
Password: password,
|
|
|
|
}
|
|
|
|
|
2022-04-05 15:35:53 +00:00
|
|
|
response, err := c.Do("POST", "/api/latest/fleet/login", "", params)
|
2018-05-04 16:53:21 +00:00
|
|
|
if err != nil {
|
2022-04-05 15:35:53 +00:00
|
|
|
return "", fmt.Errorf("POST /api/latest/fleet/login: %w", err)
|
2018-05-04 16:53:21 +00:00
|
|
|
}
|
|
|
|
defer response.Body.Close()
|
|
|
|
|
|
|
|
switch response.StatusCode {
|
|
|
|
case http.StatusNotFound:
|
2018-05-04 21:55:57 +00:00
|
|
|
return "", notSetupErr{}
|
2018-05-04 16:53:21 +00:00
|
|
|
}
|
|
|
|
if response.StatusCode != http.StatusOK {
|
2021-11-22 14:13:26 +00:00
|
|
|
return "", fmt.Errorf(
|
2018-05-09 23:54:23 +00:00
|
|
|
"login received status %d %s",
|
|
|
|
response.StatusCode,
|
|
|
|
extractServerErrorText(response.Body),
|
|
|
|
)
|
2018-05-04 16:53:21 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var responseBody loginResponse
|
|
|
|
err = json.NewDecoder(response.Body).Decode(&responseBody)
|
|
|
|
if err != nil {
|
2021-11-22 14:13:26 +00:00
|
|
|
return "", fmt.Errorf("decode login response: %w", err)
|
2018-05-04 16:53:21 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if responseBody.Err != nil {
|
2021-11-22 14:13:26 +00:00
|
|
|
return "", fmt.Errorf("login: %s", responseBody.Err)
|
2018-05-04 16:53:21 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return responseBody.Token, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Logout attempts to logout to the current Fleet instance.
|
|
|
|
func (c *Client) Logout() error {
|
2022-04-05 15:35:53 +00:00
|
|
|
verb, path := "POST", "/api/latest/fleet/logout"
|
2018-05-04 16:53:21 +00:00
|
|
|
var responseBody logoutResponse
|
2022-01-24 19:40:51 +00:00
|
|
|
return c.authenticatedRequest(nil, verb, path, &responseBody)
|
2018-05-04 16:53:21 +00:00
|
|
|
}
|