Last active
April 28, 2023 21:23
-
-
Save lasley/84697a4f31872b41a75a3e7280d3242e to your computer and use it in GitHub Desktop.
Sample Devise Implementation w/ OmniAuth
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class OmniauthCallbacksController < Devise::OmniauthCallbacksController | |
alias_method :facebook, :do_omniauth | |
alias_method :google, :do_omniauth | |
# It provides central callback for OmniAuth | |
def do_omniauth | |
@user = User.from_omniauth(request.env['omniauth.auth']) | |
provider_kind = @user.provider.capitalize | |
if @user.persisted? | |
# This will throw if @user is not activated | |
sign_in_and_redirect @user, :event => :authentication | |
if is_navigational_format? | |
set_flash_message(:notice, :success, :kind => provider_kind) | |
end | |
else | |
redirect_to new_user_registration_url | |
end | |
end | |
def failure | |
redirect_to root_path | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class User < ActiveRecord::Base | |
devise :database_authenticatable, :registerable, | |
:recoverable, :rememberable, :trackable, :validatable, | |
:omniauthable, :omniauth_providers => [:google, :facebook] | |
def self.from_omniauth(auth) | |
where(provider: auth.provider, uid: auth.uid).first_or_create do |user| | |
user.email = auth.info.email | |
user.password = Devise.friendly_token[0,20] | |
end | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Devise.setup do |config| | |
# Credentials | |
config.omniauth :facebook, ENV['FACEBOOK_CLIENT_ID'], ENV['FACEBOOK_CLIENT_SECRET'] | |
config.omniauth :google_oauth2, ENV['GOOGLE_CLIENT_ID'], ENV['GOOGLE_CLIENT_SECRET'], name: 'google' | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
MyApplication::Application.routes.draw do | |
devise_for :users, :controllers => { :omniauth_callbacks => "omniauth_callbacks" } | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
gem 'devise' | |
# ENV variable management | |
gem 'figaro' | |
# OmniAuth Authentication providers | |
gem 'omniauth-google-oauth2' | |
gem 'omniauth-facebook' | |
group :development, :test do | |
gem 'capybara' | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rails_helper' | |
RSpec.describe OmniauthCallbacksController, :type => :controller do | |
before(:each) do | |
request.env['devise.mapping'] = Devise.mappings[:user] | |
end | |
describe 'Facebook' do | |
context 'Success handling' do | |
before(:each) do | |
request.env['omniauth.auth'] = FactoryGirl.create(:auth_hash, :facebook) | |
get :facebook | |
end | |
let(:user) { User.find_by(email: '[email protected]') } | |
it 'should set :notice flash' do | |
expect(flash[:notice]).to exist | |
end | |
it 'should set current_user to proper user' do | |
expect(subject.current_user).to eq(user) | |
end | |
end | |
context 'Non-persisting User' do | |
before(:each) do | |
request.env['omniauth.auth'] = FactoryGirl.create( | |
:auth_hash, :facebook, :does_not_persist | |
) | |
get :facebook | |
end | |
it 'should redirect to new user registration' do | |
expect(response).to redirect_to new_user_registration_url | |
end | |
it 'should set flash :notice' do | |
expect(flash[:notice]).to exist | |
end | |
end | |
end | |
describe 'Google' do | |
context 'Success handling' do | |
before(:each) do | |
request.env['omniauth.auth'] = FactoryGirl.create(:auth_hash, :google) | |
get :facebook | |
end | |
let(:user) { User.find_by(email: '[email protected]') } | |
it 'should set :notice flash' do | |
expect(flash[:notice]).to exist | |
end | |
it 'should set current_user to proper user' do | |
expect(subject.current_user).to eq(user) | |
end | |
end | |
end | |
describe 'Failure' do | |
after(:each) do | |
Rails.application.reload_routes! | |
end | |
before(:each) do | |
Rails.application.routes.draw do | |
devise_scope :user do | |
get '/users/auth/failure' => 'omniauth_callbacks#failure' | |
end | |
root 'static_pages#index' | |
end | |
get :failure | |
end | |
it 'should redirectto root path' do | |
expect(response).to redirect_to root_path | |
end | |
it 'should set flash :alert' do | |
expect(flash[:alert]).to exist | |
end | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
FactoryGirl.define do | |
# When calling auth_hash, use one of the traits listed below for a | |
# facebook user, google user or when testing a user who does not | |
# persist, use the does_not_persist trait. | |
factory :auth_hash, class: OmniAuth::AuthHash do | |
initialize_with do | |
OmniAuth::AuthHash.new({ | |
provider: provider, | |
uid: uid, | |
info: { | |
email: email | |
} | |
}) | |
end | |
trait :facebook do | |
provider "facebook" | |
sequence(:uid) | |
email "[email protected]" | |
end | |
trait :google do | |
provider "google" | |
sequence(:uid) | |
email "[email protected]" | |
end | |
trait :does_not_persist do | |
email "" | |
end | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This file is copied to spec/ when you run 'rails generate rspec:install' | |
ENV['RAILS_ENV'] ||= 'test' | |
require File.expand_path('../../config/environment', __FILE__) | |
# Prevent database truncation if the environment is production | |
abort("The Rails environment is running in production mode!") if Rails.env.production? | |
require 'spec_helper' | |
require 'rspec/rails' | |
# Add additional requires below this line. Rails is not loaded until this point! | |
# Requires supporting ruby files with custom matchers and macros, etc, in | |
# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are | |
# run as spec files by default. This means that files in spec/support that end | |
# in _spec.rb will both be required and run as specs, causing the specs to be | |
# run twice. It is recommended that you do not name files matching this glob to | |
# end with _spec.rb. You can configure this pattern with the --pattern | |
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`. | |
# | |
# The following line is provided for convenience purposes. It has the downside | |
# of increasing the boot-up time by auto-requiring all files in the support | |
# directory. Alternatively, in the individual `*_spec.rb` files, manually | |
# require only the support files necessary. | |
# | |
# Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f } | |
# Checks for pending migration and applies them before tests are run. | |
# If you are not using ActiveRecord, you can remove this line. | |
ActiveRecord::Migration.maintain_test_schema! | |
RSpec.configure do |config| | |
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures | |
config.fixture_path = "#{::Rails.root}/spec/fixtures" | |
# If you're not using ActiveRecord, or you'd prefer not to run each of your | |
# examples within a transaction, remove the following line or assign false | |
# instead of true. | |
config.use_transactional_fixtures = true | |
# RSpec Rails can automatically mix in different behaviours to your tests | |
# based on their file location, for example enabling you to call `get` and | |
# `post` in specs under `spec/controllers`. | |
# | |
# You can disable this behaviour by removing the line below, and instead | |
# explicitly tag your specs with their type, e.g.: | |
# | |
# RSpec.describe UsersController, :type => :controller do | |
# # ... | |
# end | |
# | |
# The different available types are documented in the features, such as in | |
# https://relishapp.com/rspec/rspec-rails/docs | |
config.infer_spec_type_from_file_location! | |
# Filter lines from Rails gems in backtraces. | |
config.filter_rails_from_backtrace! | |
# arbitrary gems may also be filtered via: | |
# config.filter_gems_from_backtrace("gem name") | |
# Simplify factory_girl syntax | |
config.include FactoryGirl::Syntax::Methods | |
# Clean up the test DB after each run by truncating all the tables | |
config.after :suite do | |
DatabaseCleaner.clean_with :truncation | |
end | |
# Turn on "test mode" for OmniAuth | |
OmniAuth.config.test_mode = true | |
# Include Devise TestHelpers | |
config.include Devise::TestHelpers, type: :controller | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment