Escolar Documentos
Profissional Documentos
Cultura Documentos
AutenticacinOmniauthOauth2
Omniauth.
IntegrarOmniauthyDeviseenunaAplicacin.
AgregandoestrategiaparaautenticarconGoogle+.
EnelGemfileagregar:
gem
'omniauth-google-oauth2'
yejecutar
bundle install
luegoen
config/initializers/omniauth.rb
agregarlosiguiente:
Rails
.application.config.middleware.use
OmniAuth
::
Builder
do
provider
:google_oauth2
,
"
App Key
"
,
"
Secret Key
"
,
scope:
'email, profile, plus.me'
,
image_aspect_ratio:
'square'
,
image_size:
48
,
access_type:
'online'
OmniAuth
.config.on_failure
=
Proc
.
new
do
|env|
SessionsController
.action(
:auth_failure
).call(env)
end
end
luego
en
config/routes.rb
agregarlosiguiente:
devise_for
:users
,
:controllers
=> {
:omniauth_callbacks
=>
"callbacks"
}
luegoagregarcamposalmodelodeusuarios:
enelarchivodemigracingenerado,asegurarsedeagregarlosiguiente:
add_index :users, [:provider, :uid], unique: true
luegoejecutarlamigracin:
rake db:migrate
luegoenelmodelo
user.rb
agregarlosiguiente:
[...]
devise
,
[...]
class
<<
self
def
from_omniauth(auth_hash)
data = auth_hash.info
# Comprobando existencia de usuario
user = find_or_create_by(uid: auth_hash['uid'], provider: auth_hash['provider'])
user.location = get_social_location_for user.provider, data.location
user.image_url = data.image
user.url = get_social_url_for(user.provider, data.urls) unless data.urls.nil?
user.password = Devise.friendly_token[6,20]
user.email = data.email
user.skip_confirmation!
user.save!
user
end
private
ef
d
get_social_location_for(provider, location_hash)
case
provider
when
'linkedin'
location_hash['name']
else
location_hash
end
end
end
[...]
ef
d
get_social_url_for(provider, urls_hash)
case
provider
when
'linkedin'
urls_hash['public_profile']
else
urls_hash[provider.capitalize]
end
end
luegoen
app/controllers/callbacks_controller.rb
agregarlosiguiente:
class
CallbacksController < Devise::OmniauthCallbacksController
ef
d
self.provides_callback_for(provider)
class_eval
%Q{
def
#{provider}
@user
= User.from_omniauth(request.env["omniauth.auth"])
i
f
!
@user
.nil? &&
@user
.persisted?
sign_in_and_redirect
@user
, :event => :
authentication
set_flash_message(:
notice
,
:
success
,
kind:
"#{provider}".capitalize)
is_navigational_format?
else
session["devise.#{provider}_data"] = request.env["omniauth.auth"]
redirect_to root_path
end
end
}
end
if
[..., :
linked_in
, :
google_oauth2
].each do |
provider
|
provides_callback_for
provider
end
end
luegoenlavistaagregar:
<%= link_to
"Ingresar con Google"
, user_omniauth_authorize_path(
:google_oauth2
) %>