Skip to content

Instantly share code, notes, and snippets.

@codyeatworld
Created May 21, 2015 09:27
Show Gist options
  • Save codyeatworld/f54526fc810082a8b49b to your computer and use it in GitHub Desktop.
Save codyeatworld/f54526fc810082a8b49b to your computer and use it in GitHub Desktop.
module Permissions
class AdminPermission < BasePermission
def initialize(user)
allow_all
end
end
end
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :authorize
delegate :allow?, to: :current_permission
helper_method :allow?
delegate :allow_param?, to: :current_permission
helper_method :allow_param?
private
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
helper_method :current_user
def current_permission
@current_permission ||= Permissions.permission_for(current_user)
end
def current_resource
nil
end
def authorize
if current_permission.allow?(params[:controller], params[:action], current_resource)
current_permission.permit_params! params
else
redirect_to root_url, alert: "Not authorized."
end
end
end
module Permissions
class BasePermission
def allow?(controller, action, resource = nil)
allowed = @allow_all || @allowed_actions[[controller.to_s, action.to_s]]
allowed && (allowed == true || resource && allowed.call(resource))
end
def allow_all
@allow_all = true
end
def allow(controllers, actions, &block)
@allowed_actions ||= {}
Array(controllers).each do |controller|
Array(actions).each do |action|
@allowed_actions[[controller.to_s, action.to_s]] = block || true
end
end
end
def allow_param(resources, attributes)
@allowed_params ||= {}
Array(resources).each do |resource|
@allowed_params[resource] ||= []
@allowed_params[resource] += Array(attributes)
end
end
def allow_param?(resource, attribute)
if @allow_all
true
elsif @allowed_params && @allowed_params[resource]
@allowed_params[resource].include? attribute
end
end
def permit_params!(params)
if @allow_all
params.permit!
elsif @allowed_params
@allowed_params.each do |resource, attributes|
if params[resource].respond_to? :permit
params[resource] = params[resource].permit(*attributes)
end
end
end
end
end
end
module Permissions
class GuestPermission < BasePermission
def initialize
allow :users, [:new, :create]
allow :sessions, [:new, :create, :destroy]
allow :topics, [:index, :show]
end
end
end
module Permissions
class MemberPermission < BasePermission
def initialize(user)
allow :users, [:new, :create, :edit, :update]
allow :sessions, [:new, :create, :destroy]
allow :topics, [:index, :show, :new, :create]
allow :topics, [:edit, :update] do |topic|
topic.user_id == user.id
end
allow_param :topic, :name
end
end
end
module Permissions
def self.permission_for(user)
if user.nil?
GuestPermission.new
elsif user.admin?
AdminPermission.new(user)
else
MemberPermission.new(user)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment