2011-04-12 80 views
30

由于设计我有很多用户,我想禁止一些问题制造者。 Devise是否有内置的支持?Rails + Devise - 有没有办法禁止用户登录或重置密码?

谢谢

+0

的可能的复制[?什么是禁止/块用户设计为Rails的最佳方式(https://stackoverflow.com/questions/3894919/what-is-the禁止阻止用户使用设备为导轨) – Wit 2017-06-19 14:32:32

+0

另请参阅[操作方法:-Soft-delete-a-user-when-user-deletes-account](https://github.com/plataformatec/devise/wiki/How-to:-Soft-delete-a -user-when-user-deletes-account) – mb21 2018-01-12 09:07:25

回答

26

我刚刚在自己的项目中实现了这一点。以上,我在我的应用程序/控制器/ sessions_controller.rb(覆盖设计)定义我所做的就是类似这种克勒贝尔...

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 

然后我加了一个布尔列到被叫用户“禁止”,所以当在后端编辑用户时,主持人检查复选框,并且布尔值将返回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 

如果检测到禁止,它会自动注销它们。无论如何,不​​确定整个事情是否是“最好”的方式来分析整个事情,因为我是更新的Rails,但整个事情对我很有用,并且希望它至少能给你一个好的开始。

+1

+1工作得很好!我不认为重写after_sign_in_path_for是必要的。在应用程序控制器中实现before_filter是所需要的,但after_sign_in_path_for可能对一些有用。谢谢。 – 2011-06-10 14:05:45

+0

好的观察,没有想到,好的重构想法,我可能会实现。但是,如果您处于不需要始终检查禁止的用户且只能登录的情况下,我会选择Devise登录覆盖。但这里有几种选择来涵盖不同的情况。 – Shannon 2011-06-13 03:59:02

+0

这对Rails 3来说并不适用,但@Frank的回答确实是 – Dinedal 2012-04-20 01:36:27

-3

您可以在Users表中添加一个名为“banned”的字段。

,然后在你的控制器,你可以有这样的事情:

class UsersController < ApplicationController 
before_filter :deny_banned 

protected 
def deny_banned 
    if current_user.banned? 
    redirect_to root_path, :notice => "You are banned from this site." 
    end 
end 

end 

这是不完整的,但我希望它可以帮助你以某种方式。

+3

这不会实际登录用户,这可能会导致重大问题。 – saadlulu 2016-04-03 07:14:08

77

从色器件数独为authenticatable.rb

之前验证用户和每个请求,制定检查你的模型是通过调用model.active_for_authentication活跃?这种方法被其他设计模块覆盖。例如:可确认覆盖.active_for_authentication?只有在您的模型得到确认后才会返回true。

你自己覆盖此方法,但如果你做什么,不要忘记调用超:

def active_for_authentication? 
    super && special_condition_is_valid? 
end 

所以,当你在用户数据库标志blocked,在用户的方法模型看起来是这样的:

def active_for_authentication? 
    super && !self.blocked 
end 
+2

是的,我认为这种方法是最好的方法,那就是拥有“封锁”策略​​,谢谢弗兰克! – Kulgar 2012-06-03 18:33:18

+2

要使用此方法自定义向用户显示的错误消息,编辑'config/locales/devise.en.yml'并编辑en> devise> failure> inactive下的值 – tirdadc 2015-03-31 14:38:00

+0

如果您不想使用“inactive '失败的消息,你可以添加一个自定义的也重写'inactive_message'也见[这里](https://github.com/plataformatec/devise/blob/master/lib/devise/models/authenticatable.rb#L50 )。 – brendanwb 2016-06-07 16:27:16

相关问题