/
google.go
79 lines (68 loc) · 1.7 KB
/
google.go
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
77
78
79
package auth
/**
https://developers.google.com/identity/protocols/OAuth2WebServer
https://developers.google.com/identity/protocols/googlescopes
*/
import (
"io/ioutil"
"net/http"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
)
type GoogleUserInfo struct {
Id string `json:"id"`
Email string `json:"email"`
Name string `json:"name"`
Link string `json:"link"`
Picture string `json:"picture"`
}
type GoogleConf struct {
Web GoogleWeb `json:"web"`
}
type GoogleWeb struct {
ClientId string `json:"client_id"`
ClientSecret string `json:"client_secret"`
RedirectURLS []string `json:"redirect_uris"`
}
type Google struct {
cfg *oauth2.Config
}
func (p *Google) ParseToken(req *http.Request) ([]byte, error) {
return p.Token(req.URL.Query().Get("code"))
}
func (p *Google) Token(code string) ([]byte, error) {
tok, err := p.cfg.Exchange(oauth2.NoContext, code)
if err != nil {
return nil, err
}
client := p.cfg.Client(oauth2.NoContext, tok)
res, err := client.Get("https://www.googleapis.com/oauth2/v1/userinfo?alt=json")
if err != nil {
return nil, err
}
defer res.Body.Close()
var buf []byte
buf, err = ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
return buf, nil
}
func (p *Google) Url() string {
return p.cfg.AuthCodeURL("state")
}
//===============================================
func NewGoogle(cfg *GoogleConf) *Google {
return &Google{
cfg: &oauth2.Config{
ClientID: cfg.Web.ClientId,
ClientSecret: cfg.Web.ClientSecret,
RedirectURL: cfg.Web.RedirectURLS[0],
Scopes: []string{
"https://www.googleapis.com/auth/userinfo.profile",
"https://www.googleapis.com/auth/userinfo.email",
},
Endpoint: google.Endpoint,
},
}
}