【发布时间】:2013-06-28 10:18:04
【问题描述】:
我是 Ruby on Rails 的新手,目前我想使用 Devise gem 进行身份验证系统。系统需要只有管理员才能列出用户并创建新用户。 (我通过向 Devise 生成的用户模型添加管理员布尔字段来添加管理员角色)。我使用 Rails 3.2、Ruby 1.9.3 和最新的 Devise gem。
但是,下面列出的代码不会阻止未经身份验证的用户访问特定操作(索引、新建和创建)。
# users_controller.rb
class UsersController < Devise::RegistrationsController
before_filter :authenticate_user!, only: [:index, :new, :create]
before_filter :is_admin, only: [:index, :new, :create]
def index
end
private
def is_admin
current_user.admin?
end
end
==
# config/routes.rb
App::Application.routes.draw do
root to: 'static_pages#home'
get '/about', to: 'static_pages#about'
devise_scope :user do
get '/users', to: 'users#index'
end
devise_for :users, controllers: { sessions: "sessions", registrations: "users" }
end
authenticate_user! 方法不起作用(例如,未经身份验证的用户仍然可以访问/users 或/users/sign_up)但也不会引发任何异常。我做了一些搜索,但不知道为什么。请帮忙。
PS。对不起我的英语。
更新
感谢所有回答。我将更新is_admin 以按照指出的方式正常工作。
但这里的主要问题是未登录的用户首先可以通过authenticate_user! 过滤器(并在is_admin 方法上引发异常,因为这里的current_user 将为nil)。
# Here non logged in users does not redirect to sign in page when access to,
# for example, /users or /users/sign_up.
before_filter :authenticate_user!, only: [:index, :new, :create]
抱歉不明显。
【问题讨论】:
-
使用CanCan gem。
-
检查我的更新答案
-
非常感谢你们。我会试试的。
标签: ruby-on-rails devise