简体   繁体   中英

How I can add a custom error key in Devise custom authentication strategy?

It is necessary to make so that the authorization errors in the Devise worked in the same way as the ActiveModel::Errors in RubyOnRails, ie The error was available in the hash by the key corresponding to the field name.

I want to get response from server like this { errors: { user: 'User not found' } } or {errors: { password: 'Invalid password' } } , but I still get { error: 'User not found' } from server.

My custom strategy:

module Devise
  module Strategies
    class Password < Authenticatable

      def authenticate!
        resource  = password.present? && mapping.to.find_for_database_authentication(authentication_hash)

        if resource
          if validate(resource){ resource.valid_password?(password) }
            remember_me(resource)
            resource.after_database_authentication
            success!(resource)
          else
            errors.add(:password, I18n.t('devise.failure.invalid_password'))
            fail!(:invalid_password)
          end
        else
          errors.add(:user, I18n.t('devise.failure.user_not_found'))
          fail!(:user_not_found)
        end
      end

    end
  end
end

答案是修改config / locales / devise.en.yml,但您必须添加设置,默认情况下它们不存在。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM