John Dorean
John Dorean

Reputation: 3874

has_secure_password insisting password is not being sent when it is

I'm attempting to securely store my user's passwords with bcrypt and I'm using the has_secure_password method to do that. Unfortunately it keeps throwing back a validation error saying I'm not supplying a password, when I am.

The parameters are being sent over JSON (this is an API application) and I'm creating the user in my controller like this:

class UsersController < ApplicationController
  def create
    @user = User.create(user_params)
  end

  private
    def user_params
      params.require(:user).permit(:email, :password, :password_confirmation) if params[:user]
    end
end

my user model is the following:

class User < ActiveRecord::Base
  require 'securerandom'

  # Email and password must exist at all times
  validates :email, presence: true

  # Email must be unique and a valid email address
  validates :email, uniqueness: true
  validates :email, email_format: { message: "Email address doesn't look like an email address" }

  # Password must be a minimum of 6 characters
  # validates :password, length: { minimum: 6 }

  # Password reset code and auth token must be unique
  validates :password_reset_code, :auth_token, uniqueness: true, allow_nil: true

  # Use secure password hashing with bcrypt
  has_secure_password

  # Create a new auth token after creation, this is so they can log in automatically
  before_create :generate_auth_token

  def generate_auth_token
    self.auth_token = SecureRandom.hex(32)
  end
end

Now, I'm sending an API request to the controller action create with the following payload:

{"email": "[email protected]", "password": "testing", "password_confirmation": "testing"}

but the validation error that always comes back is that password can't be empty. I know it's something to do with has_secure_password because I had this working before without it. Also, if I change my controller method to:

def create
  @user = User.create(email: "[email protected]", password: "testing", password_confirmation: "testing")
end

it works perfectly, and I get a user created in the database with a secure password.

Any ideas why my password parameter seems to be getting lost?

Upvotes: 0

Views: 130

Answers (1)

Doon
Doon

Reputation: 20232

Your controller is looking for a user key in the params hash and it doesnt look like you Are sending one

Try setting your create payload to

 { "user": { "email":"[email protected]", 
             "password": "testing", 
             "password_confirmation": "testing" }
 }

Upvotes: 2

Related Questions