Sar*_* S. 5 ruby-on-rails devise
我是Ruby on Rails的新手,目前我想将Devise gem用于身份验证系统.系统只需要管理员可以列出用户并创建新用户.(我通过将admin boolean field添加到Devise生成的User模型中添加了admin角色).我使用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
Run Code Online (Sandbox Code Playgroud)
==
# 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
Run Code Online (Sandbox Code Playgroud)
该authenticate_user!方法不起作用(例如,未经过身份验证的用户仍可以访问/users或/users/sign_up)但也不会引发任何异常.我做了一些搜索,但没有想法为什么.请帮忙.
PS.对不起我的英语不好.
UPDATE
谢谢你的所有答案.我会更新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]
Run Code Online (Sandbox Code Playgroud)
对不起,不明白.
来自设备文档:
Devise 将创建一些帮助器以在控制器和视图中使用。要设置具有用户身份验证的控制器,只需添加以下 before_filter :
before_filter :authenticate_user!
Run Code Online (Sandbox Code Playgroud)
要验证用户是否已登录,请使用以下帮助程序:
user_signed_in?
Run Code Online (Sandbox Code Playgroud)
对于当前登录的用户,可以使用此帮助程序:
current_user
Run Code Online (Sandbox Code Playgroud)
所以,:authenticate_user!只会使所有其他助手在控制器上可用(前提是您将其放入 :before_filter 中),但定义签名/未签名用户的逻辑仍然是您的责任!
请记住,Devise 是一种身份验证解决方案,而不是授权解决方案。如果您需要处理授权(看起来像您所做的那样)而不需要自己编写所有逻辑,请使用 CanCan 之类的东西,它与 Devise 配合得很好。
| 归档时间: |
|
| 查看次数: |
2515 次 |
| 最近记录: |