0

我试图在我的应用程序中添加多个级别的用户,这是我可以想出的想法:

class ApplicationController < ActionController::Base

 before_filter :setup , :authorize
protect_from_forgery

 def setup
 @minimum_permission = "admin"
end  

def authorize
  perm = { admin: 3 , moderator: 2 ,  reader: 1 }
  perm.default = 0
  if    User.find_by_id(session[:user_id])
        unless perm[session[:user_permission].to_s.to_sym] >= perm[@minimum_permission.to_sym]
            redirect_to global_login_url, notice: "you need to have "+@minimum_permission+" privileges to access this page"
        end
  else
        redirect_to global_login_url, notice: "Please log in"
  end
end
end

在我看来,我会做类似的事情:

class FieldsController < ApplicationController
skip_before_filter :authorize
# GET /fields
# GET /fields.json
def index
@minimum_permission = "moderator"
authorize
  @fields = Field.all   
  respond_to do |format|
    format.html # index.html.erb
    format.json { render json: @fields }
  end
  end
....
end

这是我的会话控制器:

 class SessionsController < ApplicationController
 skip_before_filter :authorize
  def new
  end

 def create

user = User.find_by_cpf_no(params[:cpf_no])
if user and user.authenticate(params[:password])
  session[:user_id] = user.id
  session[:user_permission] = user.permission
  session[:user_name] = user.name
  redirect_to fields_url, alert: "successfully logged in"
else
  redirect_to fields_path, alert: "Invalid user/password combination"
end
 end

 def destroy
session[:user_id] = nil
session[:user_permission] = nil
session[:user_name] = nil
redirect_to root_path, notice: "Logged out"
 end
end

这适用于登录的人!但是当我尝试在尚未登录的情况下访问索引时,出现此错误:

“在此操作中多次调用渲染和/或重定向。请注意,您只能调用渲染或重定向,每个操作最多调用一次。另请注意,重定向和渲染都不会终止操作的执行,所以如果您想重定向后退出操作,您需要执行“redirect_to(...) and return”之类的操作。”

我怎样才能解决这个问题?还有没有更好的方法来处理多层次的用户?谢谢你

4

2 回答 2

0

So somewhere you have a before filter or other redirect sending you round in circles. The log should have given you atleast one of the lines that tried to redirect. I'd start by checking that global_login_url (not path?) is skipping all filters and that it the func exits after rendering and doesn't hit another on further down.

于 2012-06-24T22:06:16.047 回答
0

那里有很棒的库,可以满足您开箱即用的需求。看看cancan ,例如。在 cancan 的 wiki 中,您也可以找到有关基于角色的授权的条目。

于 2012-06-24T19:41:44.413 回答