deviseでユーザーが自分自身のユーザーアカウントを削除できないようにする
Railsでユーザー認証を行うのにdeviseを使うことにした。
導入方法は公式GitHubに書いてる通り簡単だし日本語で説明しているブログもいくつかあったので割愛。
で、sign_up, sign_in, sign_outとかが簡単にできるようになったんだけどsign_upで作成されたユーザーアカウントの削除もできてしまう。
将来的にどうするかは今後検討するとしてとりあえずアカウント削除のルートを閉じておくことにした。
方法は公式GitHubのWikiに書いてあったのでそれを拝借。
https://github.com/plataformatec/devise/wiki/How-To:-Disable-user-from-destroying-his-account
scope '(:locale)' do devise_for :users, :skip => [:registration] devise_scope :user do resource :registration, only: [:new, :create, :edit, :update], path: 'users', path_names: { new: 'sign_up' }, controller: 'devise/registrations', as: :user_registration do get :cancel end end end
忘れずにテストも書いておく。
# test/functional/devise/registrations_controller_test.rb require 'test_helper' class Devise::RegistrationsControllerTest < ActionController::TestCase setup do @request.env['devise.mapping'] = Devise.mappings[:user] end test "should not be able to destroy own user account" do sign_in FactoryGirl.create :user assert_raise ActionController::RoutingError do delete :destroy end end end
ユーザー自身にアカウントを即時物理削除されて良いケースってそんなにあるんだろうか。もう少し簡単にルートを閉じれても良いように思う。
あと今更だけど論理削除で良かったかもしれない。UNIQUE制約周りどうするか(どうできるのか)検討は必要だけど。