A Ruby on Rails app with authentication provided through the devise gem
- Go to https://console.developers.google.com and create your project.
- In your new project, enable the Google+ API and Contacts API.
- Go to Credentials, then select the "OAuth consent screen" tab on top, and provide your email address and product name.
- When directed to do so, create your credentials. Select Oauth client ID. Select "web application" as the application type, "http://localhost:3000" as the authorized Javascript origin, and "http://localhost:3000/oath2callback" as the authorized redirect URI.
- Get the client ID and client secret codes. You will need them to configure your source code.
- Add the following lines to the Gemfile:
gem 'omniauth'
gem 'omniauth-google-oauth2'
- In the command line shell, use the "bundle install" command to install these gems.
- Add the following line to app/models/user.rb:
devise :omniauthable, :omniauth_providers => [:google_oauth2]
- Add the following lines to app/models/user.rb:
def self.find_for_google_oauth2(access_token, signed_in_resource=nil)
data = access_token.info
user = User.where(:provider => access_token.provider, :uid => access_token.uid ).first
if user
return user
else
registered_user = User.where(:email => access_token.info.email).first
if registered_user
return registered_user
else
user = User.create(name: data["name"],
provider:access_token.provider,
email: data["email"],
uid: access_token.uid ,
password: Devise.friendly_token[0,20],
)
end
end
end
- Enter the following commands:
rails g migration AddProviderToUsers provider:string uid:string
bundle exec rake db:migrate
Add the text "omniauth_callbacks: 'users/omniauth_callbacks'" to the "devise_for :users, controllers: {}" section. The end result should look something like:
devise_for :users, controllers: { sessions: 'users/sessions',
passwords: 'users/passwords', registrations: 'users/registrations',
confirmations: 'users/confirmations',
omniauth_callbacks: 'users/omniauth_callbacks' }
Add the following lines:
Rails.application.config.middleware.use OmniAuth::Builder do
provider :google_oauth2, ENV["GOOGLE_CLIENT_ID"], ENV["GOOGLE_CLIENT_SECRET"]
end
Add the following lines to config/initializers/devise.rb:
require 'omniauth-google-oauth2'
config.omniauth :google_oauth2, 'APP_ID', 'APP_SECRET', { access_type: 'offline', approval_prompt: '' }
Add the following lines within the pre-existing class:
def google_oauth2
@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
Add the following line:
<%= link_to "Sign in with Google", user_omniauth_authorize_path(:google_oauth2) %>