Skip to content

Commit 1b7d0e0

Browse files
author
Ryan Bigg
committed
Section 7.1.3: Restrict access to project actions to admins only
1 parent ff4a0ba commit 1b7d0e0

File tree

4 files changed

+40
-0
lines changed

4 files changed

+40
-0
lines changed

ticketee/app/controllers/projects_controller.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
class ProjectsController < ApplicationController
2+
before_action :authorize_admin!, except: [:index, :show]
23
before_action :set_project, only: [:show,
34
:edit,
45
:update,
@@ -55,4 +56,15 @@ def set_project
5556
def project_params
5657
params.require(:project).permit(:name, :description)
5758
end
59+
60+
private
61+
62+
def authorize_admin!
63+
authenticate_user!
64+
65+
unless current_user.admin?
66+
flash[:alert] = "You must be an admin to do that."
67+
redirect_to root_path
68+
end
69+
end
5870
end

ticketee/spec/controllers/projects_controller_spec.rb

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,28 @@
11
require 'rails_helper'
22

33
RSpec.describe ProjectsController, :type => :controller do
4+
let(:user) { FactoryGirl.create(:user) }
5+
before do
6+
allow(controller).to receive(:authenticate_user!)
7+
allow(controller).to receive(:current_user).and_return(user)
8+
end
9+
10+
context "standard users" do
11+
{ new: :get,
12+
create: :post,
13+
edit: :get,
14+
update: :put,
15+
destroy: :delete }.each do |action, method|
16+
17+
it "cannot access the #{action} action" do
18+
send(method, action, :id => FactoryGirl.create(:project))
19+
20+
expect(response).to redirect_to(root_path)
21+
expect(flash[:alert]).to eql("You must be an admin to do that.")
22+
end
23+
end
24+
end
25+
426
it "displays an error for a missing project" do
527
get :show, id: "not-here"
628

ticketee/spec/features/deleting_projects_spec.rb

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
require "rails_helper"
22

33
feature "Deleting projects" do
4+
before do
5+
login_as(FactoryGirl.create(:user, :admin))
6+
end
47
scenario "Deleting a project" do
58
FactoryGirl.create(:project, name: "Sublime Text 3")
69

ticketee/spec/features/editing_projects_spec.rb

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
require "rails_helper"
22

33
feature "Editing Projects" do
4+
before do
5+
login_as(FactoryGirl.create(:user, :admin))
6+
end
47
before do
58
FactoryGirl.create(:project, name: "Sublime Text 3")
69

0 commit comments

Comments
 (0)