Last active
December 25, 2015 16:39
-
-
Save Electron-libre/7007807 to your computer and use it in GitHub Desktop.
This show how to not write right management with Pundit.
This file contains hidden or 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 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 |
This file contains hidden or 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 PersonPolicy < ApplicationPolicy | |
class Scope < Struct.new(:user, :scope) | |
def resolve | |
scope | |
end | |
end | |
end |
This file contains hidden or 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 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