13
"golang.org/x/oauth2/yandex"
14
"xelbot.com/reprogl/container"
18
ProviderNotFound = errors.New("oauth: no matching provider found")
23
yandexProvider = "yandex"
24
vkProvider = "vkontakte"
27
func SetLogger(l *log.Logger) {
31
func SupportedProvider(name string) (found bool) {
42
func ConfigByProvider(name string) (*oauth2.Config, error) {
43
cnf := container.GetConfig()
44
url := container.GenerateAbsoluteURL("oauth-verification", "provider", name)
48
return &oauth2.Config{
49
ClientID: cnf.OAuthYandexID,
50
ClientSecret: cnf.OAuthYandexSecret,
51
Endpoint: yandex.Endpoint,
55
return &oauth2.Config{
56
ClientID: cnf.OAuthVkID,
57
ClientSecret: cnf.OAuthVkSecret,
60
Scopes: []string{"vkid.personal_info", "email"},
64
return nil, ProviderNotFound
67
func AdditionalParams(name string) []string {
68
params := make([]string, 0)
71
return []string{"device_id"}
77
func UserDataByCode(providerName, code, verifier string, additional map[string]string) (*UserData, error) {
78
oauthConfig, err := ConfigByProvider(providerName)
83
options := make([]oauth2.AuthCodeOption, 1)
84
options[0] = oauth2.VerifierOption(verifier)
86
for key, value := range additional {
87
options = append(options, oauth2.SetAuthURLParam(key, value))
90
token, err := oauthConfig.Exchange(context.Background(), code, options...)
95
if tokenScope := token.Extra("scope"); tokenScope != nil {
96
logger.Printf("[OAUTH] token scope: %s", tokenScope)
99
resourceOwner, err := resourceOwnerByProvider(providerName, token)
104
return resourceOwner.GetUserData()
107
func resourceOwnerByProvider(name string, token *oauth2.Token) (ResourceOwnerInterface, error) {
110
return &yandexResourceOwner{accessToken: token.AccessToken}, nil
112
return &vkResourceOwner{accessToken: token.AccessToken}, nil
115
return nil, ProviderNotFound
118
func doRequest(request *http.Request) ([]byte, error) {
119
client := http.Client{
120
Timeout: 5 * time.Second,
123
response, err := client.Do(request)
128
if response.StatusCode != http.StatusOK {
129
return nil, errors.New("oauth: response status code is " + strconv.Itoa(response.StatusCode))
132
defer response.Body.Close()
133
buf, err := io.ReadAll(response.Body)
138
logger.Printf("[OAUTH] user data: %s", buf)