Rails 3:如何限制访问Web界面以使用Doorkeeper gem添加oauth授权的应用程序

Cyb*_*ber 9 ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1 ruby-on-rails-3.2

我有一个使用Device + doorkeeper的Rails应用程序.我也使用cancan进行角色管理.在我的应用程序中,我http://localhost:3000/oauth/applications/new用于注册我的应用程序以获取Client和Secret id.目前任何用户都可以通过Web界面注册应用程序来获取客户端和机密ID,我需要限制访问权限,以便只有管理员可以注册应用程序.

我在doorkeeper.rb文件中看到了一些代码

# If you want to restrict access to the web interface for adding oauth authorized applications, you need to declare the block below.
  # admin_authenticator do
  #   # Put your admin authentication logic here.
  #   # Example implementation:
  #   Admin.find_by_id(session[:admin_id]) || redirect_to(new_admin_session_url)
  # end
Run Code Online (Sandbox Code Playgroud)

我尝试过如下,但没有工作......

admin_authenticator do
  if(current_user)
    current_user.role? :admin
  else
    redirect_to(new_user_session_url)
  end
end
Run Code Online (Sandbox Code Playgroud)

提前致谢......

coo*_*sse 7

我使用的代码很好用

admin_authenticator do
  redirect_to new_user_session_url unless current_user && current_user.admin?
end
Run Code Online (Sandbox Code Playgroud)

  • 也许更好的是`redirect_to new_user_session_url,除非current_user.try(:admin?)`但我还没有测试过 (2认同)

Cor*_*Foy 5

那么,你的逻辑不正确.基本上,你让每个作为current_user的人都可以访问.你真的想要这样的东西:

admin_authenticator do
  if(current_user && current_user.role?(:admin))
    #do nothing
  else
    redirect_to(new_user_session_url)
  end
end
Run Code Online (Sandbox Code Playgroud)

你也可以这样做

admin_authenticator do
  if(current_user)
    redirect_to(not_authorized_url) unless current_user.role?(:admin)
  else
    redirect_to(new_user_session_url)
  end
end
Run Code Online (Sandbox Code Playgroud)

哪个可以让您将用户发送到正确的错误页面