add encryption and get page

This commit is contained in:
Aleksandr Trushkin
2024-01-29 00:09:30 +03:00
parent cc69847c4b
commit 5a49956661
7 changed files with 432 additions and 33 deletions

View File

@ -13,6 +13,7 @@ import (
"strings"
"git.loyso.art/frx/eway/internal/config"
"git.loyso.art/frx/eway/internal/crypto"
"git.loyso.art/frx/eway/internal/entity"
"github.com/go-resty/resty/v2"
@ -36,38 +37,54 @@ type client struct {
type Config config.Eway
func New(cfg Config, log zerolog.Logger) (client, error) {
if cfg.SessionID == "" {
return client{}, entity.SimpleError("no session id provided")
}
if cfg.SessionUser == "" {
return client{}, entity.SimpleError("no session user provided")
}
cookies := []*http.Cookie{
{
Name: "session_id",
Value: cfg.SessionID,
Domain: "eway.elevel.ru",
HttpOnly: true,
},
{
Name: "session_user",
Value: cfg.SessionUser,
Domain: "eway.elevel.ru",
HttpOnly: true,
},
}
func New(ctx context.Context, cfg Config, log zerolog.Logger) (client, error) {
httpclient := resty.New().
SetDebug(cfg.Debug).
SetCookies(cookies).
// SetCookies(cookies).
SetBaseURL("https://eway.elevel.ru/api")
return client{
c := client{
http: httpclient,
log: log.With().Str("client", "eway").Logger(),
}, nil
}
if cfg.SessionID == "" || cfg.SessionUser == "" {
if cfg.Login == "" || cfg.Password == "" {
return client{}, entity.SimpleError("no auth method provided")
}
decryptedPassword, err := crypto.Decrypt(cfg.Password)
if err != nil {
return client{}, fmt.Errorf("decrypting password: %w", err)
}
err = c.login(ctx, cfg.Login, decryptedPassword)
if err != nil {
return client{}, err
}
log.Info().Msg("login successful")
} else if cfg.SessionID != "" && cfg.SessionUser != "" {
cookies := []*http.Cookie{
{
Name: "session_id",
Value: cfg.SessionID,
Domain: "eway.elevel.ru",
HttpOnly: true,
},
{
Name: "session_user",
Value: cfg.SessionUser,
Domain: "eway.elevel.ru",
HttpOnly: true,
},
}
c.http.SetCookies(cookies)
} else {
return client{}, entity.SimpleError("bad configuration: either session_id and session_user should be set or login and password")
}
return c, nil
}
type GetGoodsNewParams struct {
@ -181,8 +198,6 @@ func (c client) GetGoodsRemnants(
return nil, fmt.Errorf("reading raw body: %w", err)
}
c.log.Debug().RawJSON("response", data).Msg("body prepared")
out = make(entity.MappedGoodsRemnants, len(productIDs))
err = json.NewDecoder(bytes.NewReader(data)).Decode(&out)
if err != nil {
@ -234,3 +249,23 @@ func (c client) GetGoodsNew(
return mapResponseByOrder(response), response.RecordsTotal, nil
}
func (c client) login(ctx context.Context, user, pass string) error {
resp, err := c.http.R().
SetDoNotParseResponse(true).
SetFormData(map[string]string{
"username": user,
"password": pass,
}).Post("https://eway.elevel.ru/")
if err != nil {
return fmt.Errorf("sending request: %w", err)
}
if resp.IsError() {
zerolog.Ctx(ctx).Warn().Int("code", resp.StatusCode()).Msg("bad response")
return entity.SimpleError("request was not successful")
}
return nil
}