Skip to content

Instantly share code, notes, and snippets.

@taf2
Created April 28, 2020 14:17
Show Gist options
  • Save taf2/9793d47570a029bd0fe6ff287f12c0f6 to your computer and use it in GitHub Desktop.
Save taf2/9793d47570a029bd0fe6ff287f12c0f6 to your computer and use it in GitHub Desktop.
Example oauth2 client for CallTrackingMetrics.com
#
# Example OAuth2 Application for CallTrackingMetrics.com
# Users are redirected to your application and prompted to allow access to their CallTrackingMetrics account with the given permissions
# After accepting they are redirected back to your applicaiton's /authorize URL via GET request.
# In this request you will receive a 'code' that you must send via a POST request back to CTM to get an access token and refresh token.
# Later when the access token expires you can renew it via the refresh request.
#
require 'sinatra'
require 'curb'
require 'uri'
require 'json'
ID='id-token-insert'
SK='sec-key-insert'
TOKEN_URL='https://api.calltrackingmetrics.com/oauth2/token'
class App < Sinatra::Base
get '/' do
%(
<a href="https://api.calltrackingmetrics.com/oauth2/authorize?client_id=#{ID}&redirect_uri=https://your-domain.example.com/authorize&response_type=code&scope=profile">Access CallTrackingMetrics</a>
)
end
post '/refresh' do
request.body.rewind
request_payload = JSON.parse request.body.read
if request_payload['refresh_token'].nil?
return [400, "error"]
end
res = Curl.post(TOKEN_URL, {
grant_type: 'refresh_token',
client_id: ID,
client_secret: SK,
refresh_token: request_payload['refresh_token']
})
tokens = JSON.parse(res.body)
tokens.to_json
end
get '/authorize' do
code = params['code']
# ?client_id={your-client-id}&redirect_uri={your-redirect-url.com}&code={the-code-we-gave-you}
res = Curl.post(TOKEN_URL, {
grant_type: 'authorization_code',
client_id: ID,
client_secret: SK,
redirect_uri: 'https://your-domain.example.com/authorize',
code: code
})
tokens = JSON.parse(res.body)
%(
<html>
<body>
<script>
window.opener.postMessage(#{tokens.to_json})
window.close();
</script>
</body>
</html>
)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment