Skip to content

Instantly share code, notes, and snippets.

@stevepolitodesign
Last active January 24, 2022 14:36
Show Gist options
  • Save stevepolitodesign/3865c500839f9ef55f60831e2cf59fb5 to your computer and use it in GitHub Desktop.
Save stevepolitodesign/3865c500839f9ef55f60831e2cf59fb5 to your computer and use it in GitHub Desktop.
Handle unauthorized requests in Rails from scratch

Before

# 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

After

# 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment