Skip to content

Commit

Permalink
Rubocop refactor and general cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
zquestz committed May 30, 2017
1 parent ca584d2 commit 5ca2302
Show file tree
Hide file tree
Showing 16 changed files with 374 additions and 295 deletions.
18 changes: 18 additions & 0 deletions .rubocop.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
ClassLength:
Enabled: false
Layout/IndentHeredoc:
Enabled: false
Metrics/AbcSize:
Enabled: false
Metrics/BlockLength:
ExcludedMethods: ['describe', 'context']
Metrics/CyclomaticComplexity:
Enabled: false
Metrics/LineLength:
Enabled: false
Metrics/MethodLength:
Enabled: false
Metrics/PerceivedComplexity:
Enabled: false
Style/FileName:
Enabled: false
9 changes: 6 additions & 3 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,19 +1,22 @@
# Changelog
All notable changes to this project will be documented in this file.

## 0.5.0 - 2017-02-13
## 0.5.0 - 2017-05-29

### Added
- Nothing.
- Rubocop checks to specs.
- Defaulted dev environment to ruby 2.3.4.

### Deprecated
- Nothing.

### Removed
- Testing support for older versions of ruby not supported by OmniAuth 1.5.
- Key `[:urls]['Google']` no longer exists, it has been renamed to `[:urls][:google]`.

### Fixed
- Nothing.
- Updated all code to rubocop conventions. This includes the Ruby 1.9 hash syntax when appropriate.
- Example javascript flow now picks up ENV vars for google key and secret.

## 0.4.1 - 2016-03-14

Expand Down
7 changes: 2 additions & 5 deletions Gemfile
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
# frozen_string_literal: true

source 'https://rubygems.org'

gemspec

group :example do
gem 'sinatra'
gem 'rack', '~> 1.6.0'
end
128 changes: 65 additions & 63 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ For more details, read the Google docs: https://developers.google.com/accounts/d
Add to your `Gemfile`:

```ruby
gem "omniauth-google-oauth2"
gem 'omniauth-google-oauth2'
```

Then `bundle install`.
Expand All @@ -36,7 +36,7 @@ Here's an example for adding the middleware to a Rails app in `config/initialize

```ruby
Rails.application.config.middleware.use OmniAuth::Builder do
provider :google_oauth2, ENV["GOOGLE_CLIENT_ID"], ENV["GOOGLE_CLIENT_SECRET"]
provider :google_oauth2, ENV['GOOGLE_CLIENT_ID'], ENV['GOOGLE_CLIENT_SECRET']
end
```

Expand Down Expand Up @@ -91,66 +91,69 @@ Here's an example of a possible configuration where the strategy name is changed

```ruby
Rails.application.config.middleware.use OmniAuth::Builder do
provider :google_oauth2, ENV["GOOGLE_CLIENT_ID"], ENV["GOOGLE_CLIENT_SECRET"],
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
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"]`:
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
"provider" => "google_oauth2",
"uid" => "100000000000000000000",
"info" => {
"name" => "John Smith",
"email" => "[email protected]",
"first_name" => "John",
"last_name" => "Smith",
"image" => "https://lh4.googleusercontent.com/photo.jpg",
"urls" => {
"google" => "https://plus.google.com/+JohnSmith"
}
},
"credentials" => {
"token" => "TOKEN",
"refresh_token" => "REFRESH_TOKEN",
"expires_at" => 1496120719,
"expires" => true
},
"extra" => {
"id_token" => "ID_TOKEN",
"id_info" => {
"azp" => "APP_ID",
"aud" => "APP_ID",
"sub" => "100000000000000000000",
"email" => "[email protected]",
"email_verified" => true,
"at_hash" => "HK6E_P6Dh8Y93mRNtsDB1Q",
"iss" => "accounts.google.com",
"iat" => 1496117119,
"exp" => 1496120719
},
:extra => {
:raw_info => {
:sub => "123456789",
:email => "[email protected]",
: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"
},
:id_info => {
"iss" => "accounts.google.com",
"at_hash" => "HK6E_P6Dh8Y93mRNtsDB1Q",
"email_verified" => "true",
"sub" => "10769150350006150715113082367",
"azp" => "APP_ID",
"email" => "[email protected]",
"aud" => "APP_ID",
"iat" => 1353601026,
"exp" => 1353604926,
"openid_id" => "https://www.google.com/accounts/o8/id?id=ABCdfdswawerSDFDsfdsfdfjdsf"
}
"raw_info" => {
"kind" => "plus#personOpenIdConnect",
"gender" => "male",
"sub" => "100000000000000000000",
"name" => "John Smith",
"given_name" => "John",
"family_name" => "Smith",
"profile" => "https://plus.google.com/+JohnSmith",
"picture" => "https://lh4.googleusercontent.com/photo.jpg?sz=50",
"email" => "[email protected]",
"email_verified" => "true",
"locale" => "en",
"hd" => "company.com"
}
}
}
```

Expand All @@ -161,19 +164,19 @@ First define your application id and secret in `config/initializers/devise.rb`.
Configuration options can be passed as the last parameter here as key/value pairs.

```ruby
config.omniauth :google_oauth2, "GOOGLE_CLIENT_ID", "GOOGLE_CLIENT_SECRET", { }
config.omniauth :google_oauth2, 'GOOGLE_CLIENT_ID', 'GOOGLE_CLIENT_SECRET', {}
```

Then add the following to 'config/routes.rb' so the callback routes are defined.

```ruby
devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" }
devise_for :users, controllers: { omniauth_callbacks: 'users/omniauth_callbacks' }
```

Make sure your model is omniauthable. Generally this is "/app/models/user.rb"

```ruby
devise :omniauthable, :omniauth_providers => [:google_oauth2]
devise :omniauthable, omniauth_providers: [:google_oauth2]
```

Then make sure your callbacks controller is setup.
Expand All @@ -182,13 +185,13 @@ Then make sure your callbacks controller is setup.
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.from_omniauth(request.env["omniauth.auth"])
@user = User.from_omniauth(request.env['omniauth.auth'])

if @user.persisted?
flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Google"
sign_in_and_redirect @user, :event => :authentication
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"].except(:extra) #Removing extra as it can overflow some session stores
session['devise.google_data'] = request.env['omniauth.auth'].except(:extra) #Removing extra as it can overflow some session stores
redirect_to new_user_registration_url, alert: @user.errors.full_messages.join("\n")
end
end
Expand All @@ -200,12 +203,12 @@ and bind to or create the user
```ruby
def self.from_omniauth(access_token)
data = access_token.info
user = User.where(:email => data["email"]).first
user = User.where(email: data['email']).first

# Uncomment the section below if you want users to be created if they don't exist
# unless user
# user = User.create(name: data["name"],
# email: data["email"],
# user = User.create(name: data['name'],
# email: data['email'],
# password: Devise.friendly_token[0,20]
# )
# end
Expand Down Expand Up @@ -269,8 +272,7 @@ window.gpAsyncInit = function() {
}, function(response) {
if (response && !response.error) {
// google authentication succeed, now post data to server.
jQuery.ajax({type: 'POST', url: "/auth/google_oauth2/callback",
data: response,
jQuery.ajax({type: 'POST', url: '/auth/google_oauth2/callback', data: response,
success: function(data) {
// response from server
}
Expand Down Expand Up @@ -305,7 +307,7 @@ OmniAuth.config.full_host = Rails.env.production? ? 'https://domain.com' : 'http

## License

Copyright (c) 2016 by Josh Ellithorpe
Copyright (c) 2017 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:

Expand Down
5 changes: 3 additions & 2 deletions Rakefile
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
#!/usr/bin/env rake
# frozen_string_literal: true

require File.join('bundler', 'gem_tasks')
require File.join('rspec', 'core', 'rake_task')

RSpec::Core::RakeTask.new(:spec)

task :default => :spec
task default: :spec
6 changes: 4 additions & 2 deletions examples/Gemfile
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
# frozen_string_literal: true

source 'https://rubygems.org'

gem 'sinatra'
gem 'omniauth-google-oauth2'
gem 'omniauth-google-oauth2', '~> 0.5'
gem 'sinatra', '~> 1.4'
29 changes: 22 additions & 7 deletions examples/config.ru
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
# frozen_string_literal: true

# Sample app for Google OAuth2 Strategy
# Make sure to setup the ENV variables GOOGLE_KEY and GOOGLE_SECRET
# Run with "bundle exec rackup"
Expand All @@ -15,6 +17,7 @@ require 'omniauth-google-oauth2'
# http://railsapps.github.io/openssl-certificate-verify-failed.html
OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE

# Main example app for omniauth-google-oauth2
class App < Sinatra::Base
get '/' do
<<-HTML
Expand All @@ -37,7 +40,7 @@ class App < Sinatra::Base
immediate: true,
response_type: 'code',
cookie_policy: 'single_host_origin',
client_id: 'YOUR_CLIENT_ID',
client_id: '#{ENV['GOOGLE_KEY']}',
scope: 'email profile'
}, function(response) {
return;
Expand All @@ -48,7 +51,7 @@ class App < Sinatra::Base
immediate: false,
response_type: 'code',
cookie_policy: 'single_host_origin',
client_id: 'YOUR_CLIENT_ID',
client_id: '#{ENV['GOOGLE_KEY']}',
scope: 'email profile'
}, function(response) {
if (response && !response.error) {
Expand Down Expand Up @@ -80,26 +83,38 @@ class App < Sinatra::Base

post '/auth/:provider/callback' do
content_type 'text/plain'
request.env['omniauth.auth'].to_hash.inspect rescue "No Data"
begin
request.env['omniauth.auth'].to_hash.inspect
rescue
'No Data'
end
end

get '/auth/:provider/callback' do
content_type 'text/plain'
request.env['omniauth.auth'].to_hash.inspect rescue "No Data"
begin
request.env['omniauth.auth'].to_hash.inspect
rescue
'No Data'
end
end

get '/auth/failure' do
content_type 'text/plain'
request.env['omniauth.auth'].to_hash.inspect rescue "No Data"
begin
request.env['omniauth.auth'].to_hash.inspect
rescue
'No Data'
end
end
end

use Rack::Session::Cookie, :secret => ENV['RACK_COOKIE_SECRET']
use Rack::Session::Cookie, secret: ENV['RACK_COOKIE_SECRET']

use OmniAuth::Builder do
# For additional provider examples please look at 'omni_auth.rb'
# The key provider_ignores_state is only for AJAX flows. It is not recommended for normal logins.
provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET'], {access_type: "offline", prompt: "consent", provider_ignores_state: true, scope: 'email,profile,calendar'}
provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET'], access_type: 'offline', prompt: 'consent', provider_ignores_state: true, scope: 'email,profile,calendar'
end

run App.new
Loading

0 comments on commit 5ca2302

Please sign in to comment.