codeword/internal/adapters/client/auth.go

67 lines
1.7 KiB
Go
Raw Normal View History

2024-01-04 14:57:30 +00:00
package client
import (
"encoding/json"
"fmt"
2024-11-22 11:22:08 +00:00
"gitea.pena/PenaSide/codeword/internal/models"
2024-01-04 14:57:30 +00:00
"github.com/gofiber/fiber/v2"
"go.uber.org/zap"
)
type AuthClientDeps struct {
2025-01-02 10:44:52 +00:00
AuthUrl string
Logger *zap.Logger
2024-01-04 14:57:30 +00:00
}
type AuthClient struct {
2025-01-02 10:44:52 +00:00
authUrl string
fiberClient *fiber.Client
logger *zap.Logger
2024-01-04 14:57:30 +00:00
}
func NewAuthClient(deps AuthClientDeps) *AuthClient {
return &AuthClient{
2025-01-02 10:44:52 +00:00
authUrl: deps.AuthUrl,
fiberClient: fiber.AcquireClient(),
logger: deps.Logger,
2024-01-04 14:57:30 +00:00
}
}
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 {
2025-01-02 10:44:52 +00:00
a.logger.Error("Failed to encode request body", zap.Error(err))
2024-01-04 14:57:30 +00:00
return nil, err
}
2025-01-02 10:44:52 +00:00
agent := a.fiberClient.Post(fmt.Sprintf("%s/auth/exchange", a.authUrl))
2024-01-04 14:57:30 +00:00
agent.Set("Content-Type", "application/json").Body(bodyBytes)
statusCode, resBody, errs := agent.Bytes()
if len(errs) > 0 {
for _, err := range errs {
2025-01-02 10:44:52 +00:00
a.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)
2025-01-02 10:44:52 +00:00
a.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 {
2025-01-02 10:44:52 +00:00
a.logger.Error("failed to unmarshal auth service response", zap.Error(err))
2024-01-04 14:57:30 +00:00
return nil, err
}
return &tokens, nil
}