customer/internal/client/oauth.go
2023-05-16 04:12:34 +03:00

69 lines
2.0 KiB
Go

package client
import (
"context"
"github.com/sirupsen/logrus"
"golang.org/x/oauth2"
"penahub.gitlab.yandexcloud.net/pena-services/pena-social-auth/internal/models"
"penahub.gitlab.yandexcloud.net/pena-services/pena-social-auth/internal/utils"
"penahub.gitlab.yandexcloud.net/pena-services/pena-social-auth/pkg/client"
)
type OAuthClientDeps struct {
Logger *logrus.Logger
Config *oauth2.Config
}
type OAuthClient struct {
logger *logrus.Logger
config *oauth2.Config
}
func NewOAuthClient(deps *OAuthClientDeps) *OAuthClient {
return &OAuthClient{
logger: deps.Logger,
config: deps.Config,
}
}
func (receiver *OAuthClient) Exchange(ctx context.Context, code string, options ...oauth2.AuthCodeOption) (*oauth2.Token, error) {
if receiver.config.Endpoint.AuthStyle < 4 {
return receiver.config.Exchange(ctx, code, options...)
}
if receiver.config.Endpoint.AuthStyle == models.BodyAuthStyle {
return receiver.bodyExchange(ctx, code)
}
return nil, nil
}
func (receiver *OAuthClient) AuthCodeURL(state string, options ...oauth2.AuthCodeOption) string {
return receiver.config.AuthCodeURL(state, options...)
}
func (receiver *OAuthClient) bodyExchange(ctx context.Context, code string) (*oauth2.Token, error) {
response, err := client.Post[oauth2.Token, any](ctx, &client.RequestSettings{
URL: receiver.config.Endpoint.TokenURL,
Headers: map[string]string{"Content-Type": "application/json"},
Body: map[string]string{
"grant_type": "authorization_code",
"redirect_uri": receiver.config.RedirectURL,
"client_id": receiver.config.ClientID,
"client_secret": receiver.config.ClientSecret,
"code": code,
},
})
if err != nil {
receiver.logger.Errorf("failed to exchange code on <bodyExchange> of <OAuthClient>: %v", err)
return nil, err
}
if response.Error != nil {
receiver.logger.Errorf("failed request on <bodyExchange> of <OAuthClient>: %s", receiver.config.Endpoint.TokenURL)
return nil, utils.DetermineClientErrorResponse(response.StatusCode)
}
return response.Body, nil
}