6th December, 2022

securing a mounted rails engine when rolling your own auth from scratch

Rails makes it wonderfully easy to roll your own auth nowadays, which I like to do – no devise needed here.

The fewer dependencies the better!
– Me, fairly regularly

One dependency I am using though is good_job. This comes with a handy dashboard that can be mounted as a rails engine.

# config/routes.rb
Rails.application.routes.draw do
  # ...
  mount GoodJob::Engine => 'jobs'
end

This is great, except leaving this open to the entire world is a bad idea. So, how do we ensure that we’re authenticated before we load it? I struggled to find a non-devise answer to this, which does make it easy with the following;

authenticate :user, ->(user) { user.admin? } do
  mount GoodJob::Engine => 'jobs'
end

So, without devise what to do? I’m at bit of a loss, so I’ve just implemented the basic auth for now. Feels dirty though, surely there’s way to use the auth from the main app instead?

GoodJob::Engine.middleware.use(Rack::Auth::Basic) do |username, password|
  ActiveSupport::SecurityUtils.secure_compare(ENV["GOODJOB_USERNAME"], username) &&
    ActiveSupport::SecurityUtils.secure_compare(ENV["GOODJOB_PASSWORD"], password)
end

Tip! Don't forget to set those environment variables!