Skip to content

Instantly share code, notes, and snippets.

@chanakasan
Forked from stevenharman/constraint_staff.rb
Last active September 2, 2015 16:41
Show Gist options
  • Save chanakasan/61c39e3f070734539d36 to your computer and use it in GitHub Desktop.
Save chanakasan/61c39e3f070734539d36 to your computer and use it in GitHub Desktop.
Use Routing Constraints to limit access to Rails Routes. An example from Brewdega Cellar app.
module Constraint
class Staff
def matches?(request)
warden(request).authenticated? &&
warden(request).user.staff?
end
private
def warden(request)
request.env['warden']
end
end
end
require 'constraint/staff'
describe Constraint::Staff do
subject(:constraint) { described_class.new }
let(:a_request) { double('Request', env: { 'warden' => warden }) }
let(:warden) { double('Warden') }
it 'denies an unauthenticated user' do
warden.stub(:authenticated?) { false }
expect(constraint.matches?(a_request)).to be_false
end
context 'when authenticated' do
let(:user) { double('User') }
before do
warden.stub(:authenticated?) { true }
warden.stub(:user) { user }
end
it 'denies a non-staff user' do
user.stub(:staff?) { false }
expect(constraint.matches?(a_request)).to be_false
end
it 'allows an staff user' do
user.stub(:staff?) { true }
expect(constraint.matches?(a_request)).to be_true
end
end
end
BrewdegaCellar::Application.routes.draw do
namespace :staff, constraints: Constraint::Staff.new do
resource :style_guide, only: [:show]
resource :mobile_desktop_preference, only: [:show, :destroy]
resources :maintenance_tasks, only: [:index, :create]
resources :neglected_data, only: [:index]
require 'sidekiq/web'
mount Sidekiq::Web => 'sidekiq', as: :background_jobs
root to: 'dashboards#show'
end
get '/:username' => 'cellars#show', as: :cellar
root :to => 'home#index'
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment