2024-09-07 19:14:29 +03:00
|
|
|
package client
|
|
|
|
|
2024-09-08 13:50:05 +03:00
|
|
|
import (
|
|
|
|
"gitea.24example.ru/spavelit/bpiek/api"
|
|
|
|
"github.com/go-resty/resty/v2"
|
|
|
|
)
|
2024-09-07 19:14:29 +03:00
|
|
|
|
|
|
|
const (
|
2024-09-08 13:50:05 +03:00
|
|
|
AuthApiUrl = "https://bp.iek.ru/oauth/login"
|
|
|
|
BaseApiUrl = "https://bp.iek.ru/api/catalog/v1/"
|
2024-09-07 19:14:29 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
type (
|
|
|
|
Client struct {
|
|
|
|
HTTPClient *resty.Client
|
|
|
|
}
|
|
|
|
|
|
|
|
AuthSuccess struct {
|
|
|
|
TokenType string `json:"token_type"`
|
|
|
|
AccessToken string `json:"access_token"`
|
|
|
|
IdToken string `json:"id_token"`
|
|
|
|
RefreshToken string `json:"refresh_token"`
|
|
|
|
ExpiresIn int `json:"expires_in"`
|
|
|
|
Scope string `json:"scope"`
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
2024-09-08 13:50:05 +03:00
|
|
|
func NewClient(credentials api.Credentials) *Client {
|
2024-09-07 19:14:29 +03:00
|
|
|
authSuccess := &AuthSuccess{}
|
|
|
|
client := resty.New()
|
2024-09-08 13:50:05 +03:00
|
|
|
client.SetBaseURL(BaseApiUrl)
|
2024-09-07 19:14:29 +03:00
|
|
|
|
|
|
|
response, err := client.R().
|
|
|
|
SetFormData(map[string]string{
|
2024-09-08 13:50:05 +03:00
|
|
|
"username": credentials.Username,
|
|
|
|
"password": credentials.Password,
|
2024-09-07 19:14:29 +03:00
|
|
|
}).
|
|
|
|
SetResult(&authSuccess).
|
2024-09-08 13:50:05 +03:00
|
|
|
Post(AuthApiUrl)
|
2024-09-07 19:14:29 +03:00
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if response.StatusCode() != 200 {
|
|
|
|
panic("Auth failed. Invalid credentials")
|
|
|
|
}
|
|
|
|
|
|
|
|
client.SetHeader("Content-Type", "application/json")
|
2024-09-08 13:50:05 +03:00
|
|
|
client.SetHeader("Authorization", authSuccess.TokenType+" "+authSuccess.AccessToken)
|
2024-09-07 19:14:29 +03:00
|
|
|
|
|
|
|
return &Client{
|
|
|
|
HTTPClient: client,
|
|
|
|
}
|
|
|
|
}
|