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

46 lines
1.4 KiB
Ruby
Raw Normal View History

# frozen_string_literal: true
2014-06-18 17:09:14 +03:00
module Users
class OmniauthCallbacksController < Devise::OmniauthCallbacksController
skip_before_action :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']
unless auth_hash.info.email.present?
flash[:error] = "Email field is missing in your #{provider} account"
redirect_to new_user_registration_path
return
end
username = auth_hash.info.email.split('@')[0]
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
user.username = "#{username}@#{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
redirect_to root_path, notice: "#{user.email} signed in successfully with #{provider}"
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