Skip to content

Instantly share code, notes, and snippets.

@FsDevNinja
Created November 17, 2016 18:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FsDevNinja/20b55eb9b1656426a5ca172da964691a to your computer and use it in GitHub Desktop.
Save FsDevNinja/20b55eb9b1656426a5ca172da964691a to your computer and use it in GitHub Desktop.
Omniauth and Devise Solution to get Facebook, Twitter and Google login authentication.
class OmniauthCallbacksController < Devise::OmniauthCallbacksController
def twitter
@player = Player.from_omniauth(request.env["omniauth.auth"])
if @player.persisted?
sign_in_and_redirect @player
set_flash_message(:notice, :success, :kind => twitter) if is_navigational_format?
else
redirect_to new_player_registration_url
end
end
def google
@player = Player.from_omniauth(request.env["omniauth.auth"])
if @player.persisted?
sign_in_and_redirect @player
set_flash_message(:notice, :success, :kind => "Google") if is_navigational_format?
else
redirect_to new_player_registration_url
end
end
def facebook
@player = Player.from_omniauth(request.env["omniauth.auth"])
if @player.persisted?
sign_in_and_redirect @player, :event => :authentication
set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format?
else
redirect_to new_player_registration_url
end
end
def failure
redirect_to root_path
end
end
class Player < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :omniauthable, :omniauth_providers => [:facebook,:twitter, :google]
def self.from_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_create do |player|
player.provider = auth.provider
player.uid = auth.uid
if player.provider == "twitter"
player.email = "#{auth.info.nickname}@twitter.com"
else
player.email = auth.info.email
end
player.password = Devise.friendly_token[0,20]
end
end
end
Rails.application.routes.draw do
devise_for :players, :controllers => { :omniauth_callbacks => "omniauth_callbacks" }
end
Devise.setup do |config|
#...
config.omniauth :facebook, ENV['FACEBOOK_KEY'], ENV['FACEBOOK_SECRET']
config.omniauth :twitter, ENV['TWITTER_KEY'], ENV['TWITTER_SECRET']
config.omniauth :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET'], name: 'google'
#...
end
#...
gem 'devise'
gem 'omniauth-twitter'
gem 'omniauth-facebook'
gem "omniauth-google-oauth2"
gem "figaro"
#...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment