Skip to content

Instantly share code, notes, and snippets.

@jules2689
Last active August 29, 2015 14:12
Show Gist options
  • Save jules2689/22879a0cadfe4904bf6b to your computer and use it in GitHub Desktop.
Save jules2689/22879a0cadfe4904bf6b to your computer and use it in GitHub Desktop.
# Will restrict the [:create, :new] actions to a parent object
# Will restrict the [:index, :show, :edit, :update, :destroy] actions to the owner (parent) of the kid
class KidsController < RestrictedParentController
...
end
class RestrictedParentController < ApplicationController
before_action :authenticate!
before_action :set_parent
before_action :set_resource, only: [:show, :edit, :update, :destroy]
before_action :authenticate_view!
protected
def authenticate!
redirect_auth current_user.role unless current_user.parent?
end
def authenticate_view!
redirect_auth current_user.role unless allowed_view?
end
def allowed_view?
current_user.parent? && current_user.role == @parent
end
def set_parent
@parent = Parent.find(params[:parent_id])
end
def set_resource
@resource = resource_constant.find(params[:id])
end
# Example:
# If we are subclassing this in KidsController,
# controller will be "kid", so this will
# capitalize and constantize it to "Kid"
def resource_constant
controller.humanize.constantize
end
# Example:
# If we are calling this from the subclasses "KidsController"
# we will get "Kids", and this will return "Kid"
def controller
params[:controller].singularize
end
# To be overriden in subclasses
def resource_params
{}
end
end
# Handles Format for Auth Methods
def redirect_auth(url)
respond_to do |format|
format.html do
flash[:error] = "You do not have permission to view or modify this resource."
redirect_to url
end
format.json do
head :unauthorized
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment