amocrm/pkg/pena-social-auth/client.go

69 lines
1.7 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package pena_social_auth
import (
"encoding/json"
"fmt"
"github.com/gofiber/fiber/v2"
"go.uber.org/zap"
"net/http"
)
type Deps struct {
PenaSocialAuthURL string
FiberClient *fiber.Client
Logger *zap.Logger
ReturnURL string
}
type Client struct {
penaSocialAuthURL string
fiberClient *fiber.Client
logger *zap.Logger
returnURL string
}
func NewClient(deps Deps) *Client {
if deps.FiberClient == nil {
deps.FiberClient = fiber.AcquireClient()
}
return &Client{
penaSocialAuthURL: deps.PenaSocialAuthURL,
fiberClient: deps.FiberClient,
returnURL: deps.ReturnURL,
logger: deps.Logger,
}
}
type GenAuthURLResp struct {
URL string `json:"url"`
}
// todo добавить state в этот запрос тут и в соц аус сервисе
func (c *Client) GenerateAmocrmAuthURL(accountID string) (string, error) {
url := c.penaSocialAuthURL + "?accessToken=" + accountID + "&returnUrl=" + c.returnURL
fmt.Println(url)
statusCode, resp, errs := c.fiberClient.Get(url).Bytes()
if len(errs) > 0 {
for _, err := range errs {
c.logger.Error("error sending request in GenerateAmocrmAuthURL", zap.Error(err))
}
return "", fmt.Errorf("request GenerateAmocrmAuthURL failed: %v", errs[0])
}
if statusCode != http.StatusOK {
errorMessage := fmt.Sprintf("received an incorrect response from GenerateAmocrmAuthURL: %d", statusCode)
c.logger.Error(errorMessage, zap.Int("status", statusCode))
return "", fmt.Errorf(errorMessage)
}
var response GenAuthURLResp
err := json.Unmarshal(resp, &response)
if err != nil {
c.logger.Error("error unmarshal GenAuthURLResp:", zap.Error(err))
return "", err
}
return response.URL, nil
}