LoginSignup
3
3

More than 5 years have passed since last update.

Rails&DeviseをAPI経由でサインアウト処理するコード例

Last updated at Posted at 2014-12-04

Rails&Deviseをベースとしたシステムを持ち、アプリを開発する場合、JSONを使って、APIで様々な処理を実装していくこととなります。

ログインについては簡単ですが、ログアウト処理の情報が少なく困りましたので、参考コードをここに載せておきます。ログアウト処理もきちんと実装しておかないと、Sessionが残ったままで、別のメールアドレス&パスワードの組み合わせを投げても、以前のユーザー情報が返ってきますので、注意が必要です。

/controllers/api/sessions_controller.rbの作成

DeviseのSessionsControllerを継承します。iOS側から、user_idをパラメータとしてうけて、sign_out処理を実装しています。セキュリティなど必要な処理は、別途加えてください。

class Api::SessionsController < Devise::SessionsController
    respond_to :json

    def destroy
        user = User.find(params[:user_id)
        if sign_out(user)
            render :json => {success: true}
        else
            render :json => {success: false}
        end
    end
end

route.rbの設定

namespace :api do 
    devise_for :users
end

これで、deviseがapiディレクトリの中で動くようになります。

iOS側からAPI通信

http://www.hogehoge.com/api/users/sign_out

にiOS側に保存してあるUser Idをパラメータにして投げる。

すると、サインアウト処理が行われるので、同じデバイスから別のユーザーでのログインなどができるようになります。

※間違いや足りないところがあれば指摘してください。よろしくお願いします。

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3