diff --git a/app/controllers/comments_controller.rb b/app/controllers/comments_controller.rb index 046a8e5d..9c9325c6 100644 --- a/app/controllers/comments_controller.rb +++ b/app/controllers/comments_controller.rb @@ -1,5 +1,6 @@ class CommentsController < ApplicationController before_action :set_comment, only: %i[ show edit update destroy ] + before_action :is_an_authorized_user, only: [:create] # GET /comments or /comments.json def index @@ -67,4 +68,11 @@ def set_comment def comment_params params.require(:comment).permit(:author_id, :photo_id, :body) end + + def is_an_authorized_user + @photo = Photo.find(params.fetch(:comment).fetch(:photo_id)) + if current_user != @photo.owner && @photo.owner.private? && !current_user.leaders.include?(@photo.owner) + redirect_back fallback_location: root_url, alert: "Not authorized" + end + end end diff --git a/app/controllers/photos_controller.rb b/app/controllers/photos_controller.rb index 78e53163..b8fe34db 100644 --- a/app/controllers/photos_controller.rb +++ b/app/controllers/photos_controller.rb @@ -1,5 +1,6 @@ class PhotosController < ApplicationController before_action :set_photo, only: %i[ show edit update destroy ] + before_action :ensure_current_user_is_owner, only: [:destroy, :update, :edit] # GET /photos or /photos.json def index @@ -63,6 +64,12 @@ def set_photo @photo = Photo.find(params[:id]) end + def ensure_current_user_is_owner + if current_user != @photo.owner + redirect_back fallback_location: root_url, alert: "You're not authorized for that." + end + end + # Only allow a list of trusted parameters through. def photo_params params.require(:photo).permit(:image, :comments_count, :likes_count, :caption, :owner_id) diff --git a/app/models/comment.rb b/app/models/comment.rb index 14a8eb00..bc318e2c 100644 --- a/app/models/comment.rb +++ b/app/models/comment.rb @@ -22,6 +22,6 @@ class Comment < ApplicationRecord belongs_to :author, class_name: "User", counter_cache: true belongs_to :photo, counter_cache: true - + has_one :owner, through: :photo validates :body, presence: true end diff --git a/app/views/comments/_comment.html.erb b/app/views/comments/_comment.html.erb index a7ee4c56..f5e69b8d 100644 --- a/app/views/comments/_comment.html.erb +++ b/app/views/comments/_comment.html.erb @@ -10,6 +10,7 @@
<%= comment.body %>