-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathauth.go
More file actions
76 lines (64 loc) · 1.81 KB
/
auth.go
File metadata and controls
76 lines (64 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// Package vk implements VKontakte API (including OAuth)
package vk
import (
"encoding/json"
"errors"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
// AccessToken response from VK
type AccessToken struct {
AccessToken string `json:"access_token"`
ExpiresIn time.Duration `json:"expires_in"`
UserID int `json:"user_id"`
UserEmail string `json:"email"`
Error string `json:"error"`
ErrorDescription string `json:"error_description"`
}
// AuthURL generates URL to authenticate via OAuth
func (api *API) AuthURL(state string) string {
query := api.requestTokenURL.Query()
query.Set("client_id", api.AppID)
if len(api.Scope) > 0 {
query.Set("scope", strings.Join(api.Scope, ","))
}
query.Set("redirect_uri", api.callbackURL.String())
query.Set("display", "page")
query.Set("v", Version)
query.Set("response_type", "code")
api.requestTokenURL.RawQuery = query.Encode()
return api.requestTokenURL.String()
}
// Authenticate with API
func (api *API) Authenticate(code string) error {
var resp *http.Response
var err error
var tok AccessToken
query := api.accessTokenURL.Query()
query = url.Values{
"client_id": {api.AppID},
"client_secret": {api.Secret},
"code": {code},
"redirect_uri": {api.callbackURL.String()},
}
api.accessTokenURL.RawQuery = query.Encode()
if resp, err = http.Get(api.accessTokenURL.String()); err != nil {
return err
}
defer resp.Body.Close()
if err = json.NewDecoder(resp.Body).Decode(&tok); err != nil {
return err
}
if tok.Error != "" {
return errors.New(tok.ErrorDescription)
}
tok.ExpiresIn *= time.Second
api.UserID = strconv.Itoa(tok.UserID)
api.UserEmail = tok.UserEmail
api.AccessToken = tok.AccessToken
api.Expiry = time.Now().Add(tok.ExpiresIn)
return nil
}