我想在我的应用中创建一个GOOGLE身份验证。所以在设置" omniauth"和"设计"正确(我认为)。在" _header.html.erb"中的布局文件夹中观点:
<% if user_signed_in? %>Signed in as <%= current_user.name %>. Not you?
<%= link_to "Sign out", destroy_user_session_path,:method => :delete %>
<% else %>
<%= link_to "Sign in with Google", user_omniauth_authorize_path(:google_oauth2) %>
<% end %>
当我尝试连接时,我点击此代码打开新页面的链接,我选择我的谷歌帐户然后接受权利,这将我重定向到同一页面。 (链接所在的位置)。我的数据库正确填写了帐户信息。
但是就像代码说我想在连接之后标题打印出已连接帐户的名称而事实并非如此。它再次打印&#34;使用google&#34;。
登录此外,我想在连接后重定向另一个页面。我怎么做。
也许我必须定义user_signed_in?
方法,如果是这样的话,在哪里以及如何?
current_user在application_controller中定义如下:
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
在我的用户模型中,我只有:
def self.find_for_google_oauth2(access_token, signed_in_resource=nil)
data = access_token.info
user = User.where(:provider => access_token.provider, :uid => access_token.uid ).first
unless user
#registered_user = User.where(:email => access_token.info.email).first
#if registered_user
# return registered_user
#else
user = User.create(
name: data["name"],
provider:access_token.provider,
email: data["email"],
uid: access_token.uid ,
password: Devise.friendly_token[0,20],
)
#end
end
p user
user
end
希望你能帮助我。
先谢谢。
PS:如果你想要一些代码,只需说出评论,我就会用代码的一部分编辑问题。
答案 0 :(得分:0)
创建OmniauthCallbacksController并添加以下代码
class OmniauthCallbacksController < ApplicationController
skip_before_filter :authenticate_user!
def all
p env["omniauth.auth"]
user = User.from_omniauth(env["omniauth.auth"])
if user.persisted?
flash[:notice] = "You are in..!!! Go to edit profile to see the status for the accounts"
sign_in_and_redirect(user)
else
session["devise.user_attributes"] = user.attributes
redirect_to new_user_registration_url
end
end
def failure
#handle you logic here..
#and delegate to super.
super
end
alias_method :google_oauth2, :all
end
在您的config / routes.rb
中devise_for :users, controllers: { omniauth_callbacks: "omniauth_callbacks" }
创建授权模型
rails g model Authorization
在迁移中添加以下代码
class CreateAuthorizations < ActiveRecord::Migration
def change
create_table :authorizations do |t|
t.string :provider
t.string :uid
t.integer :user_id
t.string :token
t.string :secret
t.timestamps
end
end
end
然后
rake db:migrate
在您的models / authorization.rb
中belongs_to :user
在您的models / user.rb
中has_many :authorizations
def self.from_omniauth(auth)
authorization = Authorization.where(:provider => auth.provider, :uid => auth.uid.to_s).first_or_initialize
authorization.token = auth.credentials.token
if authorization.user.blank?
user = User.where('email = ?', auth["info"]["email"]).first
if user.blank?
user = User.new
user.password = Devise.friendly_token[0,10]
user.email = auth.info.email
user.save
end
authorization.user_id = user.id
if auth.provider == "google_oauth2"
authorization.secret = auth.credentials.refresh_token !auth.credentials.refresh_token.blank?
authorization.secret = auth.credentials.secret
end
end
authorization.save
authorization.user
end
希望这会对你有所帮助。