thirteen-tien-len/app/controllers/application_controller.rb

46 lines
1.2 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
after_action :flash_to_http_header
if (Rails.env.development? || Rails.env.test?)
# 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.'
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