generated from PenaSide/GolangTemplate
76 lines
2.0 KiB
Go
76 lines
2.0 KiB
Go
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)
|
||
}
|