omniauth-google-oauth2-0.2.4/ 0000755 0000041 0000041 00000000000 12326755544 016060 5 ustar www-data www-data omniauth-google-oauth2-0.2.4/Rakefile 0000644 0000041 0000041 00000000247 12326755544 017530 0 ustar www-data www-data #!/usr/bin/env rake require File.join('bundler', 'gem_tasks') require File.join('rspec', 'core', 'rake_task') RSpec::Core::RakeTask.new(:spec) task :default => :spec omniauth-google-oauth2-0.2.4/Gemfile 0000644 0000041 0000041 00000000115 12326755544 017350 0 ustar www-data www-data source 'https://rubygems.org' gemspec group :example do gem 'sinatra' end omniauth-google-oauth2-0.2.4/examples/ 0000755 0000041 0000041 00000000000 12326755544 017676 5 ustar www-data www-data omniauth-google-oauth2-0.2.4/examples/Gemfile 0000644 0000041 0000041 00000000112 12326755544 021163 0 ustar www-data www-data source 'https://rubygems.org' gem 'sinatra' gem 'omniauth-google-oauth2' omniauth-google-oauth2-0.2.4/examples/omni_auth.rb 0000644 0000041 0000041 00000002713 12326755544 022211 0 ustar www-data www-data # Google's OAuth2 docs. Make sure you are familiar with all the options # before attempting to configure this gem. # https://developers.google.com/accounts/docs/OAuth2Login Rails.application.config.middleware.use OmniAuth::Builder do # Default usage, this will give you offline access and a refresh token # using default scopes 'email' and 'profile' # provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET'], { :scope => 'email,profile' } # Manual setup for offline access with a refresh token. # The prompt must be set to 'consent' # # provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET'], { # :access_type => 'offline', # :prompt => 'consent' # } # Custom scope supporting youtube. If you are customizing scopes, remember # to include the default scopes 'email' and 'profile' # # provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET'], { # :scope => 'http://gdata.youtube.com,email,profile,plus.me' # } # Custom scope for users only using Google for account creation/auth and do not require a refresh token. # # provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET'], { # :access_type => 'online', # :prompt => '' # } # To include information about people in your circles you must include the 'plus.login' scope. # # provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET'], { # :skip_friends => false, # :scope => "email,profile,plus.login" # } end omniauth-google-oauth2-0.2.4/examples/config.ru 0000644 0000041 0000041 00000002304 12326755544 021512 0 ustar www-data www-data # Sample app for Google OAuth2 Strategy # Make sure to setup the ENV variables GOOGLE_KEY and GOOGLE_SECRET # Run with "bundle exec rackup" require 'rubygems' require 'bundler' require 'sinatra' require 'omniauth' require 'omniauth-google-oauth2' # Do not use for production code. # This is only to make setup easier when running through the sample. # # If you do have issues with certs in production code, this could help: # http://railsapps.github.io/openssl-certificate-verify-failed.html OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE class App < Sinatra::Base get '/' do <<-HTML
HTML end get '/auth/:provider/callback' do content_type 'text/plain' request.env['omniauth.auth'].to_hash.inspect rescue "No Data" end get '/auth/failure' do content_type 'text/plain' request.env['omniauth.auth'].to_hash.inspect rescue "No Data" end end use Rack::Session::Cookie, :secret => ENV['RACK_COOKIE_SECRET'] use OmniAuth::Builder do # For additional provider examples please look at 'omni_auth.rb' provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET'], {} end run App.new omniauth-google-oauth2-0.2.4/omniauth-contrib.gemspec 0000644 0000041 0000041 00000001661 12326755544 022713 0 ustar www-data www-data # -*- encoding: utf-8 -*- require File.expand_path(File.join('..', 'lib', 'omniauth', 'google_oauth2', 'version'), __FILE__) Gem::Specification.new do |gem| gem.add_dependency 'omniauth', '~> 1.0' gem.authors = ["Josh Ellithorpe", "Yury Korolev"] gem.email = ["quest@mac.com"] gem.description = %q{A Google OAuth2 strategy for OmniAuth 1.x} gem.summary = %q{A Google OAuth2 strategy for OmniAuth 1.x} gem.homepage = "" gem.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } gem.files = `git ls-files`.split("\n") gem.test_files = `git ls-files -- {spec}/*`.split("\n") gem.name = "omniauth-google-oauth2" gem.require_paths = ["lib"] gem.version = OmniAuth::GoogleOauth2::VERSION gem.add_runtime_dependency 'omniauth-oauth2', '~> 1.1' gem.add_development_dependency 'rspec', '>= 2.14.0' gem.add_development_dependency 'rake' end omniauth-google-oauth2-0.2.4/spec/ 0000755 0000041 0000041 00000000000 12326755544 017012 5 ustar www-data www-data omniauth-google-oauth2-0.2.4/spec/omniauth/ 0000755 0000041 0000041 00000000000 12326755544 020636 5 ustar www-data www-data omniauth-google-oauth2-0.2.4/spec/omniauth/strategies/ 0000755 0000041 0000041 00000000000 12326755544 023010 5 ustar www-data www-data omniauth-google-oauth2-0.2.4/spec/omniauth/strategies/google_oauth2_spec.rb 0000644 0000041 0000041 00000045447 12326755544 027123 0 ustar www-data www-data require 'spec_helper' require 'omniauth-google-oauth2' describe OmniAuth::Strategies::GoogleOauth2 do let(:request) { double('Request', :params => {}, :cookies => {}, :env => {}) } let(:app) { lambda do [200, {}, ["Hello."]] end } subject do OmniAuth::Strategies::GoogleOauth2.new(app, 'appid', 'secret', @options || {}).tap do |strategy| allow(strategy).to receive(:request) { request } end end before do OmniAuth.config.test_mode = true end after do OmniAuth.config.test_mode = false end describe '#client_options' do it 'has correct site' do expect(subject.client.site).to eq('https://accounts.google.com') end it 'has correct authorize_url' do expect(subject.client.options[:authorize_url]).to eq('/o/oauth2/auth') end it 'has correct token_url' do expect(subject.client.options[:token_url]).to eq('/o/oauth2/token') end describe "overrides" do it 'should allow overriding the site' do @options = {:client_options => {'site' => 'https://example.com'}} expect(subject.client.site).to eq('https://example.com') end it 'should allow overriding the authorize_url' do @options = {:client_options => {'authorize_url' => 'https://example.com'}} expect(subject.client.options[:authorize_url]).to eq('https://example.com') end it 'should allow overriding the token_url' do @options = {:client_options => {'token_url' => 'https://example.com'}} expect(subject.client.options[:token_url]).to eq('https://example.com') end end end describe "#authorize_options" do [:access_type, :hd, :login_hint, :prompt, :scope, :state].each do |k| it "should support #{k}" do @options = {k => 'http://someval'} expect(subject.authorize_params[k.to_s]).to eq('http://someval') end end describe "redirect_uri" do it 'should default to nil' do @options = {} expect(subject.authorize_params['redirect_uri']).to eq(nil) end it 'should set the redirect_uri parameter if present' do @options = {:redirect_uri => 'https://example.com'} expect(subject.authorize_params['redirect_uri']).to eq('https://example.com') end end describe 'access_type' do it 'should default to "offline"' do @options = {} expect(subject.authorize_params['access_type']).to eq('offline') end it 'should set the access_type parameter if present' do @options = {:access_type => 'online'} expect(subject.authorize_params['access_type']).to eq('online') end end describe 'hd' do it "should default to nil" do expect(subject.authorize_params['hd']).to eq(nil) end it 'should set the hd (hosted domain) parameter if present' do @options = {:hd => 'example.com'} expect(subject.authorize_params['hd']).to eq('example.com') end end describe 'login_hint' do it "should default to nil" do expect(subject.authorize_params['login_hint']).to eq(nil) end it 'should set the login_hint parameter if present' do @options = {:login_hint => 'john@example.com'} expect(subject.authorize_params['login_hint']).to eq('john@example.com') end end describe 'prompt' do it "should default to nil" do expect(subject.authorize_params['prompt']).to eq(nil) end it 'should set the prompt parameter if present' do @options = {:prompt => 'consent select_account'} expect(subject.authorize_params['prompt']).to eq('consent select_account') end end describe 'request_visible_actions' do it "should default to nil" do expect(subject.authorize_params['request_visible_actions']).to eq(nil) end it 'should set the request_visible_actions parameter if present' do @options = {:request_visible_actions => 'something'} expect(subject.authorize_params['request_visible_actions']).to eq('something') end end describe 'include_granted_scopes' do it 'should default to nil' do expect(subject.authorize_params['include_granted_scopes']).to eq(nil) end it 'should set the include_granted_scopes parameter if present' do @options = {:include_granted_scopes => 'true'} expect(subject.authorize_params['include_granted_scopes']).to eq('true') end end describe 'scope' do it 'should expand scope shortcuts' do @options = {:scope => 'plus.me'} expect(subject.authorize_params['scope']).to eq('https://www.googleapis.com/auth/plus.me') end it 'should leave base scopes as is' do @options = {:scope => 'profile'} expect(subject.authorize_params['scope']).to eq('profile') end it 'should join scopes' do @options = {:scope => 'profile,email'} expect(subject.authorize_params['scope']).to eq('profile email') end it 'should deal with whitespace when joining scopes' do @options = {:scope => 'profile, email'} expect(subject.authorize_params['scope']).to eq('profile email') end it 'should set default scope to email,profile' do expect(subject.authorize_params['scope']).to eq('email profile') end it 'should support space delimited scopes' do @options = {:scope => 'profile email'} expect(subject.authorize_params['scope']).to eq('profile email') end it "should support extremely badly formed scopes" do @options = {:scope => 'profile email,foo,steve yeah http://example.com'} expect(subject.authorize_params['scope']).to eq('profile email https://www.googleapis.com/auth/foo https://www.googleapis.com/auth/steve https://www.googleapis.com/auth/yeah http://example.com') end end describe 'state' do it 'should set the state parameter' do @options = {:state => 'some_state'} expect(subject.authorize_params['state']).to eq('some_state') expect(subject.session['omniauth.state']).to eq('some_state') end it 'should set the omniauth.state dynamically' do allow(subject).to receive(:request) { double('Request', {:params => {'state' => 'some_state'}, :env => {}}) } expect(subject.authorize_params['state']).to eq('some_state') expect(subject.session['omniauth.state']).to eq('some_state') end end describe "overrides" do it 'should include top-level options that are marked as :authorize_options' do @options = {:authorize_options => [:scope, :foo, :request_visible_actions], :scope => 'http://bar', :foo => 'baz', :hd => "wow", :request_visible_actions => "something"} expect(subject.authorize_params['scope']).to eq('http://bar') expect(subject.authorize_params['foo']).to eq('baz') expect(subject.authorize_params['hd']).to eq(nil) expect(subject.authorize_params['request_visible_actions']).to eq('something') end describe "request overrides" do [:access_type, :hd, :login_hint, :prompt, :scope, :state].each do |k| context "authorize option #{k}" do let(:request) { double('Request', :params => {k.to_s => 'http://example.com'}, :cookies => {}, :env => {}) } it "should set the #{k} authorize option dynamically in the request" do @options = {k => ''} expect(subject.authorize_params[k.to_s]).to eq('http://example.com') end end end describe "custom authorize_options" do let(:request) { double('Request', :params => {'foo' => 'something'}, :cookies => {}, :env => {}) } it "should support request overrides from custom authorize_options" do @options = {:authorize_options => [:foo], :foo => ''} expect(subject.authorize_params['foo']).to eq('something') end end end end end describe '#authorize_params' do it 'should include any authorize params passed in the :authorize_params option' do @options = {:authorize_params => {:request_visible_actions => 'something', :foo => 'bar', :baz => 'zip'}, :hd => 'wow', :bad => 'not_included'} expect(subject.authorize_params['request_visible_actions']).to eq('something') expect(subject.authorize_params['foo']).to eq('bar') expect(subject.authorize_params['baz']).to eq('zip') expect(subject.authorize_params['hd']).to eq('wow') expect(subject.authorize_params['bad']).to eq(nil) end end describe '#token_params' do it 'should include any token params passed in the :token_params option' do @options = {:token_params => {:foo => 'bar', :baz => 'zip'}} expect(subject.token_params['foo']).to eq('bar') expect(subject.token_params['baz']).to eq('zip') end end describe "#token_options" do it 'should include top-level options that are marked as :token_options' do @options = {:token_options => [:scope, :foo], :scope => 'bar', :foo => 'baz', :bad => 'not_included'} expect(subject.token_params['scope']).to eq('bar') expect(subject.token_params['foo']).to eq('baz') expect(subject.token_params['bad']).to eq(nil) end end describe '#callback_path' do it 'has the correct callback path' do expect(subject.callback_path).to eq('/auth/google_oauth2/callback') end end describe '#extra' do let(:client) do OAuth2::Client.new('abc', 'def') do |builder| builder.request :url_encoded builder.adapter :test do |stub| stub.get('/plus/v1/people/me/openIdConnect') {|env| [200, {'content-type' => 'application/json'}, '{"sub": "12345"}']} stub.get('/plus/v1/people/12345/people/visible') {|env| [200, {'content-type' => 'application/json'}, '[{"foo":"bar"}]']} end end end let(:access_token) { OAuth2::AccessToken.from_hash(client, {}) } before { subject.stub(:access_token => access_token) } describe 'id_token' do context 'when the id_token is passed into the access token' do let(:access_token) { OAuth2::AccessToken.from_hash(client, {'id_token' => 'xyz'}) } it 'should include id_token when set on the access_token' do expect(subject.extra).to include(:id_token => 'xyz') end end context 'when the id_token is missing' do it 'should not include id_token' do expect(subject.extra).not_to have_key(:id_token) end end end describe 'raw_info' do context 'when skip_info is true' do before { subject.options[:skip_info] = true } it 'should not include raw_info' do expect(subject.extra).not_to have_key(:raw_info) end end context 'when skip_info is false' do before { subject.options[:skip_info] = false } it 'should include raw_info' do expect(subject.extra[:raw_info]).to eq('sub' => '12345') end end end describe 'raw_friend_info' do context 'when skip_info is true' do before { subject.options[:skip_info] = true } it 'should not include raw_friend_info' do expect(subject.extra).not_to have_key(:raw_friend_info) end end context 'when skip_info is false' do before { subject.options[:skip_info] = false } context 'when skip_friends is true' do before { subject.options[:skip_friends] = true } it 'should not include raw_friend_info' do expect(subject.extra).not_to have_key(:raw_friend_info) end end context 'when skip_friends is false' do before { subject.options[:skip_friends] = false } it 'should not include raw_friend_info' do expect(subject.extra[:raw_friend_info]).to eq([{'foo' => 'bar'}]) end end end end end describe 'populate auth hash urls' do it 'should populate url map in auth hash if link present in raw_info' do allow(subject).to receive(:raw_info) { {'name' => 'Foo', 'profile' => 'https://plus.google.com/123456'} } expect(subject.info[:urls]['Google']).to eq('https://plus.google.com/123456') end it 'should not populate url map in auth hash if no link present in raw_info' do allow(subject).to receive(:raw_info) { {'name' => 'Foo'} } expect(subject.info).not_to have_key(:urls) end end describe 'image options' do it "should have no image if a picture isn't present" do @options = {:image_aspect_ratio => 'square'} allow(subject).to receive(:raw_info) { {'name' => 'User Without Pic'} } expect(subject.info[:image]).to be_nil end describe "when a picture is returned from google" do it 'should return the image with size specified in the `image_size` option' do @options = {:image_size => 50} allow(subject).to receive(:raw_info) { {'picture' => 'https://lh3.googleusercontent.com/url/photo.jpg'} } expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/s50/photo.jpg') end it 'should return the image with width and height specified in the `image_size` option' do @options = {:image_size => {:width => 50, :height => 40}} allow(subject).to receive(:raw_info) { {'picture' => 'https://lh3.googleusercontent.com/url/photo.jpg'} } expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/w50-h40/photo.jpg') end it 'should return square image when `image_aspect_ratio` is specified' do @options = {:image_aspect_ratio => 'square'} allow(subject).to receive(:raw_info) { {'picture' => 'https://lh3.googleusercontent.com/url/photo.jpg'} } expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/c/photo.jpg') end it 'should return square sized image when `image_aspect_ratio` and `image_size` is set' do @options = {:image_aspect_ratio => 'square', :image_size => 50} allow(subject).to receive(:raw_info) { {'picture' => 'https://lh3.googleusercontent.com/url/photo.jpg'} } expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/s50-c/photo.jpg') end it 'should return square sized image when `image_aspect_ratio` and `image_size` has height and width' do @options = {:image_aspect_ratio => 'square', :image_size => {:width => 50, :height => 40}} allow(subject).to receive(:raw_info) { {'picture' => 'https://lh3.googleusercontent.com/url/photo.jpg'} } expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/w50-h40-c/photo.jpg') end it 'should return original image if image url does not end in `photo.jpg`' do @options = {:image_size => 50} allow(subject).to receive(:raw_info) { {'picture' => 'https://lh3.googleusercontent.com/url/photograph.jpg'} } expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/photograph.jpg') end end it 'should return original image if no options are provided' do allow(subject).to receive(:raw_info) { {'picture' => 'https://lh3.googleusercontent.com/url/photo.jpg'} } expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/photo.jpg') end it 'should return correct image if google image url has double https' do allow(subject).to receive(:raw_info) { {'picture' => 'https:https://lh3.googleusercontent.com/url/photo.jpg'} } expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/photo.jpg') end end describe 'build_access_token' do it 'should use a hybrid authorization request_uri if this is an AJAX request with a code parameter' do allow(request).to receive(:xhr?).and_return(true) allow(request).to receive(:params).and_return('code' => 'valid_code') client = double(:client) auth_code = double(:auth_code) allow(client).to receive(:auth_code).and_return(auth_code) expect(subject).to receive(:client).and_return(client) expect(auth_code).to receive(:get_token).with('valid_code', { :redirect_uri => 'postmessage'}, {}) expect(subject).not_to receive(:orig_build_access_token) subject.build_access_token end it 'should read access_token from hash if this is not an AJAX request with a code parameter' do allow(request).to receive(:xhr?).and_return(false) allow(request).to receive(:params).and_return('id_token' => 'valid_id_token', 'access_token' => 'valid_access_token') expect(subject).to receive(:verify_token).with('valid_id_token', 'valid_access_token').and_return true expect(subject).to receive(:client).and_return(:client) token = subject.build_access_token expect(token).to be_instance_of(::OAuth2::AccessToken) expect(token.token).to eq('valid_access_token') expect(token.client).to eq(:client) end it 'should call super if this is not an AJAX request' do allow(request).to receive(:xhr?).and_return(false) allow(request).to receive(:params).and_return('code' => 'valid_code') expect(subject).to receive(:orig_build_access_token) subject.build_access_token end end describe 'verify_token' do before(:each) do subject.options.client_options[:connection_build] = proc do |builder| builder.request :url_encoded builder.adapter :test do |stub| stub.get('/oauth2/v2/tokeninfo?id_token=valid_id_token&access_token=valid_access_token') do |env| [200, {'Content-Type' => 'application/json; charset=UTF-8'}, MultiJson.encode( :issued_to => '000000000000.apps.googleusercontent.com', :audience => '000000000000.apps.googleusercontent.com', :user_id => '000000000000000000000', :scope => 'profile email', :expires_in => 3514, :email => 'me@example.com', :verified_email => true, :access_type => 'online' )] end stub.get('/oauth2/v2/tokeninfo?id_token=invalid_id_token&access_token=invalid_access_token') do |env| [400, {'Content-Type' => 'application/json; charset=UTF-8'}, MultiJson.encode(:error_description => 'Invalid Value')] end end end end it 'should verify token if access_token and id_token are valid and app_id equals' do subject.options.client_id = '000000000000.apps.googleusercontent.com' expect(subject.send(:verify_token, 'valid_id_token', 'valid_access_token')).to eq(true) end it 'should not verify token if access_token and id_token are valid but app_id is false' do expect(subject.send(:verify_token, 'valid_id_token', 'valid_access_token')).to eq(false) end it 'should raise error if access_token or id_token is invalid' do expect { subject.send(:verify_token, 'invalid_id_token', 'invalid_access_token') }.to raise_error(OAuth2::Error) end end end omniauth-google-oauth2-0.2.4/spec/spec_helper.rb 0000644 0000041 0000041 00000000065 12326755544 021631 0 ustar www-data www-data require File.join('bundler', 'setup') require 'rspec' omniauth-google-oauth2-0.2.4/.travis.yml 0000644 0000041 0000041 00000000323 12326755544 020167 0 ustar www-data www-data before_install: - gem update --system 2.1.11 language: ruby rvm: - "1.8.7" - "1.9.2" - "1.9.3" - "2.0.0" - "2.1.0" - "rbx" - "jruby" matrix: allow_failures: - rvm: "rbx" - rvm: "jruby" omniauth-google-oauth2-0.2.4/lib/ 0000755 0000041 0000041 00000000000 12326755544 016626 5 ustar www-data www-data omniauth-google-oauth2-0.2.4/lib/omniauth-google-oauth2.rb 0000644 0000041 0000041 00000000056 12326755544 023452 0 ustar www-data www-data require File.join('omniauth', 'google_oauth2') omniauth-google-oauth2-0.2.4/lib/omniauth/ 0000755 0000041 0000041 00000000000 12326755544 020452 5 ustar www-data www-data omniauth-google-oauth2-0.2.4/lib/omniauth/strategies/ 0000755 0000041 0000041 00000000000 12326755544 022624 5 ustar www-data www-data omniauth-google-oauth2-0.2.4/lib/omniauth/strategies/google_oauth2.rb 0000644 0000041 0000041 00000011171 12326755544 025710 0 ustar www-data www-data require 'omniauth/strategies/oauth2' module OmniAuth module Strategies class GoogleOauth2 < OmniAuth::Strategies::OAuth2 BASE_SCOPE_URL = "https://www.googleapis.com/auth/" BASE_SCOPES = %w[profile email openid] DEFAULT_SCOPE = "email,profile" option :name, 'google_oauth2' option :skip_friends, true option :authorize_options, [:access_type, :hd, :login_hint, :prompt, :request_visible_actions, :scope, :state, :redirect_uri, :include_granted_scopes] option :client_options, { :site => 'https://accounts.google.com', :authorize_url => '/o/oauth2/auth', :token_url => '/o/oauth2/token' } def authorize_params super.tap do |params| options[:authorize_options].each do |k| params[k] = request.params[k.to_s] unless [nil, ''].include?(request.params[k.to_s]) end raw_scope = params[:scope] || DEFAULT_SCOPE scope_list = raw_scope.split(" ").map {|item| item.split(",")}.flatten scope_list.map! { |s| s =~ /^https?:\/\// || BASE_SCOPES.include?(s) ? s : "#{BASE_SCOPE_URL}#{s}" } params[:scope] = scope_list.join(" ") params[:access_type] = 'offline' if params[:access_type].nil? session['omniauth.state'] = params[:state] if params['state'] end end uid { raw_info['sub'] || verified_email } info do prune!({ :name => raw_info['name'], :email => verified_email, :first_name => raw_info['given_name'], :last_name => raw_info['family_name'], :image => image_url, :urls => { 'Google' => raw_info['profile'] } }) end extra do hash = {} hash[:id_token] = access_token['id_token'] hash[:raw_info] = raw_info unless skip_info? hash[:raw_friend_info] = raw_friend_info(raw_info['sub']) unless skip_info? || options[:skip_friends] prune! hash end def raw_info @raw_info ||= access_token.get('https://www.googleapis.com/plus/v1/people/me/openIdConnect').parsed end def raw_friend_info(id) @raw_friend_info ||= access_token.get("https://www.googleapis.com/plus/v1/people/#{id}/people/visible").parsed end def custom_build_access_token if request.xhr? && request.params['code'] verifier = request.params['code'] client.auth_code.get_token(verifier, { :redirect_uri => 'postmessage'}.merge(token_params.to_hash(:symbolize_keys => true)), deep_symbolize(options.auth_token_params || {})) elsif verify_token(request.params['id_token'], request.params['access_token']) ::OAuth2::AccessToken.from_hash(client, request.params.dup) else orig_build_access_token end end alias_method :orig_build_access_token, :build_access_token alias :build_access_token :custom_build_access_token private def prune!(hash) hash.delete_if do |_, v| prune!(v) if v.is_a?(Hash) v.nil? || (v.respond_to?(:empty?) && v.empty?) end end def verified_email raw_info['email_verified'] ? raw_info['email'] : nil end def image_url original_url = raw_info['picture'] original_url = original_url.gsub("https:https://", "https://") if original_url params_index = original_url.index('/photo.jpg') if original_url if params_index && image_size_opts_passed? original_url.insert(params_index, image_params) else original_url end end def image_size_opts_passed? !!(options[:image_size] || options[:image_aspect_ratio]) end def image_params image_params = [] if options[:image_size].is_a?(Integer) image_params << "s#{options[:image_size]}" elsif options[:image_size].is_a?(Hash) image_params << "w#{options[:image_size][:width]}" if options[:image_size][:width] image_params << "h#{options[:image_size][:height]}" if options[:image_size][:height] end image_params << 'c' if options[:image_aspect_ratio] == 'square' '/' + image_params.join('-') end def verify_token(id_token, access_token) return false unless (id_token && access_token) raw_response = client.request(:get, 'https://www.googleapis.com/oauth2/v2/tokeninfo', :params => { :id_token => id_token, :access_token => access_token }).parsed raw_response['issued_to'] == options.client_id end end end end omniauth-google-oauth2-0.2.4/lib/omniauth/google_oauth2/ 0000755 0000041 0000041 00000000000 12326755544 023210 5 ustar www-data www-data omniauth-google-oauth2-0.2.4/lib/omniauth/google_oauth2/version.rb 0000644 0000041 0000041 00000000105 12326755544 025216 0 ustar www-data www-data module OmniAuth module GoogleOauth2 VERSION = "0.2.4" end end omniauth-google-oauth2-0.2.4/lib/omniauth/google_oauth2.rb 0000644 0000041 0000041 00000000074 12326755544 023536 0 ustar www-data www-data require File.join('omniauth', 'strategies', 'google_oauth2') omniauth-google-oauth2-0.2.4/metadata.yml 0000644 0000041 0000041 00000005303 12326755544 020364 0 ustar www-data www-data --- !ruby/object:Gem::Specification name: omniauth-google-oauth2 version: !ruby/object:Gem::Version version: 0.2.4 platform: ruby authors: - Josh Ellithorpe - Yury Korolev autorequire: bindir: bin cert_chain: [] date: 2014-04-25 00:00:00.000000000 Z dependencies: - !ruby/object:Gem::Dependency name: omniauth requirement: !ruby/object:Gem::Requirement requirements: - - ~> - !ruby/object:Gem::Version version: '1.0' type: :runtime prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - ~> - !ruby/object:Gem::Version version: '1.0' - !ruby/object:Gem::Dependency name: omniauth-oauth2 requirement: !ruby/object:Gem::Requirement requirements: - - ~> - !ruby/object:Gem::Version version: '1.1' type: :runtime prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - ~> - !ruby/object:Gem::Version version: '1.1' - !ruby/object:Gem::Dependency name: rspec requirement: !ruby/object:Gem::Requirement requirements: - - ! '>=' - !ruby/object:Gem::Version version: 2.14.0 type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - ! '>=' - !ruby/object:Gem::Version version: 2.14.0 - !ruby/object:Gem::Dependency name: rake requirement: !ruby/object:Gem::Requirement requirements: - - ! '>=' - !ruby/object:Gem::Version version: '0' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - ! '>=' - !ruby/object:Gem::Version version: '0' description: A Google OAuth2 strategy for OmniAuth 1.x email: - quest@mac.com executables: [] extensions: [] extra_rdoc_files: [] files: - .gitignore - .travis.yml - Gemfile - README.md - Rakefile - examples/Gemfile - examples/config.ru - examples/omni_auth.rb - lib/omniauth-google-oauth2.rb - lib/omniauth/google_oauth2.rb - lib/omniauth/google_oauth2/version.rb - lib/omniauth/strategies/google_oauth2.rb - omniauth-contrib.gemspec - spec/omniauth/strategies/google_oauth2_spec.rb - spec/spec_helper.rb homepage: '' licenses: [] metadata: {} post_install_message: rdoc_options: [] require_paths: - lib required_ruby_version: !ruby/object:Gem::Requirement requirements: - - ! '>=' - !ruby/object:Gem::Version version: '0' required_rubygems_version: !ruby/object:Gem::Requirement requirements: - - ! '>=' - !ruby/object:Gem::Version version: '0' requirements: [] rubyforge_project: rubygems_version: 2.0.7 signing_key: specification_version: 4 summary: A Google OAuth2 strategy for OmniAuth 1.x test_files: [] omniauth-google-oauth2-0.2.4/.gitignore 0000644 0000041 0000041 00000000313 12326755544 020045 0 ustar www-data www-data *.gem *.rbc .bundle .config .yardoc .ruby-gemset .ruby-version .rvmrc Gemfile.lock InstalledFiles _yardoc coverage doc/ lib/bundler/man pkg rdoc spec/reports test/tmp test/version_tmp tmp .powenv .idea/ omniauth-google-oauth2-0.2.4/checksums.yaml.gz 0000444 0000041 0000041 00000000652 12326755544 021351 0 ustar www-data www-data _ZSAk0nYlž|Hcl6tsKC 8wv}oޛ~{zY|~%Iu~N%$K0xױ;@CZXzVs0u;chv 3[`)K?K;u97V'kN6sgcUaKZM 4&b]dyδ*u(QbM@*5r @U8Ч9`^M dM!8~LhƮ A3:ucb[·q !Qcgp%:Cnhfpl; r ~b4A.ډ_-2yaBjΫJQ*u~NpoU [7t\gP ғܝ7Vre omniauth-google-oauth2-0.2.4/README.md 0000644 0000041 0000041 00000026136 12326755544 017347 0 ustar www-data www-data # OmniAuth Google OAuth2 Strategy Strategy to authenticate with Google via OAuth2 in OmniAuth. Get your API key at: https://code.google.com/apis/console/ Note the Client ID and the Client Secret. For more details, read the Google docs: https://developers.google.com/accounts/docs/OAuth2 ## Installation Add to your `Gemfile`: ```ruby gem "omniauth-google-oauth2" ``` Then `bundle install`. ## Usage Here's an example for adding the middleware to a Rails app in `config/initializers/omniauth.rb`: ```ruby Rails.application.config.middleware.use OmniAuth::Builder do provider :google_oauth2, ENV["GOOGLE_CLIENT_ID"], ENV["GOOGLE_CLIENT_SECRET"] end ``` You can now access the OmniAuth Google OAuth2 URL: `/auth/google_oauth2` For more examples please check out `examples/omni_auth.rb` NOTE: While developing your application, if you change the scope in the initializer you will need to restart your app server. ## Configuration You can configure several options, which you pass in to the `provider` method via a hash: * `scope`: A comma-separated list of permissions you want to request from the user. See the [Google OAuth 2.0 Playground](https://developers.google.com/oauthplayground/) for a full list of available permissions. Caveats: * The `email` and `profile` scopes are used by default. By defining your own `scope`, you override these defaults. If you need these scopes, don't forget to add them yourself! * Scopes starting with `https://www.googleapis.com/auth/` do not need that prefix specified. So while you can use the smaller scope `books` since that permission starts with the mentioned prefix, you should use the full scope URL `https://docs.google.com/feeds/` to access a user's docs, for example. * `prompt`: A space-delimited list of string values that determines whether the user is re-prompted for authentication and/or consent. Possible values are: * `none`: No authentication or consent pages will be displayed; it will return an error if the user is not already authenticated and has not pre-configured consent for the requested scopes. This can be used as a method to check for existing authentication and/or consent. * `consent`: The user will always be prompted for consent, even if he has previously allowed access a given set of scopes. * `select_account`: The user will always be prompted to select a user account. This allows a user who has multiple current account sessions to select one amongst them. If no value is specified, the user only sees the authentication page if he is not logged in and only sees the consent page the first time he authorizes a given set of scopes. * `image_aspect_ratio`: The shape of the user's profile picture. Possible values are: * `original`: Picture maintains its original aspect ratio. * `square`: Picture presents equal width and height. Defaults to `original`. * `image_size`: The size of the user's profile picture. The image returned will have width equal to the given value and variable height, according to the `image_aspect_ratio` chosen. Additionally, a picture with specific width and height can be requested by setting this option to a hash with `width` and `height` as keys. If only `width` or `height` is specified, a picture whose width or height is closest to the requested size and requested aspect ratio will be returned. Defaults to the original width and height of the picture. * `name`: The name of the strategy. The default name is `google_oauth2` but it can be changed to any value, for example `google`. The OmniAuth URL will thus change to `/auth/google` and the `provider` key in the auth hash will then return `google`. * `access_type`: Defaults to `offline`, so a refresh token is sent to be used when the user is not present at the browser. Can be set to `online`. Note that if you need a refresh token, google requires you to also to specify the option `prompt: 'consent'`, which is not a default. * `login_hint`: When your app knows which user it is trying to authenticate, it can provide this parameter as a hint to the authentication server. Passing this hint suppresses the account chooser and either pre-fill the email box on the sign-in form, or select the proper session (if the user is using multiple sign-in), which can help you avoid problems that occur if your app logs in the wrong user account. The value can be either an email address or the sub string, which is equivalent to the user's Google+ ID. * `include_granted_scopes`: If this is provided with the value true, and the authorization request is granted, the authorization will include any previous authorizations granted to this user/application combination for other scopes. See Google's [Incremental Autorization](https://developers.google.com/accounts/docs/OAuth2WebServer#incrementalAuth) for additional details. Here's an example of a possible configuration where the strategy name is changed, the user is asked for extra permissions, the user is always prompted to select his account when logging in and the user's profile picture is returned as a thumbnail: ```ruby Rails.application.config.middleware.use OmniAuth::Builder do provider :google_oauth2, ENV["GOOGLE_CLIENT_ID"], ENV["GOOGLE_CLIENT_SECRET"], { :name => "google", :scope => "email, profile, plus.me, http://gdata.youtube.com", :prompt => "select_account", :image_aspect_ratio => "square", :image_size => 50 } end ``` ## Auth Hash Here's an example of an authentication hash available in the callback by accessing `request.env["omniauth.auth"]`: ```ruby { :provider => "google_oauth2", :uid => "123456789", :info => { :name => "John Doe", :email => "john@company_name.com", :first_name => "John", :last_name => "Doe", :image => "https://lh3.googleusercontent.com/url/photo.jpg" }, :credentials => { :token => "token", :refresh_token => "another_token", :expires_at => 1354920555, :expires => true }, :extra => { :raw_info => { :sub => "123456789", :email => "user@domain.example.com", :email_verified => true, :name => "John Doe", :given_name => "John", :family_name => "Doe", :profile => "https://plus.google.com/123456789", :picture => "https://lh3.googleusercontent.com/url/photo.jpg", :gender => "male", :birthday => "0000-06-25", :locale => "en", :hd => "company_name.com" } } } ``` ### Devise For devise, you should also make sure you have an OmniAuth callback controller setup ```ruby class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController def google_oauth2 # You need to implement the method below in your model (e.g. app/models/user.rb) @user = User.find_for_google_oauth2(request.env["omniauth.auth"], current_user) if @user.persisted? flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Google" sign_in_and_redirect @user, :event => :authentication else session["devise.google_data"] = request.env["omniauth.auth"] redirect_to new_user_registration_url end end end ``` and bind to or create the user ```ruby def self.find_for_google_oauth2(access_token, signed_in_resource=nil) data = access_token.info user = User.where(:email => data["email"]).first unless user user = User.create(name: data["name"], email: data["email"], password: Devise.friendly_token[0,20] ) end user end ``` Detailed example at https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview#google-oauth2-example ### One-time Code Flow (Hybrid Authentication) Google describes the One-time Code Flow [here](https://developers.google.com/+/web/signin/server-side-flow). This hybrid authentication flow has significant functional and security advantages over a pure server-side or pure client-side flow. The following steps occur in this flow: 1. The client (web browser) authenticates the user directly via Google's JS API. During this process assorted modals may be rendered by Google. 2. On successful authentication, Google returns a one-time use code, which requires the Google client secret (which is only available server-side). 3. Using a AJAX request, the code is POSTed to the Omniauth Google OAuth2 callback. 4. The Omniauth Google OAuth2 gem will validate the code via a server-side request to Google. If the code is valid, then Google will return an access token and, if this is the first time this user is authenticating against this application, a refresh token. Both of these should be stored on the server. The response to the AJAX request indicates the success or failure of this process. This flow is immune to replay attacks, and conveys no useful information to a man in the middle. The omniauth-google-oauth2 gem supports this mode of operation out of the box. Implementors simply need to add the appropriate JavaScript to their web page, and they can take advantage of this flow. An example JavaScript snippet follows. ```javascript jQuery(function() { return $.ajax({ url: 'https://apis.google.com/js/client:plus.js?onload=gpAsyncInit', dataType: 'script', cache: true }); }); window.gpAsyncInit = function() { $('.googleplus-login').click(function(e) { e.preventDefault(); gapi.auth.authorize({ immediate: true, response_type: 'code', cookie_policy: 'single_host_origin', client_id: '000000000000.apps.googleusercontent.com', scope: 'email profile' }, function(response) { if (response && !response.error) { // google authentication succeed, now post data to server and handle data securely jQuery.ajax({type: 'POST', url: "/auth/google_oauth2/callback", dataType: 'json', data: response, success: function(json) { // response from server }); } else { // google authentication failed } }); }); }; ``` ## Build Status [](https://travis-ci.org/zquestz/omniauth-google-oauth2) ## License Copyright (c) 2013 by Josh Ellithorpe 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.