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

76 lines
2.0 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 google
import (
"context"
"net/http"
"github.com/labstack/echo/v4"
"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/pkg/utils"
)
// TODO:
// 1) Необходимо вынести все ошибки в отдельный пакет
// 2) Реализовать map'у для возврата JSON ошибок
type GoogleClient interface {
GetUserInformation(ctx context.Context, accessToken string) (*models.GoogleUserInformation, error)
}
type Deps struct {
GoogleOAuthConfig *oauth2.Config
Client GoogleClient
Logger *logrus.Logger
}
type Controller struct {
oAuth *oauth2.Config
logger *logrus.Logger
client GoogleClient
state string
}
func New(deps *Deps) *Controller {
return &Controller{
oAuth: deps.GoogleOAuthConfig,
logger: deps.Logger,
client: deps.Client,
state: utils.GetRandomString(10),
}
}
func (receiver *Controller) Auth(ctx echo.Context) error {
url := receiver.oAuth.AuthCodeURL(receiver.state, oauth2.AccessTypeOffline)
return ctx.Redirect(http.StatusTemporaryRedirect, url)
}
func (receiver *Controller) Callback(ctx echo.Context) error {
callbackState := ctx.FormValue("state")
callbackCode := ctx.FormValue("code")
if callbackState != receiver.state {
receiver.logger.Errorln("state is not valid")
return ctx.JSON(http.StatusBadRequest, "state is not valid")
}
token, err := receiver.oAuth.Exchange(ctx.Request().Context(), callbackCode)
if err != nil {
receiver.logger.Errorln("exchange error: ", err.Error())
return ctx.JSON(http.StatusBadRequest, err.Error())
}
userInformation, err := receiver.client.GetUserInformation(ctx.Request().Context(), token.AccessToken)
if err != nil {
receiver.logger.Errorln("get user information error: ", err.Error())
return ctx.JSON(http.StatusInternalServerError, err.Error())
}
return ctx.JSON(http.StatusOK, userInformation)
}