69 lines
1.7 KiB
Go
69 lines
1.7 KiB
Go
package client
|
||
|
||
import (
|
||
"codeword/internal/models"
|
||
"encoding/json"
|
||
"fmt"
|
||
"github.com/gofiber/fiber/v2"
|
||
"go.uber.org/zap"
|
||
)
|
||
|
||
type AuthClientDeps struct {
|
||
AuthUrl string
|
||
FiberClient *fiber.Client
|
||
Logger *zap.Logger
|
||
}
|
||
|
||
type AuthClient struct {
|
||
deps AuthClientDeps
|
||
}
|
||
|
||
func NewAuthClient(deps AuthClientDeps) *AuthClient {
|
||
if deps.FiberClient == nil {
|
||
deps.FiberClient = fiber.AcquireClient()
|
||
}
|
||
return &AuthClient{
|
||
deps: deps,
|
||
}
|
||
}
|
||
|
||
func (a *AuthClient) RefreshAuthToken(userID, signature string) (*models.RefreshResponse, error) {
|
||
body := models.AuthRequestBody{
|
||
UserID: userID,
|
||
Signature: signature,
|
||
}
|
||
|
||
bodyBytes, err := json.Marshal(body)
|
||
if err != nil {
|
||
a.deps.Logger.Error("Failed to encode request body", zap.Error(err))
|
||
return nil, err
|
||
}
|
||
|
||
agent := a.deps.FiberClient.Post(a.deps.AuthUrl)
|
||
agent.Set("Content-Type", "application/json").Body(bodyBytes)
|
||
//todo надо что-то придумать с авторизаиционными токенами
|
||
agent.Set("Authorization", "Bearer "+"123")
|
||
|
||
statusCode, resBody, errs := agent.Bytes()
|
||
if len(errs) > 0 {
|
||
for _, err := range errs {
|
||
a.deps.Logger.Error("Error in refresh auth token request", zap.Error(err))
|
||
}
|
||
return nil, fmt.Errorf("request failed: %v", errs)
|
||
}
|
||
|
||
if statusCode != fiber.StatusOK {
|
||
errorMessage := fmt.Sprintf("received an incorrect response from the authentication service: %d", statusCode)
|
||
a.deps.Logger.Error(errorMessage, zap.Int("status", statusCode))
|
||
return nil, fmt.Errorf(errorMessage)
|
||
}
|
||
|
||
var tokens models.RefreshResponse
|
||
if err := json.Unmarshal(resBody, &tokens); err != nil {
|
||
a.deps.Logger.Error("failed to unmarshal auth service response", zap.Error(err))
|
||
return nil, err
|
||
}
|
||
|
||
return &tokens, nil
|
||
}
|