scinote-web/app/controllers/client_api/permissions_controller.rb

64 lines
2 KiB
Ruby
Raw Normal View History

2017-12-02 00:15:15 +08:00
module ClientApi
class PermissionsController < ApplicationController
before_action :generate_permissions_object, only: :status
2017-12-04 20:25:48 +08:00
2017-12-13 15:57:50 +08:00
def status
2017-12-02 00:15:15 +08:00
respond_to do |format|
format.json do
2017-12-04 20:25:48 +08:00
render json: @permissions, status: :ok
2017-12-02 00:15:15 +08:00
end
end
end
2017-12-04 20:25:48 +08:00
private
def generate_permissions_object
sanitize_permissions!
@permissions = {}
2018-01-08 23:28:20 +08:00
obj = @resource.fetch(:type)
.constantize
.public_send(:find_by_id, @resource.fetch(:id) {
raise ArgumentError, 'ID must be present'
}) if @resource
2018-01-12 18:38:52 +08:00
@required_permissions.each do |permission|
trim_permission = permission.gsub('can_', '')
2018-01-08 23:28:20 +08:00
if @resource
# return false if object does not exist
2018-01-12 18:38:52 +08:00
result = obj ? @holder.eval(trim_permission, current_user, obj) : false
2018-01-08 23:28:20 +08:00
@permissions.merge!(permission => result)
else
2017-12-04 20:25:48 +08:00
@permissions.merge!(
2018-01-08 23:28:20 +08:00
permission => @holder.eval_generic(
2018-01-12 18:38:52 +08:00
trim_permission, current_user
2018-01-08 23:28:20 +08:00
)
2017-12-04 20:25:48 +08:00
)
end
end
end
def sanitize_permissions!
2018-01-08 23:28:20 +08:00
@required_permissions = params.fetch(:requiredPermissions) do
2017-12-04 20:25:48 +08:00
:permissions_array_missing
end
@holder = Canaid::PermissionsHolder.instance
@required_permissions.each do |permission|
2018-01-08 23:28:20 +08:00
next if @holder.has_permission?(permission.gsub('can_', ''))
2017-12-04 20:25:48 +08:00
# this error should happen only in development
raise ArgumentError, "Method #{permission} has no related " \
"permission registered."
end
# sanitize resource, this error should happen only in development
raise ArgumentError,
"Resource #{@resource} does not exists" unless resource_valid?
end
def resource_valid?
@resource = params[:resource]
return true unless @resource
2018-01-08 23:28:20 +08:00
return true if Object.const_get(@resource.fetch(:type).classify)
2017-12-04 20:25:48 +08:00
rescue NameError
return false
end
2017-12-02 00:15:15 +08:00
end
end