Last active
September 2, 2015 16:41
-
-
Save stevenharman/0424c2d72af84d8762cc to your computer and use it in GitHub Desktop.
Use Routing Constraints to limit access to Rails Routes. An example from Brewdega Cellar app.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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