我遵循了 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 和 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/
卷曲的使用不正确吗?还是
我需要先登录,然后在 POST 请求中的 cookie 中设置会话?还是
我在做一些愚蠢的猴子?
我对 Rails 和 Ruby 相当陌生,因此非常感谢任何帮助。谢谢。