|
| 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 | +} |
0 commit comments