我想构建一个基于 Ruby on Rails 的 Web 应用程序。为了进行身份验证,我使用 devise gem。一切都很好:我可以创建帐户、登录、注销等。
但是我这里有一个问题。我希望能够在不提供密码的情况下注册,但仍然能够使用另一个帐户的密码进行注册。
我已在 config/initializers/devise.rb 上将密码长度设置为从 0 到 128
config.password_length = 0..128
但是接下来要做的事情是什么?
谢谢
最佳答案
好的,我在这里回复作为答案。
感谢 Ammar Shah,我找到了如何获取有密码的用户和没有密码的用户。
首先在lib/devise/strategies(创建文件夹)中创建一个名为database_authenticable.rb的文件,代码如下:
require 'devise/strategies/authenticatable'
module Devise
module Strategies
# Default strategy for signing in a user, based on their email and password in the database.
class DatabaseAuthenticatable < Authenticatable
def authenticate!
if password.blank?
authentication_hash[:encrypted_password] = ''
end
resource = mapping.to.find_for_database_authentication(authentication_hash)
hashed = false
if validate(resource){ hashed = true; resource.valid_password?(password) }
remember_me(resource)
resource.after_database_authentication
success!(resource)
end
mapping.to.new.password = password if !hashed && Devise.paranoid
fail(:not_found_in_database) unless resource
end
end
end
end
Warden::Strategies.add(:database_authenticatable, Devise::Strategies::DatabaseAuthenticatable)
然后在 devise_create_user.rb 迁移中添加:
t.string :remember_token
最后在user.rb模型中:
before_create :remember_value
def valid_password?(password)
if password.blank?
true
else
super
end
end
def password_required?
new_record? ? false : super
end
def remember_value
self.remember_token ||= Devise.friendly_token
end
谢谢 Ammar Shah 帮助我!
关于ruby-on-rails - Ruby on Rails - 设计注册空白密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41691575/