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

来源:互联网 发布:tensorflow cnn 教程 编辑:程序博客网 时间:2024/05/16 00:35

限制访问权限

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

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

下面为这些按钮增加权限,在连接元素外面包一个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  endend

增加了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