Rails + Devise: How to force logout a user in a controller

On our way to write code for bioddicted, we encounter a case that we need to force a user to logout. We are using devise & OmniAuth for authentication.

bioddicted のコードを Rails を使って書いています。認証には devise と OmniAuth を組み合わせて使っているのですが、ユーザーをコントローラ内のロジックで強制的にログアウトさせたいケースが出てきました。sessions#destroy は http DELETE リクエストしか受け取ってくれないし、どうしたものやら。具体的には以下のようなケースです(このあと英語です)。

The case is ... :

  1. User login to bioddicted.de with facebook account
  2. (time pasts)
  3. devise session is still valid but facebook token has been already expired

Firstly, I tried to redirect a user with redirect_to.

redirect_to :controller=>"user/sessions", :action=>"destroy"

But it didn't work since the devise/sessions#destroy method only accepts http DELETE requests. What can we do /^o^\フッジサーン (Fujisan)? After dogs' walk and lunch, I found a solution. There is a helper method!

Module: Devise::Controllers::Helpers — Documentation for plataformatec/devise (master)

The code is ... :

if provider == "facebook" && !has_valid_fb_token
	sign_out @user
	redirect_to :root
end

Happy coding :D

RailsによるアジャイルWebアプリケーション開発 第4版

RailsによるアジャイルWebアプリケーション開発 第4版