【问题标题】:Nil user in CanCanCan ability.rbCanCanCan 能力.rb 中的零用户
【发布时间】:2018-03-16 09:02:31
【问题描述】:

尝试从 React 组件获取异步请求。但是由于权限无效,它总是失败。

示例工作请求:

Started GET "/" for 127.0.0.1 at 2017-10-04 16:32:00 -0400
Processing by EventsController#index as HTML
  User Load (0.4ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?  [["id", 1], ["LIMIT", 1]]
  Rendering events/index.html.erb within layouts/application

异步请求失败示例:

Started GET "/events/search?ne_lat=37.82915414554321&ne_lng=-122.13221051635742&sw_lat=37.72060601151162&sw_lng=-122.70658948364257" for 127.0.0.1 at 2017-10-04 16:32:07 -0400
Processing by EventsController#search as */*
  Parameters: {"ne_lat"=>"37.82915414554321", "ne_lng"=>"-122.13221051635742", "sw_lat"=>"37.72060601151162", "sw_lng"=>"-122.70658948364257"}
  ... #NOTE: printing 'user' from byebug in ability.rb shows it as nil
CanCan::AccessDenied (You are not authorized to access this page.):

请注意,失败的请求不会从数据库查询中选择/加载用户。有什么想法可能会出错吗? Ability.rb 权限允许这个请求,但是异步调用时没有正确填写用户。

此请求以前使用 jQuery 工作,但我已使用 fetch 重写它。

这里是控制器

class EventsController < ApplicationController
  before_action :set_event, only: [:show, :edit, :update, :destroy]
  load_and_authorize_resource

  def index
    @events = Event.all
  end
  ...
  def search
    local_events = Event.includes(:address).references(:address)
      .where("latitude >= ? AND latitude <= ? AND longitude >= ? AND longitude <= ?",       
          params[:sw_lat], params[:ne_lat], params[:sw_lng], params[:ne_lng]
          )
      .limit(50)

    render json: local_events, only: [:id,:name,:description,:start], include: { address: { only: [:latitude,:longitude,:street_address] }}
  end

end

还有能力.rb

class Ability
  include CanCan::Ability

  def initialize(user)
    can :read, :all
    byebug
    return if user == nil #user must be logged in after this point

    #events
    can [:search], Event
    ...
  end
end

【问题讨论】:

  • 显示EventsController
  • 完成。您还有什么建议添加的吗?

标签: ruby-on-rails reactjs devise fetch-api cancancan


【解决方案1】:

异步请求不会从 DB 中查询用户,因为会话中没有用户 ID。会话中没有用户ID,因为Fetch APIfetch默认不包含cookies。

为了发送带有获取请求集credentials 选项的cookie 到"same-origin""include"

fetch(url, {  
  credentials: 'include'  // or 'same-origin' (see the link below)
})

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Sending_a_request_with_credentials_included

【讨论】:

  • 非常感谢!我决定使用same-origin 而不是include。你什么时候有外国网站的凭据?什么样的用例需要include - 当用户拥有特殊凭据并且它不是 API 密钥时?
  • 我不确定我能否就您的问题给出一个合格的答案。它是 StackOverflow 上一个新问题的好候选。祝你好运!
猜你喜欢
  • 2015-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多