|
| 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