From 15c45ca83c7bf70c7140ac740cebd76e5c0c97fb Mon Sep 17 00:00:00 2001 From: Dan Elbert Date: Thu, 21 Jan 2016 11:47:30 -0600 Subject: [PATCH] Added some security --- app/controllers/application_controller.rb | 8 ++++++++ app/controllers/recipes_controller.rb | 23 ++++++++++++++--------- 2 files changed, 22 insertions(+), 9 deletions(-) diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 778c726..d6fe376 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -17,6 +17,14 @@ class ApplicationController < ActionController::Base end end + def ensure_owner(item) + unless current_user && item && (item.user_id == current_user.id || current_user.admin?) + flash[:warning] = "Operation Not Permitted" + return redirect_to root_path + end + yield if block_given? + end + def current_user @current_user ||= User.find(session[:user_id]) if session[:user_id] end diff --git a/app/controllers/recipes_controller.rb b/app/controllers/recipes_controller.rb index 8eabbf5..ccf7c26 100644 --- a/app/controllers/recipes_controller.rb +++ b/app/controllers/recipes_controller.rb @@ -28,6 +28,7 @@ class RecipesController < ApplicationController # GET /recipes/1/edit def edit + ensure_owner @recipe end # POST /recipes @@ -44,21 +45,25 @@ class RecipesController < ApplicationController # PATCH/PUT /recipes/1 def update - if @recipe.update(recipe_params) - redirect_to @recipe, notice: 'Recipe was successfully updated.' - else - render :edit + ensure_owner(@recipe) do + if @recipe.update(recipe_params) + redirect_to @recipe, notice: 'Recipe was successfully updated.' + else + render :edit + end end end # DELETE /recipes/1 def destroy - @recipe.deleted = true + ensure_owner(@recipe) do + @recipe.deleted = true - if @recipe.save - redirect_to recipes_url, notice: 'Recipe was successfully destroyed.' - else - redirect_to recipes_url, error: 'Recipe could not be destroyed.' + if @recipe.save + redirect_to recipes_url, notice: 'Recipe was successfully destroyed.' + else + redirect_to recipes_url, error: 'Recipe could not be destroyed.' + end end end