# app/controllers/concerns/authorizable.rb
module Authorizable
extend ActiveSupport::Concern
included do
def authorize_request(from:, against:)
if from != against
raise Authorizable::NotAuthorized
end
end
end
class NotAuthorized < StandardError
def initialize(message="You are not authorized to make this request")
super
end
end
end
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
include Authorizable
rescue_from Authorizable::NotAuthorized, with: :handle_unauthorized_request
private
def handle_unauthorized_request
redirect_to root_path, alert: "You are not allowed to perform that action"
end
end
# app/controllers/webpages_controller.rb
class WebpagesController < ApplicationController
def destroy
@webpage = Webpage.find_by!(slug: params[:slug])
authorize_request(from: current_user, against: @webpage.user)
@webpage.nullify_owner
redirect_to my_links_path, notice: "Link deleted."
end
end
# app/controllers/webpages_controller.rb
class WebpagesController < ApplicationController
def destroy
@webpage = current_user.webpages.find_by!(slug: params[:slug])
@webpage.nullify_owner
redirect_to my_links_path, notice: "Link deleted."
end
end