diff --git a/app/controllers/comments_controller.rb b/app/controllers/comments_controller.rb index 046a8e5d..ebe41025 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: [:destroy, :create] # GET /comments or /comments.json def index @@ -63,6 +64,13 @@ def set_comment @comment = Comment.find(params[:id]) 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 + # Only allow a list of trusted parameters through. def comment_params params.require(:comment).permit(:author_id, :photo_id, :body) diff --git a/app/controllers/photos_controller.rb b/app/controllers/photos_controller.rb index 78e53163..d77bbdc8 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 @@ -51,6 +52,7 @@ def update # DELETE /photos/1 or /photos/1.json def destroy @photo.destroy + respond_to do |format| format.html { redirect_back fallback_location: root_url, notice: "Photo was successfully destroyed." } format.json { head :no_content } @@ -63,6 +65,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..0761b0e8 100644 --- a/app/models/comment.rb +++ b/app/models/comment.rb @@ -22,6 +22,7 @@ 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/photos/_photo.html.erb b/app/views/photos/_photo.html.erb index f0de50b8..343d771b 100644 --- a/app/views/photos/_photo.html.erb +++ b/app/views/photos/_photo.html.erb @@ -7,6 +7,7 @@