如何无需修改全部15个账户端点实现员工账户访问权限限制?
问题分析与解决方案
当前的实现方式显然不是最优解——15个端点都要重复编写用户类型判断逻辑,不仅代码冗余度极高,后续维护(比如调整权限规则、新增用户类型)时容易出现漏改,而且硬编码ACCOUNTS_IDS也会导致权限调整不够灵活。
以下是几种无需逐个修改端点的优化方案:
1. 模型层封装权限过滤Scope
在Account模型中定义一个动态Scope,把用户权限对应的查询逻辑统一封装,所有控制器方法直接调用该Scope即可:
class Account < ApplicationRecord scope :accessible_by, ->(user) do case user.user_type when 'Admin' all when 'Employee' where(id: ACCOUNTS_IDS) # 建议后续替换为数据库存储的权限配置,而非硬编码数组 when 'Manager' all.includes(:account_managers).exclude_pending end end end
之后所有账户相关端点的查询逻辑可以统一简化:
def index @accounts = Account.accessible_by(@current_user) @accounts = optional_paginate(@accounts) end def show @account = Account.accessible_by(@current_user).find(params[:id]) end
2. 控制器层面用Concern封装权限逻辑
创建一个控制器关注点,将获取可访问账户的逻辑抽离出来,所有账户相关控制器直接引入该关注点:
# app/controllers/concerns/account_authorization_concern.rb module AccountAuthorizationConcern extend ActiveSupport::Concern private def accessible_accounts case @current_user.user_type when 'Admin' Account.all when 'Employee' Account.where(id: ACCOUNTS_IDS) when 'Manager' Account.all.includes(:account_managers).exclude_pending end end end
在控制器中引入并使用:
class AccountsController < ApplicationController include AccountAuthorizationConcern def index @accounts = optional_paginate(accessible_accounts) end def edit @account = accessible_accounts.find(params[:id]) end # 其他端点同理 end
3. 优化权限配置的灵活性
如果员工可访问的账户是动态变化的,建议把ACCOUNTS_IDS从硬编码数组改为数据库存储(比如给Employee模型添加关联表或字段,存储其可访问的账户ID集合),这样调整权限时无需修改代码,直接操作数据即可:
# 示例:假设Employee模型有account_ids字段存储可访问账户ID when 'Employee' Account.where(id: @current_user.account_ids)
内容的提问来源于stack exchange,提问作者b d
相关产品推荐
相关产品推荐

