Last active
August 29, 2015 14:12
-
-
Save jules2689/22879a0cadfe4904bf6b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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