deny is a simple DSL for doing authorizations in Ruby on Rails controllers. It follows the principle of default deny: all requests are denied unless explicitly permitted.
First, include the Deny module to your ApplicationController. This sets up
the controller to deny all requests made.
class ApplicationController
include Deny::Controller
end
Lets say you have a ProjectsController:
class ProjectsController < ApplicationController
def show
end
helper_method :project
def project
@project ||= Project.find(params[:id])
end
end
If you now try to access projects#show now, you'll get a 402 Forbidden
error page. The behavior is customizable.
Allow rules perform authorization on action context per each request.
If all defined allow rules return true, the request is permitted. Otherwise
the request is forbidden. The request will also be forbidden if you don't
specify any allow rules for it.
The rules can take a form of Ruby code block that is executed on all actions, or use a generic matcher created elsewhere.
For example, to define all admins and project members can access projects#show,
you could do:
class ProjectsController < ApplicationController
authorization_on :show do
allow :admin
allow do
@project = Project.find(params[:id])
@project.members.include?(@project)
end
end
def show
something
end
end
The generic admin rule could be defined in ApplicationController:
class ApplicationController < ActionController::Base
allow_rule(:admin) do
current_user.admin?
end
end