osem-fcy/app/controllers/users/omniauth_callbacks_controller.rb

40 lines
1.2 KiB
Ruby
Raw Normal View History

2014-06-18 17:09:14 +03:00
module Users
class OmniauthCallbacksController < Devise::OmniauthCallbacksController
skip_before_filter :verify_authenticity_token
2014-08-12 11:51:59 +03:00
skip_authorization_check
2014-06-18 16:58:30 +03:00
User.omniauth_providers.each do |provider|
2014-06-18 17:09:14 +03:00
define_method(provider) { handle(provider) }
end
2014-06-18 16:58:30 +03:00
2014-06-18 17:09:14 +03:00
private
2014-06-18 16:58:30 +03:00
2014-06-18 17:09:14 +03:00
def handle(provider)
2014-06-18 16:58:30 +03:00
auth_hash = request.env['omniauth.auth']
2014-11-04 17:42:47 +01:00
uid = auth_hash[:uid]
2014-06-18 16:58:30 +03:00
openid = Openid.find_for_oauth(auth_hash) # Get or create openid
# If openid exists and is associated with a user, sign in with associated user,
# even if the email of the associated user and the email of the provided openid are different
2014-07-21 14:27:32 +02:00
unless (user = openid.user)
2014-06-18 16:58:30 +03:00
user = User.find_for_auth(auth_hash, current_user) # Get or create users
2014-11-04 17:42:47 +01:00
user.username = "#{uid}@#{provider}" if user.username.blank?
2014-06-18 16:58:30 +03:00
end
begin
user.save!
if openid.user != user
openid.user = user
end
openid.save!
sign_in user
flash[:notice] = "#{user.email} signed in successfully with #{provider}"
redirect_to request.env['omniauth.origin'] || root_path
2014-07-21 14:37:26 +02:00
rescue => e
2014-11-04 17:42:47 +01:00
flash[:error] = e.message
redirect_back_or_to new_user_registration_path
2014-06-18 16:58:30 +03:00
end
end
2014-06-18 17:09:14 +03:00
end
end