Rails 使用 devise 从两个数据库表进行身份验证登录

Rails Sign in using devise to authenticate from two db tables

我有 2 个数据库 table,即 coreteamuser。两种型号都配置了设计。 现在要登录核心团队,我的 API 是:localhost:3000/api/v1/core_teams/sign_in 以及以下请求数据。

{ 
  "core_team": {
    "email": "ba+admin@gmail.com",
    "password": "Password21"
  }
}

而用户登录的API是:localhost:3000//api/v1/users/sign_in 使用以下请求数据。

{
  "user": {
    "email": "ba+user@gmail.com",
    "password": "Password20"
  }
}

下面是我的 routes.rb 文件

 Rails.application.routes.draw do

 root to: 'users#index'

scope 'api/v1', defaults: { format: :json } do
 devise_for :core_teams, controllers: {
   sessions: 'api/v1/sessions',
   passwords: 'api/v1/passwords'
  }

 devise_for :users, controllers: {
   sessions: 'api/v1/sessions',
   invitations: 'api/v1/invitations',
   passwords: 'api/v1/passwords',
   registrations: 'api/v1/registrations'
  }
  end
end

我正在使用 devise sessionscontroller 登录。唯一的区别是我呈现数据的方式。

我的sessions_controller.rb如下:

module Api
 module V1
  class SessionsController < Devise::SessionsController
   private

    def respond_with(resource, _opts = {})
      render json: resource
    end

    def respond_to_on_destroy
      head :no_content
    end

   end
  end
 end

现在我的目标是只有一个 API 调用使用相同类型的请求数据登录。有两个不同用户的原因 table 是我的应用程序是多租户的,核心团队在租户之外,用户在租户内部。

试试这个

路线

post "/api/v1/sign_in" => "api/v1/sessions#create"

devise_for :users, ...
devise_for :core_teams, ...

api/v1/sessions_controller.rb

module Api
  module V1
    class SessionsController < Devise::SessionsController
      before_action :rewrite_request_params, only: %i[create]

    protected
      def devise_mapping
        @devise_mapping ||= Devise.mappings[account_name || :user]
      end

    private
      def rewrite_request_params
        return unless account_name
        request.params[account_name] = {
          email: params[:email],
          password: params[:password],
        }
      end

      def account_name
        @account_name ||= account.class.name.underscore.to_sym if account
      end

      def account
        return if params[:email].blank?
        return @account if defined? @account
        @account = CoreTeam.find_by(email: params[:email]) || User.find_by(email: params[:email])
      end
    end
  end
end

这将允许您将 UserCoreTeam

的参数提交给 /api/v1/sign_in

首先它将在 core_teams table 中查找 account,然后是 users table。如果找到它将重写 request.params

# core_teams
$.post('/api/v1/sign_in', {
  "email": "ba+admin@gmail.com",
  "password": "Password21"
})

# users
$.post('/api/v1/sign_in', {
  "email": "ba+user@gmail.com",
  "password": "Password20"
})