【问题标题】:Cancan ability not finding userCancan 无法找到用户
【发布时间】:2015-11-02 15:27:53
【问题描述】:

我使用Cancan 来确保只有拥有权限的用户才能删除我的 Rails 应用程序中的对象。我有一个配套的移动应用程序,它使用用户的 auth_token 提交删除请求。这是请求的样子:

Started DELETE "/projects/888?auth_token=ArpuyxbDyjtyn67r3JgF"
Processing by ProjectsController#destroy as */*
Parameters: {"auth_token"=>"ArpuyxbDyjtyn67r3JgF", "id"=>"888", "project"=>{}}

但我知道该用户未经授权。

这是我放入控制器的内容:

class ProjectsController < ApplicationController
 def destroy
    @project = Project.find(params[:id])
    if params[:auth_token]
      current_user = User.where(:authentication_token => params[:auth_token]).first
    end

    authorize! :destroy, @project
    @project.destroy
    respond_to do |format|
      format.html{ redirect_to user_path(current_user.username) }
      format.json { head :no_content}
    end    
  end
end

这是我的ability.rb文件:

class Ability
  include CanCan::Ability

  def initialize(user)

    user ||= User.new

    can :destroy, Project do |project|
        project.user == user || (user && user.admin?)
    end
end

检查我的数据库,正在为用户传递正确的 auth_token。

如何让cancan用户将用户与传入的auth_token参数匹配,从而满足能力权限?

【问题讨论】:

  • 不应该是user ||= User.new吗?
  • @Levsero 谢谢,你是对的。不幸的是,这并没有从根本上解决我发布的问题。

标签: ruby-on-rails authentication devise cancan auth-token


【解决方案1】:

我认为问题在于您设置了一个局部变量current_user,而不是拥有一个查找并返回当前用户的控制器方法。 Cancan 正在寻找一种控制器方法来查找 current_user。

【讨论】:

  • 我认为应用程序将能够使用传递的身份验证令牌自动确定当前用户 - 这是我应该使用 devise 还是使用 cancan 解决的问题?
  • 只要确保您实际上是使用 devise 登录用户,如果这是问题,应该修复它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-28
  • 1970-01-01
  • 2017-02-03
相关资源
最近更新 更多