从头开始有简单的身份验证,我想要用于登录/注销/注册的 RESTfull API。
用户注册按预期工作
curl -v -H 'Content-Type: application/json' -H 'Accept: application/vnd.greenapp.v1' -X POST http://localhost:3000/api/users/ -d "{\"user\":{\"email\":\"user1@example.com\",\"password\":\"secret\",\"password_confirmation\":\"secret\"}}"
但是我无法让 session#new 和 sessions#destroy 工作。这是我的控制器:
module Api
module V1
class SessionsController < ApplicationController
skip_before_filter :verify_authenticity_token,
:if => Proc.new { |c| c.request.format == 'application/json' }
respond_to :json
def create
user = User.find_by_email(params[:email])
if user && user.authenticate(params[:password])
render status: :ok,
json: { success: true,
info: "Logged in sucessfully.",
data: { auth_token: user.auth_token } }
else
render status: :unprocessable_entity,
json: { success: false,
info: "Login failed." }
end
end
def destroy
cookies.delete(:auth_token)
render status: 200,
json: { success: true,
info: "Logged out sucessfully." }
end
end
end
end
登录命令
curl -v -H 'Content-Type: application/json' -H 'Accept: application/vnd.greenapp.v1' -X POST http://localhost:3000/api/sessions -d "{\"user\":{\"email\":\"user1@example.com\",\"password\":\"secret\"}}"
日志:
Processing by Api::V1::SessionsController#create as JSON
Parameters: {"user"=>{"email"=>"user1@example.com", "password"=>"[FILTERED]"}, "session"=>{"user"=>{"email"=>"user1@example.com", "password"=>"[FILTERED]"}}}
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."email" IS NULL LIMIT 1
Completed 422 Unprocessable Entity in 1ms (Views: 0.2ms | ActiveRecord: 0.4ms)
你知道如何处理注销吗?它应该基于auth_token吗?