Skip to content

Instantly share code, notes, and snippets.

@vjm
Last active January 4, 2016 03:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vjm/e7d9dbb7603553bfbd2a to your computer and use it in GitHub Desktop.
Save vjm/e7d9dbb7603553bfbd2a to your computer and use it in GitHub Desktop.
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
if Rails.env.development?
# https://github.com/RailsApps/rails-devise-pundit/issues/10
include Pundit
# https://github.com/elabs/pundit#ensuring-policies-are-used
after_action :verify_authorized, except: :index
after_action :verify_policy_scoped, only: :index
rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
private
def user_not_authorized
flash[:alert] = "Access denied." # TODO: make sure this isn't hard coded English.
redirect_to (request.referrer || root_path) # Send them back to them page they came from, or to the root page.
end
end
end
# config/initializers/pundit.rb
# Extends the ApplicationController to add Pundit for authorization.
# Modify this file to change the behavior of a 'not authorized' error.
# Be sure to restart your server when you modify this file.
module PunditHelper
extend ActiveSupport::Concern
included do
include Pundit
# https://github.com/elabs/pundit#ensuring-policies-are-used
after_filter :verify_authorized, except: :index
after_filter :verify_policy_scoped, only: :index
rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
end
private
def user_not_authorized
flash[:alert] = "Access denied." # TODO: make sure this isn't hard coded English.
redirect_to (request.referrer || root_path)
end
end
ApplicationController.send :include, PunditHelper unless Rails.env.development?
@Meekohi
Copy link

Meekohi commented Apr 1, 2015

Hey is there a point of doing one thing in dev and another in prod? Why not just move everything to application_controller.rb?

@peterkle
Copy link

peterkle commented Jan 4, 2016

From the forum post in comment: "If you move the Pundit includes into the ApplicationController, move them back when you are done with development so you get the benefit of faster performance."

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment