【问题标题】:restful_authentication: authorized? = NoMethodError (but logged_in? works fine...?)restful_authentication:授权? = NoMethodError(但logged_in?工作正常......?)
【发布时间】:2010-09-22 21:49:39
【问题描述】:

我不明白为什么一种方法会起作用,而如果它们来自同一个 lib 文件,另一种方法会抛出 NoMethodError。

# app/views/bunnies/show.html.erb
<% if logged_in? %>
  <%= current_user.login %> |
  <%= link_to 'Logout', logout_path %> |
  <% if authorized? %>
    <%= link_to 'Edit Details', edit_bunny_path(@broker) %> |
  <% end %>
  <%= link_to 'Back', bunnies_path %>
<% end %>

... 为 authorized? 引发 NoMethodError。如果我评论说如果被屏蔽,则页面可以正常工作(使用logged_in?)。

# lib/authenticated_system.rb
def logged_in?
  !!current_user
end

def authorized?
  current_user.login == "admin"
end

# app/controllers/application.rb
class ApplicationController < ActionController::Base
  include AuthenticatedSystem
end

什么给了?

【问题讨论】:

  • 您是否覆盖了“已授权”?在 app/controllers/application.rb 中?还是你修改了/lib/authenticated_system.rb?
  • 我只根据提供的示例修改了 /lib/authenticated_system.rb。上面的行是这个插件中我放在 application.rb 中的唯一一行。

标签: ruby-on-rails authentication


【解决方案1】:

是的,所以我仍然不明白为什么这不起作用,但我找到了替代解决方案。

(1) 保留 authenticated_system.rb 原样。

(2)在controllers/application.rb中添加辅助方法:

helper_method :is_admin?
def is_admin?
  if logged_in? && current_user.login == "admin"
    true
  else
    false
  end
end

(3) 使用辅助方法而不是authorized?。如果有人想解释为什么原始代码不起作用,我会全力以赴!

(感谢this post

【讨论】:

    【解决方案2】:

    我猜你在抛出错误时没有登录。 NoMethod 不是指#authorized?。它实际上是指 current_user 的#login 方法。如果您没有登录,则 current_user 为 nil,当在 #authorized? 中调用 current_user.login 时会导致 NoMethod。

    有没有类似授权的助手?检查用户状态应该包括检查logged_in?首先绕过这个问题。试试这个...

    def authorized?
      logged_in? and current_user.login == "admin"
    end
    

    这样,如果未登录,您就会跳出条件,并且除非您确实有可用的对象,否则您不会尝试访问 #login 方法。

    您还可以查看一些与 Restful_Authentication 一起使用的可用的基于角色的身份验证方案。如果您的访问模式比仅仅检查管理员更复杂,那么使用其中一个插件会更容易。

    顺便说一下,在authenticated_system.rb 的更下方,您会发现以下代码:

    # Inclusion hook to make #current_user and #logged_in?
    # available as ActionView helper methods.
    def self.included(base)
      base.send :helper_method, :current_user, :logged_in?, :authorized? if base.respond_to? :helper_method
    end
    

    这就是使该模块中的方法可用作视图中的辅助方法的原因。如果您向 authenticated_system.rb 添加一个返回用户状态的方法(例如,#superuser? 之类的东西),您需要将该方法符号添加到此代码中的 base.send 调用中。同样,如果您发现自己为访问控制编写了大量代码,那么学习其中的一个插件是有必要的。

    【讨论】:

    • 谢谢 - 目前,我的用户设置非常简单,但它会增长。有没有特别推荐的插件?
    • 如果您只需要管理员检查,那么您的 RA 黄金。 rbac 插件的问题是它们都可以工作,但它们都不能满足你的所有需求。我认为 Role Requirement 插件是一个很好的入门插件 (code.google.com/p/rolerequirement),也是一个值得学习的好插件。
    • 你的 s/b 你是。 ;) 讨厌拼写错误。
    【解决方案3】:
    def is_admin?
      logged_in? && current_user.login == "admin"
    end
    

    够了

    【讨论】:

      猜你喜欢
      • 2019-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多