我的个人博客问题得到授权

时间:2019-01-01 20:17:35

标签: ruby-on-rails pundit ruby-on-rails-5.2

在我的个人项目上使用Pundit编写策略时遇到一些麻烦。

由于某种原因,每当我尝试更新博客帖子时,我都会收到未执行授权错误,并且如果不提交空白帖子也无法创建博客帖子。

这是我的帖子控制器:

class PostsController < ApplicationController
before_action :authenticate_user!, except: [:index, :show]

after_action :verify_authorized, except: [:index, :show]

def index
 @posts = Post.order(created_at: :desc).page(params[:page]).per(10)
 #authorize @posts
end

def new
 authorize @post
 @post = current_user.posts.build
 if @post.save
  redirect_to @post, notice: 'Post was successfully created.'
 else
  render :new
 end
end

def show
 set_post
end

def edit
 set_post
 authorize @post
end

def update
 set_post
 authorize @post
 @post.update(post_params)
 redirect_to @post
end

def destroy
 set_post
 authorize @post
 @post.destroy

 redirect_to action: "index", notice: "The post was removed"
end

def upvote
    @post.upvote_from current_user
    authorize @post
end

def downvote
    @post.downvote_from current_user
    authorize @post
end



def create
    @post = current_user.posts.build(post_params)
    authorize @post
    respond_to do |format|
        if @post.save
            format.html {redirect_to @post, notice: 'Blog post has been posted!'}
            format.json {render :show, status: :created, location: @post}
        else
            format.html {render :new}
            format.json {render json: @post.errors, status: :unprocessable_entity}
        end
    end

end

private
  def post_params
      params.require(:post).permit(:title, :content, :header_image, uploads: [])
  end

  def set_post
      @post = Post.friendly.find(params[:id])
#    authorize @post
  end

end

这也是我的发布政策。我不知道错误是来自策略还是控制器:

class PostPolicy < ApplicationPolicy
 class Scope < Scope
  def resolve
   scope.where(user_id: @user.try(:id))
  end
 end

 attr_reader :user, :post

 def initialize(user, post)
   @user = user
   @post = post
 end


def show?
 true
end

def index?
 true
end

def create?
 is_contributor_or_admin?
end

def update?
 is_author_of_post_or_admin?
end

def destroy?
 is_author_of_post_or_admin?
end





private

 def user_not_authorized
  flash[:alert] = "Can't let you do that, " + @user.username + "!"
 end

 def is_admin?
  @user.role_id == 1
 end

 def is_contributor_or_admin?
  @user.role_id == 1 || @user.role_id == 2
 end

 def is_author_of_post_or_admin?
  @user.role_id == 1 || @post.user.username == @user.username
 end


end

我希望我能找到一种创建策略的方法。如果您还需要其他信息(例如其他文件的代码)或有关格式的任何问题,请告诉我。

0 个答案:

没有答案