oauth2 0.0.1

Sign up to get free protection for your applications and to get access to all the features.
data/.document ADDED
@@ -0,0 +1,5 @@
1
+ README.rdoc
2
+ lib/**/*.rb
3
+ bin/*
4
+ features/**/*.feature
5
+ LICENSE
data/.gitignore ADDED
@@ -0,0 +1,24 @@
1
+ .rvmrc
2
+ /live
3
+
4
+ ## MAC OS
5
+ .DS_Store
6
+
7
+ ## TEXTMATE
8
+ *.tmproj
9
+ tmtags
10
+
11
+ ## EMACS
12
+ *~
13
+ \#*
14
+ .\#*
15
+
16
+ ## VIM
17
+ *.swp
18
+
19
+ ## PROJECT::GENERAL
20
+ coverage
21
+ rdoc
22
+ pkg
23
+
24
+ ## PROJECT::SPECIFIC
data/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2009 Michael Bleigh
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.rdoc ADDED
@@ -0,0 +1,61 @@
1
+ = OAuth2
2
+
3
+ A Ruby wrapper for the OAuth 2.0 specification. This is a work in progress, being built first to solve the pragmatic process of connecting to existing OAuth 2.0 endpoints (a.k.a. Facebook) with the goal of building it up to meet the entire specification over time.
4
+
5
+ == Installation
6
+
7
+ gem install oauth2
8
+
9
+ == Web Server Example (Sinatra)
10
+
11
+ Below is a fully functional example of a Sinatra application that would authenticate to Facebook utilizing the OAuth 2.0 web server flow.
12
+
13
+ require 'rubygems'
14
+ require 'sinatra'
15
+ require 'oauth2'
16
+ require 'json'
17
+
18
+ def client
19
+ OAuth2::Client.new('5a816feeea97e6c7188a12f8e98a2c0f', 'd04fafd7d173b0e80853adab158fbd1f', :site => 'https://graph.facebook.com')
20
+ end
21
+
22
+ get '/auth/facebook' do
23
+ redirect client.web_server.authorize_url(
24
+ :redirect_uri => redirect_uri,
25
+ :scope => 'email,offline_access'
26
+ )
27
+ end
28
+
29
+ get '/auth/facebook/callback' do
30
+ begin
31
+ access_token = client.web_server.access_token(params[:code], :redirect_uri => redirect_uri)
32
+ user = JSON.parse(access_token.get('/me'))
33
+ rescue OAuth2::ErrorWithResponse => e
34
+ raise e.response.body
35
+ end
36
+
37
+ user.inspect
38
+ end
39
+
40
+ def redirect_uri
41
+ uri = URI.parse(request.url)
42
+ uri.path = '/auth/facebook/callback'
43
+ uri.query = nil
44
+ uri.to_s
45
+ end
46
+
47
+ That's all there is to it! You can use the access token like you would with the OAuth gem, calling HTTP verbs on it etc.
48
+
49
+ == Note on Patches/Pull Requests
50
+
51
+ * Fork the project.
52
+ * Make your feature addition or bug fix.
53
+ * Add tests for it. This is important so I don't break it in a
54
+ future version unintentionally.
55
+ * Commit, do not mess with rakefile, version, or history.
56
+ (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)
57
+ * Send me a pull request. Bonus points for topic branches.
58
+
59
+ == Copyright
60
+
61
+ Copyright (c) 2010 Michael Bleigh. See LICENSE for details.
data/Rakefile ADDED
@@ -0,0 +1,45 @@
1
+ require 'rubygems'
2
+ require 'rake'
3
+
4
+ begin
5
+ require 'jeweler'
6
+ Jeweler::Tasks.new do |gem|
7
+ gem.name = "oauth2"
8
+ gem.summary = %Q{A Ruby wrapper for the OAuth 2.0 protocol.}
9
+ gem.description = %Q{A Ruby wrapper for the OAuth 2.0 protocol built with a similar style to the original OAuth gem.}
10
+ gem.email = "michael@intridea.com"
11
+ gem.homepage = "http://github.com/intridea/oauth2"
12
+ gem.authors = ["Michael Bleigh"]
13
+ gem.add_development_dependency "rspec", ">= 1.2.9"
14
+ # gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings
15
+ end
16
+ Jeweler::GemcutterTasks.new
17
+ rescue LoadError
18
+ puts "Jeweler (or a dependency) not available. Install it with: gem install jeweler"
19
+ end
20
+
21
+ require 'spec/rake/spectask'
22
+ Spec::Rake::SpecTask.new(:spec) do |spec|
23
+ spec.libs << 'lib' << 'spec'
24
+ spec.spec_files = FileList['spec/**/*_spec.rb']
25
+ end
26
+
27
+ Spec::Rake::SpecTask.new(:rcov) do |spec|
28
+ spec.libs << 'lib' << 'spec'
29
+ spec.pattern = 'spec/**/*_spec.rb'
30
+ spec.rcov = true
31
+ end
32
+
33
+ task :spec => :check_dependencies
34
+
35
+ task :default => :spec
36
+
37
+ require 'rake/rdoctask'
38
+ Rake::RDocTask.new do |rdoc|
39
+ version = File.exist?('VERSION') ? File.read('VERSION') : ""
40
+
41
+ rdoc.rdoc_dir = 'rdoc'
42
+ rdoc.title = "oauth2 #{version}"
43
+ rdoc.rdoc_files.include('README*')
44
+ rdoc.rdoc_files.include('lib/**/*.rb')
45
+ end
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 0.0.1
data/lib/oauth2.rb ADDED
@@ -0,0 +1,11 @@
1
+ module OAuth2
2
+ class ErrorWithResponse < StandardError; attr_accessor :response end
3
+ class AccessDenied < ErrorWithResponse; end
4
+ class HTTPError < ErrorWithResponse; end
5
+ end
6
+
7
+ require 'oauth2/uri'
8
+ require 'oauth2/client'
9
+ require 'oauth2/strategy/base'
10
+ require 'oauth2/strategy/web_server'
11
+ require 'oauth2/access_token'
@@ -0,0 +1,28 @@
1
+ module OAuth2
2
+ class AccessToken
3
+ def initialize(client, token)
4
+ @client = client
5
+ @token = token
6
+ end
7
+
8
+ def request(verb, path, params = {}, headers = {})
9
+ @client.request(verb, path, params.merge('access_token' => @token), headers)
10
+ end
11
+
12
+ def get(path, params = {}, headers = {})
13
+ request(:get, path, params, headers)
14
+ end
15
+
16
+ def post(path, params = {}, headers = {})
17
+ request(:post, path, params, headers)
18
+ end
19
+
20
+ def put(path, params = {}, headers = {})
21
+ request(:put, path, params, headers)
22
+ end
23
+
24
+ def delete(path, params = {}, headers = {})
25
+ request(:delete, path, params, headers)
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,84 @@
1
+ require 'net/https'
2
+
3
+ module OAuth2
4
+ class Client
5
+ attr_accessor :id, :secret, :site, :options
6
+
7
+ # Instantiate a new OAuth 2.0 client using the
8
+ # client ID and client secret registered to your
9
+ # application.
10
+ #
11
+ # Options:
12
+ #
13
+ # <tt>:site</tt> :: Specify a base URL for your OAuth 2.0 client.
14
+ # <tt>:authorize_path</tt> :: Specify the path to the authorization endpoint.
15
+ # <tt>:authorize_url</tt> :: Specify a full URL of the authorization endpoint.
16
+ # <tt>:access_token_path</tt> :: Specify the path to the access token endpoint.
17
+ # <tt>:access_token_url</tt> :: Specify the full URL of the access token endpoint.
18
+ def initialize(client_id, client_secret, opts = {})
19
+ self.id = client_id
20
+ self.secret = client_secret
21
+ self.site = opts.delete(:site) if opts[:site]
22
+ self.options = opts
23
+ end
24
+
25
+ def authorize_url
26
+ return options[:authorize_url] if options[:authorize_url]
27
+
28
+ uri = URI.parse(site)
29
+ uri.path = options[:authorize_path] || "/oauth/authorize"
30
+ uri.to_s
31
+ end
32
+
33
+ def access_token_url
34
+ return options[:access_token_url] if options[:access_token_url]
35
+
36
+ uri = URI.parse(site)
37
+ uri.path = options[:access_token_path] || "/oauth/access_token"
38
+ uri.to_s
39
+ end
40
+
41
+ def request(verb, url_or_path, params = {}, headers = {})
42
+ if url_or_path[0..3] == 'http'
43
+ uri = URI.parse(url_or_path)
44
+ path = uri.path
45
+ else
46
+ uri = URI.parse(self.site)
47
+ path = (uri.path + url_or_path).gsub('//','/')
48
+ end
49
+
50
+ net = Net::HTTP.new(uri.host, uri.port)
51
+ net.use_ssl = (uri.scheme == 'https')
52
+
53
+ net.start do |http|
54
+ if verb == :get
55
+ uri.query_hash = uri.query_hash.merge(params)
56
+ path += "?#{uri.query}"
57
+ end
58
+
59
+ req = Net::HTTP.const_get(verb.to_s.capitalize).new(path, headers)
60
+
61
+ unless verb == :get
62
+ req.set_form_data(params)
63
+ end
64
+
65
+ response = http.request(req)
66
+
67
+ case response
68
+ when Net::HTTPSuccess
69
+ response.body
70
+ when Net::HTTPUnauthorized
71
+ e = OAuth2::AccessDenied.new("Received HTTP 401 when retrieving access token.")
72
+ e.response = response
73
+ raise e
74
+ else
75
+ e = OAuth2::HTTPError.new("Received HTTP #{response.code} when retrieving access token.")
76
+ e.response = response
77
+ raise e
78
+ end
79
+ end
80
+ end
81
+
82
+ def web_server; OAuth2::Strategy::WebServer.new(self) end
83
+ end
84
+ end
@@ -0,0 +1,33 @@
1
+ module OAuth2
2
+ module Strategy
3
+ class Base #:nodoc:
4
+ def initialize(client)#:nodoc:
5
+ @client = client
6
+ end
7
+
8
+ def authorize_url(options = {}) #:nodoc:
9
+ uri = URI.parse(@client.authorize_url)
10
+ uri.query_hash = authorize_params(options)
11
+ uri.to_s
12
+ end
13
+
14
+ def authorize_params(options = {}) #:nodoc:
15
+ options = options.inject({}){|h,(k,v)| h[k.to_s] = v; h}
16
+ {'client_id' => @client.id}.merge(options)
17
+ end
18
+
19
+ def access_token_url(options = {})
20
+ uri = URI.parse(@client.access_token_url)
21
+ uri.query_hash = access_token_params(options)
22
+ uri.to_s
23
+ end
24
+
25
+ def access_token_params(options = {})
26
+ {
27
+ 'client_id' => @client.id,
28
+ 'client_secret' => @client.secret
29
+ }.merge(options)
30
+ end
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,22 @@
1
+ module OAuth2
2
+ module Strategy
3
+ class WebServer < Base
4
+ def authorize_params(options = {}) #:nodoc:
5
+ super(options).merge('type' => 'web_server')
6
+ end
7
+
8
+ def access_token(code, options = {})
9
+ response = @client.request(:get, @client.access_token_url, access_token_params(code, options))
10
+ token = response.split('&').inject({}){|h,kv| (k,v) = kv.split('='); h[k] = v; h}['access_token']
11
+ OAuth2::AccessToken.new(@client, token)
12
+ end
13
+
14
+ def access_token_params(code, options = {})
15
+ super(options).merge({
16
+ 'type' => 'web_server',
17
+ 'code' => code
18
+ })
19
+ end
20
+ end
21
+ end
22
+ end
data/lib/oauth2/uri.rb ADDED
@@ -0,0 +1,14 @@
1
+ require 'uri'
2
+ require 'cgi'
3
+
4
+ module URI
5
+ class Generic
6
+ def query_hash
7
+ CGI.parse(self.query || '').inject({}){|hash, (k,v)| hash[k] = (v.size == 1 ? v.first : v); hash}
8
+ end
9
+
10
+ def query_hash=(hash)
11
+ self.query = hash.map{|(k,v)| "#{k}=#{CGI.escape(v)}"}.join('&')
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,38 @@
1
+ require 'spec_helper'
2
+
3
+ describe OAuth2::Client do
4
+ subject{ OAuth2::Client.new('abc','def', :site => 'https://api.example.com')}
5
+
6
+ describe '#initialize' do
7
+ it 'should assign id and secret' do
8
+ subject.id.should == 'abc'
9
+ subject.secret.should == 'def'
10
+ end
11
+
12
+ it 'should assign site from the options hash' do
13
+ subject.site.should == 'https://api.example.com'
14
+ end
15
+ end
16
+
17
+ %w(authorize access_token).each do |path_type|
18
+ describe "##{path_type}_url" do
19
+ it "should default to a path of /oauth/#{path_type}" do
20
+ subject.send("#{path_type}_url").should == "https://api.example.com/oauth/#{path_type}"
21
+ end
22
+
23
+ it "should be settable via the :#{path_type}_path option" do
24
+ subject.options[:"#{path_type}_path"] = '/oauth/custom'
25
+ subject.send("#{path_type}_url").should == 'https://api.example.com/oauth/custom'
26
+ end
27
+
28
+ it "should be settable via the :#{path_type}_url option" do
29
+ subject.options[:"#{path_type}_url"] = 'https://abc.com/authorize'
30
+ subject.send("#{path_type}_url").should == 'https://abc.com/authorize'
31
+ end
32
+ end
33
+ end
34
+
35
+ it '#web_server should instantiate a WebServer strategy with this client' do
36
+ subject.web_server.should be_kind_of(OAuth2::Strategy::WebServer)
37
+ end
38
+ end
@@ -0,0 +1,7 @@
1
+ require 'spec_helper'
2
+
3
+ describe OAuth2::Strategy::Base do
4
+ it 'should initialize with a Client' do
5
+ lambda{ OAuth2::Strategy::Base.new(OAuth2::Client.new('abc','def')) }.should_not raise_error
6
+ end
7
+ end
@@ -0,0 +1,20 @@
1
+ require 'spec_helper'
2
+
3
+ describe OAuth2::Strategy::WebServer do
4
+ let(:client){ OAuth2::Client.new('abc','def', :site => 'http://api.example.com') }
5
+ subject { client.web_server }
6
+ describe '#authorize_url' do
7
+ it 'should include the client_id' do
8
+ subject.authorize_url.should be_include('client_id=abc')
9
+ end
10
+
11
+ it 'should include the type' do
12
+ subject.authorize_url.should be_include('type=web_server')
13
+ end
14
+
15
+ it 'should include passed in options' do
16
+ cb = 'http://myserver.local/oauth/callback'
17
+ subject.authorize_url(:redirect_uri => cb).should be_include("redirect_uri=#{CGI.escape(cb)}")
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,29 @@
1
+ require 'spec_helper'
2
+
3
+ describe URI::Generic do
4
+ subject{ URI.parse('http://example.com')}
5
+
6
+ describe '#query_hash' do
7
+ it 'should be a hash of the query parameters' do
8
+ subject.query_hash.should == {}
9
+ subject.query = 'abc=def&foo=123'
10
+ subject.query_hash.should == {'abc' => 'def', 'foo' => '123'}
11
+ end
12
+ end
13
+
14
+ describe '#query_hash=' do
15
+ it 'should set the query' do
16
+ subject.query_hash = {'abc' => 'def'}
17
+ subject.query.should == 'abc=def'
18
+ subject.query_hash = {'abc' => 'foo', 'bar' => 'baz'}
19
+ subject.query.should be_include('abc=foo')
20
+ subject.query.should be_include('bar=baz')
21
+ subject.query.split('&').size.should == 2
22
+ end
23
+
24
+ it 'should escape stuff' do
25
+ subject.query_hash = {'abc' => '$%!!'}
26
+ subject.query.should == "abc=#{CGI.escape('$%!!')}"
27
+ end
28
+ end
29
+ end
data/spec/spec.opts ADDED
@@ -0,0 +1,2 @@
1
+ --color
2
+ --backtrace
@@ -0,0 +1,9 @@
1
+ $LOAD_PATH.unshift(File.dirname(__FILE__))
2
+ $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
3
+ require 'oauth2'
4
+ require 'spec'
5
+ require 'spec/autorun'
6
+
7
+ Spec::Runner.configure do |config|
8
+
9
+ end
data/specs.watchr ADDED
@@ -0,0 +1,61 @@
1
+ # Run me with:
2
+ #
3
+ # $ watchr specs.watchr
4
+
5
+ # --------------------------------------------------
6
+ # Convenience Methods
7
+ # --------------------------------------------------
8
+ def all_test_files
9
+ Dir['spec/**/*_spec.rb']
10
+ end
11
+
12
+ def run_test_matching(thing_to_match)
13
+ matches = all_test_files.grep(/#{thing_to_match}/i)
14
+ if matches.empty?
15
+ puts "Sorry, thanks for playing, but there were no matches for #{thing_to_match}"
16
+ else
17
+ run matches.join(' ')
18
+ end
19
+ end
20
+
21
+ def run(files_to_run)
22
+ puts("Running: #{files_to_run}")
23
+ system("clear;spec -cfs --backtrace #{files_to_run}")
24
+ no_int_for_you
25
+ end
26
+
27
+ def run_all_tests
28
+ # system("clear;rake spec")
29
+ run(all_test_files.join(' '))
30
+ end
31
+
32
+ # --------------------------------------------------
33
+ # Watchr Rules
34
+ # --------------------------------------------------
35
+ watch('^spec/(.*)_spec\.rb') { |m| run_test_matching(m[1]) }
36
+ watch('^lib/(.*)\.rb') { |m| run_test_matching(m[1]) }
37
+ watch('^sites/(.*)\.rb') { |m| run_test_matching(m[1]) }
38
+ watch('^spec/spec_helper\.rb') { run_all_tests }
39
+ watch('^spec/support/.*\.rb') { run_all_tests }
40
+
41
+ # --------------------------------------------------
42
+ # Signal Handling
43
+ # --------------------------------------------------
44
+
45
+ def no_int_for_you
46
+ @sent_an_int = nil
47
+ end
48
+
49
+ Signal.trap 'INT' do
50
+ if @sent_an_int then
51
+ puts " A second INT? Ok, I get the message. Shutting down now."
52
+ exit
53
+ else
54
+ puts " Did you just send me an INT? Ugh. I'll quit for real if you do it again."
55
+ @sent_an_int = true
56
+ Kernel.sleep 1.5
57
+ run_all_tests
58
+ end
59
+ end
60
+
61
+ # vim:ft=ruby
metadata ADDED
@@ -0,0 +1,98 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: oauth2
3
+ version: !ruby/object:Gem::Version
4
+ prerelease: false
5
+ segments:
6
+ - 0
7
+ - 0
8
+ - 1
9
+ version: 0.0.1
10
+ platform: ruby
11
+ authors:
12
+ - Michael Bleigh
13
+ autorequire:
14
+ bindir: bin
15
+ cert_chain: []
16
+
17
+ date: 2010-04-22 00:00:00 -04:00
18
+ default_executable:
19
+ dependencies:
20
+ - !ruby/object:Gem::Dependency
21
+ name: rspec
22
+ prerelease: false
23
+ requirement: &id001 !ruby/object:Gem::Requirement
24
+ requirements:
25
+ - - ">="
26
+ - !ruby/object:Gem::Version
27
+ segments:
28
+ - 1
29
+ - 2
30
+ - 9
31
+ version: 1.2.9
32
+ type: :development
33
+ version_requirements: *id001
34
+ description: A Ruby wrapper for the OAuth 2.0 protocol built with a similar style to the original OAuth gem.
35
+ email: michael@intridea.com
36
+ executables: []
37
+
38
+ extensions: []
39
+
40
+ extra_rdoc_files:
41
+ - LICENSE
42
+ - README.rdoc
43
+ files:
44
+ - .document
45
+ - .gitignore
46
+ - LICENSE
47
+ - README.rdoc
48
+ - Rakefile
49
+ - VERSION
50
+ - lib/oauth2.rb
51
+ - lib/oauth2/access_token.rb
52
+ - lib/oauth2/client.rb
53
+ - lib/oauth2/strategy/base.rb
54
+ - lib/oauth2/strategy/web_server.rb
55
+ - lib/oauth2/uri.rb
56
+ - spec/oauth2/client_spec.rb
57
+ - spec/oauth2/strategy/base_spec.rb
58
+ - spec/oauth2/strategy/web_server_spec.rb
59
+ - spec/oauth2/uri_spec.rb
60
+ - spec/spec.opts
61
+ - spec/spec_helper.rb
62
+ - specs.watchr
63
+ has_rdoc: true
64
+ homepage: http://github.com/intridea/oauth2
65
+ licenses: []
66
+
67
+ post_install_message:
68
+ rdoc_options:
69
+ - --charset=UTF-8
70
+ require_paths:
71
+ - lib
72
+ required_ruby_version: !ruby/object:Gem::Requirement
73
+ requirements:
74
+ - - ">="
75
+ - !ruby/object:Gem::Version
76
+ segments:
77
+ - 0
78
+ version: "0"
79
+ required_rubygems_version: !ruby/object:Gem::Requirement
80
+ requirements:
81
+ - - ">="
82
+ - !ruby/object:Gem::Version
83
+ segments:
84
+ - 0
85
+ version: "0"
86
+ requirements: []
87
+
88
+ rubyforge_project:
89
+ rubygems_version: 1.3.6
90
+ signing_key:
91
+ specification_version: 3
92
+ summary: A Ruby wrapper for the OAuth 2.0 protocol.
93
+ test_files:
94
+ - spec/oauth2/client_spec.rb
95
+ - spec/oauth2/strategy/base_spec.rb
96
+ - spec/oauth2/strategy/web_server_spec.rb
97
+ - spec/oauth2/uri_spec.rb
98
+ - spec/spec_helper.rb