Skip to content

Instantly share code, notes, and snippets.

@ontarionick
Created February 18, 2015 19:42
Show Gist options
  • Save ontarionick/22608a703f358a984c9d to your computer and use it in GitHub Desktop.
Save ontarionick/22608a703f358a984c9d to your computer and use it in GitHub Desktop.
Hubspot auth handler for use in private or public API
require 'httparty'
class HubspotAuthHandler
HUBSPOT_LOGIN_URL = "https://login.hubspot.com/login/newLoginSubmit?loginPortalId=-1&loginRedirectUrl=&includeAuthToken=false"
HUBSPOT_HANDSHAKE_URL = "https://login.hubspot.com/login/api-verify"
def initialize(username, password)
@username = username
@password = password
set_auth_token_and_expires_at
end
def auth_token
set_auth_token_and_expires_at if DateTime.now > @expires_at
@auth_token
end
def expires_at
set_auth_token_and_expires_at if DateTime.now > @expires_at
@expires_at
end
private
def set_auth_token_and_expires_at
login_response = HTTParty.post(HUBSPOT_LOGIN_URL, login_form_data)
@portal_id = login_response.request.uri.path.split("/").last
@cookie = login_response.request.options[:headers]["Cookie"]
handshake_response = HTTParty.post(HUBSPOT_HANDSHAKE_URL, handshake_form_data)
access_token = handshake_response["auth"]["access_token"]
@auth_token = access_token["token"]
@expires_at = Time.at(access_token["expires_at"] / 1000.0).to_datetime
end
def login_form_data
{
query: {
username: @username,
password: @password,
},
}
end
def handshake_form_data
{
query: {
portalId: @portal_id,
},
headers: {
'Cookie' => @cookie,
},
}
end
end
@auth = HubspotAuthHandler.new("foo.bar@foobar.com", "password")
puts @auth.auth_token
puts @auth.expires_at
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment