加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails设计authenticatate_user无法正常工作

发布时间:2020-12-17 03:16:28 所属栏目:百科 来源:网络整理
导读:我是 Ruby on Rails的新手,目前我想将Devise gem用于身份验证系统.系统只需要管理员可以列出用户并创建新用户. (我通过将admin boolean field添加到Devise生成的User模型中添加了admin角色).我使用Rails 3.2,Ruby 1.9.3和最新的Devise gem. 但是,下面列出的
我是 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,: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.对不起我的英语不好.

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!,:create]

对不起,不明白.

解决方法

从设计文档:

Devise will create some helpers to use inside your controllers and views. To set up a controller with user authentication,just add this before_filter:

before_filter :authenticate_user!

To verify if a user is signed in,use the following helper:

user_signed_in?

For the current signed-in user,this helper is available:

current_user

那么,:authenticate_user!只会让控制器上的所有其他助手都可用(前提是你把它放到:before_filter中),但是你仍然有责任为签名/未签名的用户定义逻辑!

请记住,Devise是一种身份验证解决方案,而不是授权解决方案.如果您需要处理授权(似乎就是这样),而不需要自己编写所有逻辑,请使用CanCan之类的东西,它与Devise一起非常有效.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读