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

来源:互联网 发布:大数据开发语言 编辑:程序博客网 时间:2024/06/05 10:45


限制访问权限

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

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

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

[ruby] view plaincopy
  1. <li>  
  2.   <p class="episodeId"><%= episode.episode_id %></p>  
  3.   <h3><%= link_to episode.title, episode_path(episode.identifier) %></h3>  
  4.   <p class="summary"><%= episode.summary %></p>  
  5.   <p class="tagList">  
  6.     Tags: <% episode.tags.each do |tag| %><%= link_to tag.title, tag_path(tag.title) %><% end %>  
  7.   </p>  
  8.   <% if admin? %>  
  9.   <p class="adminActions">  
  10.     <%= link_to "Edit", edit_episode_path(episode) %>  
  11.     <%= link_to "Destroy", episode_path(episode), :confirm => "Are you sure?":method => :delete %>  
  12.   </p>  
  13.   <% end %>  
  14. </li>  

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

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

[ruby] view plaincopy
  1. class ApplicationController < ActionController::Base  
  2.   helper_method :admin?    
  3.   protected  
  4.   def admin?  
  5.     false  
  6.   end    
  7. end  

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

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

即将完成

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

[ruby] view plaincopy
  1. class EpisodesController < ApplicationController  
  2.   before_filter :authorize:except => [:index:show ]  
  3.     
  4.   def index  
  5.     @episodes = Episode.find(:all)  
  6.   end  
  7.   # show, new, create, edit, update and destroy methods hidden.  
  8. end  

增加了before_filter的控制器类。

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

[ruby] view plaincopy
  1. class ApplicationController < ActionController::Base  
  2.   helper_method :admin?    
  3.   protected  
  4.   def admin?  
  5.     false  
  6.   end    
  7.   
  8.   def authorize  
  9.     unless admin?  
  10.       flash[:error] = “Unauthorized access”  
  11.       redirect_to home_path  
  12.       false  
  13.     end  
  14.   end  
  15. 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
原创粉丝点击