Class: Worochi::OAuth

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

Overview

Implements OAuth2 authorization code flow for obtaining user tokens.

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



16
17
18
19
20
21
22
23
24
# File 'lib/worochi/oauth.rb', line 16

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)


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

def client
  @client
end

#optionsHashie::Mash

OAuth2 options.

Returns:

  • (Hashie::Mash)


8
9
10
# File 'lib/worochi/oauth.rb', line 8

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



42
43
44
45
46
47
# File 'lib/worochi/oauth.rb', line 42

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



30
31
32
33
34
35
36
# File 'lib/worochi/oauth.rb', line 30

def flow_start(state=nil)
  client.site = options.site
  opts = { scope: scope }
  opts[:state] = state if state
  opts[:redirect_uri] = options.redirect_uri if options.redirect_uri
  client.auth_code.authorize_url(opts)
end

#refresh!(hash) ⇒ Hashie::Mash

Refreshes the access token using the refresh token.

Parameters:

  • hash (Hash)

    stored hash for the token

Returns:

  • (Hashie::Mash)

    Updated OAuth2 token



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

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