Streamline
Streamline

Reputation: 2122

How do I override the PasswordsController actions in a rails app with ActiveAdmin & Devise

I have a rails app that is setup to use ActiveAdmin and Devise.

I want to override the edit and update actions in the PasswordsController. As far as I can tell, ActiveAdmin is relying on Devise's PasswordsController.

Do I need to use ActiveAdmin's method for customizing a controller / resource to do this? If so what resource is in play to "register" for the PasswordsController?

Or do I need to copy Devise's entire PasswordsController from the gem to somewhere in my app and change the actions I want to change? If so what folder would I put my copy of the Devise controller so it overrides the gem's version?

What is the correct way to do this?

Upvotes: 8

Views: 3780

Answers (2)

Luis Colón
Luis Colón

Reputation: 325

My approach, which you can apply to any of the ActiveAdmin::Devise controllers, was to update the ActiveAdmin::Devise.config right before setting it in devise_for in the routes file. I needed to do a before_action on the SessionsController

config/routes.rb

Rails.application.routes.draw do
  ActiveAdmin::Devise.config[:controllers][:sessions] = 'admin/sessions'

  devise_for :admin_users, ActiveAdmin::Devise.config
      
  # other routes
end

app/controllers/admin/sessions_controler

module Admin
  class SessionsController < ActiveAdmin::Devise::SessionsController
    before_action :authorize, except: [:new, :create]
  end
end

This works for me on a Rails 6 api only app.

Upvotes: 4

seanlinsley
seanlinsley

Reputation: 3205

All of the devise-related code lives in lib/active_admin/devise.rb, including these controller definitions:

module ActiveAdmin
  module Devise

    class SessionsController < ::Devise::SessionsController
      include ::ActiveAdmin::Devise::Controller
    end

    class PasswordsController < ::Devise::PasswordsController
      include ::ActiveAdmin::Devise::Controller
    end

    class UnlocksController < ::Devise::UnlocksController
      include ::ActiveAdmin::Devise::Controller
    end

    class RegistrationsController < ::Devise::RegistrationsController
       include ::ActiveAdmin::Devise::Controller
    end

    class ConfirmationsController < ::Devise::ConfirmationsController
       include ::ActiveAdmin::Devise::Controller
    end

  end
end

You should be able to monkey-patch the PasswordsController to modify its behavior inside your app:

# config/initializers/active_admin_devise_sessions_controller.rb
class ActiveAdmin::Devise::PasswordsController

  # ...

end

Upvotes: 6

Related Questions