简体   繁体   中英

Allow multiple users with same email with Devise Token Auth

I'd like to allow multiple users with the same email to be created, using devise-token-auth .

Rather than this error being thrown.

@details={:email=>[{:error=>:taken, :value=>"testttt@gmail.com"}]}>

I expected that removing devise:validatable from user.r b would have worked, but it did not.

user.rb

class User < ActiveRecord::Base
  extend Devise::Models
  include DeviseTokenAuth::Concerns::User
  
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable
end

I found this a similar SO question from years ago, but the suggestions did not work.

I'm wondering if this is specifically a devise-token-auth issue, rather than devise.

Has anyone solved this before?

I could only find a hacky way to achieve this so far, and wanted to share.

Given there doesn't appear to be a simple way to do this.

I had to set the provider method from DeviseTokenAuth::Concerns::ResourceFinder to nil . The default is hardcoded "email" .

    def provider
      nil
    end

So when build_resource is called in the registrations_controller.rb , it won't auto set provider="email" .

Without provider="email" , the "Email already taken" error no longer thrown.

    def build_resource
      @resource            = resource_class.new(sign_up_params)
      @resource.provider   = provider

      # honor devise configuration for case_insensitive_keys
      if resource_class.case_insensitive_keys.include?(:email)
        @resource.email = sign_up_params[:email].try(:downcase)
      else
        @resource.email = sign_up_params[:email]
      end
    end

But by changing the logic above, uid is no longer updated with the value of the user's email. So I added a callback on User.rb to compensate.

  after_initialize do
    self.uid = self.email
  end

This works, but I'd love a simpler way to achieve this.

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