【发布时间】:2016-11-11 09:39:22
【问题描述】:
我已经使用omniauth-facebook 成功实现了Devise,现在我正在尝试使用Twitter。我几乎将 Facebook 的 Devise settings 复制到了 Twitter 的方法中。但是,在成功批准我的应用程序使用我的 Twitter 帐户后,我被重定向回我的用户注册页面 (http://localhost:3000/users/sign_up)。为什么是这样?
控制台输出
Started GET "/users/auth/twitter/callback?oauth_token=zeIyTgAAAAAAwAQEAAABVcusPxc&oauth_verifier=q24BAAziukc8bF6nnaxuRoouuGaPuoF3" for ::1 at 2016-07-08 14:01:51 -0400
I, [2016-07-08T14:01:51.984997 #44805] INFO -- omniauth: (twitter) Callback phase initiated.
Processing by Users::OmniauthCallbacksController#twitter as HTML
Parameters: {"oauth_token"=>"zeIyTgAAAAAAwAQEAAABVcusPxc", "oauth_verifier"=>"q24BAAziukc8bF6nnaxuRoouuGaPuoF3"}
User Load (0.7ms) SELECT "users".* FROM "users" WHERE "users"."provider" = $1 AND "users"."uid" = $2 ORDER BY "users"."id" ASC LIMIT 1 [["provider", "twitter"], ["uid", "248829852"]]
(0.2ms) BEGIN
(0.1ms) ROLLBACK
Redirected to http://localhost:3000/users/sign_up
Completed 302 Found in 165ms (ActiveRecord: 1.0ms)
控制器/用户/omniauth_callbacks_controller.rb
类用户::OmniauthCallbacksController
if @user.persisted?
sign_in_and_redirect @user, :event => :authentication #this will throw if @user is not activated
set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format?
else
session["devise.facebook_data"] = request.env["omniauth.auth"]
redirect_to new_user_registration_url
end
end
def twitter
@user = User.from_omniauth(request.env["omniauth.auth"])
if @user.persisted?
sign_in_and_redirect @user, :event => :authentication #this will throw if @user is not activated
set_flash_message(:notice, :success, :kind => "Twitter") if is_navigational_format?
else
session["devise.twitter_data"] = request.env["omniauth.auth"].except("extra")
redirect_to new_user_registration_url
end
end
def failure
redirect_to root_path
end
end
models/user.rb
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:omniauthable, :omniauth_providers => [:facebook, :twitter]
def self.from_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.email = auth.info.email
user.password = Devise.friendly_token[0,20]
user.name = auth.info.name # assuming the user model has a name
user.image = auth.info.image # assuming the user model has an image
end
end
end
config/routes.rb
Rails.application.routes.draw do
devise_for :users,
:controllers => { :omniauth_callbacks => "users/omniauth_callbacks" }
root 'welcome#index'
end
【问题讨论】:
-
您是否正在做任何验证以确保您的模型中存在电子邮件?
-
其实,没有。我还没有对验证做任何事情......我的数据库有一个字段,但此时用户模型中没有验证。
-
我认为你应该给
Twitter用户分配一个临时电子邮件,看看会发生什么。 -
是的,这是因为缺少电子邮件。所以现在我知道它与设计相关......
-
Devise 为某些字段提供默认验证。详情请看我的回答。
标签: ruby-on-rails ruby twitter devise