Last active
May 31, 2017 11:33
-
-
Save thaleshcv/9cd90cccc77b9a3d6e45f8fa414be3dc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController | |
Devise.omniauth_configs.keys.each do |provider| | |
define_method(provider.to_s) { omniauth_callback(provider) } | |
end | |
def failure | |
redirect_to root_path | |
end | |
private | |
def omniauth_callback(provider) | |
auth_data = request.env["omniauth.auth"] | |
user = SigninWithOmniauth.new(auth_data).execute | |
if user.present? && user.persisted? | |
sign_in_and_redirect user, event: :authentication | |
set_flash_message(:notice, :success, kind: provider.to_s.capitalize) if is_navigational_format? | |
else | |
session["devise.oauth_data"] = auth_data.except(:extra) | |
redirect_to new_user_session_path | |
end | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SigninWithOmniauth | |
def initialize(auth_data) | |
@auth_data = auth_data | |
end | |
def execute | |
authentication = Authentication.from_omniauth(auth_data) | |
raise(AuthError, I18n.t(:failed, scope: [:messages, :auth])) unless authentication.persisted? | |
if authentication.user.nil? | |
attach_authentication_to_user(authentication, existing_user || new_user) | |
end | |
authentication.user | |
end | |
private | |
def existing_user | |
User.find_by_email(auth_data.info.email) | |
end | |
def new_user | |
User.create(name: auth_data.info.name, email: auth_data.info.email) do |user| | |
user.password = Devise.friendly_token[0,20] | |
user.skip_confirmation! | |
end | |
end | |
def attach_authentication_to_user(authentication, user) | |
authentication.update_column(:user_id, user) | |
end | |
attr_reader :auth_data | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment