使用has_secure_password

时间:2018-05-30 10:42:28

标签: ruby-on-rails api bcrypt

我使用rails new recruiter --api -S -C -T -d postgresql创建了一个新的Rails应用,以获得一个简单的API。然后我取消注释gem 'bcrypt', '~> 3.1.7'并运行bundle install。然后,我创建了一个带有rails g scaffold User email:string:uniq password_digest:string is_admin:boolean is_agent:boolean的用户脚手架,并将has_secure_password添加到模型中。当我向/users发送POST请求时,我得到"password": "can't be blank"

# user.rb

class User < ApplicationRecord
  has_secure_password
end
# users_controller.rb

class UsersController < ApplicationController
  before_action :set_user, only: [:show, :update, :destroy]

  # GET /users
  def index
    @users = User.all

    render json: @users
  end

  # GET /users/1
  def show
    render json: @user
  end

  # POST /users
  def create
    @user = User.new(user_params)

    if @user.save
      render json: @user, status: :created, location: @user
    else
      render json: @user.errors, status: :unprocessable_entity
    end
  end

  # PATCH/PUT /users/1
  def update
    if @user.update(user_params)
      render json: @user
    else
      render json: @user.errors, status: :unprocessable_entity
    end
  end

  # DELETE /users/1
  def destroy
    @user.destroy
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_user
      @user = User.find(params[:id])
    end

    # Only allow a trusted parameter "white list" through.
    def user_params
      params.require(:user).permit(:email, :password_digest, :is_admin, :is_agent)
    end
end

这是Postman的JSON POST请求: JSON POST request from Postman

我做错了什么?我希望这可以创建一个新用户,其加密密码保存在password_digest中。我尝试重新运行迁移并重新启动服务器。我尝试将password_confirmation的条目添加到JSON POST请求中。结果相同。我甚至在bcrypthas_secure_password之外的所有相同步骤中构建了一个测试应用程序,并且POST返回新用户,因此,问题必须与我如何使用{{1} }。我可以在Rails控制台中看到密码没有与用户一起传递,但是,我不知道为什么。

bcrypt

2 个答案:

答案 0 :(得分:0)

您不允许user_params中的密码。可能像以下一样可以工作

def user_params
      params.require(:user).permit(:email, :password, :is_admin, :is_agent)
end

有关密码摘要的更多信息https://medium.com/@tpstar/password-digest-column-in-user-migration-table-871ff9120a5

此外,JSON请求需要包装在user对象中:

{
  "user":
  {
    "email": "user@example.com",
    "password": "password",
    "is_admin": true,
    "is_agent": true
  }
}

答案 1 :(得分:0)

问题在于:

params.require(:user).permit(:email, :password_digest, :is_admin, :is_agent)

您发送:password,但允许:password_digest