【问题标题】:Devise Omniauth "encrypted_password may not be NULL" for new user为新用户设计 Omniauth“encrypted_pa​​ssword 可能不是 NULL”
【发布时间】:2011-07-10 14:58:07
【问题描述】:

我正在使用带有 Omniauth 的 Devise 让用户使用 Facebook 登录我的应用程序。我使用 Railscast 教程来启动和运行它。

如果用户已经是我网站的成员,则通过 facebook 进行身份验证可以正常工作。使用 facebook 对新用户进行身份验证时会出现问题。当它为我的用户模型创建新用户时,我收到“users.encrypted_pa​​ssword 可能不是 NULL”错误。我不知道如何将密码从 Facebook 信息传递给 User 模型。

这就是我所拥有的:

authentations_controller.rb

class AuthenticationsController < ApplicationController
 def index
  @authentications = current_user.authentications if current_user
 end

def create
  omniauth = request.env["omniauth.auth"]
  authentication = Authentication.find_by_provider_and_uid(omniauth['provider'],   omniauth['uid'])
 if authentication
   flash[:notice] = "Signed in successfully."
   sign_in_and_redirect(:user, authentication.user)
 elsif current_user
   current_user.authentications.create!(:provider => omniauth['provider'], :uid => omniauth['uid'])
   flash[:notice] = "Authentication successful."
   redirect_to authentications_url
 else
   user = User.new
   user.apply_omniauth(omniauth)
   if user.save
     flash[:notice] = "Signed in successfully."
     sign_in_and_redirect(:user, user)
   else
     session[:omniauth] = omniauth.except('extra')
     redirect_to new_user_registration_url
   end
  end
end

用户.rb

 def apply_omniauth(omniauth)
  self.email = omniauth['user_info']['email'] if email.blank?
  authentications.build(:provider => omniauth['provider'], :uid => omniauth['uid'])
 end


 def password_required?
   (authentications.empty? || !password.blank?) && super
 end

任何帮助都会很棒,在此先感谢!

【问题讨论】:

    标签: ruby-on-rails devise omniauth


    【解决方案1】:

    在从 facebook omniauth 创建新用户时添加 :password => Devise.friendly_token[0,20]。

    我相信 Devise 期望在密码字段中创建用户。由于在执行 facebook oauth 时没有密码(至少在您的应用程序端),您只需要创建一个虚拟密码,如上所示。

    有关更多信息,请参阅此内容: https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview

    【讨论】:

    • 非常感谢,我之前曾尝试实现此功能,但显然不正确。现在一切正常。希望该链接可以帮助其他人。
    • 用户能知道密码是什么吗?
    猜你喜欢
    • 2019-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多