Add Forbiden Exception and refactor existing actions

openid
Micha Wrobel 13 years ago
parent 4f47f0a7fc
commit 5d52be2bae

@ -5,6 +5,10 @@ class ApplicationController < ActionController::Base
rescue_from(ActiveRecord::RecordNotFound) { render 'exceptions/not_found' }
class Unauthorized < Exception; end
class Forbiden < Exception; end
rescue_from Unauthorized, :with => :unathorized
rescue_from Forbiden, :with => :forbiden
helper_method :current_user
@ -28,4 +32,19 @@ class ApplicationController < ActionController::Base
raise Unauthorized unless current_user
end
def forbiden
if request.xhr?
render :json => "Forbiden", :status => 403
else
redirect_to root_path, :alert => "This action is forbiden"
end
end
def unathorized
if request.xhr?
render :json => "Unauthorized", :status => 401
else
redirect_to login_path, :notice => "Please login"
end
end
end

@ -24,7 +24,7 @@ class CommentsController < ApplicationController
if comment.user == current_user
respond_with comment.delete
else
raise Unauthorized
raise Forbiden
end
end

@ -0,0 +1,69 @@
require 'spec_helper'
class FakeController < ApplicationController
def foo
raise Unauthorized
end
def bar
raise Forbiden
end
end
describe FakeController do
describe "#ensure_authenticated!" do
end
describe "action raise unauthorized" do
context "when xhr" do
before{ request.stub(:xhr?).and_return(true) }
it "response with 401" do
get :foo
response.status.should == 401
end
end
context "when typical request" do
it "redirects to login_path" do
get :foo
flash[:notice].should == "Please login"
should redirect_to(login_path)
end
end
end
context "when action raise forbiden" do
context "when xhr" do
before{ request.stub(:xhr?).and_return(true) }
it "response with 401" do
get :bar
response.status.should == 403
end
end
context "when typical request" do
it "redirects to root_path" do
get :bar
flash[:alert].should == "This action is forbiden"
should redirect_to(root_path)
end
end
end
end

@ -82,7 +82,7 @@ describe CommentsController do
it "calls delete on comment" do
comment.should_receive(:delete)
delete :destroy, :id => 1
delete :destroy, :id => 1, :format => :json
end
end
@ -94,10 +94,14 @@ describe CommentsController do
comment.stub(:user).and_return(other_user)
end
it "raise Unauthorized exception" do
expect {
delete :destroy, :id => 1
}.to raise_error
it "doesn't call delete on comment" do
comment.should_not_receive(:delete)
delete :destroy, :id => 1, :format => :json
end
it "responses with 403 when xhr" do
xhr :delete, :destroy, :id => 1, :format => :json
response.status.should == 403
end
end

Loading…
Cancel
Save