如何使用 Devise 停止软删除用户的登录 [英] How to stop soft deleted user's login with Devise

查看:21
本文介绍了如何使用 Devise 停止软删除用户的登录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在 Rails 项目中使用 Devise 进行用户注册/身份验证.当用户想要注销他们的帐户时,用户对象会以如下方式软删除.

I currently use Devise for user registration/authentication in a Rails project. When a user wants to cancel their account, the user object is soft deleted in a way like the following.

如何软删除"使用 Devise 的用户

我的实现方式与此略有不同.用户模型有一个属性deleted_flag".并且,soft_delete 方法执行update_attributue(:deleted_flag, true)"

My implmenetation has a small difference this way. User model has an attribute 'deleted_flag'. And, soft_delete method executes "update_attribtue(:deleted_flag, true)"

但是,我必须执行 sign_in 操作.我的实现如下.

But, I have to implment sign_in action. In my implmenetation is the following.

class SessionsController < Devise::SessionsController
  def create
    resource = warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#new")    

    if resource.deleted_flag
      p "deleted account : " + resource.deleted_flag.to_s
      sign_out(resource)
      render :controller => :users, :action => :index
    else
      if is_navigational_format?
        if resource.sign_in_count == 1
          set_flash_message(:notice, :signed_in_first_time)
        else
          set_flash_message(:notice, :signed_in)
        end
      end
      sign_in(resource_name, resource)
      respond_with resource, :location => redirect_location(resource_name, resource)
    end
  end
end

我觉得这段代码有奇怪的地方.

I think this code has strange points.

如果被删除的用户尝试加入,系统允许登录并立即注销.而且,系统无法显示 flash[:alert] 消息...

If deleted user tries to sing in, the system permit logging and make log out immediately. And, the system cann't display flash[:alert] message...

我想知道两点.

  1. 如何实现禁止已删除用户登录?
  2. 如何实现在已删除用户尝试登录时显示 flash[:alert]?

推荐答案

要阻止已软删除"的用户,最好的方法是覆盖用户模型上的 find_for_authentication 类方法.如:

To stop a user that has been 'soft deleted', the best way is to overwrite the find_for_authentication class method on the user model. Such as:

Class User < ActiveRecord::Base
  def self.find_for_authentication(conditions)
    super(conditions.merge(:deleted_flag => false))
  end

这将通过设计生成无效的电子邮件或密码闪存消息(因为它找不到要进行身份验证的用户)

This will generate a invalid email or password flash message by devise (because it cannot find the user to authenticate)

就您的第二个问题而言,您需要在控制器中使用一些 for of 方法来添加特定的 Flash 消息.但是,在我看来,您应该将软"删除的用户视为数据库中根本不存在的用户.因此,如果他们尝试登录,他们应该只会收到有效的电子邮件或密码消息.

As far as your second question though, you'll need some for of method in your controller to add a particular flash message. However, in my opinion you should treat users that are 'soft' deleted the same as if they didn't exist in the database at all. Thus if they tried to log in, they should just get an valid email or password message.

这篇关于如何使用 Devise 停止软删除用户的登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆