-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgoogle.go
More file actions
73 lines (61 loc) · 1.6 KB
/
google.go
File metadata and controls
73 lines (61 loc) · 1.6 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
//go:build !wasm
package user
import (
"context"
"encoding/json"
"net/http"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
)
type GoogleProvider struct {
ClientID string
ClientSecret string
RedirectURL string
config *oauth2.Config
}
func (p *GoogleProvider) Name() string {
return "google"
}
func (p *GoogleProvider) ensureConfig() {
if p.config == nil {
p.config = &oauth2.Config{
ClientID: p.ClientID,
ClientSecret: p.ClientSecret,
RedirectURL: p.RedirectURL,
Scopes: []string{"https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile"},
Endpoint: google.Endpoint,
}
}
}
func (p *GoogleProvider) AuthCodeURL(state string) string {
p.ensureConfig()
return p.config.AuthCodeURL(state)
}
func (p *GoogleProvider) ExchangeCode(ctx context.Context, code string) (*oauth2.Token, error) {
p.ensureConfig()
return p.config.Exchange(ctx, code)
}
func (p *GoogleProvider) GetUserInfo(ctx context.Context, token *oauth2.Token) (OAuthUserInfo, error) {
client := p.config.Client(ctx, token)
resp, err := client.Get("https://www.googleapis.com/oauth2/v2/userinfo")
if err != nil {
return OAuthUserInfo{}, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return OAuthUserInfo{}, ErrInvalidCredentials
}
var data struct {
ID string `json:"id"`
Email string `json:"email"`
Name string `json:"name"`
}
if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
return OAuthUserInfo{}, err
}
return OAuthUserInfo{
ID: data.ID,
Email: data.Email,
Name: data.Name,
}, nil
}