Skip to content

Instantly share code, notes, and snippets.

@Electron-libre
Last active December 25, 2015 16:39
Show Gist options
  • Select an option

  • Save Electron-libre/7007807 to your computer and use it in GitHub Desktop.

Select an option

Save Electron-libre/7007807 to your computer and use it in GitHub Desktop.

Revisions

  1. Electron-libre revised this gist Oct 16, 2013. 2 changed files with 35 additions and 0 deletions.
    27 changes: 27 additions & 0 deletions application_controller.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,27 @@
    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
    8 changes: 8 additions & 0 deletions person_policy.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,8 @@
    class PersonPolicy < ApplicationPolicy

    class Scope < Struct.new(:user, :scope)
    def resolve
    scope
    end
    end
    end
  2. Electron-libre created this gist Oct 16, 2013.
    29 changes: 29 additions & 0 deletions pundit_metaprograming_acces_rights.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,29 @@
    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