Skip to content

Instantly share code, notes, and snippets.

@t0nylombardi
Last active May 5, 2016 23:49
Show Gist options
  • Save t0nylombardi/68194f1f867a24f0572c to your computer and use it in GitHub Desktop.
Save t0nylombardi/68194f1f867a24f0572c to your computer and use it in GitHub Desktop.
Code For OmniAuth
## omniauth_controller
class OmniauthCallbacksController < Devise::OmniauthCallbacksController
def facebook
@auth = request.env["omniauth.auth"]
@user ||= User.find_for_facebook_oauth(@auth)
if @user.persisted?
sign_in @user
redirect_to home_path
set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format?
else
session["devise.facebook_data"] = request.env["omniauth.auth"].except('extra')
redirect_to home_path
end
end
def destroy
reset_session
redirect_to root_url, :notice => 'Signed out!'
end
def failure
reset_session
redirect_to root_url, :alert => "Authentication error: #{params[:message]}"
end
end
## models/user.rb
class User < ActiveRecord::Base
# Relations
has_many :posts
has_one :profile
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:omniauthable, omniauth_providers: [:facebook]
# Validations
# :email
validates_format_of :email, with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
def self.find_for_facebook_oauth(auth)
if user = User.find_by_email(auth.info.email)
user
else
user = User.create(
provider: auth.provider,
uid: auth.uid,
email: auth.info.email,
password: Devise.friendly_token[0,20]
)
@username = '@' + auth.extra.raw_info.name.tr!(' ', '_').downcase
user.create_profile(
username: @username,
first_name: auth.info.first_name,
last_name: auth.info.last_name,
gender: auth.extra.raw_info.gender,
country: auth.extra.raw_info.locale,
image: auth.info.image
)
if auth.info.image.present?
user.profile.remote_image_url = auth.info.image
user.profile.save!
end
if auth.extra.raw_info.username.present?
user.profile.username = auth.extra.raw_info.username
user.profile.save!
else
user.profile.username = @username
end
user
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment