How to skip has_secure_password validations

后端 未结 3 519
忘掉有多难
忘掉有多难 2020-12-09 03:22

In my app, only admins can create new User records. The user is emailed an activation link where they set their password.

I\'d like to use the has_secure_passord met

3条回答
  •  春和景丽
    2020-12-09 04:06

    I decided to do my own custom authentication. The following solution will validate passwords but only when they are being set. This allows admins to create users without adding a password.

    class User < ActiveRecord::Base
      include BCrypt
    
      attr_accessor :password, :password_confirmation
    
      validates :password, length: (6..32), confirmation: true, if: :setting_password?
    
      def password=(password)
        @password = password
        self.password_hash = Password.create(password)
      end
    
      def authenticate(password)
        password.present? && password_hash.present? && Password.new(password_hash) == password
      end
    
    private
    
      def setting_password?
        password || password_confirmation
      end
    
    end
    

    If someone posts an answer that allows me to still use the has_secure_password method, I'll accept it instead.

提交回复
热议问题