【问题标题】:Check if user is valid for authentication only if uses database authenticable仅当使用可验证的数据库时才检查用户是否对验证有效
【发布时间】:2018-11-30 11:12:24
【问题描述】:

用户可以通过 OmniAuth 或通过电子邮件和密码登录我们的应用程序(但前提是他们被邀请)。

我们有一个方法,它检查用户是否可以通过电子邮件和密码登录,如下所示:

def active_for_authentication?
  super && valid_for_authentication
end

private
# Check wheter user was invited or not   
def valid_for_authentication
  User.invitation_accepted.find_by(id: id).present?
end

这很好,但是当我想通过 OmniAuth 登录时,这种方法会阻止我。 如果使用 OmniAuth 身份验证,是否可以指定绕过此方法?

【问题讨论】:

    标签: ruby-on-rails devise devise-invitable


    【解决方案1】:

    您可以在执行active_for_authentication之前检查以下方法吗?线条

    如果使用omniauth 登录返回一些res 数据,以下行将添加逻辑unless res.present?

    def logged_using_omniauth? request
      res = nil
      omniauth = request.env["omniauth.auth"]
      res = Authentication.find_by_provider_and_uid 
      (omniauth['provider'], omniauth['uid']) if omniauth
      res  
    end
    

    【讨论】:

      【解决方案2】:

      最后,我以另一种方式解决了这个问题。 active_for_authentication?valid_for_authentication 已删除。

      然后在app/models/user.rb中我基于https://github.com/plataformatec/devise/wiki/How-To:-Allow-users-to-sign-in-using-their-username-or-email-address#overwrite-devises-find_for_database_authentication-method-in-user-model定义了以下代码

        def self.find_for_database_authentication(warden_conditions)
          if valid_for_database_authentication?(warden_conditions)
            super
          else
            throw :warden, message: not_allowed_for_authentication
          end
        end
      
        # Check wheter user was invited or not
        private_class_method def self.valid_for_database_authentication?(params)
          User.invitation_accepted.find_by(params).present?
        end
      
        private_class_method def self.not_allowed_for_authentication
          I18n.t('devise.failure.user.not_allowed_for_authentication')
        end
      

      【讨论】:

      • 工作解决方案+1
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-08
      相关资源
      最近更新 更多