即使omniauth控制器确认登录成功,我似乎也无法从我的数据库中保存用户。我遵循了omniauth wiki的说明:https ://github.com/plataformatec/devise/wiki/OmniAuth%3A-Overview
用户.rb:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :omniauthable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :encrypted_password, :provider, :uid
attr_accessor :email, :password, :password_confirmation, :remember_me, :provider, :uid, :name
def self.from_omniauth(auth)
where(auth.slice(:provider, :uid)).first_or_initialize.tap do |user|
user.provider = auth.provider
user.uid = auth.uid
user.email = auth.info.email
user.encrypted_password = Devise.friendly_token[0,20]
user.save!
end
end
def self.find_for_facebook_oauth(auth, signed_in_resource=nil)
user = User.where(:provider => auth.provider, :uid => auth.uid).first
unless user
user = User.create(
provider:auth.provider,
uid:auth.uid,
email:auth.info.email,
encrypted_password:Devise.friendly_token[0,20]
)
#user.ensure_authentication_token!
#added extra to create authentication for user
user.save
end
user
end
def self.new_with_session(params, session)
super.tap do |user|
if data = session["devise.facebook_data"] && session["devise.facebook_data"]["extra"]["raw_info"]
user.email = data["email"] if user.email.blank?
end
end
end
end
omniauth_callback_controller.rb:
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def passthru
render :file => "#{Rails.root}/public/404.html", :status => 404, :layout => false
# Or alternatively,
# raise ActionController::RoutingError.new('Not Found')
end
def facebook
# You need to implement the method below in your model (e.g. app/models/user.rb)
@user = User.find_for_facebook_oauth(request.env["omniauth.auth"], current_user)
#@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 => "Facebook") if is_navigational_format?
else
session["devise.facebook_data"] = request.env["omniauth.auth"]
#redirect_to new_user_registration_url
redirect_to messages_url
end
end
end
我尝试使用默认设计控制器登录,它通过用户数据库。由于我无法存储到数据库,我也无法获取 uid。