58 lines
1.7 KiB
Ruby
58 lines
1.7 KiB
Ruby
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
|
|
protect_from_forgery unless: -> { request.format.json? }
|
|
# skip_before_action :verify_authenticity_token
|
|
after_action :flash_to_http_header
|
|
before_action :get_footer_tokens
|
|
|
|
if (Rails.env.development? || Rails.env.test?)
|
|
include Pundit
|
|
after_action :verify_authorized, unless: -> { devise_controller? }
|
|
# after_action :verify_policy_scoped, only: :index
|
|
rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
|
|
|
|
private
|
|
|
|
def user_not_authorized(exception)
|
|
policy_name = exception.policy.class.to_s.underscore
|
|
# flash[:alert] = "#{policy_name}.#{exception.query}"
|
|
# flash[:alert] = "Unable to #{exception.query[0..-2]} #{policy_name.split("_")[0].capitalize}"
|
|
flash[:error] = t "#{policy_name}.#{exception.query}", scope: "pundit", default: :default
|
|
redirect_to (request.referrer || root_path)
|
|
end
|
|
end
|
|
|
|
def authenticate_user!(args = nil)
|
|
current_user.present?
|
|
end
|
|
|
|
def current_user
|
|
super || User.where(soft_token: soft_token).first_or_initialize
|
|
end
|
|
|
|
private
|
|
|
|
def add_body_css_class(css_class)
|
|
@body_css_classes ||= []
|
|
@body_css_classes << css_class
|
|
end
|
|
|
|
def get_footer_tokens
|
|
@footer_tokens = authorize Token.all
|
|
end
|
|
|
|
def flash_to_http_header
|
|
return unless request.xhr?
|
|
return if flash.empty?
|
|
response.headers['X-FlashMessages'] = flash.to_hash.to_json
|
|
flash.discard # don't want the flash to appear when you reload page
|
|
end
|
|
|
|
def soft_token
|
|
session[:user_token] ||= SecureRandom.hex(8)
|
|
end
|
|
|
|
end
|