Skip to content

How To: Secure Trestle with Devise

Stefan Wrobel edited this page May 18, 2020 · 6 revisions

Integration with trestle-auth

As of version 0.4.0 of trestle-auth, Devise integration is now properly supported. See the trestle-auth README for instructions.

Previous solution (trestle-auth not used, or < 0.4.0)

Create a lib/trestle-devise/controller_methods.rb file. Add the following contents, customizing the before_action(s) to suit your particular needs:

module Trestle
  module Auth
    module ControllerMethods
      extend ActiveSupport::Concern

      included do
        before_action :authenticate_user!
        before_action :require_president!
      end

      protected

      def require_president!
        redirect_to root_url, alert: "Only the president is authorized to access this area" unless current_user.roles?(:potus)
      end
    end
  end
end

Add the following to your config/initializers/trestle.rb file:

Trestle.configure do |config|
  # Optional, but it is always nice to give folks the option of
  # logging out:
  config.hook("view.header") do
    render "admin/header"
  end
  # ...
end
require 'trestle-devise/controller_methods'
Trestle::ApplicationController.send(:include, Trestle::Auth::ControllerMethods)

Optionally, add the custom header that allows folks to log out of devise app/views/admin/_header.html.haml:

%p{style: 'padding-top:15px;'}
  = link_to destroy_session_path(:user), :method => :delete do
    %i.fa.fa-sign-out
    Logout

Restart your server.