验证失败:密码不能为空

时间:2015-03-19 06:18:34

标签: ruby-on-rails omniauth ruby-on-rails-4.2 omniauth-twitter

我有一个应用程序,基于Rails 4.2并尝试使用RailsCasts #241 Simple OmniAuth进行Twitter身份验证 但是有这个问题:Validation failed: Password can't be blank!
我到处搜索答案,但没有找到解决办法!

user.rb

class User < ActiveRecord::Base

    has_secure_password
    validates :password, length: { minimum: 6 }, allow_blank: true
    def self.create_with_omniauth(auth)
        create! do |user|
            user.provider = auth.provider
            user.uid = auth.uid
            user.name = auth.info.name
        end
    end
end

sessions_controller.rb

class SessionsController < ApplicationController
   def login
   end

   def create
       @user = User.find_by_email(params[:email])
       if @user && @user.authenticate(params[:password])
           session[:user_id] = @user.id
           redirect_to root_path
       else
           redirect_to :back
       end
   end

   def create_session
       auth = request.env['omniauth.auth']
       user = User.find_by_provider_and_uid(auth['provider'], auth['uid'])    || User.create_with_omniauth(auth)
       session[:user_id] = user.id
       redirect_to root_url, notice: 'Signed in!'
   end

   def logout
       reset_session
       redirect_to root_path
   end
end

routes.rb

  get 'sessions/login'
  get 'sessions/logout'
  post 'sessions' => 'sessions#create'

  get '/auth/:provider/callback' => 'sessions#create_session'
  post '/auth/:provider/callback' => 'sessions#create_session'

  get 'registration' => 'users#new', as: 'registration'

解决方案
编辑 user.rb 后,模型如下:

class User < ActiveRecord::Base

    has_secure_password
    validates :password, length: { minimum: 6 }
    require 'securerandom'
    def self.create_with_omniauth(auth)
       create! do |user|
          user.provider = auth.provider
          user.uid = auth.uid
          user.name = auth.info.name
          user.password = SecureRandom.urlsafe_base64
       end
    end
end

2 个答案:

答案 0 :(得分:5)

我认为这是

的问题
has_secure_password 

尝试对其进行评论,您可以覆盖has_secure_password

has_secure_password(validations: false)

这会发生,因为它会自动添加

validates_presence_of :password_digest 

因此,当指定allow_blank或allow_null时,它将不起作用

答案 1 :(得分:3)

另一种方法是在用户创建时输入随机密码。例如,如omniauth-google-oauth2自述文件中所示。所以你可以改变你的代码:

require 'securerandom'
def self.create_with_omniauth(auth)
    create! do |user|
        user.provider = auth.provider
        user.uid = auth.uid
        user.name = auth.info.name
        user.password = SecureRandom.urlsafe_base64
    end
end