我正在开发我的第一个 rails api 服务器。
我的User
模型有一个控制器,看起来像这样:
class UsersController < ApplicationController
def index
if current_user.admin?
@users = User.all
render json: @users
else
render json: { message: 'You do not have the appropriate permissions to access this resource' }, status: 401
end
end
def show
if User.exists?(@id)
@id = params[:id]
if current_user.id.to_s == @id || current_user.admin?
@user = User.find(@id)
render json: @user
else
render json: { message: 'You do not have the appropriate permissions to access this resource' }, status: 401
end
else
render json: { message: 'Requested resource not found' }, status: 404
end
end
end
对于这两种控制器方法,我想要并且目前拥有的是:
/users
仅当发出请求的经过身份验证的用户具有角色时才获取所有用户admin
/users/:id
id
仅当发出请求的经过身份验证的用户具有匹配id
或具有角色时才获取用户admin
当前的实现打破了 DRY 理念。原因是处理请求用户是否有权访问所请求资源的逻辑在两个控制器方法中重复。此外,任何模型的控制器方法show
都会重复检查请求的资源是否存在的逻辑。我也觉得这种实现方式适用于胖控制器,我宁愿它们是瘦的。
我想从社区和以前解决过这个问题的人那里知道什么;为了符合 DRY 理念并保持控制器瘦身,最好的方法是什么。
很高兴知道:我正在使用devise和devise-token-auth进行身份验证。