I'm working on my first rails api server.
I've got a controller for my User
model that looks as such:
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
What I want and currently have for these two controller methods is:
/users
fetch all users only if the authenticated user making the request is of roleadmin
/users/:id
fetch a user byid
only if the authenticated user making the request has a matchingid
or is of roleadmin
The current implementation breaks the DRY philosophy. The reasoning is that the logic for handling whether or not the requesting user has the permissions to access the requested resource(s) is repeated across both controller methods. Furthermore, any model's controller method for show
will repeat the logic for checking whether or not the requested resource exists. I also feel like this kind of implementation makes for fat controllers, where I'd rather them be skinny.
What I want to know from the community and from those that have solved this problem before; what is the best way to go about this in order to conform to the DRY philosophy and to keep controllers skinny.
Good to know: I'm using devise and devise-token-auth for authentication.