open_auth2 0.0.8

Sign up to get free protection for your applications and to get access to all the features.
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source "http://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in villan.gemspec
4
+ gemspec
data/License ADDED
@@ -0,0 +1,9 @@
1
+ (The MIT License)
2
+
3
+ Copyright (c) 2012, Senthil A. <senthil196@gmail.com>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/Rakefile ADDED
@@ -0,0 +1,126 @@
1
+ # Author:
2
+ # Tom Preston-Werner part of his https://github.com/mojombo/rakegem
3
+ #
4
+ # Modified:
5
+ # Senthil A
6
+
7
+ require 'date'
8
+
9
+ # Helper functions
10
+
11
+ def name
12
+ @name ||= Dir['*.gemspec'].first.split('.').first
13
+ end
14
+
15
+ def version
16
+ line = File.read("lib/#{name}/version.rb")[/^\s*VERSION\s*=\s*.*/]
17
+ line.match(/.*VERSION\s*=\s*['"](.*)['"]/)[1]
18
+ end
19
+
20
+ def date
21
+ Date.today.to_s
22
+ end
23
+
24
+ def rubyforge_project
25
+ name
26
+ end
27
+
28
+ def gemspec_file
29
+ "#{name}.gemspec"
30
+ end
31
+
32
+ def gem_file
33
+ "open_auth2-#{version}.gem"
34
+ end
35
+
36
+ def replace_header(head, header_name)
37
+ head.sub!(/(\.#{header_name}\s*= ').*'/) { "#{$1}#{send(header_name)}'"}
38
+ end
39
+
40
+ # Standard tasks
41
+
42
+ task :default => :spec
43
+ require "rspec/core/rake_task"
44
+ RSpec::Core::RakeTask.new(:spec) do |spec|
45
+ spec.pattern = 'spec/**/*_spec.rb'
46
+ spec.rspec_opts = ['--backtrace']
47
+ end
48
+
49
+ desc "Generate SimpleCov test coverage and open in your browser"
50
+ task :coverage do
51
+ sh "rake spec COVERAGE=true"
52
+ sh "open coverage/index.html"
53
+ end
54
+
55
+ desc "Open an irb session preloaded with this library"
56
+ task :irb do
57
+ sh "irb -rubygems -r ./lib/#{name}.rb"
58
+ end
59
+
60
+ desc "Open a pry session preloaded with this library"
61
+ task :pry do
62
+ sh "pry -r ./lib/#{name}.rb"
63
+ end
64
+
65
+ # Custom tasks (add your own tasks here)
66
+
67
+ desc "Open a pry session with examples/fb loaded"
68
+ task :fb do
69
+ sh "pry -r ./examples/fb.rb"
70
+ end
71
+
72
+ desc "Open a pry session with examples/google loaded"
73
+ task :google do
74
+ sh "pry -r ./examples/google.rb"
75
+ end
76
+
77
+ # Packaging tasks
78
+
79
+ desc "Create tag v#{version} and build and push #{gem_file} to Rubygems"
80
+ task :release => :build do
81
+ unless `git branch` =~ /^\* master$/
82
+ puts "You must be on the master branch to release!"
83
+ exit!
84
+ end
85
+ sh "git commit --allow-empty -a -m 'Release #{version}'"
86
+ sh "git tag v#{version}"
87
+ sh "git push origin master"
88
+ sh "git push origin v#{version}"
89
+ sh "gem push pkg/open-auth2-#{version}.gem"
90
+ end
91
+
92
+ desc "Build #{gem_file} into the pkg directory"
93
+ task :build => :gemspec do
94
+ sh "mkdir -p pkg"
95
+ sh "gem build #{gemspec_file}"
96
+ #sh "mv #{gem_file} pkg"
97
+ end
98
+
99
+ desc "Generate #{gemspec_file}"
100
+ task :gemspec do
101
+ # read spec file and split out manifest section
102
+ spec = File.read(gemspec_file)
103
+ head, manifest, tail = spec.split(" # = MANIFEST =\n")
104
+
105
+ # replace name version and date
106
+ replace_header(head, :name)
107
+ replace_header(head, :version)
108
+ replace_header(head, :date)
109
+ #comment this out if your rubyforge_project has a different name
110
+ replace_header(head, :rubyforge_project)
111
+
112
+ # determine file list from git ls-files
113
+ files = `git ls-files`.
114
+ split("\n").
115
+ sort.
116
+ reject { |file| file =~ /^\./ }.
117
+ reject { |file| file =~ /^(rdoc|pkg)/ }.
118
+ map { |file| " #{file}" }.
119
+ join("\n")
120
+
121
+ # piece file back together and write
122
+ manifest = " s.files = %w[\n#{files}\n ]\n"
123
+ spec = [head, manifest, tail].join(" # = MANIFEST =\n")
124
+ File.open(gemspec_file, 'w') { |io| io.write(spec) }
125
+ puts "Updated #{gemspec_file}"
126
+ end
data/Readme.markdown ADDED
@@ -0,0 +1,235 @@
1
+ # OpenAuth2 [![Build Status](https://secure.travis-ci.org/sent-hil/OpenAuth2.png?branch=master)][travis]
2
+
3
+ [travis]: http://travis-ci.org/sent-hil/OpenAuth2
4
+
5
+ OpenAuth2 is a thin OAuth2 wrapper written on top of Faraday in Ruby. The goal is a simple, well documented, easy to use interface for all your OAuth2 needs.
6
+
7
+ * This software is alpha, you're either very brave or very foolish to use this in production of rockets or anything else.
8
+
9
+ ## Config
10
+
11
+ To begin, let's setup the configuration. Here we're assuming connection to Facebook api. OpenAuth2 supports Google and Facebook out of the box (more to come soon). Other sites can be configured manually.
12
+
13
+ ```ruby
14
+ require 'open_auth2'
15
+
16
+ # get this info by signing your app at developers.facebook.com
17
+ client_id = 'enter in your own value'
18
+ client_secret = 'enter in your own value'
19
+ redirect_uri = 'enter in your own value'
20
+
21
+ config = OpenAuth2::Config.new do |c|
22
+ # indicate what kind of provider you want to use
23
+ # Accepts: :google, :facebook or :default
24
+
25
+ c.provider = :facebook
26
+
27
+ c.client_id = client_id
28
+ c.client_secret = client_secret
29
+ c.redirect_uri = redirect_uri
30
+ c.scope = ['publish_stream']
31
+ end
32
+ ```
33
+
34
+ ## Client
35
+
36
+ Next, initialize a `client` object, which we'll use to make requests and pass in the `config` object we created earlier.
37
+
38
+ ```ruby
39
+ client = OpenAuth2::Client.new do |c|
40
+ c.config = config
41
+ end
42
+ ```
43
+
44
+ `Client#connection` returns a `Faraday::Connection` object, which can be used to setup middleware.
45
+
46
+ ```ruby
47
+ client.connection do
48
+ response :logger
49
+ end
50
+ ```
51
+
52
+ ## Authenticate Url
53
+
54
+ To start the OAuth2 exotic dance, you'll need to obtain a 'code' from the server, which you can then use to request an 'access_token'. Redirect the user/yourself to this url to obtain that 'code'.
55
+
56
+ ```ruby
57
+ client.build_code_url
58
+ ```
59
+
60
+ `build_code_url` takes optional params hash, which will be bundled into the url.
61
+
62
+ ```ruby
63
+ client.build_code_url(:scope => 'publish_stream')
64
+ ```
65
+
66
+ ## Access token
67
+
68
+ Access token is used to sign the request so the server can identify the client sending the request. If you already have an access token, add it to the client with a block.
69
+
70
+ ```ruby
71
+ access_token = 'enter in your value'
72
+ refresh_token = 'enter in your value'
73
+
74
+ client.configure do |c|
75
+ c.access_token = access_token
76
+
77
+ # optional, for fb its same as above
78
+ c.refresh_token = refresh_token
79
+ end
80
+ ```
81
+
82
+ ## GET Access Token
83
+
84
+ If you don't have an access token, we'll need to ask the server for it.
85
+
86
+ `token#configure` is similar to `client#connection`.
87
+
88
+ ```ruby
89
+ token = client.token
90
+ token.configure do
91
+ response :logger
92
+ end
93
+
94
+ # asks Facebook for access_token
95
+ token.get
96
+
97
+ # the following methods are now available
98
+ client.access_token
99
+ client.refresh_token
100
+ client.token_expires_at
101
+ client.token_expired?
102
+ client.token_arrived_at
103
+ ```
104
+
105
+ ## GET Refresh Token
106
+
107
+ ```ruby
108
+ # tells Facebook api to extend the expiration of the access_token
109
+ token.refresh
110
+ ```
111
+
112
+ ## GET request
113
+
114
+ To make an api call, simply call `get` with a hash containing `path`.
115
+
116
+ ```ruby
117
+ client.get(:path => '/cocacola')
118
+ ```
119
+
120
+ `get` accepts a Hash as second argument, which can be used to pass in additional parameters.
121
+
122
+ ```ruby
123
+ client.get(:path => '/cocacola', :limit => 1)
124
+ ```
125
+
126
+ ## Faraday convenience methods
127
+
128
+ `Client#get` is a convenience method that calls `Faraday#get`. You can drop down to Faraday connection object itself and make requests via that also.
129
+
130
+ ```ruby
131
+ client.connection.get do |conn|
132
+ conn.url('/cocacola')
133
+ end
134
+ ```
135
+
136
+ `Client#run_request` points to `Faraday#run_request`. It takes hash since I can never remember the order in which to pass the arguments.
137
+
138
+ ```ruby
139
+ path = "https://graph.facebook.com/cocacola"
140
+ client.run_request(verb: :get, path: path, body: nil, header: nil)
141
+
142
+ # same as
143
+ client.connection.run_request(:get, path, nil, nil)
144
+ ```
145
+
146
+ ## Plugins
147
+
148
+ Since various OAuth2 providers differ in their implementation, OpenAuth2 provides a simple plugin system to accomodate the differences, rather than 'one shoe fits all' approach. Facebook and Google plugins are builtin, but it is trivial to add new ones.
149
+
150
+ There are only three requirements:
151
+
152
+ 1. Should be under right namespace (OpenAuth2::Provider)
153
+ 1. Should contain #options method
154
+ 1. Should contain #parse method
155
+
156
+ To use the plugin, call `Config#provider=` with name of the provider. OpenAuth2 upcases and camelizes the name and looks for the constant under OpenAuth2::Provider namespace.
157
+
158
+ ### Plugin Example
159
+
160
+ ```ruby
161
+ module OpenAuth2
162
+ module Provider
163
+ class Default
164
+
165
+ # Provider::Base contains keys of various accepted Options,
166
+ # while Provider::Default contains the default options and
167
+ # their values. You can however override them here.
168
+ #
169
+ def options
170
+ {
171
+ :response_type => 'code',
172
+ :access_token_grant_name => 'authorization_code',
173
+ :refresh_token_grant_name => 'refresh_token',
174
+ :refresh_token_name => :refresh_token,
175
+ :scope => [],
176
+ }
177
+ end
178
+
179
+ # Called after AccessToken#get and #refresh response are received
180
+ # from provider.
181
+ #
182
+ def parse(config, response_body)
183
+ # parse the response body
184
+ access_token = response_body.gsub('access_token=', '')
185
+
186
+ # update config to reflect new information
187
+ config.access_token = access_token
188
+ config.token_arrived_at = Time.now
189
+ end
190
+ end
191
+ end
192
+ end
193
+ ```
194
+
195
+ ## Examples
196
+
197
+ See examples/ for more ... (its a surprise).
198
+
199
+ ## Requirements
200
+
201
+ * ActiveSupport
202
+ * Faraday
203
+ * URI
204
+ * Json
205
+
206
+ ## Supported Versions
207
+
208
+ * MRI 1.9.2
209
+ * MRI 1.9.3
210
+ * jRuby (jruby --1.9 rspec)
211
+ * Rubinius 2.0.0dev (RBXOPT=-X19 rbx- S rspec)
212
+
213
+ ## Install
214
+
215
+ $ gem install open_auth2
216
+
217
+ ## Source
218
+
219
+ OpenAuth2's git repo is available on GitHub:
220
+
221
+ https://github.com/senthilnambi/OpenAuth2
222
+
223
+ ## Development
224
+
225
+ You will need these gems to get tests to pass:
226
+
227
+ * rspec2
228
+ * rake
229
+ * SimpleCov (optional for coverage)
230
+
231
+ See [meta](https://github.com/senthilnambi/meta) for more info on contributing and technology used to create this gem.
232
+
233
+ ## Copyright
234
+
235
+ Copyright (c) 2012 Senthil A. See License for details.
data/Spec.markdown ADDED
File without changes
data/examples/fb.rb ADDED
@@ -0,0 +1,20 @@
1
+ require_relative '../lib/open_auth2'
2
+
3
+ ClientId = '216091171753850'
4
+ ClientSecret = '56f751bef00d6d21e858566b873ac8f8'
5
+ Code = ''
6
+ AccessToken = ''
7
+
8
+ @config = OpenAuth2::Config.new do |c|
9
+ c.provider = :facebook
10
+ c.client_id = ClientId
11
+ c.client_secret = ClientSecret
12
+ c.code = Code
13
+ c.access_token = AccessToken
14
+ c.redirect_uri = 'http://localhost:9393/'
15
+ c.scope = ['manage_pages', 'read_insights']
16
+ end
17
+
18
+ @client = OpenAuth2::Client.new(@config)
19
+ @url = @client.build_code_url
20
+ @token = @client.token
@@ -0,0 +1,57 @@
1
+ require_relative '../lib/open_auth2'
2
+ require 'json'
3
+
4
+ ClientId = '948773240950.apps.googleusercontent.com'
5
+ ClientSecret = 'MTkeuqOhFTbfRbd27BcEROTl'
6
+ Code = nil
7
+ AccessToken = 'ya29.AHES6ZRL6dKYn5HvssNQvH15KXTc76jCd9KC6Wfsir74whQ'
8
+ RefreshToken = '1/2hTXHN9FULj7v_hVOIoyHn6BpOQS6uDOw-xllInXnTU'
9
+ PostEmail = 'senthil196@gmail.com'
10
+
11
+ @config = OpenAuth2::Config.new do |c|
12
+ c.provider = :google
13
+ c.code = Code
14
+ c.client_id = ClientId
15
+ c.client_secret = ClientSecret
16
+ c.access_token = AccessToken
17
+ c.refresh_token = RefreshToken
18
+ c.scope = ['https://www.googleapis.com/auth/calendar']
19
+ c.redirect_uri = 'http://localhost:9393/google/callback'
20
+ c.path_prefix = '/calendar/v3'
21
+ end
22
+
23
+ @client = OpenAuth2::Client.new do |c|
24
+ c.config = @config
25
+ end
26
+
27
+ #@token = @client.token
28
+
29
+ #params = {:approval_prompt => 'force', :access_type => 'offline'}
30
+ #@url = @token.build_code_url(params)
31
+
32
+ # get request
33
+ @list = @client.get(:path => '/users/me/calendarList')
34
+
35
+ @post_url = "/calendar/v3/calendars/#{PostEmail}/events"
36
+ @body = {
37
+ "summary" => "From OpenAuth2",
38
+ "start" => {"dateTime"=>"2012-10-03T10:00:00.000-07:00"},
39
+ "end" => {"dateTime"=>"2012-10-03T10:25:00.000-07:00"}
40
+ }
41
+ @body = JSON.dump(@body)
42
+
43
+ # post request
44
+ def make_request
45
+ @response = @client.post(:path => @post_url,
46
+ :body => @body,
47
+ :content_type => "application/json")
48
+ end
49
+
50
+ #header = {"Content-Type" => "application/json"}
51
+ #full_url = "#{post_url}?access_token=#{AccessToken}"
52
+
53
+ # post request via #run_request
54
+ #@client.run_request(:verb => :post,
55
+ #:path => full_url,
56
+ #:body => body,
57
+ #:header => header)
@@ -0,0 +1,184 @@
1
+ module OpenAuth2
2
+
3
+ # Makes GET/POST requests to OAuth server.
4
+ class Client
5
+ extend DelegateToConfig
6
+
7
+ attr_accessor :faraday_url
8
+
9
+ # Use to set config.
10
+ #
11
+ # Accepts:
12
+ # config - (optional) OpenAuth2::Config object.
13
+ #
14
+ # Examples:
15
+ # config = OpenAuth2::Config.new do |c|
16
+ # c.provider = :facebook
17
+ # end
18
+ #
19
+ # # set via block
20
+ # OpenAuth2::Client.new do |c|
21
+ # c.config = config
22
+ # end
23
+ #
24
+ # # or pass it as an argument
25
+ # OpenAuth2::Client.new(config)
26
+ #
27
+ def initialize(config=nil)
28
+ @config = config
29
+ yield self if block_given?
30
+ @faraday_url = endpoint
31
+ end
32
+
33
+ # Use to set/change config after #initialize.
34
+ #
35
+ # Examples:
36
+ # client = OpenAuth2::Client.new
37
+ #
38
+ # client.configure do |c|
39
+ # c.access_token = :access_token
40
+ # c.refresh_token = :refresh_token
41
+ # end
42
+ #
43
+ # Returns: self.
44
+ #
45
+ def configure
46
+ yield self if block_given?
47
+ end
48
+
49
+ # Use this to get & refresh access/refresh tokens.
50
+ #
51
+ # Returns: Token object.
52
+ #
53
+ def token
54
+ @token ||= Token.new(config)
55
+ end
56
+
57
+ # Examples:
58
+ # client.build_code_url
59
+ # #=> 'http://...'
60
+ #
61
+ # # or
62
+ # client.build_code_url(:scope => 'publish_stream')
63
+ #
64
+ # Accepts:
65
+ # params - (optional) Hash of additional config to be bundled into
66
+ # the url.
67
+ #
68
+ # Returns: String (url).
69
+ #
70
+ def build_code_url(params={})
71
+ token.build_code_url(params)
72
+ end
73
+
74
+ # Makes GET request to OAuth server. If access_token is available
75
+ # we pass that along to identify ourselves.
76
+ #
77
+ # Accepts:
78
+ # hash
79
+ # :path - (required)
80
+ #
81
+ # Examples:
82
+ # client.get(:path => '/cocacola')
83
+ # client.get(:path => '/cocacola', :limit => 1)
84
+ #
85
+ # Returns: Faraday response object.
86
+ #
87
+ def get(hash)
88
+ connection.get do |conn|
89
+ path = hash.delete(:path)
90
+
91
+ if path_prefix
92
+ path = "#{path_prefix}#{path}"
93
+ end
94
+
95
+ hash.merge!(:access_token => access_token) if access_token
96
+
97
+ conn.url(path, hash)
98
+ end
99
+ end
100
+
101
+ # Makes POST request to OAuth server.
102
+ #
103
+ # Accepts:
104
+ # hash
105
+ # :path - (required)
106
+ # :content_type - (optional)
107
+ # :body - (optional)
108
+ #
109
+ # Examples:
110
+ # # using query params (fb uses this)
111
+ # client.post(:path => "/me/feed?message='From OpenAuth2'")
112
+ #
113
+ # # using body (google uses this)
114
+ # body = JSON.dump(:message => "From OpenAuth2)
115
+ # client.post(:path => "/me/feed,
116
+ # :body => body,
117
+ # :content_type => 'application/json')
118
+ #
119
+ # Returns: Faraday response object.
120
+ #
121
+ def post(hash)
122
+ connection.post do |conn|
123
+ if hash[:content_type]
124
+ conn.headers["Content-Type"] = hash[:content_type]
125
+ end
126
+
127
+ conn.url(hash[:path], :access_token => access_token)
128
+ conn.body = hash[:body]
129
+ end
130
+ end
131
+
132
+ # Makes request to OAuth server via Faraday#run_request. It takes
133
+ # Hash since I can never remember the order in which to pass the
134
+ # arguments.
135
+ #
136
+ # Accepts:
137
+ # hash
138
+ # :verb - (required) GET/POST etc.
139
+ # :path - (required)
140
+ # :body - (optional)
141
+ # :header - (optional)
142
+ #
143
+ # Examples:
144
+ # # public GET request
145
+ # path = "https://graph.facebook.com/cocacola"
146
+ # client.run_request(verb: :get, path: path, body: nil,
147
+ # header: nil)
148
+ #
149
+ # # private GET request
150
+ # path = "/me/likes?access_token=..."
151
+ # client.run_request(verb: :get, path: path, body: nil,
152
+ # header: nil)
153
+ #
154
+ # Returns: Faraday response object.
155
+ #
156
+ def run_request(hash)
157
+ connection.run_request(hash[:verb], hash[:path], hash[:body],
158
+ hash[:header])
159
+ end
160
+
161
+ # Yields: Faraday object, so user can choose choose their own
162
+ # middleware.
163
+ #
164
+ # Examples:
165
+ # config = OpenAuth2::Config.new
166
+ # client = OpenAuth2::Client.new(config)
167
+ #
168
+ # client.connection do
169
+ # response :logger
170
+ # end
171
+ #
172
+ # Returns: Faraday object.
173
+ #
174
+ def connection(&blk)
175
+ @connection ||= Faraday.new(:url => @faraday_url) do |builder|
176
+ builder.request :url_encoded
177
+ builder.adapter :net_http
178
+ builder.instance_eval(&blk) if block_given?
179
+ end
180
+
181
+ @connection
182
+ end
183
+ end
184
+ end