AnA*_*ice 34 ruby-on-rails devise ruby-on-rails-3
由于设计我有很多用户,我想禁止一些问题制定者.Devise是否内置了这种支持?
谢谢
小智 85
从authenticatable doku for authenticatable.rb:
在验证用户和每个请求之前,Devise通过调用model.active_for_authentication?来检查您的模型是否处于活动状态.其他设计模块会覆盖此方法.例如,:确认覆盖.active_for_authentication?如果您的模型已确认,则仅返回true.
你自己覆盖这个方法,但是如果你这样做,别忘了给super打电话:
def active_for_authentication?
super && special_condition_is_valid?
end
Run Code Online (Sandbox Code Playgroud)
因此,当您blocked在用户数据库中有一个标志时,用户模型中的方法如下所示:
def active_for_authentication?
super && !self.blocked
end
Run Code Online (Sandbox Code Playgroud)
Sha*_*non 31
我自己在项目中实现了这一点.我所做的与上面的Kleber类似,我在app/controllers/sessions_controller.rb(重写Devise)中定义了这个...
class SessionsController < Devise::SessionsController
protected
def after_sign_in_path_for(resource)
if resource.is_a?(User) && resource.banned?
sign_out resource
flash[:error] = "This account has been suspended for violation of...."
root_path
else
super
end
end
end
Run Code Online (Sandbox Code Playgroud)
然后我向用户添加了一个名为'banned'的布尔列,以便主持人在后端编辑用户时选中复选框,布尔值将返回true.
但是有一个缺陷......如果用户已经登录然后被禁止,他们仍然可以访问网站上的内容(评论等),至少在他们的会话到期或他们退出之前.所以我在app/controllers/application_controller.rb中做了这个...
class ApplicationController < ActionController::Base
before_filter :banned?
def banned?
if current_user.present? && current_user.banned?
sign_out current_user
flash[:error] = "This account has been suspended...."
root_path
end
end
end
Run Code Online (Sandbox Code Playgroud)
如果检测到禁令,它会自动注销.无论如何,不确定这整个事情是影响整个事情的"最佳"方式,因为我对Rails更新,但整个事情对我有用,并希望它至少会给你一个良好的开端.