2016-09-06 30 views
-1

編輯:最初的目標是使用before_action作爲對用戶的阻止程序show對於非「無管理當前」用戶的操作。換句話說,只讓管理員或當前用戶執行show操作。根據我的經驗,我明白這是實現它的簡單方法是通過阻止操作內部的執行,但會導致代碼重複。Ruby on Rails - 作爲行動預防者的before_action

原文:我試圖建立一些複雜的before_action配置:

enter image description here

在布爾邏輯,我可以將其配置爲: LOGGED_IN和(管理員或電流)

LOGGED_IN /未登錄,管理員和當前功能已定義

before_action :logged_in_user,  only: [:show] 
before_action :current_user,  only: [:show] #correct - the some 
before_action :admin_user,   only: [:show] 

它應該按定義的邏輯工作

+0

不知道你在這裏試圖完成什麼。你能添加更多的上下文/解釋/代碼嗎? – LukeS

+0

我試圖阻止訪問,以顯示不符合條件 – ChaosPredictor

+1

條件的用戶,如?:'before_action:redirect_if_not_allowed',然後在您的'redirect_if_not_allowed'函數中:'redirect_to index_path if not_logged_in || logged_in_but_not_admin',然後在'not_logged_in'和'logged_in_but_not_admin'中定義邏輯。 – fanta

回答

1

你在這裏混淆了兩個截然不同的東西 - 認證和授權。

你並不需要一個非常複雜的邏輯門 - 你需要爲每個問題分開回調。

class ApplicationController < ActionController::Base 

    private 

    def authenticate_user! 
     flash[:error] = "Please sign in." 
     redirect_to new_session_path and return 
    end 
end 

因此,讓我們設置一個非常簡單的身份驗證和授權示例。規則如下:


  • 任何訪問者可以查看索引並顯示
  • 用戶可以創建新的書籍
  • 已經創建了一本書或管理員可以修改現有用戶的任何簽字記錄

class BooksController < ApplicationController 

    before_action :authenticate_user!, except: [:show, :index] 
    before_action :set_book, except: [:new, :index] 
    before_action :authorize!, except: [:new, :create, :show, :index] 

    private 

    def set_book  
     @user = Book.find(params[:id]) 
    end 

    def authorize! 
     unless @book.user == current_user || current_user.admin? 
     redirect_to users_path, alert: 'You are not authorized.' and return 
     end 
    end 
end 

但是你應該小號通過整合和學習Devise,CanCanCan和Pundit等現有解決方案來實現。當你掌握了你可以推出自己的。

+0

謝謝@max!現在我認爲最好在動作中實施它 – ChaosPredictor

+1

不,它不是更好地在動作中實施它。這導致您在整個控制器中複製相同的認證/授權邏輯。 – max

+0

我可以請你爲這個問題投票嗎?這個問題是關閉的,因爲我寫的不清楚,但我已經編輯它 – ChaosPredictor