0

帮我解决问题:

我有两个设计模型(用户和管理员)

我有一些带有路由的后模型和控制器:

/posts
/posts/80
/posts/80/edit

我想要:管理员拥有所有访问权限用户可以访问:

/post
   and 
/post/80 ( if he is creator of this post ) 

我这样做了:

    class PostsController < ApplicationController
        before_filter :check_guest_logged_in!, :except => [:index, :show]

.
.
.
    private

    def check_guest_logged_in! 
      if user_signed_in?
        authenticate_user!  

      elsif admin_signed_in?
        authenticate_admin!
      else
        redirect_to root_path
      end   
    end

但在这种情况下,如果用户授权,他可以放入浏览器

/posts/80/edit

并且他可以访问(即使他不是这篇文章的创建者)

我怎样才能解决这个问题 ?

我想要这样私人的东西

    def check_guest_logged_in! 
      if user_signed_in?
        authenticate_user!

    if ( current_user.id == @post.user.id ) 
    else
      return false;
    end     

      elsif admin_signed_in?
        authenticate_admin!
      else
        redirect_to root_path
      end   
    end

但它不起作用

4

1 回答 1

3

我的建议是使用 CanCan gem

https://github.com/ryanb/cancan

这是一个很好的railscast

http://railscasts.com/episodes/192-authorization-with-cancan

使用 cancan 你可以做这样的事情

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new # guest user (not logged in)
    if user.admin?
      can :manage, :all
    else
      can :read, :all
    end
  end
end
于 2012-09-13T22:43:00.287 回答