Class: Worochi::OAuth

Inherits:
Object
  • Object
show all
Defined in:
lib/worochi/oauth.rb

Overview

Implements OAuth2 authorization code flow for obtaining user tokens.

Constant Summary collapse

INTERNAL_OPTS =

List of options that should not be sent with HTTP requests.

[:id_env, :secret_env, :token_url, :authorize_url, :site,
:token_site, :service]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(service, redirect_uri = nil) ⇒ OAuth

Returns a new instance of OAuth.

Parameters:

  • service (Symbol)

    service name

  • redirect_uri (String) (defaults to: nil)

    callback URL if required


20
21
22
23
24
25
26
27
28
# File 'lib/worochi/oauth.rb', line 20

def initialize(service, redirect_uri=nil)
  @options = Worochi::Config.service_opts(service).oauth
  options.service = service
  options.redirect_uri = redirect_uri
  opts = { site: options.site }
  opts[:authorize_url] = options.authorize_url if options.authorize_url
  opts[:token_url] = options.token_url if options.token_url
  @client = OAuth2::Client.new(id, secret, opts)
end

Instance Attribute Details

#clientOAuth2::Client (readonly)

The OAuth2 client

Returns:

  • (OAuth2::Client)

16
17
18
# File 'lib/worochi/oauth.rb', line 16

def client
  @client
end

#optionsHashie::Mash

OAuth2 options.

Returns:

  • (Hashie::Mash)

12
13
14
# File 'lib/worochi/oauth.rb', line 12

def options
  @options
end

Instance Method Details

#flow_end(code) ⇒ Hashie::Mash Also known as: get_token

Retrieves the token using the temporary authorization code.

Parameters:

  • code (String)

    authorization code from the first part

Returns:

  • (Hashie::Mash)

    OAuth2 token


45
46
47
48
49
50
# File 'lib/worochi/oauth.rb', line 45

def flow_end(code)
  client.site = options.token_site || options.site
  opts = {}
  opts[:redirect_uri] = options.redirect_uri if options.redirect_uri
  Hashie::Mash.new(client.auth_code.get_token(code, opts).to_hash)
end

#flow_start(state = nil) ⇒ String

Returns the URL to start the authorization flow.

Parameters:

  • state (String) (defaults to: nil)

    optional security verification state

Returns:

  • (String)

    URL to begin flow


34
35
36
37
38
39
# File 'lib/worochi/oauth.rb', line 34

def flow_start(state=nil)
  client.site = options.site
  opts = params
  opts[:state] = state if state
  client.auth_code.authorize_url(opts)
end

#refresh(hash) ⇒ Hashie::Mash

Refreshes an existing access token using the refresh token.

Parameters:

  • hash (Hash)

    stored hash for the token

Returns:

  • (Hashie::Mash)

    Updated OAuth2 token


56
57
58
59
60
61
62
63
# File 'lib/worochi/oauth.rb', line 56

def refresh(hash)
  token = OAuth2::AccessToken.from_hash(@client, hash)
  begin
    Hashie::Mash.new(token.refresh!.to_hash)
  rescue OAuth2::Error
    raise Worochi::Error, 'Invalid refresh token'
  end
end