module Googol::Authenticable

Provides methods to authenticate as an account (either Google or Youtube).

Public Class Methods

new(attrs = {}) click to toggle source

Initialize an object with either an authorization code or a refresh token

@see developers.google.com/accounts/docs/OAuth2

@param [Hash] attrs Authentication credentials to access the account @option attrs [String] :code The OAuth2 authorization code @option attrs [String] :redirect_url The page to redirect after the OAuth2 page @option attrs [String] :access_token The authorization token for immediate access @option attrs [String] :refresh_token The refresh token for offline access

@note The refresh token never expires but the access token expires after 1 hour.

If the access token has expired, initialize the object again with the
refresh token.
# File lib/googol/authenticable.rb, line 25
def initialize(attrs = {})
  @code = attrs[:code]
  @refresh_token = attrs[:refresh_token]
  @credentials = {access_token: attrs[:access_token]} if attrs[:access_token]
  @redirect_url = attrs.fetch :redirect_url, 'http://example.com/'
end

Private Class Methods

included(base) click to toggle source
# File lib/googol/authenticable.rb, line 64
def self.included(base)
  base.extend ClassMethods
end

Public Instance Methods

credentials() click to toggle source

Return the authorization credentials of an account for this app.

@see …

@return [Hash]

* :client_id [String] ...
* :client_secret [String] ...
* ...
# File lib/googol/authenticable.rb, line 40
def credentials
  @credentials ||= request! method: :post,
    host: 'https://accounts.google.com', path: '/o/oauth2/token',
    body: credentials_params
end

Private Instance Methods

credentials_params() click to toggle source

Provides the credentials to access Google API as an authorized user.

There are ways to do this:

  • For first-time users (who do not have a refresh token but only an authorization code): the code is submitted to Google to obtain an access token (to use immediately) and a refresh_token

  • For existing users (who have a refresh token): the refresh token is submitted to Google to obtain a new access token

# File lib/googol/authenticable.rb, line 56
def credentials_params
  if @refresh_token
    {grant_type: :refresh_token, refresh_token: @refresh_token}
  else
    {grant_type: :authorization_code, code: @code, redirect_uri: @redirect_url}
  end.merge client_id: client_id, client_secret: client_secret
end