Skip to content

Commit 172172b

Browse files
Adding a Hubspot provider for Goth (#531)
1 parent e9e5240 commit 172172b

File tree

4 files changed

+334
-0
lines changed

4 files changed

+334
-0
lines changed

providers/hubspot/hubspot.go

+173
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,173 @@
1+
package hubspot
2+
3+
import (
4+
"encoding/json"
5+
"fmt"
6+
"github.com/markbates/goth"
7+
"golang.org/x/oauth2"
8+
"io"
9+
"net/http"
10+
"net/url"
11+
"strconv"
12+
"time"
13+
)
14+
15+
// These vars define the Authentication and Token URLS for Hubspot.
16+
var (
17+
AuthURL = "https://app.hubspot.com/oauth/authorize"
18+
TokenURL = "https://api.hubapi.com/oauth/v1/token"
19+
)
20+
21+
const (
22+
userEndpoint = "https://api.hubapi.com/oauth/v1/access-tokens/"
23+
)
24+
25+
type hubspotUser struct {
26+
Token string `json:"token"`
27+
User string `json:"user"`
28+
HubDomain string `json:"hub_domain"`
29+
Scopes []string `json:"scopes"`
30+
ScopeToScopeGroupPKs []int `json:"scope_to_scope_group_pks"`
31+
TrialScopes []string `json:"trial_scopes"`
32+
TrialScopeToScopeGroupPKs []int `json:"trial_scope_to_scope_group_pks"`
33+
HubID int `json:"hub_id"`
34+
AppID int `json:"app_id"`
35+
ExpiresIn int `json:"expires_in"`
36+
UserID int `json:"user_id"`
37+
TokenType string `json:"token_type"`
38+
}
39+
40+
// Provider is the implementation of `goth.Provider` for accessing Hubspot.
41+
type Provider struct {
42+
ClientKey string
43+
Secret string
44+
CallbackURL string
45+
HTTPClient *http.Client
46+
config *oauth2.Config
47+
providerName string
48+
}
49+
50+
// New creates a new Hubspot provider and sets up important connection details.
51+
// You should always call `hubspot.New` to get a new provider. Never try to
52+
// create one manually.
53+
func New(clientKey, secret, callbackURL string, scopes ...string) *Provider {
54+
p := &Provider{
55+
ClientKey: clientKey,
56+
Secret: secret,
57+
CallbackURL: callbackURL,
58+
providerName: "hubspot",
59+
}
60+
p.config = newConfig(p, scopes)
61+
return p
62+
}
63+
64+
// Name is the name used to retrieve this provider later.
65+
func (p *Provider) Name() string {
66+
return p.providerName
67+
}
68+
69+
// SetName is to update the name of the provider (needed in case of multiple providers of 1 type)
70+
func (p *Provider) SetName(name string) {
71+
p.providerName = name
72+
}
73+
74+
func (p *Provider) Client() *http.Client {
75+
return goth.HTTPClientWithFallBack(p.HTTPClient)
76+
}
77+
78+
// Debug is a no-op for the hubspot package.
79+
func (p *Provider) Debug(debug bool) {}
80+
81+
// BeginAuth asks Hubspot for an authentication end-point.
82+
func (p *Provider) BeginAuth(state string) (goth.Session, error) {
83+
return &Session{
84+
AuthURL: p.config.AuthCodeURL(state),
85+
}, nil
86+
}
87+
88+
// FetchUser will go to Hubspot and access basic information about the user.
89+
func (p *Provider) FetchUser(session goth.Session) (goth.User, error) {
90+
s := session.(*Session)
91+
user := goth.User{
92+
AccessToken: s.AccessToken,
93+
Provider: p.Name(),
94+
RefreshToken: s.RefreshToken,
95+
}
96+
97+
if user.AccessToken == "" {
98+
// data is not yet retrieved since accessToken is still empty
99+
return user, fmt.Errorf("%s cannot get user information without accessToken", p.providerName)
100+
}
101+
102+
response, err := p.Client().Get(userEndpoint + url.QueryEscape(user.AccessToken))
103+
if err != nil {
104+
return user, err
105+
}
106+
defer response.Body.Close()
107+
108+
if response.StatusCode != http.StatusOK {
109+
return user, fmt.Errorf("%s responded with a %d trying to fetch user information", p.providerName, response.StatusCode)
110+
}
111+
112+
responseBytes, err := io.ReadAll(response.Body)
113+
if err != nil {
114+
return user, err
115+
}
116+
117+
var u hubspotUser
118+
if err := json.Unmarshal(responseBytes, &u); err != nil {
119+
return user, err
120+
}
121+
122+
// Extract the user data we got from Google into our goth.User.
123+
user.Email = u.User
124+
user.UserID = strconv.Itoa(u.UserID)
125+
accessTokenExpiration := time.Now()
126+
if u.ExpiresIn > 0 {
127+
accessTokenExpiration = accessTokenExpiration.Add(time.Duration(u.ExpiresIn) * time.Second)
128+
} else {
129+
accessTokenExpiration = accessTokenExpiration.Add(30 * time.Minute)
130+
}
131+
user.ExpiresAt = accessTokenExpiration
132+
// Google provides other useful fields such as 'hd'; get them from RawData
133+
if err := json.Unmarshal(responseBytes, &user.RawData); err != nil {
134+
return user, err
135+
}
136+
137+
return user, nil
138+
}
139+
140+
func newConfig(provider *Provider, scopes []string) *oauth2.Config {
141+
c := &oauth2.Config{
142+
ClientID: provider.ClientKey,
143+
ClientSecret: provider.Secret,
144+
RedirectURL: provider.CallbackURL,
145+
Endpoint: oauth2.Endpoint{
146+
AuthURL: AuthURL,
147+
TokenURL: TokenURL,
148+
},
149+
Scopes: []string{},
150+
}
151+
152+
if len(scopes) > 0 {
153+
c.Scopes = append(c.Scopes, scopes...)
154+
}
155+
156+
return c
157+
}
158+
159+
// RefreshTokenAvailable refresh token is provided by auth provider or not
160+
func (p *Provider) RefreshTokenAvailable() bool {
161+
return true
162+
}
163+
164+
// RefreshToken get new access token based on the refresh token
165+
func (p *Provider) RefreshToken(refreshToken string) (*oauth2.Token, error) {
166+
token := &oauth2.Token{RefreshToken: refreshToken}
167+
ts := p.config.TokenSource(goth.ContextForClient(p.Client()), token)
168+
newToken, err := ts.Token()
169+
if err != nil {
170+
return nil, err
171+
}
172+
return newToken, err
173+
}

providers/hubspot/hubspot_test.go

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package hubspot_test
2+
3+
import (
4+
"github.com/markbates/goth/providers/hubspot"
5+
"os"
6+
"testing"
7+
8+
"github.com/markbates/goth"
9+
"github.com/stretchr/testify/assert"
10+
)
11+
12+
func Test_New(t *testing.T) {
13+
t.Parallel()
14+
a := assert.New(t)
15+
p := provider()
16+
17+
a.Equal(p.ClientKey, os.Getenv("HUBSPOT_KEY"))
18+
a.Equal(p.Secret, os.Getenv("HUBSPOT_SECRET"))
19+
a.Equal(p.CallbackURL, "/foo")
20+
}
21+
22+
func Test_Implements_Provider(t *testing.T) {
23+
t.Parallel()
24+
a := assert.New(t)
25+
a.Implements((*goth.Provider)(nil), provider())
26+
}
27+
28+
func Test_BeginAuth(t *testing.T) {
29+
t.Parallel()
30+
a := assert.New(t)
31+
p := provider()
32+
session, err := p.BeginAuth("test_state")
33+
s := session.(*hubspot.Session)
34+
a.NoError(err)
35+
a.Contains(s.AuthURL, "https://app.hubspot.com/oauth/authoriz")
36+
}
37+
38+
func Test_SessionFromJSON(t *testing.T) {
39+
t.Parallel()
40+
a := assert.New(t)
41+
42+
p := provider()
43+
session, err := p.UnmarshalSession(`{"AuthURL":"https://app.hubspot.com/oauth/authoriz","AccessToken":"1234567890"}`)
44+
a.NoError(err)
45+
46+
s := session.(*hubspot.Session)
47+
a.Equal(s.AuthURL, "https://app.hubspot.com/oauth/authoriz")
48+
a.Equal(s.AccessToken, "1234567890")
49+
}
50+
51+
func provider() *hubspot.Provider {
52+
return hubspot.New(os.Getenv("HUBSPOT_KEY"), os.Getenv("HUBSPOT_SECRET"), "/foo")
53+
}

providers/hubspot/session.go

+60
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package hubspot
2+
3+
import (
4+
"encoding/json"
5+
"errors"
6+
"github.com/markbates/goth"
7+
"strings"
8+
)
9+
10+
// Session stores data during the auth process with Hubspot.
11+
type Session struct {
12+
AuthURL string
13+
AccessToken string
14+
RefreshToken string
15+
}
16+
17+
var _ goth.Session = &Session{}
18+
19+
// GetAuthURL will return the URL set by calling the `BeginAuth` function on the Hubspot provider.
20+
func (s Session) GetAuthURL() (string, error) {
21+
if s.AuthURL == "" {
22+
return "", errors.New(goth.NoAuthUrlErrorMessage)
23+
}
24+
return s.AuthURL, nil
25+
}
26+
27+
// Authorize the session with Hubspot and return the access token to be stored for future use.
28+
func (s *Session) Authorize(provider goth.Provider, params goth.Params) (string, error) {
29+
p := provider.(*Provider)
30+
token, err := p.config.Exchange(goth.ContextForClient(p.Client()), params.Get("code"))
31+
32+
if err != nil {
33+
return "", err
34+
}
35+
36+
if !token.Valid() {
37+
return "", errors.New("Invalid token received from provider")
38+
}
39+
40+
s.AccessToken = token.AccessToken
41+
s.RefreshToken = token.RefreshToken
42+
return token.AccessToken, err
43+
}
44+
45+
// Marshal the session into a string
46+
func (s Session) Marshal() string {
47+
b, _ := json.Marshal(s)
48+
return string(b)
49+
}
50+
51+
func (s Session) String() string {
52+
return s.Marshal()
53+
}
54+
55+
// UnmarshalSession wil unmarshal a JSON string into a session.
56+
func (p *Provider) UnmarshalSession(data string) (goth.Session, error) {
57+
s := &Session{}
58+
err := json.NewDecoder(strings.NewReader(data)).Decode(s)
59+
return s, err
60+
}

providers/hubspot/session_test.go

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package hubspot_test
2+
3+
import (
4+
"github.com/markbates/goth/providers/hubspot"
5+
"testing"
6+
7+
"github.com/markbates/goth"
8+
"github.com/stretchr/testify/assert"
9+
)
10+
11+
func Test_Implements_Session(t *testing.T) {
12+
t.Parallel()
13+
a := assert.New(t)
14+
s := &hubspot.Session{}
15+
16+
a.Implements((*goth.Session)(nil), s)
17+
}
18+
19+
func Test_GetAuthURL(t *testing.T) {
20+
t.Parallel()
21+
a := assert.New(t)
22+
s := &hubspot.Session{}
23+
24+
_, err := s.GetAuthURL()
25+
a.Error(err)
26+
27+
s.AuthURL = "/foo"
28+
29+
url, _ := s.GetAuthURL()
30+
a.Equal(url, "/foo")
31+
}
32+
33+
func Test_ToJSON(t *testing.T) {
34+
t.Parallel()
35+
a := assert.New(t)
36+
s := &hubspot.Session{}
37+
38+
data := s.Marshal()
39+
a.Equal(data, `{"AuthURL":"","AccessToken":"","RefreshToken":""}`)
40+
}
41+
42+
func Test_String(t *testing.T) {
43+
t.Parallel()
44+
a := assert.New(t)
45+
s := &hubspot.Session{}
46+
47+
a.Equal(s.String(), s.Marshal())
48+
}

0 commit comments

Comments
 (0)