~tim/mailchimp3

mailchimp3/lib/mailchimp3/oauth.rb -rw-r--r-- 929 bytes
836bcd45Tim Morgan Release 1.3.1 3 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
require 'oauth2'
require 'json'

module MailChimp3
  class OAuth
    def initialize
      @oauth = OAuth2::Client.new(
        MailChimp3.config.client_id,
        MailChimp3.config.client_secret,
        site: 'https://login.mailchimp.com',
        authorize_url: '/oauth2/authorize',
        token_url: '/oauth2/token'
      )
    end

    def authorize_url(redirect_uri:)
      @oauth.auth_code.authorize_url(redirect_uri: redirect_uri)
    end

    def complete_auth(code, redirect_uri:)
      token = @oauth.auth_code.get_token(
        code,
        redirect_uri: redirect_uri
      )
      {
        token: token,
        token_string: token.token,
        metadata: metadata(token)
      }
    end

    private

    def metadata(token)
      JSON.parse(token.get('/oauth2/metadata').body).tap do |hash|
        hash.keys.each do |key|
          hash[key.to_sym] = hash.delete(key)
        end
      end
    end
  end
end