注销用户并将令牌更改为NIL

时间:2014-09-01 06:11:37

标签: ruby ruby-on-rails-3 api session login

我已经开始为我的rails应用程序创建一个Api。我目前正在创建用于登录的会话控制器。

退出似乎有效,但我真的希望能够注销用户并将用户oauth_token设置为NIL。(oauth_token = nil)

我已尝试过以下代码,但似乎无法通过使用oauth_token找到正确的用户。

卷曲命令

 curl -v -H 'Content-Type: application/json' -H 'Accept: application/json' -X DELETE 
http://localhost:3000/api/sessions/\?auth_token\=5c147a84cd5418771b9063dddcbfde96d5a8630b

API CONTROLLER

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 destroy 
        user = User.find_by_oauth_token(params[:session][:oauth_token])
        if user.present?
          user.oauth_token = nil
          user.save
        end
        sign_out
        render :status => 200,
         :json => { :success => true,
                    :info => "Logged Out",
                    :data => {} }
      end

    end
  end
end

CONTROLLER

class SessionsController < ApplicationController

  def destroy
    sign_out
    redirect_to root_path
  end

end

会话助手

def sign_out 
  current_user = nil
  cookies.delete(:remember_token)
end

路线

### API Routes
namespace :api, defaults: {format: 'json'} do
  scope module: :v1, constraints: ApiConstraints.new(version: 1, default: true) do
    resources :sessions, only: [:new, :create, :destroy]
  end
end

日志

Started DELETE "/api/sessions/?auth_token=5c147a84cd5418771b9063dddcbfde96d5a8630b" 
for 127.0.0.1 at 2014-09-01 00:05:37 -0700
Processing by Api::V1::SessionsController#destroy as JSON
  Parameters: {"auth_token"=>"5c147a84cd5418771b9063dddcbfde96d5a8630b", "session"=>{}}
  User Load (1.7ms)  SELECT "users".* FROM "users" WHERE "users"."oauth_token" IS NULL LIMIT 1
Completed 200 OK in 130ms (Views: 0.4ms | ActiveRecord: 6.4ms)

1 个答案:

答案 0 :(得分:0)

我能够通过将我的Curl Command更改为:

来解决这个问题
curl -v -H 'Content-Type: application/json' -H 'Accept: application/json' -X DELETE
http://localhost:3000/api/sessions -d 
"{\"session\":{\"oauth_token\":\"5c147a84cd5418771b9063dddcbfde96d5a8630b\"}}"