generated from PenaSide/GolangTemplate
72 lines
1.8 KiB
Go
72 lines
1.8 KiB
Go
package vk
|
|
|
|
import (
|
|
"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"
|
|
)
|
|
|
|
type VKClient interface {
|
|
GetUserInformation(token *oauth2.Token) (*models.VKUserInformation, error)
|
|
}
|
|
|
|
type Deps struct {
|
|
VKOAuthConfig *oauth2.Config
|
|
Client VKClient
|
|
Logger *logrus.Logger
|
|
}
|
|
|
|
type Controller struct {
|
|
oAuth *oauth2.Config
|
|
logger *logrus.Logger
|
|
client VKClient
|
|
state string
|
|
}
|
|
|
|
func New(deps *Deps) *Controller {
|
|
return &Controller{
|
|
oAuth: deps.VKOAuthConfig,
|
|
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 {
|
|
queries := ctx.Request().URL.Query()
|
|
callbackCode := queries.Get("code")
|
|
callbackState := queries.Get("state")
|
|
|
|
if callbackState != receiver.state {
|
|
receiver.logger.Errorln("state is not valid on <Callback> of <AmocrmController>")
|
|
|
|
return ctx.JSON(http.StatusBadRequest, "state is not valid")
|
|
}
|
|
|
|
token, err := receiver.oAuth.Exchange(ctx.Request().Context(), callbackCode)
|
|
if err != nil {
|
|
receiver.logger.Errorf("exchange error: %v", err)
|
|
|
|
return ctx.JSON(http.StatusBadRequest, err.Error())
|
|
}
|
|
|
|
userInformation, err := receiver.client.GetUserInformation(token)
|
|
if err != nil {
|
|
receiver.logger.Errorf("get user information error: %v", err)
|
|
|
|
return ctx.JSON(http.StatusInternalServerError, err.Error())
|
|
}
|
|
|
|
return ctx.JSON(http.StatusOK, userInformation)
|
|
}
|