reso_web_api 0.2.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 4476a6c7c91ca11a6ee826b17173fb7f05875f9a
4
+ data.tar.gz: b926a43a312ee862f0139729cac0893bfbba53ac
5
+ SHA512:
6
+ metadata.gz: f97635ef226ae6e694a5dacf135fac8c43b78b87af4b3c05659b07c2380e991a3866fe9b90b30c72ab9782f584da007052e8070751a5cc9f84aa26fd27e821a2
7
+ data.tar.gz: 944f6747aebf0ec3862548c919f79bf15b826a714d71451e12402bd1ed9205a783ca7c2ba07f7b5660f60c393623e3ca99362990108a6b5f39127c4c1e75344e
@@ -0,0 +1,15 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /log/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+
11
+ # rspec failure tracking
12
+ .rspec_status
13
+
14
+ # Gemfile.lock should /not/ be checked in for gems
15
+ Gemfile.lock
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
@@ -0,0 +1 @@
1
+ reso_web_api
@@ -0,0 +1 @@
1
+ 2.2
@@ -0,0 +1,11 @@
1
+ # CHANGELOG
2
+
3
+ ## 0.2.0
4
+
5
+ * Refactored code and simplified design
6
+ * Middleware-based authentication mechanism
7
+ * Added comprehensive tests
8
+
9
+ ## 0.1.0
10
+
11
+ * Initial release
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ source "https://rubygems.org"
2
+
3
+ git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
4
+
5
+ # Specify your gem's dependencies in reso_web_api.gemspec
6
+ gemspec
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2018 W+R Studios
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,88 @@
1
+ # ResoWebApi
2
+
3
+ A Ruby library to connects to MLS servers conforming to the [RESO Web API][reso-web-api] standard.
4
+
5
+ [reso-web-api]: https://www.reso.org/reso-web-api/
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'reso_web_api'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install reso_web_api
22
+
23
+ ## Usage
24
+
25
+ ### Authentication
26
+
27
+ Instantiating an API client requires two things: an endpoint (i.e. service URL) and an authentication strategy.
28
+ You may either instantiate the auth strategy directly and pass it to the client constructor (in the `:auth` parameter), or you may choose to pass a nested hash with options for configuring the strategy instead, as below:
29
+
30
+ ```ruby
31
+ require 'reso_web_api'
32
+
33
+ client = ResoWebApi::Client.new(
34
+ endpoint: 'https://api.my-mls.org/RESO/OData/',
35
+ auth: {
36
+ strategy: ResoWebApi::Authentication::TokenAuth,
37
+ endpoint: 'https://oauth.my-mls.org/connect/token',
38
+ client_id: 'deadbeef',
39
+ client_secret: 'T0pS3cr3t',
40
+ scope: 'odata'
41
+ }
42
+ end
43
+ ```
44
+
45
+ Note that if you choose this option, you _may_ specify the strategy implementation by passing its _class_ as the `:strategy` option.
46
+ If you omit the `:strategy` parameter, it will default to `ResoWebApi::Authentication::TokenAuth`.
47
+
48
+ ### Accessing Data
49
+
50
+ #### Standard Resources
51
+
52
+ Since most RESO Web API servers will likely adhere to the RESO Data Dictionary, we've created some shortcuts for the standard resources
53
+
54
+ ```ruby
55
+ # Iterate over all properties -- WARNING! Might take a long time
56
+ client.properties.each do |property|
57
+ puts "#{property['ListPrice']} #{property['StandardStatus']}"
58
+ end
59
+ ```
60
+
61
+ The following methods are provided:
62
+
63
+ - Property: use `#properties`
64
+ - Member: use `#members`
65
+ - Office: use `#office`
66
+ - Media: use `#media`
67
+
68
+ #### Other Resources
69
+
70
+ Other resources may be access using the `#resources` method on the client, which may be accessed as a hash like this:
71
+
72
+ ```ruby
73
+ client.resources['OpenHouse'].first # Access the 'OpenHouse' collectionh
74
+ ```
75
+
76
+ ## Development
77
+
78
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
79
+
80
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
81
+
82
+ ## Contributing
83
+
84
+ Bug reports and pull requests are welcome on GitHub at https://github.com/wrstudios/reso_web_api.
85
+
86
+ ## License
87
+
88
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "reso_web_api"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,30 @@
1
+ require 'json'
2
+ require 'logger'
3
+ require 'odata4'
4
+
5
+ require 'reso_web_api/version'
6
+ require 'reso_web_api/errors'
7
+ require 'reso_web_api/client'
8
+
9
+ module ResoWebApi
10
+ def self.client(options = {})
11
+ Thread.current[:reso_web_api_client] ||= ResoWebApi::Client.new(options)
12
+ end
13
+
14
+ def self.reset
15
+ reset_configuration
16
+ Thread.current[:reso_web_api_client] = nil
17
+ end
18
+
19
+ def self.logger
20
+ if @logger.nil?
21
+ @logger = Logger.new(STDOUT)
22
+ @logger.level = Logger::INFO
23
+ end
24
+ @logger
25
+ end
26
+
27
+ def self.logger=(logger)
28
+ @logger = logger
29
+ end
30
+ end
@@ -0,0 +1,4 @@
1
+ require_relative 'authentication/access'
2
+ require_relative 'authentication/auth_strategy'
3
+ require_relative 'authentication/middleware'
4
+ require_relative 'authentication/token_auth'
@@ -0,0 +1,23 @@
1
+ module ResoWebApi
2
+ module Authentication
3
+ # Session class for TokenAuth. This stores the access token, the token type
4
+ # (usually `Bearer`), and the expiration date of the token.
5
+ class Access
6
+ attr_accessor :token, :expires, :token_type
7
+
8
+ def initialize(options = {})
9
+ @token = options['access_token']
10
+ @expires = Time.now + options['expires_in']
11
+ @token_type = options['token_type']
12
+ end
13
+
14
+ def expired?
15
+ Time.now > expires
16
+ end
17
+
18
+ def valid?
19
+ !!token && !expired?
20
+ end
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,26 @@
1
+ module ResoWebApi
2
+ module Authentication
3
+ # This base class defines the basic interface support by all client authentication implementations.
4
+ class AuthStrategy < BaseClient
5
+ attr_reader :access
6
+
7
+ # @abstract Perform requests to authenticate the client with the API
8
+ # @return [Access] The access token object
9
+ def authenticate(*)
10
+ raise NotImplementedError, 'Implement me!'
11
+ end
12
+
13
+ # Ensure that a valid access token is present or raise an exception
14
+ # @raise [ResoWebApi::Errors::AccessDenied] If authentication fails
15
+ def ensure_valid_access!
16
+ @access = authenticate unless access && access.valid?
17
+ access
18
+ end
19
+
20
+ # Resets access
21
+ def reset
22
+ @access = nil
23
+ end
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,46 @@
1
+ module ResoWebApi
2
+ module Authentication
3
+ # Authentication middleware
4
+ # Ensures that each request is made with proper `Authorization` header set
5
+ # and raises an exception if a request yields a `401 Access Denied` response.
6
+ class Middleware < Faraday::Middleware
7
+ AUTH_HEADER = 'Authorization'.freeze
8
+
9
+ def initialize(app, auth)
10
+ super(app)
11
+ @auth = auth
12
+ end
13
+
14
+ def call(request_env)
15
+ retries = 1
16
+
17
+ begin
18
+ authorize_request(request_env)
19
+
20
+ @app.call(request_env).on_complete do |response_env|
21
+ raise_if_unauthorized(response_env)
22
+ end
23
+ rescue Errors::AccessDenied
24
+ raise if retries == 0
25
+ @auth.reset
26
+ retries -= 1
27
+ retry
28
+ end
29
+ end
30
+
31
+ private
32
+
33
+ def authorize_request(request_env)
34
+ @auth.ensure_valid_access!
35
+
36
+ request_env[:request_headers].merge!(
37
+ AUTH_HEADER => "#{@auth.access.token_type} #{@auth.access.token}"
38
+ )
39
+ end
40
+
41
+ def raise_if_unauthorized(response_env)
42
+ raise Errors::AccessDenied if response_env[:status] == 401
43
+ end
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,40 @@
1
+ module ResoWebApi
2
+ module Authentication
3
+ # This implements a basic token authentication, in which a username/password
4
+ # (or API key / secret) combination is sent to a special token endpoint in
5
+ # exchange for a HTTP Bearer token with a limited lifetime.
6
+ class TokenAuth < AuthStrategy
7
+ option :client_id
8
+ option :client_secret
9
+ option :grant_type, default: proc { 'client_credentials' }
10
+ option :scope
11
+
12
+ def authenticate
13
+ response = connection.post nil, auth_params
14
+ body = JSON.parse response.body
15
+
16
+ unless response.success?
17
+ message = "#{response.reason_phrase}: #{body['error'] || response.body}"
18
+ raise Errors::AccessDenied, response: response, message: message
19
+ end
20
+
21
+ Access.new(body)
22
+ end
23
+
24
+ def connection
25
+ super.basic_auth(client_id, client_secret) && super
26
+ end
27
+
28
+ private
29
+
30
+ def auth_params
31
+ {
32
+ client_id: client_id,
33
+ client_secret: client_secret,
34
+ grant_type: grant_type,
35
+ scope: scope
36
+ }
37
+ end
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,36 @@
1
+ require 'faraday'
2
+ require 'dry-initializer'
3
+
4
+ module ResoWebApi
5
+ # Base class for Faraday-based HTTP clients
6
+ class BaseClient
7
+ extend Dry::Initializer
8
+
9
+ option :endpoint
10
+ option :user_agent, default: proc { USER_AGENT }
11
+ option :adapter, default: proc { Faraday::default_adapter }
12
+ option :logger, default: proc { ResoWebApi.logger }
13
+
14
+ USER_AGENT = "Reso Web API Ruby Gem v#{VERSION}"
15
+
16
+ # Return the {Faraday::Connection} object for this client.
17
+ # Yields the connection object being constructed (for customzing middleware).
18
+ # @return [Faraday::Connection] The connection object
19
+ def connection(&block)
20
+ @connection ||= Faraday.new(url: endpoint, headers: headers) do |conn|
21
+ conn.request :url_encoded
22
+ conn.response :logger, logger
23
+ yield conn if block_given?
24
+ conn.adapter adapter unless conn.builder.send(:adapter_set?)
25
+ end
26
+ end
27
+
28
+ # Return the headers to be sent with every request.
29
+ # @return [Hash] The request headers.
30
+ def headers
31
+ {
32
+ :user_agent => user_agent
33
+ }
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,53 @@
1
+ require_relative 'base_client'
2
+ require_relative 'authentication'
3
+ require_relative 'resources'
4
+
5
+ module ResoWebApi
6
+ # Main class to run requests against a RESO Web API server.
7
+ class Client < BaseClient
8
+ include Resources
9
+
10
+ option :auth
11
+
12
+ def initialize(options = {})
13
+ super(options)
14
+ ensure_valid_auth_strategy!
15
+ end
16
+
17
+ # Headers to be send along with requests
18
+ # @return [Hash] The request headers
19
+ def headers
20
+ super.merge({ accept: 'application/json' })
21
+ end
22
+
23
+ # Return the {Faraday::Connection} object for this client.
24
+ # Yields the connection object being constructed (for customzing middleware).
25
+ # @return [Faraday::Connection] The connection object
26
+ def connection(&block)
27
+ super do |conn|
28
+ conn.use Authentication::Middleware, @auth
29
+ yield conn if block_given?
30
+ end
31
+ end
32
+
33
+ # Returns a proxied {OData4::Service} that attempts to ensure a properly
34
+ # authenticated and authorized connection
35
+ # @return [OData4::Service] The service instance.
36
+ def service
37
+ @service ||= OData4::Service.new(connection)
38
+ end
39
+
40
+ private
41
+
42
+ def ensure_valid_auth_strategy!
43
+ if auth.is_a?(Hash)
44
+ strategy = auth.delete(:strategy) || Authentication::TokenAuth
45
+ if strategy.is_a?(Class) && strategy <= Authentication::AuthStrategy
46
+ @auth = strategy.new(auth)
47
+ else
48
+ raise ArgumentError, "#{strategy} is not a valid auth strategy"
49
+ end
50
+ end
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,22 @@
1
+ module ResoWebApi
2
+ class Error < StandardError; end
3
+
4
+ class NetworkError < Error
5
+ attr_reader :response
6
+
7
+ def initialize(options = {})
8
+ # Support the standard initializer for errors
9
+ opts = options.is_a?(Hash) ? options : { message: options.to_s }
10
+ @response = opts[:response]
11
+ super(opts[:message])
12
+ end
13
+
14
+ def status
15
+ response && response.status
16
+ end
17
+ end
18
+
19
+ module Errors
20
+ class AccessDenied < NetworkError; end
21
+ end
22
+ end
@@ -0,0 +1,21 @@
1
+ module ResoWebApi
2
+ # Grants access to a service's resources in a convenient manner
3
+ module Resources
4
+ STANDARD_RESOURCES = {
5
+ properties: 'Property',
6
+ members: 'Member',
7
+ offices: 'Office',
8
+ media: 'Media'
9
+ }
10
+
11
+ STANDARD_RESOURCES.each do |method, resource|
12
+ define_method(method) do
13
+ resources[resource]
14
+ end
15
+ end
16
+
17
+ def resources
18
+ service
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,3 @@
1
+ module ResoWebApi
2
+ VERSION = "0.2.0"
3
+ end
@@ -0,0 +1,31 @@
1
+
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "reso_web_api/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "reso_web_api"
8
+ spec.version = ResoWebApi::VERSION
9
+ spec.authors = ["Christoph Wagner"]
10
+ spec.email = ["christoph@wrstudios.com"]
11
+
12
+ spec.summary = %q{RESO Web API for Ruby}
13
+ spec.description = %q{Allows communication with MLS systems conforming to the RESO Web API standard}
14
+ spec.homepage = "https://github.com/wrstudios/reso_web_api"
15
+ spec.license = "MIT"
16
+
17
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
18
+ f.match(%r{^(test|spec|features)/})
19
+ end
20
+ spec.bindir = "exe"
21
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
22
+ spec.require_paths = ["lib"]
23
+
24
+ spec.add_dependency 'faraday', '~> 0.15.0'
25
+ spec.add_dependency 'odata4', '~> 0.9.1'
26
+ spec.add_dependency 'dry-initializer', '~> 1.4.1'
27
+
28
+ spec.add_development_dependency "bundler", "~> 1.16"
29
+ spec.add_development_dependency "rake", "~> 10.0"
30
+ spec.add_development_dependency "rspec", "~> 3.0"
31
+ end
metadata ADDED
@@ -0,0 +1,152 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: reso_web_api
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.2.0
5
+ platform: ruby
6
+ authors:
7
+ - Christoph Wagner
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2018-05-15 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: faraday
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: 0.15.0
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: 0.15.0
27
+ - !ruby/object:Gem::Dependency
28
+ name: odata4
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: 0.9.1
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: 0.9.1
41
+ - !ruby/object:Gem::Dependency
42
+ name: dry-initializer
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: 1.4.1
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: 1.4.1
55
+ - !ruby/object:Gem::Dependency
56
+ name: bundler
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '1.16'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '1.16'
69
+ - !ruby/object:Gem::Dependency
70
+ name: rake
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '10.0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '10.0'
83
+ - !ruby/object:Gem::Dependency
84
+ name: rspec
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - "~>"
88
+ - !ruby/object:Gem::Version
89
+ version: '3.0'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - "~>"
95
+ - !ruby/object:Gem::Version
96
+ version: '3.0'
97
+ description: Allows communication with MLS systems conforming to the RESO Web API
98
+ standard
99
+ email:
100
+ - christoph@wrstudios.com
101
+ executables: []
102
+ extensions: []
103
+ extra_rdoc_files: []
104
+ files:
105
+ - ".gitignore"
106
+ - ".rspec"
107
+ - ".ruby-gemset"
108
+ - ".ruby-version"
109
+ - CHANGELOG.md
110
+ - Gemfile
111
+ - LICENSE
112
+ - README.md
113
+ - Rakefile
114
+ - bin/console
115
+ - bin/setup
116
+ - lib/reso_web_api.rb
117
+ - lib/reso_web_api/authentication.rb
118
+ - lib/reso_web_api/authentication/access.rb
119
+ - lib/reso_web_api/authentication/auth_strategy.rb
120
+ - lib/reso_web_api/authentication/middleware.rb
121
+ - lib/reso_web_api/authentication/token_auth.rb
122
+ - lib/reso_web_api/base_client.rb
123
+ - lib/reso_web_api/client.rb
124
+ - lib/reso_web_api/errors.rb
125
+ - lib/reso_web_api/resources.rb
126
+ - lib/reso_web_api/version.rb
127
+ - reso_web_api.gemspec
128
+ homepage: https://github.com/wrstudios/reso_web_api
129
+ licenses:
130
+ - MIT
131
+ metadata: {}
132
+ post_install_message:
133
+ rdoc_options: []
134
+ require_paths:
135
+ - lib
136
+ required_ruby_version: !ruby/object:Gem::Requirement
137
+ requirements:
138
+ - - ">="
139
+ - !ruby/object:Gem::Version
140
+ version: '0'
141
+ required_rubygems_version: !ruby/object:Gem::Requirement
142
+ requirements:
143
+ - - ">="
144
+ - !ruby/object:Gem::Version
145
+ version: '0'
146
+ requirements: []
147
+ rubyforge_project:
148
+ rubygems_version: 2.6.14
149
+ signing_key:
150
+ specification_version: 4
151
+ summary: RESO Web API for Ruby
152
+ test_files: []