simple_token_authentication 不允许的参数

Unpermitted parameters with simple_token_authentication

所以我在 Rails API Mode 中创建了一个参与者 model

控制器的外观如下:

class ParticipantsController < ApplicationController
    acts_as_token_authentication_handler_for User

    def create
        binding.pry
        participant = Participant.new(participant_params)
        puts "INFO: ----------------------------"
        puts participant.inspect
        puts params
        if(participant.save)
            render json: {
                status: 'SUCCESS',
                message: 'Participant link created',
                data: participant
            }, status: :created
        else 
            render json: {
                status: 'ERROR',
                message: 'Participant link not created',
                data: participant.errors
            }, status: :unprocessable_entity
        end
    end

    private def participant_params
        params.permit(:id_request, :user_id)
    end
end

这是 User 模型:

class User < ApplicationRecord
  acts_as_token_authenticatable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable

  validates :firstname, presence: true
  validates :lastname, presence: true
  validates :username, presence: true
  validates :address, presence: true
  validates :idcard, presence: true
end

第二行你会看到这个:acts_as_token_authentication_handler_for User

这允许我在 React 中的提取请求中添加身份验证 headers。

这是我获取它的方式:

participateToContribution = id_request => {
    const data = {
      id_request: id_request,
      user_id: localStorage.getItem('email')
    }
    console.log(data)

    fetch('http://localhost:3000/participants', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-User-Email': localStorage.getItem('email'),
        'X-User-Token': localStorage.getItem('token')
      },
      data: data
    })
  }

我用其他控制器完成了此操作并且效果很好,但现在由于某些原因,当我获取此 rails returns 时出现此错误:

Started POST "/participants" for 127.0.0.1 at 2019-07-11 19:08:36 +0200
Processing by ParticipantsController#create as */*
  User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."email" = ? ORDER BY "users"."id" ASC LIMIT ?  [["email", "titivermeesch@gmail.com"], ["LIMIT", 1]]
  ↳ /home/tristan/.rvm/gems/ruby-2.6.3/gems/activerecord-5.2.3/lib/active_record/log_subscriber.rb:98
Unpermitted parameters: :user_email, :user_token
   (0.2ms)  begin transaction
  ↳ app/controllers/participants_controller.rb:7
   (0.2ms)  rollback transaction
  ↳ app/controllers/participants_controller.rb:7
Completed 422 Unprocessable Entity in 11ms (Views: 0.4ms | ActiveRecord: 0.7ms)

我试图在 .permit() 中添加这 2 个字段,但这给了我另一个错误(我的其他控制器中没有任何这些,只是复制粘贴)。

Started POST "/participants" for 127.0.0.1 at 2019-07-11 19:13:15 +0200
   (0.5ms)  SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
  ↳ /home/tristan/.rvm/gems/ruby-2.6.3/gems/activerecord-5.2.3/lib/active_record/log_subscriber.rb:98
Processing by ParticipantsController#create as */*
  User Load (0.6ms)  SELECT  "users".* FROM "users" WHERE "users"."email" = ? ORDER BY "users"."id" ASC LIMIT ?  [["email", "titivermeesch@gmail.com"], ["LIMIT", 1]]
  ↳ /home/tristan/.rvm/gems/ruby-2.6.3/gems/activerecord-5.2.3/lib/active_record/log_subscriber.rb:98
Completed 500 Internal Server Error in 56ms (ActiveRecord: 3.3ms)



ActiveModel::UnknownAttributeError (unknown attribute 'user_email' for Participant.):

app/controllers/participants_controller.rb:5:in `create'

这是从 front-end 部分发送到此控制器的内容:

{id_request: 1, user_id: "titivermeesch@gmail.com"}

GitHub代码:https://github.com/titivermeesch/neighbourhood-app

pry 输出:

     4: def create
 =>  5:     binding.pry
     6:     participant = Participant.new(participant_params)
     7:     puts "INFO: ----------------------------"
     8:     puts participant.inspect
     9:     puts params
    10:     if(participant.save)
    11:         render json: {
    12:             status: 'SUCCESS',
    13:             message: 'Participant link created',
    14:             data: participant
    15:         }, status: :created
    16:     else
    17:         render json: {
    18:             status: 'ERROR',
    19:             message: 'Participant link not created',
    20:             data: participant.errors
    21:         }, status: :unprocessable_entity
    22:     end
    23: end

在这种情况下,您应该将这些字段(电子邮件和令牌)添加到您的用户 class。这里我们有一个 https://gist.github.com/bosskovic/816623404b60b30726a8

的完整示例

如果您已经有了这些字段,您只需将 user_email 参数正确映射到 email 列即可。

你不允许他们在这里

private

def participants_params
    params.permit(:id_request, :user_id)
end

您必须像这样将它们添加到该数组中

private

def participants_params
    params.permit(:id_request, :user_id, :user_email, :user_token)
end

现在你说那会引发错误,因为 user_email 不是参与者的字段。您需要添加它以便为其保存值,否则您需要将其从发送的参数数组中取出,然后对象将被保存。你不能发送未经许可的参数并尝试保存它,它只是行不通。

唯一的其他解决方案是重新编写您的创建方法,但这并不是真正的解决方案。

def create
  participant = Participant.new
  participant.request_id = params[:participant][:id_request]
  participant.user_id = params[:participant][:user_id]
  if(participant.save)

  ...

更新 fetch

fetch('http://localhost:3000/participants', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-User-Email': localStorage.getItem('email'),
    'X-User-Token': localStorage.getItem('token')
  },
  body: JSON.stringify({data)
})

}

和数据

const data = {
     participant: {

      id_request: id_request,
      user_id: localStorage.getItem('email')
    }
}

participant_params作为

def participants_params
  params.require(:participant).permit(:id_request, :user_id)
end