omniauth-oauth2-1.7.1/0000755000004100000410000000000014012452541014572 5ustar www-datawww-dataomniauth-oauth2-1.7.1/.travis.yml0000644000004100000410000000056614012452541016712 0ustar www-datawww-databundler_args: --without development before_install: - gem update --system - gem update bundler cache: bundler env: global: - JRUBY_OPTS="$JRUBY_OPTS --debug" language: ruby rvm: - jruby-9000 - 2.4.4 - 2.5.3 - jruby-head - ruby-head - truffleruby-head matrix: allow_failures: - rvm: jruby-head - rvm: ruby-head fast_finish: true sudo: false omniauth-oauth2-1.7.1/.rspec0000644000004100000410000000003314012452541015703 0ustar www-datawww-data--colour --format=progress omniauth-oauth2-1.7.1/README.md0000644000004100000410000000440614012452541016055 0ustar www-datawww-data# OmniAuth OAuth2 [![Gem Version](http://img.shields.io/gem/v/omniauth-oauth2.svg)][gem] [![Build Status](http://img.shields.io/travis/omniauth/omniauth-oauth2.svg)][travis] [![Code Climate](http://img.shields.io/codeclimate/maintainability/intridea/omniauth-oauth2.svg)][codeclimate] [![Coverage Status](http://img.shields.io/coveralls/intridea/omniauth-oauth2.svg)][coveralls] [![Security](https://hakiri.io/github/omniauth/omniauth-oauth2/master.svg)](https://hakiri.io/github/omniauth/omniauth-oauth2/master) [gem]: https://rubygems.org/gems/omniauth-oauth2 [travis]: http://travis-ci.org/omniauth/omniauth-oauth2 [codeclimate]: https://codeclimate.com/github/intridea/omniauth-oauth2 [coveralls]: https://coveralls.io/r/intridea/omniauth-oauth2 This gem contains a generic OAuth2 strategy for OmniAuth. It is meant to serve as a building block strategy for other strategies and not to be used independently (since it has no inherent way to gather uid and user info). ## Creating an OAuth2 Strategy To create an OmniAuth OAuth2 strategy using this gem, you can simply subclass it and add a few extra methods like so: ```ruby require 'omniauth-oauth2' module OmniAuth module Strategies class SomeSite < OmniAuth::Strategies::OAuth2 # Give your strategy a name. option :name, "some_site" # This is where you pass the options you would pass when # initializing your consumer from the OAuth gem. option :client_options, {:site => "https://api.somesite.com"} # You may specify that your strategy should use PKCE by setting # the pkce option to true: https://tools.ietf.org/html/rfc7636 option :pkce, true # These are called after authentication has succeeded. If # possible, you should try to set the UID without making # additional calls (if the user id is returned with the token # or as a URI parameter). This may not be possible with all # providers. uid{ raw_info['id'] } info do { :name => raw_info['name'], :email => raw_info['email'] } end extra do { 'raw_info' => raw_info } end def raw_info @raw_info ||= access_token.get('/me').parsed end end end end ``` That's pretty much it! omniauth-oauth2-1.7.1/LICENSE.md0000644000004100000410000000211114012452541016171 0ustar www-datawww-dataCopyright (C) 2014 Michael Bleigh, Erik Michaels-Ober and Intridea, Inc. 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 is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 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. omniauth-oauth2-1.7.1/spec/0000755000004100000410000000000014012452541015524 5ustar www-datawww-dataomniauth-oauth2-1.7.1/spec/helper.rb0000644000004100000410000000124314012452541017330 0ustar www-datawww-data$LOAD_PATH.unshift File.expand_path("..", __FILE__) $LOAD_PATH.unshift File.expand_path("../../lib", __FILE__) if RUBY_VERSION >= "1.9" require "simplecov" require "coveralls" SimpleCov.formatters = [SimpleCov::Formatter::HTMLFormatter, Coveralls::SimpleCov::Formatter] SimpleCov.start do minimum_coverage(78.48) end end require "rspec" require "rack/test" require "webmock/rspec" require "omniauth" require "omniauth-oauth2" RSpec.configure do |config| config.expect_with :rspec do |c| c.syntax = :expect end config.extend OmniAuth::Test::StrategyMacros, :type => :strategy config.include Rack::Test::Methods config.include WebMock::API end omniauth-oauth2-1.7.1/spec/omniauth/0000755000004100000410000000000014012452541017350 5ustar www-datawww-dataomniauth-oauth2-1.7.1/spec/omniauth/strategies/0000755000004100000410000000000014012452541021522 5ustar www-datawww-dataomniauth-oauth2-1.7.1/spec/omniauth/strategies/oauth2_spec.rb0000644000004100000410000001076314012452541024272 0ustar www-datawww-datarequire "helper" describe OmniAuth::Strategies::OAuth2 do def app lambda do |_env| [200, {}, ["Hello."]] end end let(:fresh_strategy) { Class.new(OmniAuth::Strategies::OAuth2) } before do OmniAuth.config.test_mode = true end after do OmniAuth.config.test_mode = false end describe "Subclassing Behavior" do subject { fresh_strategy } it "performs the OmniAuth::Strategy included hook" do expect(OmniAuth.strategies).to include(OmniAuth::Strategies::OAuth2) expect(OmniAuth.strategies).to include(subject) end end describe "#client" do subject { fresh_strategy } it "is initialized with symbolized client_options" do instance = subject.new(app, :client_options => {"authorize_url" => "https://example.com"}) expect(instance.client.options[:authorize_url]).to eq("https://example.com") end it "sets ssl options as connection options" do instance = subject.new(app, :client_options => {"ssl" => {"ca_path" => "foo"}}) expect(instance.client.options[:connection_opts][:ssl]).to eq(:ca_path => "foo") end end describe "#authorize_params" do subject { fresh_strategy } it "includes any authorize params passed in the :authorize_params option" do instance = subject.new("abc", "def", :authorize_params => {:foo => "bar", :baz => "zip"}) expect(instance.authorize_params["foo"]).to eq("bar") expect(instance.authorize_params["baz"]).to eq("zip") end it "includes top-level options that are marked as :authorize_options" do instance = subject.new("abc", "def", :authorize_options => %i[scope foo state], :scope => "bar", :foo => "baz") expect(instance.authorize_params["scope"]).to eq("bar") expect(instance.authorize_params["foo"]).to eq("baz") expect(instance.authorize_params["state"]).not_to be_empty end it "includes random state in the authorize params" do instance = subject.new("abc", "def") expect(instance.authorize_params.keys).to eq(["state"]) expect(instance.session["omniauth.state"]).not_to be_empty end it "includes custom state in the authorize params" do instance = subject.new("abc", "def", :state => proc { "qux" }) expect(instance.authorize_params.keys).to eq(["state"]) expect(instance.session["omniauth.state"]).to eq("qux") end it "includes PKCE parameters if enabled" do instance = subject.new("abc", "def", :pkce => true) expect(instance.authorize_params[:code_challenge]).to be_a(String) expect(instance.authorize_params[:code_challenge_method]).to eq("S256") expect(instance.session["omniauth.pkce.verifier"]).to be_a(String) end end describe "#token_params" do subject { fresh_strategy } it "includes any authorize params passed in the :authorize_params option" do instance = subject.new("abc", "def", :token_params => {:foo => "bar", :baz => "zip"}) expect(instance.token_params).to eq("foo" => "bar", "baz" => "zip") end it "includes top-level options that are marked as :authorize_options" do instance = subject.new("abc", "def", :token_options => %i[scope foo], :scope => "bar", :foo => "baz") expect(instance.token_params).to eq("scope" => "bar", "foo" => "baz") end it "includes the PKCE code_verifier if enabled" do instance = subject.new("abc", "def", :pkce => true) # setup session instance.authorize_params expect(instance.token_params[:code_verifier]).to be_a(String) end end describe "#callback_phase" do subject { fresh_strategy } it "calls fail with the client error received" do instance = subject.new("abc", "def") allow(instance).to receive(:request) do double("Request", :params => {"error_reason" => "user_denied", "error" => "access_denied"}) end expect(instance).to receive(:fail!).with("user_denied", anything) instance.callback_phase end end end describe OmniAuth::Strategies::OAuth2::CallbackError do let(:error) { Class.new(OmniAuth::Strategies::OAuth2::CallbackError) } describe "#message" do subject { error } it "includes all of the attributes" do instance = subject.new("error", "description", "uri") expect(instance.message).to match(/error/) expect(instance.message).to match(/description/) expect(instance.message).to match(/uri/) end it "includes all of the attributes" do instance = subject.new(nil, :symbol) expect(instance.message).to eq("symbol") end end end omniauth-oauth2-1.7.1/.rubocop.yml0000644000004100000410000000242114012452541017043 0ustar www-datawww-dataAllCops: NewCops: enable Gemspec/RequiredRubyVersion: Enabled: false Layout/AccessModifierIndentation: EnforcedStyle: outdent Layout/LineLength: AllowURI: true Enabled: false Layout/SpaceInsideHashLiteralBraces: EnforcedStyle: no_space Lint/MissingSuper: Enabled: false Metrics/AbcSize: Max: 18 Metrics/BlockLength: Exclude: - spec/omniauth/strategies/oauth2_spec.rb Metrics/BlockNesting: Max: 2 Metrics/ClassLength: Max: 110 Metrics/MethodLength: CountComments: false Max: 10 Metrics/ParameterLists: Max: 4 CountKeywordArgs: true Naming/FileName: Exclude: - lib/omniauth-oauth2.rb Style/CollectionMethods: PreferredMethods: map: 'collect' reduce: 'inject' find: 'detect' find_all: 'select' Style/Documentation: Enabled: false Style/DoubleNegation: Enabled: false Style/ExpandPathArguments: Enabled: false Style/FrozenStringLiteralComment: Enabled: false Style/HashSyntax: EnforcedStyle: hash_rockets Style/StderrPuts: Enabled: false Style/StringLiterals: EnforcedStyle: double_quotes Style/TrailingCommaInArguments: EnforcedStyleForMultiline: comma Style/TrailingCommaInHashLiteral: EnforcedStyleForMultiline: comma Style/TrailingCommaInArrayLiteral: EnforcedStyleForMultiline: comma omniauth-oauth2-1.7.1/.gitignore0000644000004100000410000000024014012452541016556 0ustar www-datawww-data*.gem *.rbc .bundle .config .yardoc Gemfile.lock InstalledFiles _yardoc coverage doc/ lib/bundler/man pkg rdoc spec/reports test/tmp test/version_tmp tmp *.swp omniauth-oauth2-1.7.1/omniauth-oauth2.gemspec0000644000004100000410000000200314012452541021156 0ustar www-datawww-datalib = File.expand_path("../lib", __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "omniauth-oauth2/version" Gem::Specification.new do |gem| gem.add_dependency "oauth2", "~> 1.4" gem.add_dependency "omniauth", [">= 1.9", "< 3"] gem.add_development_dependency "bundler", "~> 2.0" gem.authors = ["Michael Bleigh", "Erik Michaels-Ober", "Tom Milewski"] gem.email = ["michael@intridea.com", "sferik@gmail.com", "tmilewski@gmail.com"] gem.description = "An abstract OAuth2 strategy for OmniAuth." gem.summary = gem.description gem.homepage = "https://github.com/omniauth/omniauth-oauth2" gem.licenses = %w[MIT] gem.executables = `git ls-files -- bin/*`.split("\n").collect { |f| File.basename(f) } gem.files = `git ls-files`.split("\n") gem.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") gem.name = "omniauth-oauth2" gem.require_paths = %w[lib] gem.version = OmniAuth::OAuth2::VERSION end omniauth-oauth2-1.7.1/Rakefile0000755000004100000410000000046514012452541016247 0ustar www-datawww-data#!/usr/bin/env rake require "bundler/gem_tasks" require "rspec/core/rake_task" RSpec::Core::RakeTask.new task :test => :spec begin require "rubocop/rake_task" RuboCop::RakeTask.new rescue LoadError task :rubocop do $stderr.puts "RuboCop is disabled" end end task :default => %i[spec rubocop] omniauth-oauth2-1.7.1/lib/0000755000004100000410000000000014012452541015340 5ustar www-datawww-dataomniauth-oauth2-1.7.1/lib/omniauth-oauth2/0000755000004100000410000000000014012452541020364 5ustar www-datawww-dataomniauth-oauth2-1.7.1/lib/omniauth-oauth2/version.rb0000644000004100000410000000010714012452541022374 0ustar www-datawww-datamodule OmniAuth module OAuth2 VERSION = "1.7.1".freeze end end omniauth-oauth2-1.7.1/lib/omniauth/0000755000004100000410000000000014012452541017164 5ustar www-datawww-dataomniauth-oauth2-1.7.1/lib/omniauth/strategies/0000755000004100000410000000000014012452541021336 5ustar www-datawww-dataomniauth-oauth2-1.7.1/lib/omniauth/strategies/oauth2.rb0000644000004100000410000001316314012452541023071 0ustar www-datawww-datarequire "oauth2" require "omniauth" require "securerandom" require "socket" # for SocketError require "timeout" # for Timeout::Error module OmniAuth module Strategies # Authentication strategy for connecting with APIs constructed using # the [OAuth 2.0 Specification](http://tools.ietf.org/html/draft-ietf-oauth-v2-10). # You must generally register your application with the provider and # utilize an application id and secret in order to authenticate using # OAuth 2.0. class OAuth2 include OmniAuth::Strategy def self.inherited(subclass) OmniAuth::Strategy.included(subclass) end args %i[client_id client_secret] option :client_id, nil option :client_secret, nil option :client_options, {} option :authorize_params, {} option :authorize_options, %i[scope state] option :token_params, {} option :token_options, [] option :auth_token_params, {} option :provider_ignores_state, false option :pkce, false option :pkce_verifier, nil option :pkce_options, { :code_challenge => proc { |verifier| Base64.urlsafe_encode64( Digest::SHA2.digest(verifier), :padding => false, ) }, :code_challenge_method => "S256", } attr_accessor :access_token def client ::OAuth2::Client.new(options.client_id, options.client_secret, deep_symbolize(options.client_options)) end credentials do hash = {"token" => access_token.token} hash["refresh_token"] = access_token.refresh_token if access_token.expires? && access_token.refresh_token hash["expires_at"] = access_token.expires_at if access_token.expires? hash["expires"] = access_token.expires? hash end def request_phase redirect client.auth_code.authorize_url({:redirect_uri => callback_url}.merge(authorize_params)) end def authorize_params # rubocop:disable Metrics/AbcSize, Metrics/MethodLength options.authorize_params[:state] = SecureRandom.hex(24) if OmniAuth.config.test_mode @env ||= {} @env["rack.session"] ||= {} end params = options.authorize_params .merge(options_for("authorize")) .merge(pkce_authorize_params) session["omniauth.pkce.verifier"] = options.pkce_verifier if options.pkce session["omniauth.state"] = params[:state] params end def token_params options.token_params.merge(options_for("token")).merge(pkce_token_params) end def callback_phase # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity error = request.params["error_reason"] || request.params["error"] if error fail!(error, CallbackError.new(request.params["error"], request.params["error_description"] || request.params["error_reason"], request.params["error_uri"])) elsif !options.provider_ignores_state && (request.params["state"].to_s.empty? || request.params["state"] != session.delete("omniauth.state")) fail!(:csrf_detected, CallbackError.new(:csrf_detected, "CSRF detected")) else self.access_token = build_access_token self.access_token = access_token.refresh! if access_token.expired? super end rescue ::OAuth2::Error, CallbackError => e fail!(:invalid_credentials, e) rescue ::Timeout::Error, ::Errno::ETIMEDOUT => e fail!(:timeout, e) rescue ::SocketError => e fail!(:failed_to_connect, e) end protected def pkce_authorize_params return {} unless options.pkce options.pkce_verifier = SecureRandom.hex(64) # NOTE: see https://tools.ietf.org/html/rfc7636#appendix-A { :code_challenge => options.pkce_options[:code_challenge] .call(options.pkce_verifier), :code_challenge_method => options.pkce_options[:code_challenge_method], } end def pkce_token_params return {} unless options.pkce {:code_verifier => session.delete("omniauth.pkce.verifier")} end def build_access_token verifier = request.params["code"] client.auth_code.get_token(verifier, {:redirect_uri => callback_url}.merge(token_params.to_hash(:symbolize_keys => true)), deep_symbolize(options.auth_token_params)) end def deep_symbolize(options) options.each_with_object({}) do |(key, value), hash| hash[key.to_sym] = value.is_a?(Hash) ? deep_symbolize(value) : value end end def options_for(option) hash = {} options.send(:"#{option}_options").select { |key| options[key] }.each do |key| hash[key.to_sym] = if options[key].respond_to?(:call) options[key].call(env) else options[key] end end hash end # An error that is indicated in the OAuth 2.0 callback. # This could be a `redirect_uri_mismatch` or other class CallbackError < StandardError attr_accessor :error, :error_reason, :error_uri def initialize(error, error_reason = nil, error_uri = nil) self.error = error self.error_reason = error_reason self.error_uri = error_uri end def message [error, error_reason, error_uri].compact.join(" | ") end end end end end OmniAuth.config.add_camelization "oauth2", "OAuth2" omniauth-oauth2-1.7.1/lib/omniauth-oauth2.rb0000644000004100000410000000010714012452541020707 0ustar www-datawww-datarequire "omniauth-oauth2/version" require "omniauth/strategies/oauth2" omniauth-oauth2-1.7.1/Gemfile0000644000004100000410000000112614012452541016065 0ustar www-datawww-datasource "https://rubygems.org" gem "rake", "~> 12.0" group :test do gem "addressable", "~> 2.3.8", :platforms => %i[jruby ruby_18] gem "coveralls" gem "json", :platforms => %i[jruby ruby_18 ruby_19] gem "mime-types", "~> 1.25", :platforms => %i[jruby ruby_18] gem "rack-test" gem "rest-client", "~> 1.8.0", :platforms => %i[jruby ruby_18] gem "rspec", "~> 3.2" gem "rubocop", ">= 0.51", :platforms => %i[ruby_19 ruby_20 ruby_21 ruby_22 ruby_23 ruby_24] gem "simplecov", ">= 0.9" gem "webmock", "~> 3.0" end # Specify your gem's dependencies in omniauth-oauth2.gemspec gemspec omniauth-oauth2-1.7.1/.github/0000755000004100000410000000000014012452541016132 5ustar www-datawww-dataomniauth-oauth2-1.7.1/.github/workflows/0000755000004100000410000000000014012452541020167 5ustar www-datawww-dataomniauth-oauth2-1.7.1/.github/workflows/main.yml0000644000004100000410000000210514012452541021634 0ustar www-datawww-dataname: Ruby on: push: branches: [ master ] pull_request: branches: [ master ] jobs: test: runs-on: ubuntu-18.04 strategy: fail-fast: false matrix: os: [ubuntu, macos] ruby: [2.5, 2.6, 2.7, head, debug, truffleruby, truffleruby-head] steps: - uses: actions/checkout@v2 - name: Set up Ruby uses: ruby/setup-ruby@v1 with: ruby-version: ${{ matrix.ruby }} bundler-cache: true - name: Install dependencies run: bundle install - name: Run tests run: bundle exec rake test-jruby: runs-on: ubuntu-18.04 strategy: fail-fast: false matrix: os: [ubuntu, macos] jruby: [jruby, jruby-head] steps: - uses: actions/checkout@v2 - name: Set up Ruby uses: ruby/setup-ruby@v1 with: ruby-version: ${{ matrix.jruby }} bundler-cache: true - name: Install dependencies env: JRUBY_OPTS: --debug run: bundle install - name: Run tests env: JRUBY_OPTS: --debug run: bundle exec rake