【发布时间】:2010-10-08 23:14:14
【问题描述】:
我在我的 Rails 应用程序中使用 Devise 进行身份验证,我希望能够阻止某些帐户并防止用户使用被阻止的电子邮件重新注册。我只是不确定最好的方法是什么。
我的第一个想法是重写会话和注册控制器,以检查模型是否存在阻塞位的用户,但我觉得可能有更优雅的方法。
【问题讨论】:
标签: ruby-on-rails ruby authentication registration devise
我在我的 Rails 应用程序中使用 Devise 进行身份验证,我希望能够阻止某些帐户并防止用户使用被阻止的电子邮件重新注册。我只是不确定最好的方法是什么。
我的第一个想法是重写会话和注册控制器,以检查模型是否存在阻塞位的用户,但我觉得可能有更优雅的方法。
【问题讨论】:
标签: ruby-on-rails ruby authentication registration devise
最好的方法是设计方式:
下面假设您正在使用设计 database_authenticable 模块和您的应用程序的用户模型名称 User。
1.实现一个 account_active? 方法。
在 users 表中添加布尔 account_active 列或在 User 模型中定义 account_active? 方法(您可以选择自己的方法名称)。例如:
# app/models/user.rb
def account_active?
blocked_at.nil?
end
2。覆盖模型(用户)中的active_for_authentication? 方法。
# app/models/user.rb
def active_for_authentication?
super && account_active?
end
3.添加返回 Flash 消息翻译的方法。
每当 active_for_authentication? 返回 false 时,Devise 都会使用 inactive_message 方法询问您的模型处于非活动状态的原因。
# app/models/user.rb
def inactive_message
account_active? ? super : :locked
end
就是这样。您无需关心sign_out 或redirect_to 用户。
此外,用户在下次请求时立即被锁定,而不是在下次登录后。
【讨论】:
app/models/user.rb 中(假设 user.rb 是你的模型负责应用程序的用户)
我会这样做:
def after_sign_in_path_for(resource)
if resource.is_a?(User) && resource.banned?
sign_out resource
banned_user_path
else
super
end
end
【讨论】:
before_action,而不是使用after_sign_in_path_for。
更好的解决方案是覆盖 active_for_authentication?设计模型(用户)上的方法。像这样:
def active_for_authentication?
super && !self.banned?
end
【讨论】: