2011-01-07 60 views
1

我遵循Tony Amoyal的指南Rails Authentication with Devise and CanCan part 2 – Restful Resources for Administrators並創建用戶控制器。設計CanCan無法創建用戶通過帖子時使用捲曲

我已經啓用了基於令牌的身份驗證,並且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 &刪除它工作正常請求。注意AUTH_TOKEN參數(這是管理員用戶的令牌)

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

POST請求似乎並不工作,重定向這表明身份驗證使用所提供的令牌沒有打進。

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":"[email protected]"}}' -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"=>"[email protected]"}} 
Completed in 88ms 
Redirected to https://localhost:3000/ 

是使用捲曲的不正確的?或
我是否需要先登錄,然後在POST請求中的Cookie中設置會話?或
我在做一些愚蠢的monkies?

對Rails來說相當新&紅寶石,所以任何幫助,非常感謝。謝謝。

回答

0

添加到您的控制器:

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

這是告訴控制器不檢查接收POST時Rails的期待形式真實性令牌。

+0

謝謝。不幸的是,我無法驗證答案,因爲我們因各種原因決定使用Sinatra進行上述項目。 – Sai 2011-09-09 04:08:38