Skip to content

Instantly share code, notes, and snippets.

@yury
Created October 31, 2011 07:35
Show Gist options
  • Save yury/1327076 to your computer and use it in GitHub Desktop.
Save yury/1327076 to your computer and use it in GitHub Desktop.
OmniAuth Devise
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def facebook
create_auth
end
def twitter
create_auth
end
def google
create_auth
end
private
def omniauth
@omniauth ||= (env["omniauth.auth"] || {}).except("extra")
end
def create_auth
data = omniauth['user_info']
@uid ||= omniauth['uid']
@provider ||= omniauth['provider'] || params[:action]
@email ||= data['email']
@auth = Api::V2::Service.where(provider: @provider, uid: @uid).first
user_signed_in? ? handle_signed_in_user : handle_not_signed_in_user
end
def handle_signed_in_user
# the user is currently signed in
try_to_update_avatar current_user
# check if this service is already linked to his/her account,
# if not, add it
if @auth
flash[:notice] = I18n.t 'devise.omniauth_callbacks.success',
kind: @provider.capitalize
redirect_to services_path
else
current_user.services.create(provider: @provider,
uid: @uid,
auth: omniauth)
flash[:notice] = I18n.t 'devise.omniauth_callbacks.success', kind: @provider.capitalize
redirect_to services_path
end
end
def handle_not_signed_in_user
# check if user has already signed in using this service provider and
# continue with sign in process if yes
if @auth
flash[:notice] = I18n.t 'devise.omniauth_callbacks.success', kind: @provider.capitalize
sign_in_and_redirect(:user, @auth.user)
else
# search for a user with this email address
if existing_user = Api::V2::User.where(email:(@email || '').downcase).first
try_to_update_avatar existing_user
# map this new login method via a service provider to an existing account if the email address is the same
existing_user.services.create(provider: @provider,
uid: @uid,
auth: omniauth)
flash[:notice] = I18n.t 'devise.omniauth_callbacks.success',
kind: @provider.capitalize
sign_in_and_redirect(:user, existing_user)
else
session["devise.omniauth"] = omniauth
user = Api::V2::User.new_with_session(params, session)
# do not send confirmation email, we directly save and confirm
# the new document
if user.valid?
user.skip_confirmation!
user.save!
user.confirm!
flash[:notice] = I18n.t 'devise.omniauth_callbacks.success',
kind: @provider.capitalize
sign_in_and_redirect(:user, user)
else
flash[:notice] = I18n.t 'devise.omniauth_callbacks.more_fields_to_fill'
redirect_to new_user_registration_path
end
end
end
end
private
def try_to_update_avatar user
# We don't support avatars yet
# if user.avatar.blank?
# user.remote_avatar_url = omniauth['user_info']['image']
# user.save
# end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment