我应该在我的学生表中添加password_digest列以使student.authenticate(password)运行吗?即使我正在使用Devise?

我正在按照以下链接的步骤在我的代码中实现基于令牌的身份验证API:

https://www.twilio.com/docs/runtime/quickstart/programmable-sms-functions

authentication_controller.rb是:

class AuthenticationController < ApplicationController
 skip_before_action :authenticate_request
 skip_before_action :verify_authenticity_token

 def authenticate
  binding.pry
   command = AuthenticateStudent.call(params[:corporative_email],params[:password])

   if command.success?
     render json: { auth_token: command.result }
   else
     render json: { error: command.errors },status: :unauthorized
   end
 end
end

authenticate_student.rb是:

class AuthenticateStudent
  prepend SimpleCommand

  def initialize(corporative_email,password)
    binding.pry
    @corporative_email = corporative_email
    @password = password
  end

  def call
    binding.pry
    JsonWebToken.encode(student_id: student.id) if student
  end

  private

  attr_accessor :corporative_email,:password

  def student
    binding.pry
    student = Student.find_by_corporative_email(corporative_email)
    return student if student && student.authenticate(password)

    errors.add :student_authentication,'invalid credentials'
    nil
  end
end

一切正常,直到最后一次撬动,代码在student.authenticate(password)中断,服务器返回“ ArgumentError(错误的参数数量(给定0,应为1))”: “。在控制台上,“密码”按预期返回“ 123456”,这对我来说意味着给定的参数编号应为1而不是零。

有人知道这里发生了什么吗?

zuoduzu 回答:我应该在我的学生表中添加password_digest列以使student.authenticate(password)运行吗?即使我正在使用Devise?

我找到了答案。如果您使用的是devise并想按照下面的教程进行操作,请忽略“ gem'bcrypt'”部分以及与之相关的所有内容(包括has_secure_password方法)。

https://www.pluralsight.com/guides/token-based-authentication-with-ruby-on-rails-5-api

最后在commands / authenticate_student.rb(我以学生为单位,已由学生更改用户)替换行:

return student if student && student.authenticate(password)

作者:

return student if student && student.valid_password?(password)

valid_password?是一种设计方法,将执行与身份验证相同的工作。

就是这样!

本文链接:https://www.f2er.com/3135556.html

大家都在问