thirteen-tien-len/app/controllers/application_controller.rb
2023-09-18 18:01:45 +00:00

46 lines
1.3 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
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}"
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 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