2018-05-07 16:47:29 -07:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
2014-06-18 17:09:14 +03:00
|
|
|
module Users
|
|
|
|
|
class OmniauthCallbacksController < Devise::OmniauthCallbacksController
|
2019-05-04 20:48:16 +02:00
|
|
|
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
|
|
|
|
2014-07-14 16:16:02 +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']
|
2017-10-21 02:38:41 +05:30
|
|
|
unless auth_hash.info.email.present?
|
|
|
|
|
flash[:error] = "Email field is missing in your #{provider} account"
|
|
|
|
|
redirect_to new_user_registration_path
|
|
|
|
|
return
|
|
|
|
|
end
|
2017-10-13 22:30:08 +05:30
|
|
|
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
|
2017-10-13 22:30:08 +05:30
|
|
|
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
|
2019-12-20 08:26:22 -05:00
|
|
|
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
|