Skip to content

Instantly share code, notes, and snippets.

@Electron-libre
Last active December 25, 2015 16:39
Show Gist options
  • Save Electron-libre/7007807 to your computer and use it in GitHub Desktop.
Save Electron-libre/7007807 to your computer and use it in GitHub Desktop.
This show how to not write right management with Pundit.
class ApplicationController < ActionController::Base
# Includes Authorization mechanism
include Pundit
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
# Globally rescue Authorization Errors in controller.
# Returning 403 Forbidden if permission is denied
rescue_from Pundit::NotAuthorizedError, with: :permission_denied
# Enforces access right checks for individuals resources
after_filter :verify_authorized, :except => :index
# Enforces access right checks for collections
after_filter :verify_policy_scoped, :only => :index
private
def permission_denied
head 403
end
end
class PersonPolicy < ApplicationPolicy
class Scope < Struct.new(:user, :scope)
def resolve
scope
end
end
end
class ApplicationPolicy
attr_reader :user, :record
def initialize(user, record)
@user = user
@record = record
end
def user_activities
@user.roles.select(:activities).distinct.map(&:activities).flatten
end
def inferred_activity(method)
"#{@record.class.name.downcase}:#{method.to_s}"
end
def method_missing(name,*args)
if name.to_s.last == '?'
user_activities.include?(inferred_activity(name.to_s.gsub('?','')))
else
super
end
end
def scope
Pundit.policy_scope!(user, record.class)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment