RailsCasts中文版,#20 Restricting Access 为页面增加权限校验2

限制访问权限

在上一篇中,我们在文章列表页增加了编辑和删除操作的连接,暂时还没有进行访问控制;以至于所有访问者都能看到并进行操作。

本应是管理员看到的按钮对所有人可见了。

下面为这些按钮增加权限,在连接元素外面包一个edit方法的调用,只有返回true了才可见。

<li>
  <p class="episodeId"><%= episode.episode_id %></p>
  <h3><%= link_to episode.title, episode_path(episode.identifier) %></h3>
  <p class="summary"><%= episode.summary %></p>
  <p class="tagList">
    Tags: <% episode.tags.each do |tag| %><%= link_to tag.title, tag_path(tag.title) %><% end %>
  </p>
  <% if admin? %>
  <p class="adminActions">
    <%= link_to "Edit", edit_episode_path(episode) %>
    <%= link_to "Destroy", episode_path(episode), :confirm => "Are you sure?", :method => :delete %>
  </p>
  <% end %>
</li>

在编辑和删除操作连接上增加了admin?方法的调用。

然后是实现admin?方法,应该把这个方法写在哪里? 这里的场景是要在View中调用这个方法,理应写在application_helper.rb中。但是我觉得关于权限判断的逻辑将来也有可能在控制器中调用,所以还是写在ApplicationController中吧。


class ApplicationController < ActionController::Base
  helper_method :admin?  
  protected
  def admin?
    false
  end  
end

ApplicationController类中增加admin?方法的定义。

现在的实现很简单,直接返回false(下一篇中会继续实现),不过已经可以使用了。别忘了设置为helper_method以便在View中能够被调用。

即将完成

现在倒是能够通过调用admin?方法检查对非管理员隐藏连接了,但是还有问题:如果通过直接输入网址,依然能够转向编辑和删除页面。这个问题通过使用before_filter方法来解决。


class EpisodesController < ApplicationController
  before_filter :authorize, :except => [:index, :show ]
  
  def index
    @episodes = Episode.find(:all)
  end
  # show, new, create, edit, update and destroy methods hidden.
end

增加了before_filter的控制器类。

before_filter方法会在这个控制器除了indexshow方法以外的任何一个方法调用之前被调用,并执行authorize方法。我们在ApplicationController中增加authorize方法,以便其他控制器也能使用


class ApplicationController < ActionController::Base
  helper_method :admin?  
  protected
  def admin?
    false
  end  

  def authorize
    unless admin?
      flash[:error] = “Unauthorized access”
      redirect_to home_path
      false
    end
  end
end

增加了authorize方法的ApplicationController

这个方法检查当前登录的用户是不是具有管理员权限,如果没有显示一个错误并且重定向到首页。这样就实现了直接访问新建文章页面后,被自动重定向回首页。当然,也可以抛出一个404 (找不到页面)错误,让未授权用户有所感知。

#TODO:

admin?方法还需要补充业务逻辑。下一篇介绍。


作者授权:Your welcome to post the translated text on your blog as well if the episode is free(not Pro). I just ask that you post a link back to the original episode on railscasts.com.

原文链接:http://railscasts.com/episodes/20-restricting-access


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值