我正在使用RoR 5.2,devise和omniauth-trello gem。 我无法使用Trello登录。 我需要创建在没有现有用户的情况下使用返回的提供程序和uid登录的功能:如果不存在该用户,则应该创建用户。
我已经添加了 config / routes.rb:
devise_for :users, controllers: { omniauth_callbacks: 'omniauth_callbacks' }
config / initializers / devise.rb:
config.omniauth :trello, "#{Rails.application.credentials.trello[:key]}", "#{Rails.application.credentials.trello[:secret]}"
config / initializers / omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do
provider :trello, Rails.application.credentials.trello[:key], Rails.application.credentials.trello[:secret],
app_name: "Trello-Rooney", scope: 'read,write,account', expiration: 'never'
end
app / controllers / omniauth_callbacks_controller.rb
class OmniauthCallbacksController < Devise::OmniauthCallbacksController
def trello
@user = User.from_omniauth(request.env['omniauth.auth'])
if @user.persisted?
sign_in_and_redirect @user, event: :authentication
set_flash_message(:notice, :success, kind: 'Trello') if is_navigational_format?
end
end
end
app / models / user.rb
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable, :omniauthable, omniauth_providers: %i[trello]
def self.from_omniauth(auth)
user = User.where(provider: auth.provider, uid: auth.uid.to_s).first
return user if user
email = auth.info[:email]
while email.nil?
generated_email = "#{SecureRandom.base58(10)}@roonyx.trello"
if User.where(email: generated_email).blank?
email = generated_email
end
end
user = User.where(email: email).first
if user
user.update(provider: auth.provider, uid: auth.uid)
else
password = Devise.friendly_token[0, 12]
user = User.create!(email: email, password: password, password_confirmation: password, provider: auth.provider, uid: auth.uid)
end
user
end
end
但是当我尝试使用Trello登录时,我会在控制台中看到它。看起来它不会引起我的回调。有人可以帮忙吗?预先谢谢你。
E, [2019-05-13T14:10:29.647241 #19958] ERROR -- omniauth: (trello) Authentication failure! service_unavailable: Net::HTTPFatalError, 500 "Internal Server Error"
[2019-05-13 14:10:29] (pida=19958) INFO -- : Processing by OmniauthCallbacksController#failure as HTML
[2019-05-13 14:10:29] (pida=19958) INFO -- : Parameters: {"oauth_token"=>"47215df2b25b4fc089953da32acf0730", "oauth_verifier"=>"8a0b310f2afe98d0aebbd2073efc5b54"}
[2019-05-13 14:10:29] (pida=19958) INFO -- : Redirected to http://localhost:3000/users/sign_in
[2019-05-13 14:10:29] (pida=19958) INFO -- : Completed 302 Found in 1ms (ActiveRecord: 0.0ms)
答案 0 :(得分:2)
错误就在您的日志中:
Authentication failure! service_unavailable: Net::HTTPFatalError, 500 "Internal Server Error"
因为您插入了OmniAuth::Builder
中间件,所以未触发您的回调。您可以尝试删除它并检查与回调一起发送的params
。
一旦删除了中间件,您就可以在回调操作的顶部放置一个byebug
或一个binding.pry
。进入调试器后,检查request.env['omniauth.auth']
的值。那应该使您对问题所在有一些了解。在不了解环境的情况下很难说更多。