使用Curl时,Devise CanCan无法通过Post创建用户

时间:2011-01-07 08:12:24

标签: ruby-on-rails-3 devise cancan

我按照Tony Amoyal的指南Rails Authentication with Devise and CanCan part 2 – Restful Resources for Administrators创建了用户控制器。

我启用了基于令牌的身份验证,并且CanCan设置为只允许管理员访问以执行任何有用的操作。

注意的代码片段是

class User < ActiveRecord::Base
  before_save :ensure_authentication_token

  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, :token_authenticatable

  attr_accessible :company_name, :role, :email, :password, :password_confirmation, :remember_me

  ROLES = %w[admin customer]  
end

class UsersController < ApplicationController
  before_filter :get_user, :only => [:index,:new,:edit]
  load_and_authorize_resource

  ...
end

class Ability
    include CanCan::Ability

    def initialize(user)
      user ||= User.new # guest user

      if user.role == "admin"      
        can :manage, :all
      elsif user.role == "customer"
        can :address, :lookup
        cannot [:new, :create, :edit, :update, :destroy, :index], [User]
        can [:show], [User], :id => user.id
      end
    end    
end

现在我使用curl制作GET,PUT&amp; DELETE请求它工作正常。注意auth_token参数(它是管理员用户的标记)

curl -k -H "Content-Type: application/json" -X GET https://localhost:3000/users.json?auth_token=Z6Sgkd65w1oCWckpNrdya54FkHy6sMgWLn1BNno7wa9xSEi0xvoxfrRD4Y8z -i

POST请求似乎不起作用并被重定向,这表明身份验证没有使用提供的令牌启动。

发布请求:

curl -k -H "Content-Type: application/json" -X POST https://localhost:3000/users -d '{"auth_token":"Z6Sgkd65w1oCWckpNrdya54FkHy6sMgWLn1BNno7wa9xSEi0xvoxfrRD4Y8z", "user":{"company_name":"Test","role":"customer","password":"XXXXXXXX","password_confirmation":"XXXXXXXX","email":"test8@test.com"}}' -i

开发日志:

Started POST "/users" for 127.0.0.1 at Fri Jan 07 18:54:27 +1100 2011
  Processing by UsersController#create as */*
  Parameters: {"auth_token"=>"Z6Sgkd65w1oCWckpNrdya54FkHy6sMgWLn1BNno7wa9xSEi0xvoxfrRD4Y8z", "user"=>{"company_name"=>"Test", "password_confirmation"=>"[FILTERED]", "role"=>"customer", "password"=>"[FILTERED]", "email"=>"test8@test.com"}}
Completed   in 88ms
Redirected to https://localhost:3000/

Curl的使用是否不正确?或
我是否需要先登录,然后在POST请求中设置cookie中的会话?或
我在做一些愚蠢的僧侣吗?

Rails&amp; amp; Ruby非常感谢任何帮助。感谢。

1 个答案:

答案 0 :(得分:0)

将此添加到您的控制器:

# disable csrf protection for the controller: http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection/ClassMethods.html
  skip_before_filter :verify_authenticity_token

这告诉控制器在接收POST时不要检查Rails期望的表单真实性令牌。