我正在尝试设置 Devise 1.2 以允许通过 GitGub 进行用户身份验证。至于我可以使用 Cucumber 在本地对其进行测试,并剔除 GitHub OAuth,它似乎工作正常。但是,在我部署到 Heroku 并尝试进行身份验证后,从 GitHub 重定向回我的应用程序后出现错误。
检查 Heroku 日志,我看到的错误是......
PGError:错误:“电子邮件”列中的空值违反非空约束
显然,我要么没有从 GitHub 收到电子邮件地址,要么它在途中丢失了?
我已按照https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview和https://github.com/plataformatec/devise/wiki/OmniAuth:--Testing-%27facebook上的说明和示例进行操作%27-signup--%5BRails-3---Cucumber---Capybara---Mongoid-%5D,但针对 GitHub 而不是 Facebook 进行了修改,参考https:// GitHub 策略的 OmniAuth 源代码github.com/intridea/omniauth/blob/master/oa-oauth/lib/omniauth/strategies/github.rb。
这是我的 devise_steps.rb 文件的内容,它产生了一个通过的 Cucumber 功能:
ACCESS_TOKEN = {
:access_token => "stevejdev"
}
# Not all pieces of this hash are yet proven to be correct.
# It does, at least supply the necessary information for a
# successful login simulation though.
GITHUB_INFO = {
:user => {
:id => '12345',
:email => 'johndoe@example.com',
# login value maps to nickname and to <user> part of
# "http://github.com/<user>" in urls[GitHub]
:login => 'johnxd',
:name => 'John Doe',
# blog value maps to urls[blog]
:blog => 'http://blaagstop.com/johndoe',
}
}
When /^GitHub replies$/ do
Devise::OmniAuth.short_circuit_authorizers!
Devise::OmniAuth.stub!(:github) do |b|
b.post('/login/oauth/access_token') {
[200, {}, ACCESS_TOKEN.to_json] }
b.get('/api/v2/json/user/show?access_token=stevejdev') {
[200, {}, GITHUB_INFO.to_json ] }
end
visit user_omniauth_callback_path(:github)
end
这是我的回调处理程序:
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def github
@user = User.find_for_github_oauth(env["omniauth.auth"], current_user)
if @user.persisted?
flash[:notice] = I18n.t(
"devise.omniauth_callbacks.success", :kind => "GitHub" )
sign_in_and_redirect @user, :event => :authentication
else
session["devise.github_data"] = env["omniauth.auth"]
redirect_to new_user_registration_url
end
end
end
这是我的用户模型中的 find_for_github_oauth 定义:
def self.find_for_github_oauth(access_token, signed_in_resource=nil)
data = access_token['extra']['user_hash']
# Find the existing user or create a new one.
# Omit the password-generation code shown in the example at
# https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview
# because we're intending to use OmniAuth only, so
# presumably don't need a password.
User.find_by_email( data["email"] ) ||
User.create!( :email => data["email"] )
end