Search code examples
ruby-on-railsdevise

Validate password when signed up


I'm working on email authentication with Devise. The issue is not to validate password when signed up. Currently, users can sign up without password, just email. I want to avoid it.

apps/views/registrations/new.html.erb

    <div class="signForm">
      <p>Email</p>
      <%= f.email_field :email, autofocus: true, autocomplete: "email" %>
    </div>
    <div class="signForm">
      <p>Username</p>
      <%= f.text_field :username %>
    </div>
    <div class="signForm">
      <p>Password</p>
      <%= f.password_field :password, autocomplete: "new-password", placeholder: "***********" %>
    </div>
    <div class="signForm">
      <p>Confirmation Password</p>
      <%= f.password_field :password_confirmation, autocomplete: "new-password", placeholder: "***********" %>
    </div>
    <div class="signForm">
      <%= f.submit "Sign up" %>
    </div>

config/routes.rb

devise_for :users, controllers: {
  omniauth_callbacks: 'omniauth_callbacks',
  confirmations: 'confirmations',
  registrations: 'registrations'
}

apps/controllers/confirmations_controller.rb

class ConfirmationsController < Devise::ConfirmationsController
  def show
    self.resource = resource_class.confirm_by_token(params[:confirmation_token])
    yield resource if block_given?

    if resource.errors.empty?
      set_flash_message(:notice, :confirmed) if is_flashing_format?

      sign_in(resource)

      respond_with_navigational(resource){ redirect_to after_confirmation_path_for(resource_name, resource) }
    else
      respond_with_navigational(resource.errors, :status => :unprocessable_entity){ render :new }
    end
  end
end

apps/controllers/registrations_controller.rb

class RegistrationsController < Devise::RegistrationsController

  protected

  def update_resource(resource, params)
    resource.update_without_password(params)
  end

  def account_update_params
    devise_parameter_sanitizer.sanitize(:account_update)
  end
end

Solution

  • Try overriding password_required in your model...

    protected
    
    def password_required?
      confirmed? ? super : false
    end
    

    reference