在 Rails 3.2 应用程序中使用多个模型时,可以使用 Devise 处理身份验证。以下是如何使用 Devise 在 Rails 3.2 应用程序中处理多个模型的身份验证:
config/initializers/devise.rb
文件,并配置 Devise:Devise.setup do |config|
config.mailer_sender = 'support@example.com'
config.mailer = 'Devise::Mailer'
config.authentication_keys = [ :email ]
config.sign_out_via_token_authentication = true
endclass User < ApplicationRecord
# Include default devise modules. Others will not be touched.
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
class Admin < User
end
class Customer < User
endRails.application.routes.draw do
devise_for :users, controllers: { registrations: 'registrations' }
devise_for :admins, controllers: { registrations: 'registrations' }
devise_for :customers, controllers: { registrations: 'registrations' }
root to: 'home#index'
end在应用程序的 app/controllers/registrations_controller.rb
文件中添加 Devise 认证逻辑:class RegistrationsController < Devise::RegistrationsController
def create
build_resource(sign_up_params)
if resource.save
if resource.active_for_authentication?
set_flash_message!(:notice, :signed_up)
sign_up(resource)
else
set_flash_message!(:alert, :signed_up_but_inactive)
redirect_to :new_user_session_path
end
else
set_flash_message!(:alert, :sign_up_failed)
render :new
end
end
def update
if resource.update_with_password(update_params)
set_flash_message!(:notice, :updated)
redirect_to :edit_user_registration_path
else
set_flash_message!(:alert, :update_failed)
render :edit
end
end
end在应用程序的 app/models/user.rb
文件中添加 Devise 认证逻辑:class User < ApplicationRecord
# Include default devise modules. Others will not be touched.
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
def self.find_first_by_auth_conditions(conditions)
conditions.each do |condition|
if find_by(condition)
return find_by(condition)
end
end
nil
end
end在应用程序的 app/controllers/sessions\_controller.rb
文件中添加 Devise 认证逻辑:class SessionsController < Devise::SessionsController
def create
super
end
def update
super
end
end在应用程序的 app/models/admin.rb
文件中添加 Devise 认证逻辑:class Admin < User
end在应用程序的 app/models/customer.rb
文件中添加 Devise 认证逻辑:class Customer < User
end在应用程序的 Gemfile
中添加 Devise 和 Warden 依赖关系:gem 'devise'
gem 'warden'运行 bundle install
命令安装依赖。
5. 配置 Warden
在应用程序的 config/initializers/warden.rb
文件中配置 Warden:Warden.setup do |config|
config.authenticate_with do
warden.authenticateGemfile
中添加 Devise 的依赖关系,并运行 bundle install
命令安装依赖:models/user.rb
文件,并配置多个模型:config/routes.rb
文件中添加 Devise 认证路由:领取专属 10元无门槛券
手把手带您无忧上云