2016-09-06 10 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