我挡住了节目页面上显示的链接:我怎样才能阻止设计(Ruby on Rails的)网址ADRESS
<% if @post.user == current_user %>
links
<%end%>
,但我不能阻止URL ADRESS用于未经授权的用户:
http://localhost:3000/posts/1/edit
我能做什么?
我挡住了节目页面上显示的链接:我怎样才能阻止设计(Ruby on Rails的)网址ADRESS
<% if @post.user == current_user %>
links
<%end%>
,但我不能阻止URL ADRESS用于未经授权的用户:
http://localhost:3000/posts/1/edit
我能做什么?
你是什么寻找的是一种叫authorization
认证 =发现如果用户存在
授权 = 确定它们是否能够执行的具体要求
通过Sergei Stralenia
的答案是正确的 - 你需要使用授权的宝石之一 - Pundit和CanCanCan是两个最流行的 - 到验证用户是否能够编辑特定的对象。
关于路由,除非将其分隔成类似于admin
命名空间的东西(我将在第二个章节解释更多内容),否则将无法删除edit
路由。
-
Sergei Stralenia
的帖子展示了如何使用Pundit
,我会告诉你CanCanCan
:
#app/models/ability.rb
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
if user.admin?
can :manage, Post
else
can :read, Post
end
end
end
#app/controllers/posts_controller.rb
class PostsController < ApplicationController
def edit
@article = Post.find params[:id]
authorize! :edit, @article
end
end
联系
如果你想使一个帖子只有在“管理员”区域可编辑,你最好使用类似以下内容:
#config/routes.rb
resources :posts, only: [:index, :show]
namespace :admin do
resources :posts, only: [:new, :create, :edit, :update, :destroy]
end
这样一来,你会从字面上没有办法对非管理员用户在前端编辑/更新帖子。相反,他们必须进入admin
区域,并使其能够在其中编辑它...
#app/controllers/admin/posts_controller.rb
class Admin::PostsController < ApplicationController
#actions & authorization in here
end
在控制器上的编辑操作,执行相同的检查 - 是这样的:
@post = Post.find_by(id: params[:id])
unless @post.user == current_user
fail(ActionController::RoutingError, 'User cannot edit this post.')
end
可以简化错误检查分为:
fail(ActionController::RoutingError, 'User cannot edit this post.') unless @post.user == current_user
我希望这有助于!
使用权威宝石(https://github.com/elabs/pundit)是很好的可能性。 你的政策会看:
class PostPolicy
attr_reader :user, :post
def initialize(user, post)
@user = user
@post = post
end
def edit?
post.user == user
end
end
而且你的控制器的动作:
def edit
@post = Post.find_by(id: params[:id])
authorize @post
...
end
谢谢! :)))))) – myf
我想这样做是在你的帖子控制器使用before_filter
最好的办法,即:
before_action :authorize_admin, only: [:show, :edit, :update, :destroy]
或:
before_filter :authorize_admin, except: [:show]
其中:authorize_admin
是,你必须定义或者在帖子控制器(用于仅职位),或在应用控制器(在所有控制器使用),这样的方法:
def authorize_admin
redirect_to :new_user_session unless current_user&¤t_user.admin?
end
谢谢! :)))))) – myf
谢谢! :)))))) – myf