Skip to content

Commit 7bce57b

Browse files
rkashapovmarkbates
authored andcommitted
Support for VK.com
1 parent 1f7039e commit 7bce57b

File tree

6 files changed

+369
-0
lines changed

6 files changed

+369
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ $ go get github.com/markbates/goth
5454
* Twitch
5555
* Twitter
5656
* Uber
57+
* VK
5758
* Wepay
5859
* Xero
5960
* Yahoo

examples/main.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ import (
4949
"github.com/markbates/goth/providers/twitch"
5050
"github.com/markbates/goth/providers/twitter"
5151
"github.com/markbates/goth/providers/uber"
52+
"github.com/markbates/goth/providers/vk"
5253
"github.com/markbates/goth/providers/wepay"
5354
"github.com/markbates/goth/providers/xero"
5455
"github.com/markbates/goth/providers/yahoo"
@@ -106,6 +107,7 @@ func main() {
106107
//Auth0 allocates domain per customer, a domain must be provided for auth0 to work
107108
auth0.New(os.Getenv("AUTH0_KEY"), os.Getenv("AUTH0_SECRET"), "http://localhost:3000/auth/auth0/callback", os.Getenv("AUTH0_DOMAIN")),
108109
xero.New(os.Getenv("XERO_KEY"), os.Getenv("XERO_SECRET"), "http://localhost:3000/auth/xero/callback"),
110+
vk.New(os.Getenv("VK_KEY"), os.Getenv("VK_SECRET"), "http://localhost:3000/auth/vk/callback"),
109111
)
110112

111113
// OpenID Connect is based on OpenID Connect Auto Discovery URL (https://openid.net/specs/openid-connect-discovery-1_0-17.html)
@@ -157,6 +159,7 @@ func main() {
157159
m["auth0"] = "Auth0"
158160
m["openid-connect"] = "OpenID Connect"
159161
m["xero"] = "Xero"
162+
m["vk"] = "VK"
160163

161164
var keys []string
162165
for k := range m {

providers/vk/session.go

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
package vk
2+
3+
import (
4+
"encoding/json"
5+
"errors"
6+
"strings"
7+
"time"
8+
9+
"github.com/markbates/goth"
10+
)
11+
12+
// Session stores data during the auth process with VK.
13+
type Session struct {
14+
AuthURL string
15+
AccessToken string
16+
ExpiresAt time.Time
17+
userID int64
18+
email string
19+
}
20+
21+
// GetAuthURL returns the URL for the authentication end-point for the provider.
22+
func (s *Session) GetAuthURL() (string, error) {
23+
if s.AuthURL == "" {
24+
return "", errors.New(goth.NoAuthUrlErrorMessage)
25+
}
26+
return s.AuthURL, nil
27+
}
28+
29+
// Marshal the session into a string
30+
func (s *Session) Marshal() string {
31+
b, _ := json.Marshal(s)
32+
return string(b)
33+
}
34+
35+
// Authorize the session with VK and return the access token to be stored for future use.
36+
func (s *Session) Authorize(provider goth.Provider, params goth.Params) (string, error) {
37+
p := provider.(*Provider)
38+
token, err := p.config.Exchange(goth.ContextForClient(p.Client()), params.Get("code"))
39+
if err != nil {
40+
return "", err
41+
}
42+
43+
if !token.Valid() {
44+
return "", errors.New("Invalid token received from provider")
45+
}
46+
47+
email, ok := token.Extra("email").(string)
48+
if !ok {
49+
return "", errors.New("Cannot fetch user email")
50+
}
51+
52+
userID, ok := token.Extra("user_id").(float64)
53+
if !ok {
54+
return "", errors.New("Cannot fetch user ID")
55+
}
56+
57+
s.AccessToken = token.AccessToken
58+
s.ExpiresAt = token.Expiry
59+
s.email = email
60+
s.userID = int64(userID)
61+
return s.AccessToken, err
62+
}
63+
64+
// UnmarshalSession will unmarshal a JSON string into a session.
65+
func (p *Provider) UnmarshalSession(data string) (goth.Session, error) {
66+
sess := new(Session)
67+
err := json.NewDecoder(strings.NewReader(data)).Decode(&sess)
68+
return sess, err
69+
}

providers/vk/session_test.go

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package vk_test
2+
3+
import (
4+
"testing"
5+
6+
"github.com/markbates/goth"
7+
"github.com/markbates/goth/providers/vk"
8+
"github.com/stretchr/testify/assert"
9+
)
10+
11+
func Test_Implements_Session(t *testing.T) {
12+
t.Parallel()
13+
a := assert.New(t)
14+
s := &vk.Session{}
15+
16+
a.Implements((*goth.Session)(nil), s)
17+
}
18+
19+
func Test_GetAuthURL(t *testing.T) {
20+
t.Parallel()
21+
a := assert.New(t)
22+
s := &vk.Session{}
23+
24+
_, err := s.GetAuthURL()
25+
a.Error(err)
26+
27+
s.AuthURL = "/foo"
28+
29+
url, _ := s.GetAuthURL()
30+
a.Equal(url, "/foo")
31+
}
32+
33+
func Test_ToJSON(t *testing.T) {
34+
t.Parallel()
35+
a := assert.New(t)
36+
s := &vk.Session{}
37+
38+
data := s.Marshal()
39+
a.Equal(data, `{"AuthURL":"","AccessToken":"","ExpiresAt":"0001-01-01T00:00:00Z"}`)
40+
}

providers/vk/vk.go

Lines changed: 180 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,180 @@
1+
// Package vk implements the OAuth2 protocol for authenticating users through vk.com.
2+
// This package can be used as a reference implementation of an OAuth2 provider for Goth.
3+
package vk
4+
5+
import (
6+
"bytes"
7+
"encoding/json"
8+
"errors"
9+
"fmt"
10+
"io"
11+
"io/ioutil"
12+
"net/http"
13+
14+
"github.com/markbates/goth"
15+
"golang.org/x/oauth2"
16+
)
17+
18+
var (
19+
authURL = "https://oauth.vk.com/authorize"
20+
tokenURL = "https://oauth.vk.com/access_token"
21+
endpointUser = "https://api.vk.com/method/users.get"
22+
apiVersion = "5.71"
23+
)
24+
25+
// New creates a new VK provider and sets up important connection details.
26+
// You should always call `vk.New` to get a new provider. Never try to
27+
// create one manually.
28+
func New(clientKey, secret, callbackURL string, scopes ...string) *Provider {
29+
p := &Provider{
30+
ClientKey: clientKey,
31+
Secret: secret,
32+
CallbackURL: callbackURL,
33+
providerName: "vk",
34+
}
35+
p.config = newConfig(p, scopes)
36+
return p
37+
}
38+
39+
// Provider is the implementation of `goth.Provider` for accessing Github.
40+
type Provider struct {
41+
ClientKey string
42+
Secret string
43+
CallbackURL string
44+
HTTPClient *http.Client
45+
config *oauth2.Config
46+
providerName string
47+
version string
48+
}
49+
50+
// Name is the name used to retrieve this provider later.
51+
func (p *Provider) Name() string {
52+
return p.providerName
53+
}
54+
55+
// SetName is to update the name of the provider (needed in case of multiple providers of 1 type)
56+
func (p *Provider) SetName(name string) {
57+
p.providerName = name
58+
}
59+
60+
func (p *Provider) Client() *http.Client {
61+
return goth.HTTPClientWithFallBack(p.HTTPClient)
62+
}
63+
64+
// BeginAuth asks VK for an authentication end-point.
65+
func (p *Provider) BeginAuth(state string) (goth.Session, error) {
66+
url := p.config.AuthCodeURL(state)
67+
session := &Session{
68+
AuthURL: url,
69+
}
70+
71+
return session, nil
72+
}
73+
74+
// FetchUser will go to VK and access basic information about the user.
75+
func (p *Provider) FetchUser(session goth.Session) (goth.User, error) {
76+
sess := session.(*Session)
77+
user := goth.User{
78+
AccessToken: sess.AccessToken,
79+
Provider: p.Name(),
80+
ExpiresAt: sess.ExpiresAt,
81+
Email: sess.email,
82+
}
83+
84+
if user.AccessToken == "" {
85+
return user, fmt.Errorf("%s cannot get user information without accessToken", p.providerName)
86+
}
87+
88+
fields := "photo_200,nickname"
89+
requestURL := fmt.Sprintf("%s?user_ids=%d&fields=%s&access_token=%s&v=%s", endpointUser, sess.userID, fields, sess.AccessToken, apiVersion)
90+
response, err := p.Client().Get(requestURL)
91+
if err != nil {
92+
return user, err
93+
}
94+
defer response.Body.Close()
95+
96+
if response.StatusCode != http.StatusOK {
97+
return user, fmt.Errorf("%s responded with a %d trying to fetch user information", p.providerName, response.StatusCode)
98+
}
99+
100+
bits, err := ioutil.ReadAll(response.Body)
101+
102+
err = json.NewDecoder(bytes.NewReader(bits)).Decode(&user.RawData)
103+
if err != nil {
104+
return user, err
105+
}
106+
107+
err = userFromReader(bytes.NewReader(bits), &user)
108+
return user, err
109+
}
110+
111+
func userFromReader(reader io.Reader, user *goth.User) error {
112+
response := struct {
113+
Response []struct {
114+
ID int `json:"id"`
115+
FirstName string `json:"first_name"`
116+
LastName string `json:"last_name"`
117+
NickName string `json:"nickname"`
118+
Photo200 string `json:"photo_200"`
119+
} `json:"response"`
120+
}{}
121+
122+
err := json.NewDecoder(reader).Decode(&response)
123+
if err != nil {
124+
return err
125+
}
126+
127+
if len(response.Response) == 0 {
128+
return fmt.Errorf("vk cannot get user information")
129+
}
130+
131+
u := response.Response[0]
132+
133+
user.UserID = string(u.ID)
134+
user.FirstName = u.FirstName
135+
user.LastName = u.LastName
136+
user.NickName = u.NickName
137+
user.AvatarURL = u.Photo200
138+
139+
return err
140+
}
141+
142+
// Debug is a no-op for the vk package.
143+
func (p *Provider) Debug(debug bool) {}
144+
145+
//RefreshToken refresh token is not provided by vk
146+
func (p *Provider) RefreshToken(refreshToken string) (*oauth2.Token, error) {
147+
return nil, errors.New("Refresh token is not provided by vk")
148+
}
149+
150+
//RefreshTokenAvailable refresh token is not provided by vk
151+
func (p *Provider) RefreshTokenAvailable() bool {
152+
return false
153+
}
154+
155+
func newConfig(provider *Provider, scopes []string) *oauth2.Config {
156+
c := &oauth2.Config{
157+
ClientID: provider.ClientKey,
158+
ClientSecret: provider.Secret,
159+
RedirectURL: provider.CallbackURL,
160+
Endpoint: oauth2.Endpoint{
161+
AuthURL: authURL,
162+
TokenURL: tokenURL,
163+
},
164+
Scopes: []string{
165+
"email",
166+
},
167+
}
168+
169+
defaultScopes := map[string]struct{}{
170+
"email": {},
171+
}
172+
173+
for _, scope := range scopes {
174+
if _, exists := defaultScopes[scope]; !exists {
175+
c.Scopes = append(c.Scopes, scope)
176+
}
177+
}
178+
179+
return c
180+
}

0 commit comments

Comments
 (0)