【问题标题】:Devise find by username or email通过用户名或电子邮件设计查找
【发布时间】:2021-04-14 17:18:48
【问题描述】:

设置后 我想在 api 会话中通过用户名或电子邮件获取用户

我将登录信息传递给参数,但 rails 吐出一个错误

User.find_for_database_authentication(:login => params[:username][:email])

模型上 find_for_database_authentication 的覆盖已经完成。

def self.find_for_database_authentication(warden_conditions)

有人有什么提示吗?

设计

class Api::SessionsController < Devise::SessionsController

  respond_to :json

  def create
    resource = User.find_for_database_authentication(:login => params[:username][:email])



    if resource.valid_password?(params[:login][:password])
      sign_in(:user, resource)

      render :json=> {:auth_token=>resource.authentication_token, :email=>resource.email}, :status => :ok
      return
    end
    invalid_login_attempt
  end
end

【问题讨论】:

  • 错误是什么?
  • 完成 401 未授权
  • 你能出示find_for_database_authentication的代码吗?
  • 当然,现在问题是代码
  • 您的登录凭据是否正确,您能否执行puts 并查看create 方法是否获取正确的数据

标签: ruby-on-rails ruby devise


【解决方案1】:

我通过像这样覆盖 find_for_database_authentication 来做到这一点:

class User
  def self.find_for_database_authentication(auth_hash)
    self.where("username = :query OR email = :query", query: auth_hash[:email]).first
  end
end

什么都不需要了。

【讨论】:

    【解决方案2】:

    试试这个:User.find_by(username: 'username')User.find_by(email: 'your@email.com')

    【讨论】:

      猜你喜欢
      • 2018-09-11
      • 2013-11-10
      • 1970-01-01
      • 1970-01-01
      • 2016-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-01
      相关资源
      最近更新 更多