class Bitly::OAuth
The Oauth class handles interacting with the Bitly
API
to setup OAuth
flows to redirect the user to authorize with Bitly
and turn the resultant code into an OAuth
access token.
Attributes
client_id[R]
client_secret[R]
Public Class Methods
new(client_id:, client_secret:)
click to toggle source
Creates a new Bitly::OAuth
client to retrieve user access tokens.
To initialize a Bitly::OAuth
client you need a client_id
and client_secret
which you will get when you register your application at bitly.com/a/oauth_apps
@example
oauth = Bitly::OAuth.new(client_id: "test", client_secret: "secret")
@param [String] client_id
The client ID from
https://bitly.com/a/oauth_apps
@param [String] client_secret
The client_secret
from
https://bitly.com/a/oauth_apps
@return [Bitly::OAuth] An authenticated Bitly::OAuth
instance @since 2.0.0
# File lib/bitly/oauth.rb, line 29 def initialize(client_id:, client_secret:) @client_id = client_id @client_secret = client_secret @client = OAuth2::Client.new( client_id, client_secret, :site => 'https://api-ssl.bitly.com', :token_url => '/oauth/access_token', ) end
Public Instance Methods
access_token(redirect_uri: nil, code: nil, username: nil, password: nil)
click to toggle source
When the user is redirected to your redirect URI, Bitly
will include a code parameter. You then use the original redirect URI and the code to retrieve an access token.
@example
oauth.access_token(redirect_uri: "https://example.com/oauth/redirect", "code") # => "9646c4f76e32c18f0afad3b3ed9524f3c917775b"
# File lib/bitly/oauth.rb, line 74 def access_token(redirect_uri: nil, code: nil, username: nil, password: nil) begin if redirect_uri && code access_token_from_code(redirect_uri: redirect_uri, code: code) elsif username && password access_token_from_credentials(username: username, password: password) else raise ArgumentError, "not enough arguments, please include a redirect_uri and code or a username and password." end rescue OAuth2::Error => e raise Bitly::Error, Bitly::HTTP::Response.new(status: e.response.status.to_s, body: e.response.body, headers: e.response.headers) end end
Private Instance Methods
access_token_from_code(redirect_uri:, code:)
click to toggle source
# File lib/bitly/oauth.rb, line 90 def access_token_from_code(redirect_uri:, code:) @client.get_token( redirect_uri: redirect_uri, code: code ).token end
access_token_from_credentials(username:, password:)
click to toggle source
# File lib/bitly/oauth.rb, line 97 def access_token_from_credentials(username:, password:) @client.password.get_token(username, password, { headers: { "Authorization" => "Basic #{authorization_header}" } }).token end