diff --git a/app/controllers/categories_controller.rb b/app/controllers/categories_controller.rb index da6c1fa..cb2db11 100644 --- a/app/controllers/categories_controller.rb +++ b/app/controllers/categories_controller.rb @@ -1,4 +1,6 @@ class CategoriesController < ApplicationController + before_action :require_admin, except: [:index, :show] + def index @categories = Category.paginate(page: params[:page], per_page: 5) end @@ -24,4 +26,11 @@ def show def category_params params.require(:category).permit(:name) end + + def require_admin + if !logged_in? || (logged_in? && !current_user.admin?) + flash[:danger] = "Only admins can perform that action." + redirect_to categories_path + end + end end diff --git a/test/controllers/categories_controller_test.rb b/test/controllers/categories_controller_test.rb index c8fb569..4e7bdbf 100644 --- a/test/controllers/categories_controller_test.rb +++ b/test/controllers/categories_controller_test.rb @@ -4,6 +4,7 @@ class CategoriesControllerTest < ActionController::TestCase def setup @category = Category.create(name: "sports") + @user = User.create(username: "John", email: "email@example.com", password: "password", admin: true) end test 'should get category index' do @@ -12,6 +13,7 @@ def setup end test 'should get category new' do + session[:user_id] = @user.id get :new assert_response :success end @@ -20,4 +22,11 @@ def setup get :show, params: { id: @category.id } assert_response :success end + + test 'should redirect create when admin not logged in' do + assert_no_difference 'Category.count' do + post :create, params: { category: { name: "sports" } } + end + assert_redirected_to categories_path + end end diff --git a/test/integration/create_categories_test.rb b/test/integration/create_categories_test.rb index 690dcf6..1dc0490 100644 --- a/test/integration/create_categories_test.rb +++ b/test/integration/create_categories_test.rb @@ -1,7 +1,13 @@ require 'test_helper' class CreateCategoriesTest < ActionDispatch::IntegrationTest + + def setup + @user = User.create(username: "John", email: "email@example.com", password: "password", admin: true) + end + test "get new category test and create category" do + sign_in_as(@user, "password") get new_category_path assert_template 'categories/new' assert_difference 'Category.count', 1 do @@ -14,6 +20,7 @@ class CreateCategoriesTest < ActionDispatch::IntegrationTest end test "invalid category submission results in failure" do + sign_in_as(@user, "password") get new_category_path assert_template 'categories/new' assert_no_difference 'Category.count' do diff --git a/test/test_helper.rb b/test/test_helper.rb index 92e39b2..61cec5f 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -7,4 +7,8 @@ class ActiveSupport::TestCase fixtures :all # Add more helper methods to be used by all tests here... + def sign_in_as(user, password) + post login_path, params: { session: { email: user.email, password: password } } + end + end