簡體   English   中英

Rails before_filter

[英]Rails before_filter

幫助我解決問題:

我有兩個設計模型(用戶和管理員)

我有一些后期的模型和控制器與路線:

/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

但它不起作用

我的建議是使用CanCan寶石

https://github.com/ryanb/cancan

這是一個很好的軌道

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM