Resolves #36087 (one of several small PRs). - [x] QA'd all new/changed functionality manually <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Refactor** * Reorganized internal API session models for improved code structure and maintainability. <!-- review_stack_entry_start --> [](https://app.coderabbit.ai/change-stack/fleetdm/fleet/pull/45908?utm_source=github_walkthrough&utm_medium=github&utm_campaign=change_stack) <!-- review_stack_entry_end --> <!-- end of auto-generated comment: release notes by coderabbit.ai -->
55 lines
1.3 KiB
Go
55 lines
1.3 KiB
Go
package service
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
|
|
"github.com/fleetdm/fleet/v4/server/fleet"
|
|
)
|
|
|
|
// 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 := fleet.LoginRequest{
|
|
Email: email,
|
|
Password: password,
|
|
}
|
|
|
|
response, err := c.Do("POST", "/api/latest/fleet/login", "", params)
|
|
if err != nil {
|
|
return "", fmt.Errorf("POST /api/latest/fleet/login: %w", err)
|
|
}
|
|
defer response.Body.Close()
|
|
|
|
if response.StatusCode == http.StatusNotFound {
|
|
return "", notSetupErr{}
|
|
}
|
|
if response.StatusCode != http.StatusOK {
|
|
return "", fmt.Errorf(
|
|
"login received status %d %s",
|
|
response.StatusCode,
|
|
extractServerErrorText(response.Body),
|
|
)
|
|
}
|
|
|
|
var responseBody fleet.LoginResponse
|
|
err = json.NewDecoder(response.Body).Decode(&responseBody)
|
|
if err != nil {
|
|
return "", fmt.Errorf("decode login response: %w", err)
|
|
}
|
|
|
|
if responseBody.Err != nil {
|
|
return "", fmt.Errorf("login: %s", responseBody.Err)
|
|
}
|
|
|
|
return responseBody.Token, nil
|
|
}
|
|
|
|
// Logout attempts to logout to the current Fleet instance.
|
|
func (c *Client) Logout() error {
|
|
verb, path := "POST", "/api/latest/fleet/logout"
|
|
var responseBody fleet.LogoutResponse
|
|
return c.authenticatedRequest(nil, verb, path, &responseBody)
|
|
}
|