forked from netlify/gotrue
/
bitbucket.go
93 lines (76 loc) · 1.96 KB
/
bitbucket.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package provider
import (
"context"
"errors"
"github.com/netlify/gotrue/conf"
"golang.org/x/oauth2"
"golang.org/x/oauth2/bitbucket"
)
// Bitbucket
const (
bitbucketBaseURL = "https://api.bitbucket.org/2.0/user"
bitbucketEmailsURL = bitbucketBaseURL + "/emails"
)
type bitbucketProvider struct {
*oauth2.Config
}
type bitbucketUser struct {
Name string `json:"display_name"`
Avatar struct {
Href string `json:"href"`
} `json:"avatar"`
}
type bitbucketEmail struct {
Email string `json:"email"`
Primary bool `json:"is_primary"`
Verified bool `json:"is_confirmed"`
}
type bitbucketEmails struct {
Values []bitbucketEmail `json:"values"`
}
// NewBitbucketProvider creates a Bitbucket account provider.
func NewBitbucketProvider(ext conf.OAuthProviderConfiguration) (Provider, error) {
if err := ext.Validate(); err != nil {
return nil, err
}
return &bitbucketProvider{
&oauth2.Config{
ClientID: ext.ClientID,
ClientSecret: ext.Secret,
Endpoint: bitbucket.Endpoint,
RedirectURL: ext.RedirectURI,
Scopes: []string{"account", "email"},
},
}, nil
}
func (g bitbucketProvider) GetOAuthToken(code string) (*oauth2.Token, error) {
return g.Exchange(oauth2.NoContext, code)
}
func (g bitbucketProvider) GetUserData(ctx context.Context, tok *oauth2.Token) (*UserProvidedData, error) {
var u bitbucketUser
if err := makeRequest(ctx, tok, g.Config, bitbucketBaseURL, &u); err != nil {
return nil, err
}
data := &UserProvidedData{
Metadata: map[string]string{
nameKey: u.Name,
avatarURLKey: u.Avatar.Href,
},
}
var emails bitbucketEmails
if err := makeRequest(ctx, tok, g.Config, bitbucketEmailsURL, &emails); err != nil {
return nil, err
}
if len(emails.Values) > 0 {
for _, e := range emails.Values {
if e.Primary {
data.Email = e.Email
data.Verified = e.Verified
}
}
}
if data.Email == "" {
return nil, errors.New("Unable to find email with Bitbucket provider")
}
return data, nil
}