我设置了Devise并为我的应用程序工作。当我添加
gem omniauth-google-oauth2
我在控制器sign_in_and_redirect
方法中遇到错误。
错误:
NoMethodError (undefined method `serialize_into_session' for String:Class):
app/controllers/users/omniauth_callbacks_controller.rb:9:in `google_oauth2'
代码:
omniauth_callbacks_controller.rb
def google_oauth2
@user = User.find_for_google_oauth2(request.env["omniauth.auth"], current_user)
if @user.persisted?
flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Google"
sign_in_and_redirect sites_path, :event => :authentication
else
session["devise.google_data"] = request.env["omniauth.auth"]
redirect_to new_user_registration_url
end
end
user.rb
def self.find_for_google_oauth2(access_token, signed_in_resource=nil)
data = access_token.info
user = User.where(:email => data["email"]).first
unless user
user = User.create(email: data["email"],
password: Devise.friendly_token[0, 20]
)
end
user
end
devise.rb
require "omniauth-google-oauth2"
config.omniauth :google_oauth2, 'CLIENT_ID', 'CLIENT_SECRET', {access_type: "offline", approval_prompt: ""}
如果我错过了什么,请告诉我。
答案 0 :(得分:0)
您的配置很好,但我在这种情况下使用omniauth-google-oauth2
,这个宝石https://rubygems.org/gems/omniauth-openid。
添加到/config/initializer/devise.rb
下一个:
require 'openid/store/filesystem'
config.omniauth :open_id, :store => OpenID::Store::Filesystem.new('/tmp'), :name => 'google', :identifier => 'https://www.google.com/accounts/o8/id', :require => 'omniauth-openid'
在omniauth_callbacks_controller.rb
内部后,User.find_for_google_oauth2...
User.find_for_open_id...
user
模型上的将self.find_for_google_oauth2
更改为self.find_for_open_id
。
请试试这个宝石吧!