2018-05-04 16:53:21 +00:00
|
|
|
package service
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"net/http"
|
|
|
|
|
2021-06-06 22:07:29 +00:00
|
|
|
"github.com/fleetdm/fleet/server/fleet"
|
2018-05-04 16:53:21 +00:00
|
|
|
"github.com/pkg/errors"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Setup attempts to setup the current Fleet instance. If setup is successful,
|
|
|
|
// an auth token is returned.
|
2019-01-02 23:27:37 +00:00
|
|
|
func (c *Client) Setup(email, username, password, org string) (string, error) {
|
2018-05-04 16:53:21 +00:00
|
|
|
params := setupRequest{
|
2021-06-06 22:07:29 +00:00
|
|
|
Admin: &fleet.UserPayload{
|
2019-01-02 23:27:37 +00:00
|
|
|
Username: &username,
|
2018-05-04 16:53:21 +00:00
|
|
|
Email: &email,
|
|
|
|
Password: &password,
|
|
|
|
},
|
2021-06-06 22:07:29 +00:00
|
|
|
OrgInfo: &fleet.OrgInfo{
|
2018-05-04 16:53:21 +00:00
|
|
|
OrgName: &org,
|
|
|
|
},
|
2021-06-06 23:58:23 +00:00
|
|
|
ServerURL: &c.addr,
|
2018-05-04 16:53:21 +00:00
|
|
|
}
|
|
|
|
|
2020-11-05 04:45:16 +00:00
|
|
|
response, err := c.Do("POST", "/api/v1/setup", "", params)
|
2018-05-04 16:53:21 +00:00
|
|
|
if err != nil {
|
2018-05-04 21:55:57 +00:00
|
|
|
return "", errors.Wrap(err, "POST /api/v1/setup")
|
2018-05-04 16:53:21 +00:00
|
|
|
}
|
|
|
|
defer response.Body.Close()
|
|
|
|
|
2021-02-02 20:16:59 +00:00
|
|
|
// If setup has already been completed, Fleet will not serve the setup
|
|
|
|
// route, which will cause the request to 404
|
2018-05-04 16:53:21 +00:00
|
|
|
if response.StatusCode == http.StatusNotFound {
|
2018-05-04 21:55:57 +00:00
|
|
|
return "", setupAlreadyErr{}
|
2018-05-04 16:53:21 +00:00
|
|
|
}
|
2018-05-09 23:54:23 +00:00
|
|
|
if response.StatusCode != http.StatusOK {
|
|
|
|
return "", errors.Errorf(
|
|
|
|
"setup received status %d %s",
|
|
|
|
response.StatusCode,
|
|
|
|
extractServerErrorText(response.Body),
|
|
|
|
)
|
|
|
|
}
|
2018-05-04 16:53:21 +00:00
|
|
|
|
|
|
|
if response.StatusCode != http.StatusOK {
|
2018-05-04 21:55:57 +00:00
|
|
|
return "", errors.Errorf("setup got HTTP %d, expected 200", response.StatusCode)
|
2018-05-04 16:53:21 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var responseBody setupResponse
|
|
|
|
err = json.NewDecoder(response.Body).Decode(&responseBody)
|
|
|
|
if err != nil {
|
2018-05-04 21:55:57 +00:00
|
|
|
return "", errors.Wrap(err, "decode setup response")
|
2018-05-04 16:53:21 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if responseBody.Err != nil {
|
2018-05-04 21:55:57 +00:00
|
|
|
return "", errors.Errorf("setup: %s", responseBody.Err)
|
2018-05-04 16:53:21 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return *responseBody.Token, nil
|
|
|
|
}
|