【问题标题】:How can I properly set up Rails 4 Devise authentication with three different user types and different authorizations for each type?如何正确设置具有三种不同用户类型和每种类型不同授权的 Rails 4 Devise 身份验证?
【发布时间】:2015-02-18 20:26:10
【问题描述】:

所以我这几天一直在研究这个问题,但无法想出一个雄辩的解决方案。网上有一些资源,但不是很全面。 这是我的情况:

规格

  • 需要对三种不同用户类型进行身份验证的 Rails 应用程序 (管理员、经理、客户)
  • 它们有非常不同的属性
  • 当他们登录时,他们会看到截然不同的视图
  • 希望维护一个登录表单
  • 每种用户类型都仅限于自己的控制器及其操作
  • 客户可以通过首页自行注册
  • 只能从管理员门户创建管理员和经理

目前,我已经设置了一个 User 类,以及 User 和 Admin、Manager、Client 之间的多态关系。我尝试使用单表继承,但由于每个用户类型都有不同的属性,我希望避免使用包含许多空值的大型单表。

建议的解决方案

  1. 多态关系。用户模型,包含管理员、经理和客户 继承。这里的问题是如何将每个模型限制为 他们各自的控制者?

  2. 用户模型,具有 has_one 关系 使用 ClientProfile 和 ManagerProfile 来处理额外的 属性。然后使用 declarative_authorization 或 CanCanCan 来 限制授权。这有助于保持应用程序干燥,只保留 一个用户模型,但视图逻辑变得复杂。

在这两种解决方案中,哪一种看起来更具可扩展性、简洁和安全?如果对通用应用程序架构有任何其他建议会更好?谢谢!

【问题讨论】:

    标签: ruby-on-rails authentication devise roles


    【解决方案1】:

    这就是我在 ROR 上设置多个用户类型的应用程序的方式

    #config/routes.rb
    AppName::Application.routes.draw do
        devise_for :users, :controllers => {
        registrations: 'users/registrations',
        :sessions => "users/sessions",
        :passwords => 'users/passwords',
        :confirmations => 'users/confirmations'
      }
    
      authenticate :user do
        namespace :users do
          ....
          get '/' => 'dashboards#index'
          root :to => 'dashboards#index'
        end
      end
    
      devise_for :admins, :controllers => {
        :sessions => "admins/sessions",
        :passwords => 'admins/passwords',
        :confirmations => 'admins/confirmations'
      }
    
      authenticate :admin do
        namespace :admins do
          ....
          get '/dashboard' => 'dashboards#index
          root :to => 'dashboards#index'
        end
      end
      root 'pages#index'
    end
    

    现在你已经有了你的路由,你可以创建你的控制器

    我有

    #app/controllers/user_controller.rb
    class UserController < ApplicationController
      before_filter :authenticate_user!
      layout 'users/default'
      before_filter :check_user_active
    
      private
      def check_user_active
        unless current_user.active
          flash[:notice]= t(:user_not_active)
          sign_out current_user
          redirect_to new_user_session_path
        end
      end
    end
    
    
    
    # app/controllers/users/sessions_controller.rb
    class Users::SessionsController < Devise::SessionsController
      layout 'users/login'
    
       def create
    
      end
    
      def destroy
      end
    end
    

    最后但并非最不重要的是意见

    只需将所有内容都放在其名称空间中,例如 #app/views/users/sessions/new.html.haml

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-07
      • 1970-01-01
      • 2017-03-29
      相关资源
      最近更新 更多