2024-01-04 14:57:30 +00:00
|
|
|
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)
|
|
|
|
|
|
|
|
statusCode, resBody, errs := agent.Bytes()
|
|
|
|
if len(errs) > 0 {
|
|
|
|
for _, err := range errs {
|
2024-01-05 11:37:06 +00:00
|
|
|
a.deps.Logger.Error("Error in exchange auth token request", zap.Error(err))
|
2024-01-04 14:57:30 +00:00
|
|
|
}
|
|
|
|
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)
|
2024-01-18 22:01:15 +00:00
|
|
|
a.deps.Logger.Error(errorMessage, zap.Int("status", statusCode), zap.String("respBody", string(resBody)), zap.String("UserID", userID),zap.String("sign", signature))
|
2024-01-04 14:57:30 +00:00
|
|
|
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
|
|
|
|
}
|