Rails设计令牌身份验证不使用电子邮件

时间:2017-08-14 14:59:56

标签: ruby-on-rails ruby devise

我想使用'用户名'字段代替'电子邮件'

我用了宝石

gem 'devise'
gem 'devise_token_auth'

我的模特'用户'

devise :database_authenticatable,
         :trackable, :registerable, :authentication_keys => [:username]
  include DeviseTokenAuth::Concerns::User
  has_many :projects

  def email_required?
    false
  end

  def email_changed?
    false
  end

我删除了' validatable'

尝试改变模型

change_column :users, :email, :string, :null => true
remove_index :users, :email

我也设置了配置device.rb

config.authentication_keys = [:username]
config.case_insensitive_keys = [:username]
config.strip_whitespace_keys = [:username]

但我仍有错误

"Email can't be blank",
"Email is not an email"

我做错了什么?谢谢

1 个答案:

答案 0 :(得分:0)

我找到了这个解决方案

的routes.rb

mount_devise_token_auth_for 'User', at: 'auth', :controllers => { :registrations => "registrations" }

然后自己注册

rails routes 有这个

                  Prefix Verb   URI Pattern                    Controller#Action
        new_user_session GET    /auth/sign_in(.:format)        devise_token_auth/sessions#new
            user_session POST   /auth/sign_in(.:format)        devise_token_auth/sessions#create
    destroy_user_session DELETE /auth/sign_out(.:format)       devise_token_auth/sessions#destroy
cancel_user_registration GET    /auth/cancel(.:format)         registrations#cancel
   new_user_registration GET    /auth/sign_up(.:format)        registrations#new
  edit_user_registration GET    /auth/edit(.:format)           registrations#edit
       user_registration PATCH  /auth(.:format)                registrations#update
                         PUT    /auth(.:format)                registrations#update
                         DELETE /auth(.:format)                registrations#destroy
                         POST   /auth(.:format)                registrations#create
     auth_validate_token GET    /auth/validate_token(.:format) devise_token_auth/token_validations#validate_token

可以使用方法

- valid_token?
- create_new_auth_token
- build_auth_header

查找

https://github.com/lynndylanhurley/devise_token_auth

Unpermitted Parameters adding new fields to Devise in rails 4.0

您也可以从devise_token_auth

中删除电子邮件验证

添加文件config / initializers / change_email_valid_devise_token_auth.rb

EmailValidator.class_eval do
  def validate_each(record, attribute, value)
  end
end